robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
9.0 KiB272 linesraw
1---@class vim._comment.Parts
2---@field left string Left part of comment
3---@field right string Right part of comment
4
5--- Get 'commentstring' at cursor
6---@param ref_position [integer,integer]
7---@return string
8local function get_commentstring(ref_position)
9  local buf_cs = vim.bo.commentstring
10
11  local ts_parser = vim.treesitter.get_parser(0, '')
12  if not ts_parser then
13    return buf_cs
14  end
15
16  -- Try to get 'commentstring' associated with local tree-sitter language.
17  -- This is useful for injected languages (like markdown with code blocks).
18  local row, col = ref_position[1] - 1, ref_position[2]
19  local ref_range = { row, col, row, col + 1 }
20
21  -- Get 'commentstring' from tree-sitter captures' metadata.
22  -- Traverse backwards to prefer narrower captures.
23  local caps = vim.treesitter.get_captures(0, { row, col })
24  for i = #caps, 1, -1 do
25    local id, metadata = caps[i].id, caps[i].metadata
26    local md_cms = metadata['bo.commentstring'] or metadata[id] and metadata[id]['bo.commentstring']
27
28    if md_cms then
29      return md_cms
30    end
31  end
32
33  -- - Get 'commentstring' from the deepest LanguageTree which both contains
34  --   reference range and has valid 'commentstring' (meaning it has at least
35  --   one associated 'filetype' with valid 'commentstring').
36  --   In simple cases using `parser:language_for_range()` would be enough, but
37  --   it fails for languages without valid 'commentstring' (like 'comment').
38  local ts_cs, res_level = nil, 0
39
40  ---@param lang_tree vim.treesitter.LanguageTree
41  ---@param level integer
42  local function traverse(lang_tree, level)
43    if not lang_tree:contains(ref_range) then
44      return
45    end
46
47    local lang = lang_tree:lang()
48    local filetypes = vim.treesitter.language.get_filetypes(lang)
49    for _, ft in ipairs(filetypes) do
50      local cur_cs = vim.filetype.get_option(ft, 'commentstring')
51      if cur_cs ~= '' and level > res_level then
52        ts_cs = cur_cs
53      end
54    end
55
56    for _, child_lang_tree in pairs(lang_tree:children()) do
57      traverse(child_lang_tree, level + 1)
58    end
59  end
60  traverse(ts_parser, 1)
61
62  return ts_cs or buf_cs
63end
64
65--- Compute comment parts from 'commentstring'
66---@param ref_position [integer,integer]
67---@return vim._comment.Parts
68local function get_comment_parts(ref_position)
69  local cs = get_commentstring(ref_position)
70
71  if cs == nil or cs == '' then
72    vim.api.nvim_echo({ { "Option 'commentstring' is empty.", 'WarningMsg' } }, true)
73    return { left = '', right = '' }
74  end
75
76  if not (type(cs) == 'string' and cs:find('%%s') ~= nil) then
77    error(vim.inspect(cs) .. " is not a valid 'commentstring'.")
78  end
79
80  -- Structure of 'commentstring': <left part> <%s> <right part>
81  local left, right = cs:match('^(.-)%%s(.-)$')
82  assert(left and right)
83  return { left = left, right = right }
84end
85
86--- Make a function that checks if a line is commented
87---@param parts vim._comment.Parts
88---@return fun(line: string): boolean
89local function make_comment_check(parts)
90  local l_esc, r_esc = vim.pesc(parts.left), vim.pesc(parts.right)
91
92  -- Commented line has the following structure:
93  -- <whitespace> <trimmed left> <anything> <trimmed right> <whitespace>
94  local regex = '^%s-' .. vim.trim(l_esc) .. '.*' .. vim.trim(r_esc) .. '%s-$'
95
96  return function(line)
97    return line:find(regex) ~= nil
98  end
99end
100
101--- Compute comment-related information about lines
102---@param lines string[]
103---@param parts vim._comment.Parts
104---@return string indent
105---@return boolean is_commented
106local function get_lines_info(lines, parts)
107  local comment_check = make_comment_check(parts)
108
109  local is_commented = true
110  local indent_width = math.huge
111  ---@type string
112  local indent
113
114  for _, l in ipairs(lines) do
115    -- Update lines indent: minimum of all indents except blank lines
116    local _, indent_width_cur, indent_cur = l:find('^(%s*)')
117    assert(indent_width_cur and indent_cur)
118
119    -- Ignore blank lines completely when making a decision
120    if indent_width_cur < l:len() then
121      -- NOTE: Copying actual indent instead of recreating it with `indent_width`
122      -- allows to handle both tabs and spaces
123      if indent_width_cur < indent_width then
124        ---@diagnostic disable-next-line:cast-local-type
125        indent_width, indent = indent_width_cur, indent_cur
126      end
127
128      -- Update comment info: commented if every non-blank line is commented
129      if is_commented then
130        is_commented = comment_check(l)
131      end
132    end
133  end
134
135  -- `indent` can still be `nil` in case all `lines` are empty
136  return indent or '', is_commented
137end
138
139--- Compute whether a string is blank
140---@param x string
141---@return boolean is_blank
142local function is_blank(x)
143  return x:find('^%s*$') ~= nil
144end
145
146--- Make a function which comments a line
147---@param parts vim._comment.Parts
148---@param indent string
149---@return fun(line: string): string
150local function make_comment_function(parts, indent)
151  local prefix, nonindent_start, suffix = indent .. parts.left, indent:len() + 1, parts.right
152  local blank_comment = indent .. vim.trim(parts.left) .. vim.trim(suffix)
153
154  return function(line)
155    if is_blank(line) then
156      return blank_comment
157    end
158    return prefix .. line:sub(nonindent_start) .. suffix
159  end
160end
161
162--- Make a function which uncomments a line
163---@param parts vim._comment.Parts
164---@return fun(line: string): string
165local function make_uncomment_function(parts)
166  local l_esc, r_esc = vim.pesc(parts.left), vim.pesc(parts.right)
167  local regex = '^(%s*)' .. l_esc .. '(.*)' .. r_esc .. '(%s-)$'
168  local regex_trimmed = '^(%s*)' .. vim.trim(l_esc) .. '(.*)' .. vim.trim(r_esc) .. '(%s-)$'
169
170  return function(line)
171    -- Try regex with exact comment parts first, fall back to trimmed parts
172    local indent, new_line, trail = line:match(regex)
173    if new_line == nil then
174      indent, new_line, trail = line:match(regex_trimmed)
175    end
176
177    -- Return original if line is not commented
178    if new_line == nil then
179      return line
180    end
181
182    -- Prevent trailing whitespace
183    if is_blank(new_line) then
184      indent, trail = '', ''
185    end
186
187    return indent .. new_line .. trail
188  end
189end
190
191--- Comment/uncomment buffer range
192---@param line_start integer
193---@param line_end integer
194---@param ref_position? [integer, integer]
195local function toggle_lines(line_start, line_end, ref_position)
196  ref_position = ref_position or { line_start, 0 }
197  local parts = get_comment_parts(ref_position)
198  local lines = vim.api.nvim_buf_get_lines(0, line_start - 1, line_end, false)
199  local indent, is_comment = get_lines_info(lines, parts)
200
201  local f = is_comment and make_uncomment_function(parts) or make_comment_function(parts, indent)
202
203  -- Direct `nvim_buf_set_lines()` essentially removes both regular and
204  -- extended marks  (squashes to empty range at either side of the region)
205  -- inside region. Use 'lockmarks' to preserve regular marks.
206  -- Preserving extmarks is not a universally good thing to do:
207  -- - Good for non-highlighting in text area extmarks (like showing signs).
208  -- - Debatable for highlighting in text area (like LSP semantic tokens).
209  --   Mostly because it causes flicker as highlighting is preserved during
210  --   comment toggling.
211  vim._with({ lockmarks = true }, function()
212    vim.api.nvim_buf_set_lines(0, line_start - 1, line_end, false, vim.tbl_map(f, lines))
213  end)
214end
215
216--- Operator which toggles user-supplied range of lines
217---@param mode string?
218---|"'line'"
219---|"'char'"
220---|"'block'"
221local function operator(mode)
222  -- Used without arguments as part of expression mapping. Otherwise it is
223  -- called as 'operatorfunc'.
224  if mode == nil then
225    vim.o.operatorfunc = operator
226    return 'g@'
227  end
228
229  -- Compute target range
230  local mark_from, mark_to = "'[", "']"
231  local lnum_from, col_from = vim.fn.line(mark_from), vim.fn.col(mark_from)
232  local lnum_to, col_to = vim.fn.line(mark_to), vim.fn.col(mark_to)
233
234  -- Do nothing if "from" mark is after "to" (like in empty textobject)
235  if (lnum_from > lnum_to) or (lnum_from == lnum_to and col_from > col_to) then
236    return
237  end
238
239  -- NOTE: use cursor position as reference for possibly computing local
240  -- tree-sitter-based 'commentstring'. Recompute every time for a proper
241  -- dot-repeat. In Visual and sometimes Normal mode it uses start position.
242  toggle_lines(lnum_from, lnum_to, vim.api.nvim_win_get_cursor(0))
243  return ''
244end
245
246--- Select contiguous commented lines at cursor
247local function textobject()
248  local lnum_cur = vim.fn.line('.')
249  local parts = get_comment_parts({ lnum_cur, vim.fn.col('.') })
250  local comment_check = make_comment_check(parts)
251
252  if not comment_check(vim.fn.getline(lnum_cur)) then
253    return
254  end
255
256  -- Compute commented range
257  local lnum_from = lnum_cur
258  while (lnum_from >= 2) and comment_check(vim.fn.getline(lnum_from - 1)) do
259    lnum_from = lnum_from - 1
260  end
261
262  local lnum_to = lnum_cur
263  local n_lines = vim.api.nvim_buf_line_count(0)
264  while (lnum_to <= n_lines - 1) and comment_check(vim.fn.getline(lnum_to + 1)) do
265    lnum_to = lnum_to + 1
266  end
267
268  -- Select range linewise for operator to act upon
269  vim.cmd('normal! ' .. lnum_from .. 'GV' .. lnum_to .. 'G')
270end
271
272return { operator = operator, textobject = textobject, toggle_lines = toggle_lines }