robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
7.3 KiB238 linesraw
1local api = vim.api
2
3local M = {}
4
5--- Table with default priorities used for highlighting:
6--- - `syntax`: `50`, used for standard syntax highlighting
7--- - `treesitter`: `100`, used for treesitter-based highlighting
8--- - `semantic_tokens`: `125`, used for LSP semantic token highlighting
9--- - `diagnostics`: `150`, used for code analysis such as diagnostics
10--- - `user`: `200`, used for user-triggered highlights such as LSP document
11---   symbols or `hl_op` autocommands
12M.priorities = {
13  syntax = 50,
14  treesitter = 100,
15  semantic_tokens = 125,
16  diagnostics = 150,
17  user = 200,
18}
19
20--- @class vim.hl.range.Opts
21--- @inlinedoc
22---
23--- Type of range. See [getregtype()]
24--- (default: `'v'` i.e. charwise)
25--- @field regtype? string
26---
27--- Indicates whether the range is end-inclusive
28--- (default: `false`)
29--- @field inclusive? boolean
30---
31--- Highlight priority
32--- (default: `vim.hl.priorities.user`)
33--- @field priority? integer
34---
35--- Time in ms before highlight is cleared
36--- (default: -1 no timeout)
37--- @field timeout? integer
38
39--- Apply highlight group to range of text.
40---
41---@param buf integer Buffer number to apply highlighting to
42---@param ns integer Namespace to add highlight to
43---@param hlgroup integer|integer[]|string|string[] Highlight group used for the text range.
44--- See the `hl_group` option in |nvim_buf_set_extmark()|.
45---@param start [integer,integer]|string Start of region as a (line, column) tuple or string accepted by |getpos()|
46---@param finish [integer,integer]|string End of region as a (line, column) tuple or string accepted by |getpos()|
47---@param opts? vim.hl.range.Opts
48--- @return uv.uv_timer_t? range_timer A timer which manages how much time the
49--- highlight has left
50--- @return fun()? range_clear A function which allows clearing the highlight manually.
51--- nil is returned if timeout is not specified
52function M.range(buf, ns, hlgroup, start, finish, opts)
53  -- Resolve buf=0 so the deferred `range_hl_clear` works correctly even after buffer-switch.
54  buf = vim._resolve_bufnr(buf)
55  opts = opts or {}
56  local regtype = opts.regtype or 'v'
57  local inclusive = opts.inclusive or false
58  local priority = opts.priority or M.priorities.user
59  local timeout = opts.timeout or -1
60
61  local v_maxcol = vim.v.maxcol
62
63  local pos1 --- @type [integer, integer, integer, integer]
64  if type(start) == 'string' then
65    pos1 = vim.fn.getpos(start)
66  else
67    pos1 = {
68      buf,
69      start[1] + 1,
70      start[2] ~= -1 and start[2] ~= v_maxcol and start[2] + 1 or v_maxcol,
71      0,
72    }
73  end
74
75  local pos2 ---@type [integer, integer, integer, integer]
76  if type(finish) == 'string' then
77    pos2 = vim.fn.getpos(finish)
78  else
79    pos2 = {
80      buf,
81      finish[1] + 1,
82      finish[2] ~= -1 and finish[2] ~= v_maxcol and finish[2] + 1 or v_maxcol,
83      0,
84    }
85  end
86
87  local buf_line_count = api.nvim_buf_line_count(buf)
88  pos1[2] = math.min(pos1[2], buf_line_count)
89  pos2[2] = math.min(pos2[2], buf_line_count)
90
91  if pos1[2] <= 0 or pos1[3] <= 0 or pos2[2] <= 0 or pos2[3] <= 0 then
92    return
93  end
94
95  vim._with({ buf = buf }, function()
96    if pos1[3] ~= v_maxcol then
97      local max_col1 = vim.fn.col({ pos1[2], '$' })
98      pos1[3] = math.min(pos1[3], max_col1)
99    end
100    if pos2[3] ~= v_maxcol then
101      local max_col2 = vim.fn.col({ pos2[2], '$' })
102      pos2[3] = math.min(pos2[3], max_col2)
103    end
104  end)
105
106  -- For non-blockwise selection, use a single extmark and only compute its bounds.
107  local bounds = regtype == 'v' or regtype == 'V'
108  local region = vim.fn.getregionpos(pos1, pos2, {
109    type = regtype,
110    exclusive = not inclusive,
111    eol = true,
112    bounds = bounds,
113  })
114  if bounds then
115    local region1 = assert(region[1])
116    if
117      regtype == 'V'
118      or region1[2][2] == pos1[2] and pos1[3] == v_maxcol
119      or region1[2][2] == pos2[2] and pos2[3] == v_maxcol
120    then
121      region1[2][2] = region1[2][2] + 1
122      region1[2][3] = 0
123    end
124  end
125
126  local extmarks = {} --- @type integer[]
127  for _, res in ipairs(region) do
128    local start_row = res[1][2] - 1
129    local start_col = res[1][3] - 1
130    local end_row = res[2][2] - 1
131    local end_col = res[2][3]
132    table.insert(
133      extmarks,
134      api.nvim_buf_set_extmark(buf, ns, start_row, start_col, {
135        hl_group = hlgroup,
136        end_row = end_row,
137        end_col = end_col,
138        priority = priority,
139        strict = false,
140      })
141    )
142  end
143
144  local range_hl_clear = function()
145    if not api.nvim_buf_is_valid(buf) then
146      return
147    end
148    for _, mark in ipairs(extmarks) do
149      api.nvim_buf_del_extmark(buf, ns, mark)
150    end
151  end
152
153  if timeout ~= -1 then
154    local range_timer = vim.defer_fn(range_hl_clear, timeout)
155    return range_timer, range_hl_clear
156  end
157end
158
159---@class (private) vim.hl.OnEventState
160---@field timer? uv.uv_timer_t Timer to clear the highlight.
161---@field clear? fun() Function to clear the highlight immediately.
162
163--- @type { [string]: vim.hl.OnEventState }
164local hl_op_state = {}
165
166local events_ns = api.nvim_create_namespace('nvim.hl.events')
167
168--- Highlights the affected text region during a |TextYankPost| or |TextPutPost| event.
169---
170--- Add this to your `init.vim`:
171---
172--- ```vim
173--- autocmd TextYankPost * silent! lua vim.hl.hl_op {higroup='Visual', timeout=300}
174--- autocmd TextPutPost  * silent! lua vim.hl.hl_op {higroup='Visual', timeout=300}
175--- ```
176---
177--- @param opts table|nil Optional parameters
178---              - event     (default: vim.v.event) Event structure.
179---              - higroup   (default: "IncSearch") Highlight group for the text region.
180---              - on_macro  (default: false) Highlight during |macro| execution.
181---              - on_visual (default: true) Highlight during |Visual| mode.
182---              - priority  (default: |vim.hl.priorities|`.user`) Integer priority.
183---              - timeout   (default: 150) Time in ms before highlight is cleared.
184function M.hl_op(opts)
185  vim.validate('opts', opts, 'table', true)
186  opts = opts or {}
187  local event = opts.event or vim.v.event
188  local on_macro = opts.on_macro or false
189  local on_visual = (opts.on_visual ~= false)
190
191  if not on_macro and vim.fn.reg_executing() ~= '' then
192    return
193  elseif
194    event.regtype == ''
195    or (event.operator ~= 'y' and event.operator ~= 'p' and event.operator ~= 'P')
196  then
197    return
198  elseif not on_visual and event.visual then
199    return
200  end
201
202  local state_key = event.operator == 'y' and 'yank' or 'put'
203  local hlgroup = opts.higroup or 'IncSearch'
204
205  local bufnr = api.nvim_get_current_buf()
206  local winid = api.nvim_get_current_win()
207
208  local state = hl_op_state[state_key]
209  -- Multicursor cascade: accumulate per-cursor, don't cancel the previous event's highlight.
210  local cascading = api.nvim__mcursor_cascading()
211  if state ~= nil and state.timer and not state.timer:is_closing() and not cascading then
212    state.timer:close()
213    assert(state.clear)
214    state.clear()
215  end
216
217  api.nvim__ns_set(events_ns, { wins = { winid } })
218  local timer, clear = M.range(bufnr, events_ns, hlgroup, "'[", "']", {
219    regtype = event.regtype,
220    inclusive = true,
221    priority = opts.priority or M.priorities.user,
222    timeout = opts.timeout or 150,
223  })
224
225  hl_op_state[state_key] = {
226    timer = timer,
227    clear = clear,
228  }
229end
230
231--- @deprecated Use |vim.hl.hl_op()| instead.
232--- @param opts? table
233function M.on_yank(opts)
234  vim.deprecate('vim.hl.on_yank', 'vim.hl.hl_op', '0.14')
235  return M.hl_op(opts)
236end
237
238return M