robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
9.3 KiB318 linesraw
1local api = vim.api
2local fn = vim.fn
3local nvim_on = require('vim._core.util').nvim_on
4
5local M = {}
6
7local skip_names = { 'string', 'character', 'singlequote', 'escape', 'symbol', 'comment' }
8
9---@param text string
10---@param byte_col integer
11---@return string
12local function char_at(text, byte_col)
13  if byte_col > #text then
14    return ''
15  end
16  return text:sub(byte_col, byte_col + vim.str_utf_end(text, byte_col))
17end
18
19---@param text string
20---@param byte_col integer
21---@return string
22local function char_before(text, byte_col)
23  local end_col = math.min(byte_col - 1, #text)
24  if end_col < 1 then
25    return ''
26  end
27  return text:sub(end_col + vim.str_utf_start(text, end_col), end_col)
28end
29
30function M.enable()
31  vim.g.loaded_matchparen = 1
32
33  if vim.g.matchparen_timeout == nil then
34    vim.g.matchparen_timeout = 300
35  end
36  if vim.g.matchparen_insert_timeout == nil then
37    vim.g.matchparen_insert_timeout = 60
38  end
39  if vim.g.matchparen_disable_cursor_hl == nil then
40    vim.g.matchparen_disable_cursor_hl = 0
41  end
42
43  local group = api.nvim_create_augroup('matchparen', { clear = true })
44
45  -- Replace all matchparen autocommands
46  nvim_on(
47    { 'CursorMoved', 'CursorMovedI', 'WinEnter', 'WinScrolled', 'TextChanged', 'TextChangedI' },
48    group,
49    function()
50      M.highlight_matching_pair()
51    end
52  )
53  nvim_on('BufWinEnter', group, function()
54    nvim_on('SafeState', group, { once = true }, function()
55      M.highlight_matching_pair()
56    end)
57  end)
58  nvim_on({ 'WinLeave', 'BufLeave', 'TextChangedP' }, group, function()
59    M.remove_matches()
60  end)
61
62  -- Define commands that will disable and enable the plugin.
63  api.nvim_create_user_command('DoMatchParen', function()
64    M.do_matchparen()
65  end, { force = true })
66  api.nvim_create_user_command('NoMatchParen', function()
67    M.no_matchparen()
68  end, { force = true })
69end
70
71--- The function that is invoked (very often) to define a ":match" highlighting
72--- for any matching paren.
73---@param win? integer
74function M.highlight_matching_pair(win)
75  win = win or api.nvim_get_current_win()
76  local buf = api.nvim_win_get_buf(win)
77
78  if vim.w[win].matchparen_ids == nil then
79    vim.w[win].matchparen_ids = {}
80  end
81  -- Remove any previous match.
82  M.remove_matches(win)
83
84  -- Avoid that we remove the popup menu.
85  if fn.pumvisible() ~= 0 then
86    return
87  end
88
89  -- Get the character under the cursor and check if it's in 'matchpairs'.
90  local cursor = api.nvim_win_get_cursor(win)
91  local c_lnum = cursor[1]
92  local c_col = cursor[2] + 1
93  local before = 0
94
95  local text = api.nvim_buf_get_lines(buf, c_lnum - 1, c_lnum, false)[1] or ''
96  -- Cursor columns are byte indexes,
97  -- while 'matchpairs' entries may be multibyte characters.
98  -- Use UTF-8 boundaries to extract the whole character around the byte column.
99  local c_before = char_before(text, c_col)
100  local c = char_at(text, c_col)
101  ---@type string[]
102  local plist = vim.split(vim.bo[buf].matchpairs, '[:,]', { trimempty = true })
103  ---@type integer?
104  local i = vim.iter(ipairs(plist)):find(function(_, item)
105    return item == c
106  end)
107  if i == nil then
108    -- not found, in Insert mode try character before the cursor
109    local mode = api.nvim_get_mode().mode
110    if c_col > 1 and (mode == 'i' or mode == 'R') then
111      before = #c_before
112      c = c_before
113      i = vim.iter(ipairs(plist)):find(function(_, item)
114        return item == c
115      end)
116    end
117    if i == nil then
118      -- not found, nothing to do
119      return
120    end
121  end
122
123  -- Figure out the arguments for searchpairpos().
124  local flags ---@type string
125  local c2 ---@type string
126  if i % 2 == 1 then
127    flags = 'nW'
128    c2 = assert(plist[i + 1])
129  else
130    flags = 'nbW'
131    c2 = c
132    c = assert(plist[i - 1])
133  end
134  if c == '[' then
135    c = [=[\[]=]
136    c2 = [=[\]]=]
137  end
138
139  -- Find the match.  When it was just before the cursor move it there for a
140  -- moment.
141  local save_cursor ---@type [integer, integer, integer, integer, integer]?
142  if before > 0 then
143    save_cursor = fn.getcurpos(win)
144    api.nvim_win_set_cursor(win, { c_lnum, c_col - before - 1 })
145  end
146
147  local skip ---@type fun(): boolean
148  if vim.g.syntax_on == nil then
149    skip = function()
150      return false
151    end
152  elseif vim.b[buf].ts_highlight ~= nil and vim.bo[buf].syntax ~= 'on' then
153    skip = function()
154      for _, capture in ipairs(vim.treesitter.get_captures_at_cursor(win)) do
155        for _, skip_name in ipairs(skip_names) do
156          if capture:find(skip_name, 1, true) ~= nil then
157            return true
158          end
159        end
160      end
161      return false
162    end
163  else
164    -- do not attempt to match when the syntax item where the cursor is
165    -- indicates there does not exist a matching parenthesis, e.g. for shells
166    -- case statement: "case $var in foobar)"
167    --
168    -- add the check behind a filetype check, so it only needs to be
169    -- evaluated for certain filetypes
170    if vim.bo[buf].filetype == 'sh' then
171      local pos = api.nvim_win_get_cursor(win)
172      ---@type integer[]
173      local stack = api.nvim_win_call(win, function()
174        return fn.synstack(pos[1], pos[2] + 1)
175      end)
176      for _, id in ipairs(stack) do
177        if fn.synIDattr(id, 'name'):lower():find('shsnglcase') ~= nil then
178          if save_cursor ~= nil then
179            api.nvim_win_call(win, function()
180              fn.setpos('.', save_cursor)
181            end)
182          end
183          return
184        end
185      end
186    end
187    -- Build an expression that detects whether the current cursor position is
188    -- in certain syntax types (string, comment, etc.), for use as
189    -- searchpairpos()'s skip argument.
190    -- We match "escape" for special items, such as lispEscapeSpecial, and
191    -- match "symbol" for lispBarSymbol.
192    skip = function()
193      local pos = api.nvim_win_get_cursor(win)
194      for _, id in ipairs(fn.synstack(pos[1], pos[2] + 1)) do
195        local name = fn.synIDattr(id, 'name'):lower()
196        for _, skip_name in ipairs(skip_names) do
197          if name:find(skip_name, 1, true) ~= nil then
198            return true
199          end
200        end
201      end
202      return false
203    end
204    -- If executing the expression determines that the cursor is currently in
205    -- one of the syntax types, then we want searchpairpos() to find the pair
206    -- within those syntax types (i.e., not skip).  Otherwise, the cursor is
207    -- outside of the syntax types and skip should keep its value so we skip
208    -- any matching pair inside the syntax types.
209    if api.nvim_win_call(win, skip) then
210      skip = function()
211        return false
212      end
213    end
214  end
215
216  -- Limit the search to lines visible in the window.
217  ---@type integer, integer
218  local stoplinetop, stoplinebottom = unpack(api.nvim_win_call(win, function()
219    return { fn.line('w0'), fn.line('w$') }
220  end))
221  local stopline ---@type integer
222  if i % 2 == 1 then
223    stopline = stoplinebottom
224  else
225    stopline = stoplinetop
226  end
227
228  -- Limit the search time to 300 msec to avoid a hang on very long lines.
229  local timeout ---@type integer
230  local mode = api.nvim_get_mode().mode
231  if mode == 'i' or mode == 'R' then
232    timeout = vim.b[buf].matchparen_insert_timeout or vim.g.matchparen_insert_timeout
233  else
234    timeout = vim.b[buf].matchparen_timeout or vim.g.matchparen_timeout
235  end
236
237  ---@type boolean, [integer, integer]|string
238  local ok, match = pcall(api.nvim_win_call, win, function()
239    return fn.searchpairpos(c, '', c2, flags, skip, stopline, timeout)
240  end)
241  if not ok then ---@cast match string
242    if save_cursor ~= nil then
243      api.nvim_win_call(win, function()
244        fn.setpos('.', save_cursor)
245      end)
246    end
247    error(match)
248  end ---@cast match [integer, integer]
249  if save_cursor ~= nil then
250    api.nvim_win_call(win, function()
251      fn.setpos('.', save_cursor)
252    end)
253  end
254
255  local m_lnum = match[1]
256  local m_col = match[2]
257
258  -- If a match is found setup match highlighting.
259  if m_lnum > 0 and m_lnum >= stoplinetop and m_lnum <= stoplinebottom then
260    local ids = vim.w[win].matchparen_ids
261    if tonumber(vim.g.matchparen_disable_cursor_hl) == 0 then
262      table.insert(
263        ids,
264        fn.matchaddpos(
265          'MatchParen',
266          { { c_lnum, c_col - before }, { m_lnum, m_col } },
267          10,
268          -1,
269          { window = win }
270        )
271      )
272    else
273      table.insert(
274        ids,
275        fn.matchaddpos('MatchParen', { { m_lnum, m_col } }, 10, -1, { window = win })
276      )
277    end
278    vim.w[win].matchparen_ids = ids
279    vim.w[win].paren_hl_on = 1
280  end
281end
282
283---@param win? integer
284function M.remove_matches(win)
285  win = win or api.nvim_get_current_win()
286
287  if vim.w[win].paren_hl_on ~= nil and vim.w[win].paren_hl_on ~= 0 then
288    local ids = vim.w[win].matchparen_ids or {}
289    while #ids > 0 do
290      pcall(fn.matchdelete, table.remove(ids, 1), win)
291    end
292    vim.w[win].matchparen_ids = ids
293    vim.w[win].paren_hl_on = 0
294  end
295end
296
297---@param tab? integer
298function M.no_matchparen(tab)
299  tab = tab or api.nvim_get_current_tabpage()
300  for _, win in ipairs(api.nvim_tabpage_list_wins(tab)) do
301    M.remove_matches(win)
302  end
303  vim.g.loaded_matchparen = nil
304  pcall(api.nvim_clear_autocmds, { group = 'matchparen' })
305end
306
307---@param tab? integer
308function M.do_matchparen(tab)
309  if vim.g.loaded_matchparen == nil then
310    M.enable()
311  end
312  tab = tab or api.nvim_get_current_tabpage()
313  for _, win in ipairs(api.nvim_tabpage_list_wins(tab)) do
314    M.highlight_matching_pair(win)
315  end
316end
317
318return M