aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua/vim/_core/help.lua
blob: 1621fc2fcd89991bcec605d472b6e8407e9f596a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
local M = {}

local echo_err = require('vim._core.util').echo_err
local fs = require('vim.fs')

local tag_exceptions = {
  -- Interpret asterisk (star, '*') literal but name it 'star'
  ['*'] = 'star',
  ['g*'] = 'gstar',
  ['[*'] = '[star',
  [']*'] = ']star',
  [':*'] = ':star',
  ['/*'] = '/star',
  ['/\\*'] = '/\\\\star',
  ['\\\\star'] = '/\\\\star',
  ['"*'] = 'quotestar',
  ['**'] = 'starstar',
  ['cpo-*'] = 'cpo-star',

  -- Literal question mark '?'
  ['?'] = '?',
  ['??'] = '??',
  [':?'] = ':?',
  ['?<CR>'] = '?<CR>',
  ['g?'] = 'g?',
  ['g?g?'] = 'g?g?',
  ['g??'] = 'g??',
  ['-?'] = '-?',
  ['q?'] = 'q?',
  ['v_g?'] = 'v_g?',
  ['/\\?'] = '/\\\\?',

  -- Backslash-escaping hell
  ['/\\%(\\)'] = '/\\\\%(\\\\)',
  ['/\\z(\\)'] = '/\\\\z(\\\\)',
  ['\\='] = '\\\\=',
  ['\\%$'] = '/\\\\%\\$',

  -- Some expressions are literal but without the 'expr-' prefix. Note: not all 'expr-' subjects!
  ['expr-!=?'] = '!=?',
  ['expr-!~?'] = '!\\~?',
  ['expr-<=?'] = '<=?',
  ['expr-<?'] = '<?',
  ['expr-==?'] = '==?',
  ['expr-=~?'] = '=\\~?',
  ['expr->=?'] = '>=?',
  ['expr->?'] = '>?',
  ['expr-is?'] = 'is?',
  ['expr-isnot?'] = 'isnot?',
}

---Transform a help tag query into a search pattern for find_tags().
---
---This function converts user input from `:help {subject}` into a regex pattern that balances
---literal matching with wildcard support. Vim help tags can contain characters that have special
---meaning in regex (like *, ?, |), but we also want to support wildcard searches.
---
---Examples:
---  '*' --> 'star' (literal match for the * command help tag)
---  'buffer*' --> 'buffer.*' (wildcard: find all buffer-related tags)
---  'CTRL-W' --> stays as 'CTRL-W' (already in tag format)
---  '^A' --> 'CTRL-A' (caret notation converted to tag format)
---
---@param word string The help subject as entered by the user
---@return string pattern The escaped regex pattern to search for in tag files
function M.escape_subject(word)
  local replacement = tag_exceptions[word]
  if replacement then
    return replacement
  end

  -- Add prefix '/\\' to patterns starting with a backslash
  -- Examples: \S, \%^, \%(, \zs, \z1, \@<, \@=, \@<=, \_$, \_^
  if word:match([[^\.$]]) or word:match('^\\[%%_z@]') then
    word = [[/\]] .. word
    word = word:gsub('[$.~]', [[\%0]])
    word = word:gsub('|', 'bar')
  else
    -- Fix for bracket expressions and curly braces:
    -- '\' --> '\\' (needs to come first)
    -- '[' --> '\[' (escape the opening bracket)
    -- ':[' --> ':\[' (escape the opening bracket)
    -- '\{' --> '\\{' (for '\{' pattern matching)
    -- '(' --> '' (parentheses around option tags should be ignored)
    word = word:gsub([[\+]], [[\\]])
    word = word:gsub([[^%[]], [[\[]])
    word = word:gsub([[^:%[]], [[:\[]])
    word = word:gsub([[^\{]], [[\\{]])
    word = word:gsub([[^%(']], [[']])

    word = word:gsub('|', 'bar')
    word = word:gsub([["]], 'quote')
    word = word:gsub('[$.~]', [[\%0]])
    word = word:gsub('%*', '.*')
    word = word:gsub('?', '.')

    -- Handle control characters.
    -- First convert raw control chars to the caret notation
    -- E.g. 0x01 --> '^A' etc.
    ---@type string
    word = word:gsub('([\1-\31])', function(ctrl_char)
      -- '^\' needs an extra backslash
      local repr = string.char(ctrl_char:byte() + 64):gsub([[\]], [[\\]])
      return '^' .. repr
    end)

    -- Change caret notation to 'CTRL-', except '^_'
    -- E.g. 'i^G^J' --> 'iCTRL-GCTRL-J'
    -- Only treat '^' as control notation when followed by a caret-notation
    -- char (a letter or one of "?@[\]^{"); otherwise leave it literal so
    -- patterns like ':set^=' are not wrongly split. '{' is included so
    -- '^{char}' matches the 'CTRL-{char}' placeholder tag.
    word = word:gsub('%^([%a?@\\[\\%]{^])', 'CTRL-%1')
    -- Add underscores around 'CTRL-X' characters
    -- E.g. 'iCTRL-GCTRL-J' --> 'i_CTRL-G_CTRL-J'
    -- Only exception: 'CTRL-{character}'
    word = word:gsub('([^-_])CTRL%-', '%1_CTRL-')
    word = word:gsub('(CTRL%-[^{])([^%u_\\-])', '%1_%2')

    -- Skip function arguments
    -- E.g. 'abs({expr})' --> 'abs'
    -- E.g. 'abs([arg])' --> 'abs'
    word = word:gsub('%({.*', '')
    word = word:gsub('%(%[.*', '')

    -- Skip punctuation after second apostrophe/curly brace
    -- E.g. ''option',' --> ''option''
    -- E.g. '{address},' --> '{address}'
    -- E.g. '`command`,' --> 'command' (backticks are removed too, but '``' stays '``')
    word = word:gsub([[^'([^']*)'.*]], [['%1']])
    word = word:gsub([[^{([^}]*)}.*]], '{%1}')
    word = word:gsub([[.*`([^`]+)`.*]], '%1')
  end

  return word
end

--- Characters that are considered punctuation for trimming help tags.
--- Dots (.) are NOT included here — they're trimmed separately as a last resort.
local trimmable_punct = {
  ['('] = true,
  [')'] = true,
  ['<'] = true,
  ['>'] = true,
  ['['] = true,
  [']'] = true,
  ['{'] = true,
  ['}'] = true,
  ['`'] = true,
  ['|'] = true,
  ['"'] = true,
  [','] = true,
  ["'"] = true,
  [' '] = true,
  ['\t'] = true,
}

--- Trim one layer of punctuation from a help tag string.
--- Uses cursor offset to intelligently trim: if cursor is on trimmable punctuation,
--- removes everything before cursor and skips past punctuation after cursor.
---
---@param tag string The tag to trim
---@param offset integer Cursor position within the tag (-1 if not applicable)
---@return string? trimmed Trimmed string, or nil if unchanged
local function trim_tag(tag, offset)
  if not tag or tag == '' then
    return nil
  end

  -- Special cases: single character tags
  if tag == '|' then
    return 'bar'
  end
  if tag == '"' then
    return 'quote'
  end

  local len = #tag
  -- start/end are 1-indexed inclusive positions into tag
  local s = 1
  local e = len

  if offset >= 0 and offset < len and trimmable_punct[tag:sub(offset + 1, offset + 1)] then
    -- Heuristic: cursor is on trimmable punctuation, skip past it to the right
    s = offset + 1
    while s <= e and trimmable_punct[tag:sub(s, s)] do
      s = s + 1
    end
  elseif offset >= 0 and offset < len then
    -- Cursor is on non-trimmable char: find start of identifier at cursor
    local cursor_pos = offset + 1 -- 1-indexed
    while cursor_pos > s and not trimmable_punct[tag:sub(cursor_pos - 1, cursor_pos - 1)] do
      cursor_pos = cursor_pos - 1
    end
    s = cursor_pos
  else
    -- No cursor info: trim leading punctuation
    while s <= e and trimmable_punct[tag:sub(s, s)] do
      s = s + 1
    end
  end

  -- Trim trailing punctuation
  while e >= s and trimmable_punct[tag:sub(e, e)] do
    e = e - 1
  end

  -- Truncate function or generic arguments, e.g. "foo('bar')" => "foo", "Task<R...>" => "Task".
  -- But keep "()" since it's part of valid tags like "vim.fn.expand()".
  for i = s, e do
    if
      tag:sub(i, i) == '<'
      or (tag:sub(i, i) == '(' and not (i + 1 <= e and tag:sub(i + 1, i + 1) == ')'))
    then
      e = i - 1
      break
    end
  end

  -- If nothing changed, return nil
  if s == 1 and e == len then
    return nil
  end

  -- If everything was trimmed, return nil
  if s > e then
    return nil
  end

  return tag:sub(s, e)
end

--- Trim namespace prefix (dots) from a help tag.
--- Only call this if regular trimming didn't find a match.
--- Returns the tag with the leftmost dot-separated segment removed.
---
---@param tag string The tag to trim
---@return string? trimmed Trimmed string, or nil if no dots found
local function trim_tag_dots(tag)
  if not tag or tag == '' then
    return nil
  end
  local after_dot = tag:match('^[^.]+%.(.+)$')
  return after_dot
end

--- For ":help!" (bang, no args): DWIM resolve a help tag from the cursor context.
--- Gets `<cWORD>` at cursor, tries it first, then trims punctuation and dots until a valid help
--- tag is found. Falls back to `<cword>` (keyword at cursor) before dot-trimming.
---
---@return string? resolved The resolved help tag, or nil if no match found
function M.resolve_tag()
  local tag = vim.fn.expand('<cWORD>') --[[@as string]]
  if not tag or tag == '' then
    return nil
  end

  -- In type annotations, "?" means nullable rather than a help-search wildcard.
  local nullable_type = tag:match('^%(`([%w_.]+)[%[%]]*%?`%)$')
  if nullable_type and #vim.fn.getcompletion(nullable_type, 'help') > 0 then
    return nullable_type
  end

  -- Compute cursor offset within <cWORD>.
  local line = vim.api.nvim_get_current_line()
  local col = vim.fn.col('.') -- 1-indexed
  local s = col
  -- Scan backward from col('.') to find the whitespace boundary.
  while s > 1 and not line:sub(s - 1, s - 1):match('%s') do
    s = s - 1
  end
  local offset = col - s -- 0-indexed offset within <cWORD>

  -- Try the original tag first.
  if #vim.fn.getcompletion(tag, 'help') > 0 then
    return tag
  end

  -- Extract |tag| reference if the cursor is inside one (help's link syntax).
  local pipe_tag = tag:match('|(.+)|')
  if pipe_tag and #vim.fn.getcompletion(pipe_tag, 'help') > 0 then
    return pipe_tag
  end

  -- Iteratively trim punctuation and try again, up to 10 times.
  local candidate = tag
  for _ = 1, 10 do
    local trimmed = trim_tag(candidate, offset)
    if not trimmed then
      break
    end
    candidate = trimmed
    -- After first trim, offset is no longer valid.
    offset = -1

    if #vim.fn.getcompletion(candidate, 'help') > 0 then
      return candidate
    end
  end

  -- Try the word (alphanumeric/underscore run) at the cursor before dot-trimming, since
  -- dot-trimming strips from the left and may move away from the cursor position.
  -- E.g. for '@lsp.type.function' with cursor on "lsp", the word is "lsp".
  -- Note: we don't use <cword> because it depends on 'iskeyword'.
  local word_s, word_e = col, col
  -- If cursor is not on a word char, find the nearest word char to the right.
  if not line:sub(col, col):match('[%w_]') then
    while word_s <= #line and not line:sub(word_s, word_s):match(