diff --git a/README.md b/README.md index c451855..335e2d2 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,10 @@ require('gitlinker').setup({ -- print message in command line message = true, + -- highlights the linked line(s) by the time in ms + -- disable highlight by setting a value equal or less than 0 + highlight_duration = 100, + -- key mapping mapping = { ["gl"] = { diff --git a/lua/gitlinker.lua b/lua/gitlinker.lua index 6340b8e..71e777e 100644 --- a/lua/gitlinker.lua +++ b/lua/gitlinker.lua @@ -1,5 +1,6 @@ local logger = require("gitlinker.logger") local Linker = require("gitlinker.linker").Linker +local highlight = require("gitlinker.highlight") --- @alias Options table --- @type Options @@ -9,6 +10,11 @@ local Defaults = { --- @type boolean message = true, + -- highlight the linked region + -- + --- @type integer + highlight_duration = 500, + -- key mappings -- --- @alias KeyMappingConfig {action:fun(url:string):nil,desc:string?} @@ -130,6 +136,15 @@ local function setup(opts) end end + -- Configure highlight group + if Configs.highlight_duration >= 0 then + vim.api.nvim_set_hl( + 0, + "NvimGitLinkerHighlightTextObject", + { link = "Search" } + ) + end + -- logger.debug("|setup| Configs:%s", vim.inspect(Configs)) end @@ -211,6 +226,10 @@ local function link(opts) if opts.action then opts.action(url) end + if opts.highlight_duration >= 0 then + highlight.show({ lstart = lk.lstart, lend = lk.lend }) + vim.defer_fn(highlight.clear, opts.highlight_duration) + end if opts.message then local msg = lk.file_changed and string.format( diff --git a/lua/gitlinker/highlight.lua b/lua/gitlinker/highlight.lua new file mode 100644 index 0000000..9f6d67a --- /dev/null +++ b/lua/gitlinker/highlight.lua @@ -0,0 +1,36 @@ +local M = {} + +-- Highlights the text selected by the specified range. +--- @param range Range? +M.show = function(range) + if not range then + return + end + local namespace = vim.api.nvim_create_namespace("NvimGitLinker") + local lstart, lend = range.lstart, range.lend + if lend and lend < lstart then + lstart, lend = lend, lstart + end + local pos1 = { lstart - 1, 1 } + local pos2 = { (lend or lstart) - 1, vim.fn.col("$") } + vim.highlight.range( + 0, + namespace, + "NvimGitLinkerHighlightTextObject", + pos1, + pos2, + { inclusive = true } + ) + -- Force the screen to highlight the text immediately + vim.cmd("redraw") +end + +-- Clears the gitlinker highlights for the buffer. +M.clear = function() + local namespace = vim.api.nvim_create_namespace("NvimGitLinker") + vim.api.nvim_buf_clear_namespace(0, namespace, 0, -1) + -- Force the screen to clear the highlight immediately + vim.cmd("redraw") +end + +return M