robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
19.8 KiB595 linesraw
1local M = {}
2
3local echo_err = require('vim._core.util').echo_err
4local fs = require('vim.fs')
5
6local tag_exceptions = {
7  -- Interpret asterisk (star, '*') literal but name it 'star'
8  ['*'] = 'star',
9  ['g*'] = 'gstar',
10  ['[*'] = '[star',
11  [']*'] = ']star',
12  [':*'] = ':star',
13  ['/*'] = '/star',
14  ['/\\*'] = '/\\\\star',
15  ['\\\\star'] = '/\\\\star',
16  ['"*'] = 'quotestar',
17  ['**'] = 'starstar',
18  ['cpo-*'] = 'cpo-star',
19
20  -- Literal question mark '?'
21  ['?'] = '?',
22  ['??'] = '??',
23  [':?'] = ':?',
24  ['?<CR>'] = '?<CR>',
25  ['g?'] = 'g?',
26  ['g?g?'] = 'g?g?',
27  ['g??'] = 'g??',
28  ['-?'] = '-?',
29  ['q?'] = 'q?',
30  ['v_g?'] = 'v_g?',
31  ['/\\?'] = '/\\\\?',
32
33  -- Backslash-escaping hell
34  ['/\\%(\\)'] = '/\\\\%(\\\\)',
35  ['/\\z(\\)'] = '/\\\\z(\\\\)',
36  ['\\='] = '\\\\=',
37  ['\\%$'] = '/\\\\%\\$',
38
39  -- Some expressions are literal but without the 'expr-' prefix. Note: not all 'expr-' subjects!
40  ['expr-!=?'] = '!=?',
41  ['expr-!~?'] = '!\\~?',
42  ['expr-<=?'] = '<=?',
43  ['expr-<?'] = '<?',
44  ['expr-==?'] = '==?',
45  ['expr-=~?'] = '=\\~?',
46  ['expr->=?'] = '>=?',
47  ['expr->?'] = '>?',
48  ['expr-is?'] = 'is?',
49  ['expr-isnot?'] = 'isnot?',
50}
51
52---Transform a help tag query into a search pattern for find_tags().
53---
54---This function converts user input from `:help {subject}` into a regex pattern that balances
55---literal matching with wildcard support. Vim help tags can contain characters that have special
56---meaning in regex (like *, ?, |), but we also want to support wildcard searches.
57---
58---Examples:
59---  '*' --> 'star' (literal match for the * command help tag)
60---  'buffer*' --> 'buffer.*' (wildcard: find all buffer-related tags)
61---  'CTRL-W' --> stays as 'CTRL-W' (already in tag format)
62---  '^A' --> 'CTRL-A' (caret notation converted to tag format)
63---
64---@param word string The help subject as entered by the user
65---@return string pattern The escaped regex pattern to search for in tag files
66function M.escape_subject(word)
67  local replacement = tag_exceptions[word]
68  if replacement then
69    return replacement
70  end
71
72  -- Add prefix '/\\' to patterns starting with a backslash
73  -- Examples: \S, \%^, \%(, \zs, \z1, \@<, \@=, \@<=, \_$, \_^
74  if word:match([[^\.$]]) or word:match('^\\[%%_z@]') then
75    word = [[/\]] .. word
76    word = word:gsub('[$.~]', [[\%0]])
77    word = word:gsub('|', 'bar')
78  else
79    -- Fix for bracket expressions and curly braces:
80    -- '\' --> '\\' (needs to come first)
81    -- '[' --> '\[' (escape the opening bracket)
82    -- ':[' --> ':\[' (escape the opening bracket)
83    -- '\{' --> '\\{' (for '\{' pattern matching)
84    -- '(' --> '' (parentheses around option tags should be ignored)
85    word = word:gsub([[\+]], [[\\]])
86    word = word:gsub([[^%[]], [[\[]])
87    word = word:gsub([[^:%[]], [[:\[]])
88    word = word:gsub([[^\{]], [[\\{]])
89    word = word:gsub([[^%(']], [[']])
90
91    word = word:gsub('|', 'bar')
92    word = word:gsub([["]], 'quote')
93    word = word:gsub('[$.~]', [[\%0]])
94    word = word:gsub('%*', '.*')
95    word = word:gsub('?', '.')
96
97    -- Handle control characters.
98    -- First convert raw control chars to the caret notation
99    -- E.g. 0x01 --> '^A' etc.
100    ---@type string
101    word = word:gsub('([\1-\31])', function(ctrl_char)
102      -- '^\' needs an extra backslash
103      local repr = string.char(ctrl_char:byte() + 64):gsub([[\]], [[\\]])
104      return '^' .. repr
105    end)
106
107    -- Change caret notation to 'CTRL-', except '^_'
108    -- E.g. 'i^G^J' --> 'iCTRL-GCTRL-J'
109    -- Only treat '^' as control notation when followed by a caret-notation
110    -- char (a letter or one of "?@[\]^{"); otherwise leave it literal so
111    -- patterns like ':set^=' are not wrongly split. '{' is included so
112    -- '^{char}' matches the 'CTRL-{char}' placeholder tag.
113    word = word:gsub('%^([%a?@\\[\\%]{^])', 'CTRL-%1')
114    -- Add underscores around 'CTRL-X' characters
115    -- E.g. 'iCTRL-GCTRL-J' --> 'i_CTRL-G_CTRL-J'
116    -- Only exception: 'CTRL-{character}'
117    word = word:gsub('([^-_])CTRL%-', '%1_CTRL-')
118    word = word:gsub('(CTRL%-[^{])([^%u_\\-])', '%1_%2')
119
120    -- Skip function arguments
121    -- E.g. 'abs({expr})' --> 'abs'
122    -- E.g. 'abs([arg])' --> 'abs'
123    word = word:gsub('%({.*', '')
124    word = word:gsub('%(%[.*', '')
125
126    -- Skip punctuation after second apostrophe/curly brace
127    -- E.g. ''option',' --> ''option''
128    -- E.g. '{address},' --> '{address}'
129    -- E.g. '`command`,' --> 'command' (backticks are removed too, but '``' stays '``')
130    word = word:gsub([[^'([^']*)'.*]], [['%1']])
131    word = word:gsub([[^{([^}]*)}.*]], '{%1}')
132    word = word:gsub([[.*`([^`]+)`.*]], '%1')
133  end
134
135  return word
136end
137
138--- Characters that are considered punctuation for trimming help tags.
139--- Dots (.) are NOT included here — they're trimmed separately as a last resort.
140local trimmable_punct = {
141  ['('] = true,
142  [')'] = true,
143  ['<'] = true,
144  ['>'] = true,
145  ['['] = true,
146  [']'] = true,
147  ['{'] = true,
148  ['}'] = true,
149  ['`'] = true,
150  ['|'] = true,
151  ['"'] = true,
152  [','] = true,
153  ["'"] = true,
154  [' '] = true,
155  ['\t'] = true,
156}
157
158--- Trim one layer of punctuation from a help tag string.
159--- Uses cursor offset to intelligently trim: if cursor is on trimmable punctuation,
160--- removes everything before cursor and skips past punctuation after cursor.
161---
162---@param tag string The tag to trim
163---@param offset integer Cursor position within the tag (-1 if not applicable)
164---@return string? trimmed Trimmed string, or nil if unchanged
165local function trim_tag(tag, offset)
166  if not tag or tag == '' then
167    return nil
168  end
169
170  -- Special cases: single character tags
171  if tag == '|' then
172    return 'bar'
173  end
174  if tag == '"' then
175    return 'quote'
176  end
177
178  local len = #tag
179  -- start/end are 1-indexed inclusive positions into tag
180  local s = 1
181  local e = len
182
183  if offset >= 0 and offset < len and trimmable_punct[tag:sub(offset + 1, offset + 1)] then
184    -- Heuristic: cursor is on trimmable punctuation, skip past it to the right
185    s = offset + 1
186    while s <= e and trimmable_punct[tag:sub(s, s)] do
187      s = s + 1
188    end
189  elseif offset >= 0 and offset < len then
190    -- Cursor is on non-trimmable char: find start of identifier at cursor
191    local cursor_pos = offset + 1 -- 1-indexed
192    while cursor_pos > s and not trimmable_punct[tag:sub(cursor_pos - 1, cursor_pos - 1)] do
193      cursor_pos = cursor_pos - 1
194    end
195    s = cursor_pos
196  else
197    -- No cursor info: trim leading punctuation
198    while s <= e and trimmable_punct[tag:sub(s, s)] do
199      s = s + 1
200    end
201  end
202
203  -- Trim trailing punctuation
204  while e >= s and trimmable_punct[tag:sub(e, e)] do
205    e = e - 1
206  end
207
208  -- Truncate function or generic arguments, e.g. "foo('bar')" => "foo", "Task<R...>" => "Task".
209  -- But keep "()" since it's part of valid tags like "vim.fn.expand()".
210  for i = s, e do
211    if
212      tag:sub(i, i) == '<'
213      or (tag:sub(i, i) == '(' and not (i + 1 <= e and tag:sub(i + 1, i + 1) == ')'))
214    then
215      e = i - 1
216      break
217    end
218  end
219
220  -- If nothing changed, return nil
221  if s == 1 and e == len then
222    return nil
223  end
224
225  -- If everything was trimmed, return nil
226  if s > e then
227    return nil
228  end
229
230  return tag:sub(s, e)
231end
232
233--- Trim namespace prefix (dots) from a help tag.
234--- Only call this if regular trimming didn't find a match.
235--- Returns the tag with the leftmost dot-separated segment removed.
236---
237---@param tag string The tag to trim
238---@return string? trimmed Trimmed string, or nil if no dots found
239local function trim_tag_dots(tag)
240  if not tag or tag == '' then
241    return nil
242  end
243  local after_dot = tag:match('^[^.]+%.(.+)$')
244  return after_dot
245end
246
247--- For ":help!" (bang, no args): DWIM resolve a help tag from the cursor context.
248--- Gets `<cWORD>` at cursor, tries it first, then trims punctuation and dots until a valid help
249--- tag is found. Falls back to `<cword>` (keyword at cursor) before dot-trimming.
250---
251---@return string? resolved The resolved help tag, or nil if no match found
252function M.resolve_tag()
253  local tag = vim.fn.expand('<cWORD>') --[[@as string]]
254  if not tag or tag == '' then
255    return nil
256  end
257
258  -- In type annotations, "?" means nullable rather than a help-search wildcard.
259  local nullable_type = tag:match('^%(`([%w_.]+)[%[%]]*%?`%)$')
260  if nullable_type and #vim.fn.getcompletion(nullable_type, 'help') > 0 then
261    return nullable_type
262  end
263
264  -- Compute cursor offset within <cWORD>.
265  local line = vim.api.nvim_get_current_line()
266  local col = vim.fn.col('.') -- 1-indexed
267  local s = col
268  -- Scan backward from col('.') to find the whitespace boundary.
269  while s > 1 and not line:sub(s - 1, s - 1):match('%s') do
270    s = s - 1
271  end
272  local offset = col - s -- 0-indexed offset within <cWORD>
273
274  -- Try the original tag first.
275  if #vim.fn.getcompletion(tag, 'help') > 0 then
276    return tag
277  end
278
279  -- Extract |tag| reference if the cursor is inside one (help's link syntax).
280  local pipe_tag = tag:match('|(.+)|')
281  if pipe_tag and #vim.fn.getcompletion(pipe_tag, 'help') > 0 then
282    return pipe_tag
283  end
284
285  -- Iteratively trim punctuation and try again, up to 10 times.
286  local candidate = tag
287  for _ = 1, 10 do
288    local trimmed = trim_tag(candidate, offset)
289    if not trimmed then
290      break
291    end
292    candidate = trimmed
293    -- After first trim, offset is no longer valid.
294    offset = -1
295
296    if #vim.fn.getcompletion(candidate, 'help') > 0 then
297      return candidate
298    end
299  end
300
301  -- Try the word (alphanumeric/underscore run) at the cursor before dot-trimming, since
302  -- dot-trimming strips from the left and may move away from the cursor position.
303  -- E.g. for '@lsp.type.function' with cursor on "lsp", the word is "lsp".
304  -- Note: we don't use <cword> because it depends on 'iskeyword'.
305  local word_s, word_e = col, col
306  -- If cursor is not on a word char, find the nearest word char to the right.
307  if not line:sub(col, col):match('[%w_]') then
308    while word_s <= #line and not line:sub(word_s, word_s):match('[%w_]') do
309      word_s = word_s + 1
310    end
311    word_e = word_s
312  end
313  while word_s > 1 and line:sub(word_s - 1, word_s - 1):match('[%w_]') do
314    word_s = word_s - 1
315  end
316  while word_e <= #line and line:sub(word_e, word_e):match('[%w_]') do
317    word_e = word_e + 1
318  end
319  word_e = word_e - 1
320  local cword = line:sub(word_s, word_e)
321  if #cword > 1 and cword ~= tag and #vim.fn.getcompletion(cword, 'help') > 0 then
322    return cword
323  end
324
325  -- Try trimming namespace dots (left-to-right).
326  for _ = 1, 10 do
327    local trimmed = trim_tag_dots(candidate)
328    if not trimmed then
329      break
330    end
331    candidate = trimmed
332
333    if #vim.fn.getcompletion(candidate, 'help') > 0 then
334      return candidate
335    end
336  end
337
338  -- No match found: return raw <cWORD> so the caller can show it in an error message.
339  return tag
340end
341
342---Populates the |local-additions| section of a help buffer with references to locally-installed
343---help files. These are help files outside of $VIMRUNTIME (typically from plugins) whose first
344---line contains a tag (e.g. *plugin-name.txt*) and a short description.
345---
346---For each help file found in 'runtimepath', the first line is extracted and added to the buffer
347---as a reference (converting '*tag*' to '|tag|'). If a translated version of a help file exists
348---in the same language as the current buffer (e.g. 'plugin.nlx' alongside 'plugin.txt'), the
349---translated version is preferred over the '.txt' file.
350function M.local_additions()
351  local buf = vim.api.nvim_get_current_buf()
352  local bufname = vim.fs.basename(vim.api.nvim_buf_get_name(buf))
353
354  -- "help.txt" or "help.??x" where ?? is a language code, see |help-translated|.
355  local lang = bufname:match('^help%.(%a%a)x$')
356  if bufname ~= 'help.txt' and not lang then
357    return
358  end
359
360  -- Find local help files
361  ---@type table<string, string>
362  local plugins = {}
363  local pattern = lang and ('doc/*.{txt,%sx}'):format(lang) or 'doc/*.txt'
364  for _, docpath in ipairs(vim.api.nvim_get_runtime_file(pattern, true)) do
365    if not vim.fs.relpath(assert(vim.env.VIMRUNTIME), docpath) then
366      -- '/path/to/doc/plugin.txt' --> 'plugin'
367      local plugname = vim.fs.basename(docpath):sub(1, -5)
368      -- prefer language-specific files over .txt
369      if not plugins[plugname] or vim.endswith(plugins[plugname], '.txt') then
370        plugins[plugname] = docpath
371      end
372    end
373  end
374
375  -- Format plugin list lines
376  -- Default to 78 if 'textwidth' is not set (e.g. in sandbox)
377  local textwidth = math.max(vim.bo[buf].textwidth, 78)
378  local lines = {}
379  for _, path in vim.spairs(plugins) do
380    local fp = io.open(path, 'r')
381    if fp then
382      local tagline = fp:read('*l') or ''
383      fp:close()
384      ---@type string, string
385      local plugname, desc = tagline:match('^%*([^*]+)%*%s*(.*)$')
386      if plugname and desc then
387        -- left-align taglink and right-align description by inserting spaces in between
388        local plug_width = vim.fn.strdisplaywidth(plugname)
389        local _, concealed_chars = desc:gsub('|', '')
390        local desc_width = vim.fn.strdisplaywidth(desc) - concealed_chars
391        -- max(l, 1) forces at least one space for if the description is too long
392        local spaces = string.rep(' ', math.max(textwidth - desc_width - plug_width - 2, 1))
393        local fmt = string.format('|%s|%s%s', plugname, spaces, desc)
394        table.insert(lines, fmt)
395      end
396    end
397  end
398
399  -- Add plugin list to local-additions section
400  for linenr, line in ipairs(vim.api.nvim_buf_get_lines(buf, 0, -1, false)) do
401    if line:find('*local-additions*', 1, true) then
402      vim._with({ buf = buf, bo = { modifiable = true, readonly = false } }, function()
403        vim.api.nvim_buf_set_lines(buf, linenr, linenr, true, lines)
404      end)
405      break
406    end
407  end
408end
409
410---Language code of a help file: "en" for "*.txt", "nl" for "*.nlx". See |help-translated|.
411---@param file string
412---@return string?
413local function helpfile_lang(file)
414  local ext = file:sub(-4):lower()
415  return ext == '.txt' and 'en' or ext:match('^%.(%a%a)x$')
416end
417
418---Report duplicate tags.
419---@param tags string[] sorted tags file lines
420local function report_duplicates(tags)
421  local prevtag
422
423  for i, tagline in ipairs(tags) do
424    local curtag = tagline:match('^[^\t]*')
425    if curtag == prevtag then
426      local curfn = tagline:match('\t([^\t]*)')
427      local prevfn = assert(tags[i - 1]):match('\t([^\t]*)')
428      local filenames = prevfn ~= curfn and (curfn .. ' and ' .. prevfn) or curfn
429      echo_err(('E154: Duplicate tag "%s" in %s'):format(curtag, filenames))
430    end
431    prevtag = curtag
432  end
433end
434
435local helptags_pattern ---@type vim.lpeg.Pattern
436do
437  local P, S, R, B, C, Ct = vim.lpeg.P, vim.lpeg.S, vim.lpeg.R, vim.lpeg.B, vim.lpeg.C, vim.lpeg.Ct
438  local any = P(1)
439  local eof = -any
440  local space = S(' \t')
441  -- Accept LF, CRLF, and an unterminated final line.
442  local newline = P('\r') ^ -1 * P('\n')
443  local line_end = newline + P('\r') ^ -1 * eof
444  local line_start = -B(any) + B(P('\n'))
445  -- Assert surrounding whitespace without consuming it, so adjacent tags can share it.
446  local tag = (line_start + B(space))
447    * P('*')
448    * C((any - S('* \t|\n')) ^ 1)
449    * P('*')
450    * #(space + line_end)
451  -- An example continues through blank or indented lines.
452  local example_line = newline + space * (any - P('\n')) ^ 0 * (P('\n') + eof)
453  local example = (line_start + B(P(' ')))
454    * P('>')
455    * R('az', '09') ^ 0
456    * line_end
457    * example_line ^ 0
458  -- Skip ordinary text in spans; consume invalid markers one character at a time.
459  local text = (any - S('*>')) ^ 1 + any
460  helptags_pattern = Ct(((example + tag + text) ^ 0) --[[@as vim.lpeg.Pattern]])
461end
462
463---Extract tags from {file} and add to list of tags. Modifies {tags}.
464---@param tags string[]
465---@param file string
466---@param name string Path of {file} relative to the help directory, as stored in the tags file.
467local function extract_tags(tags, file, name)
468  local f = io.open(file, 'r')
469  if not f then
470    echo_err(('E153: Unable to open %s for reading'):format(file))
471    return
472  end
473  -- Read once to avoid stdio calls and locking for every line.
474  local source = assert(f:read('*a'))
475  f:close()
476
477  for _, tagname in ipairs(helptags_pattern:match(source)) do
478    tags[#tags + 1] = ('%s\t%s\t/*%s*'):format(tagname, name, tagname:gsub('[\\/]', '\\%0'))
479  end
480end
481
482--- Extract tags from helpfiles and combine in a single 'tags' file.
483--- @param helpfiles string[] list of helpfiles
484--- @param dir string Help directory; tag entries name the helpfiles relative to it.
485--- @param outpath string path to write the 'tags' file to.
486--- @param index_tag string? Filename for the "help-tags" entry, if included
487--- @param ignore_writeerr boolean don't report a tags file that cannot be written
488function M.gen_tagsfile(helpfiles, dir, outpath, index_tag, ignore_writeerr)
489  -- Avoid scanning helpfiles when the output cannot be written (:helptags ALL).
490  local f = io.open(outpath, 'w')
491  if not f then
492    if not ignore_writeerr then
493      echo_err(('E152: Cannot open %s for writing'):format(outpath))
494    end
495    return
496  end
497
498  ---@type string[] Tags file lines: "tag<Tab>file<Tab>search command".
499  local tags = {}
500
501  -- (1) extract tags from all files
502  for _, file in ipairs(helpfiles) do
503    extract_tags(tags, file, fs.relpath(dir, file) or fs.basename(file))
504  end
505
506  if index_tag then
507    table.insert(tags, ('help-tags\t%s\t1'):format(index_tag))
508  end
509
510  -- (2) sort by byte value, as |tags-file-format| requires.
511  -- PUC Lua uses strcoll(), so use C collation for this sort.
512  -- The stdlib annotation omits nil, which queries the current locale.
513  --- @diagnostic disable-next-line: param-type-mismatch
514  local locale = assert(os.setlocale(nil, 'collate'))
515  os.setlocale('C', 'collate')
516  table.sort(tags)
517  os.setlocale(locale, 'collate')
518
519  -- (3) report duplicates
520  report_duplicates(tags)
521
522  -- (4) write tags to file
523  for _, tag in ipairs(tags) do
524    f:write(tag, '\n')
525  end
526  f:close()
527end
528
529--- Create a "tags" file for all help files in the given directory.
530---
531--- The directory {dir} is generally a "doc" directory that contains "*.txt"
532--- helpfiles.
533---
534--- @param dir string? Path to directory with help files. If `nil` (or |vim.NIL|),
535--- generate tags for every `doc` directory in the runtimepath.
536--- @param include_index_tag? boolean (default: false) Whether to include the "help-tags" tag.
537function M.gen_tags(dir, include_index_tag)
538  if dir == vim.NIL then
539    dir = nil
540  end
541  vim.validate('dir', dir, 'string', true)
542  vim.validate('include_index_tag', include_index_tag, 'boolean', true)
543
544  local dirs = dir and { vim.fs.normalize(dir) } or vim.api.nvim_get_runtime_file('doc', true)
545  local vimruntime = vim.fs.normalize(vim.fs.joinpath(assert(vim.env.VIMRUNTIME), 'doc'))
546
547  if dir and vim.fn.isdirectory(assert(dirs[1])) == 0 then
548    echo_err(('E150: Not a directory: %s'):format(dir))
549    return
550  end
551
552  for _, directory in ipairs(dirs) do
553    -- Resolve once for traversal and relpath(), avoiding getcwd() for every file.
554    -- Keep directory for messages and the VIMRUNTIME comparison.
555    local absdir = vim.fs.abspath(directory)
556    local files = vim.fs.find(function(name, _)
557      return helpfile_lang(name) ~= nil
558    end, {
559      path = absdir,
560      type = 'file',
561      follow = true,
562      limit = math.huge,
563    })
564
565    if vim.tbl_isempty(files) then
566      echo_err(('E151: No match: %s'):format(vim.fs.joinpath(directory, '**/*.txt')))
567    end
568
569    -- categorize helpfiles per language, see |help-translated|
570    ---@type table<string, string[]>
571    local per_lang = {}
572    for _, file in ipairs(files) do
573      local lang = assert(helpfile_lang(file))
574      per_lang[lang] = per_lang[lang] or {}
575      table.insert(per_lang[lang], file)
576    end
577
578    for lang, langfiles in pairs(per_lang) do
579      -- English is an exception: "*.txt" files generate the "tags" file.
580      local tagsfile = lang == 'en' and 'tags' or ('tags-%s'):format(lang)
581      local outpath = vim.fs.joinpath(directory, tagsfile)
582      -- ":helptags ALL" walks 'runtimepath', which may contain read-only directories.
583      local ignore_writeerr = dir == nil
584      M.gen_tagsfile(
585        langfiles,
586        absdir,
587        outpath,
588        (include_index_tag or directory == vimruntime) and tagsfile or nil,
589        ignore_writeerr
590      )
591    end
592  end
593end
594
595return M