robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
14.6 KiB499 linesraw
1// help.c: functions for Vim help
2
3#include <stdbool.h>
4#include <stdint.h>
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8
9#include "nvim/ascii_defs.h"
10#include "nvim/buffer.h"
11#include "nvim/buffer_defs.h"
12#include "nvim/change.h"
13#include "nvim/charset.h"
14#include "nvim/cmdexpand.h"
15#include "nvim/cmdexpand_defs.h"
16#include "nvim/errors.h"
17#include "nvim/eval/typval.h"
18#include "nvim/ex_cmds.h"
19#include "nvim/ex_cmds_defs.h"
20#include "nvim/ex_docmd.h"
21#include "nvim/extmark_defs.h"
22#include "nvim/fileio.h"
23#include "nvim/garray.h"
24#include "nvim/garray_defs.h"
25#include "nvim/gettext_defs.h"
26#include "nvim/globals.h"
27#include "nvim/help.h"
28#include "nvim/lua/executor.h"
29#include "nvim/macros_defs.h"
30#include "nvim/mark.h"
31#include "nvim/mbyte.h"
32#include "nvim/mbyte_defs.h"
33#include "nvim/memline.h"
34#include "nvim/memory.h"
35#include "nvim/message.h"
36#include "nvim/normal.h"
37#include "nvim/option.h"
38#include "nvim/option_defs.h"
39#include "nvim/option_vars.h"
40#include "nvim/optionstr.h"
41#include "nvim/os/fs.h"
42#include "nvim/os/input.h"
43#include "nvim/os/os.h"
44#include "nvim/os/os_defs.h"
45#include "nvim/path.h"
46#include "nvim/pos_defs.h"
47#include "nvim/runtime.h"
48#include "nvim/strings.h"
49#include "nvim/tag.h"
50#include "nvim/types_defs.h"
51#include "nvim/vim_defs.h"
52#include "nvim/window.h"
53
54#include "help.c.generated.h"
55
56/// ":help": open a read-only window on a help file
57/// ":help!": DWIM parse the best match at cursor
58void ex_help(exarg_T *eap)
59{
60  char *arg;
61  FILE *helpfd;          // file descriptor of help file
62  win_T *wp;
63  int num_matches;
64  char **matches;
65  int empty_fnum = 0;
66  int alt_fnum = 0;
67  const bool old_KeyTyped = KeyTyped;
68
69  if (eap != NULL) {
70    // A ":help" command ends at the first LF, or at a '|' that is
71    // followed by some text.  Set nextcmd to the following command.
72    for (arg = eap->arg; *arg; arg++) {
73      if (*arg == '\n' || *arg == '\r'
74          || (*arg == '|' && arg[1] != NUL && arg[1] != '|')) {
75        *arg++ = NUL;
76        eap->nextcmd = arg;
77        break;
78      }
79    }
80    arg = eap->arg;
81
82    if (eap->skip) {        // not executing commands
83      return;
84    }
85  } else {
86    arg = "";
87  }
88
89  // remove trailing blanks
90  char *p = arg + strlen(arg) - 1;
91  while (p > arg && ascii_iswhite(*p) && p[-1] != '\\') {
92    *p-- = NUL;
93  }
94
95  // Check for a specified language
96  char *lang = check_help_lang(arg);
97
98  // ":help!" (bang, no args).
99  bool helpbang = (eap != NULL && eap->forceit && *arg == NUL);
100
101  // When no argument given go to the index.
102  if (*arg == NUL && !helpbang) {
103    arg = "help.txt";
104  }
105
106  // ":help!" (bang, no args): DWIM help, resolve best tag at cursor via Lua.
107  char *allocated_arg = NULL;
108  if (helpbang) {
109    typval_T no_args[] = { { .v_type = VAR_UNKNOWN } };
110    typval_T rettv;
111    nlua_call_typval("vim._core.help", "resolve_tag", no_args, &rettv);
112    if (rettv.v_type == VAR_STRING && rettv.vval.v_string != NULL && *rettv.vval.v_string != NUL) {
113      allocated_arg = rettv.vval.v_string;  // takes ownership
114      arg = allocated_arg;
115    } else {
116      tv_clear(&rettv);
117      emsg(_(e_noident));
118      return;
119    }
120  }
121
122  // Check if there is a match for the argument.
123  int n = find_help_tags(arg, &num_matches, &matches, eap != NULL && eap->forceit);
124
125  int i = 0;
126  if (n != FAIL && lang != NULL) {
127    // Find first item with the requested language.
128    for (i = 0; i < num_matches; i++) {
129      int len = (int)strlen(matches[i]);
130      if (len > 3 && matches[i][len - 3] == '@'
131          && STRICMP(matches[i] + len - 2, lang) == 0) {
132        break;
133      }
134    }
135  }
136  if (i >= num_matches || n == FAIL) {
137    if (lang != NULL) {
138      semsg(_("E661: No '%s' help for %s"), lang, arg);
139    } else {
140      semsg(_("E149: No help for %s"), arg);
141    }
142    if (n != FAIL) {
143      FreeWild(num_matches, matches);
144    }
145    xfree(allocated_arg);
146    return;
147  }
148
149  // The first match (in the requested language) is the best match.
150  char *tag = xstrdup(matches[i]);
151  FreeWild(num_matches, matches);
152
153  // Re-use an existing help window or open a new one.
154  // Always open a new one for ":tab help".
155  if (!bt_help(curwin->w_buffer) || cmdmod.cmod_tab != 0) {
156    if (cmdmod.cmod_tab != 0) {
157      wp = NULL;
158    } else {
159      wp = NULL;
160      FOR_ALL_WINDOWS_IN_TAB(wp2, curtab) {
161        if (bt_help(wp2->w_buffer) && !wp2->w_config.hide && wp2->w_config.focusable) {
162          wp = wp2;
163          break;
164        }
165      }
166    }
167    if (wp != NULL && wp->w_buffer->b_nwindows > 0) {
168      win_enter(wp, true);
169    } else {
170      // There is no help window yet.
171      // Try to open the file specified by the "helpfile" option.
172      if ((helpfd = os_fopen(p_hf, READBIN)) == NULL) {
173        smsg(0, _("Help file \"%s\" not found"), p_hf);
174        goto erret;
175      }
176      fclose(helpfd);
177
178      // Split off help window; put it at far top if no position
179      // specified, the current window is vertically split and
180      // narrow.
181      n = WSP_HELP;
182      if (cmdmod.cmod_split == 0 && curwin->w_width != Columns
183          && curwin->w_width < 80) {
184        n |= p_sb ? WSP_BOT : WSP_TOP;
185      }
186      if (win_split(0, n) == FAIL) {
187        goto erret;
188      }
189
190      if (curwin->w_height < p_hh) {
191        win_setheight((int)p_hh);
192      }
193
194      // Open help file (do_ecmd() will set b_help flag, readfile() will
195      // set b_p_ro flag).
196      // Set the alternate file to the previously edited file.
197      alt_fnum = curbuf->b_fnum;
198      do_ecmd(0, NULL, NULL, NULL, ECMD_LASTL,
199              ECMD_HIDE + ECMD_SET_HELP,
200              NULL);  // buffer is still open, don't store info
201
202      if ((cmdmod.cmod_flags & CMOD_KEEPALT) == 0) {
203        curwin->w_alt_fnum = alt_fnum;
204      }
205      empty_fnum = curbuf->b_fnum;
206    }
207  }
208
209  restart_edit = 0;               // don't want insert mode in help file
210
211  // Restore KeyTyped, setting 'filetype=help' may reset it.
212  // It is needed for do_tag top open folds under the cursor.
213  KeyTyped = old_KeyTyped;
214
215  do_tag(NULL, tag, DT_HELP, 1, false, true);
216
217  // Delete the empty buffer if we're not using it.  Careful: autocommands
218  // may have jumped to another window, check that the buffer is not in a
219  // window.
220  if (empty_fnum != 0 && curbuf->b_fnum != empty_fnum) {
221    buf_T *buf = buflist_findnr(empty_fnum);
222    if (buf != NULL && buf->b_nwindows == 0) {
223      wipe_buffer(buf, true);
224    }
225  }
226
227  // keep the previous alternate file
228  if (alt_fnum != 0 && curwin->w_alt_fnum == empty_fnum
229      && (cmdmod.cmod_flags & CMOD_KEEPALT) == 0) {
230    curwin->w_alt_fnum = alt_fnum;
231  }
232
233erret:
234  xfree(tag);
235  xfree(allocated_arg);
236}
237
238/// ":helpclose": Close one help window
239void ex_helpclose(exarg_T *eap)
240{
241  FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
242    if (bt_help(win->w_buffer)) {
243      win_close(win, false, eap->forceit);
244      return;
245    }
246  }
247}
248
249/// In an argument search for a language specifiers in the form "@xx".
250/// Changes the "@" to NUL if found, and returns a pointer to "xx".
251///
252/// @return  NULL if not found.
253char *check_help_lang(char *arg)
254{
255  int len = (int)strlen(arg);
256
257  if (len >= 3 && arg[len - 3] == '@' && ASCII_ISALPHA(arg[len - 2])
258      && ASCII_ISALPHA(arg[len - 1])) {
259    arg[len - 3] = NUL;                 // remove the '@'
260    return arg + len - 2;
261  }
262  return NULL;
263}
264
265/// Return a heuristic indicating how well the given string matches.  The
266/// smaller the number, the better the match.  This is the order of priorities,
267/// from best match to worst match:
268///      - Match with least alphanumeric characters is better.
269///      - Match with least total characters is better.
270///      - Match towards the start is better.
271///      - Match starting with "+" is worse (feature instead of command)
272/// Assumption is made that the matched_string passed has already been found to
273/// match some string for which help is requested.  webb.
274///
275/// @param offset      offset for match
276/// @param wrong_case  no matching case
277///
278/// @return  a heuristic indicating how well the given string matches.
279int help_heuristic(char *matched_string, int offset, bool wrong_case)
280  FUNC_ATTR_PURE
281{
282  int num_letters = 0;
283  for (char *p = matched_string; *p; p++) {
284    if (ASCII_ISALNUM(*p)) {
285      num_letters++;
286    }
287  }
288
289  // Multiply the number of letters by 100 to give it a much bigger
290  // weighting than the number of characters.
291  // If there only is a match while ignoring case, add 5000.
292  // If the match starts in the middle of a word, add 10000 to put it
293  // somewhere in the last half.
294  // If the match is more than 2 chars from the start, multiply by 200 to
295  // put it after matches at the start.
296  if (offset > 0
297      && ASCII_ISALNUM(matched_string[offset])
298      && ASCII_ISALNUM(matched_string[offset - 1])) {
299    offset += 10000;
300  } else if (offset > 2) {
301    offset *= 200;
302  }
303  if (wrong_case) {
304    offset += 5000;
305  }
306  // Features are less interesting than the subjects themselves, but "+"
307  // alone is not a feature.
308  if (matched_string[0] == '+' && matched_string[1] != NUL) {
309    offset += 100;
310  }
311  return 100 * num_letters + (int)strlen(matched_string) + offset;
312}
313
314/// Compare functions for qsort() below, that checks the help heuristics number
315/// that has been put after the tagname by find_tags().
316static int help_compare(const void *s1, const void *s2)
317{
318  char *p1 = *(char **)s1 + strlen(*(char **)s1) + 1;
319  char *p2 = *(char **)s2 + strlen(*(char **)s2) + 1;
320
321  // Compare by help heuristic number first.
322  int cmp = strcmp(p1, p2);
323  if (cmp != 0) {
324    return cmp;
325  }
326
327  // Compare by strings as tie-breaker when same heuristic number.
328  return strcmp(*(char **)s1, *(char **)s2);
329}
330
331/// Find all help tags matching "arg", sort them and return in matches[], with
332/// the number of matches in num_matches.
333/// The matches will be sorted with a "best" match algorithm.
334/// When "keep_lang" is true try keeping the language of the current buffer.
335int find_help_tags(const char *arg, int *num_matches, char ***matches, bool keep_lang)
336{
337  typval_T tv_args[] = {
338    { .v_type = VAR_STRING, .vval.v_string = (char *)arg },
339    { .v_type = VAR_UNKNOWN },
340  };
341  typval_T rettv;
342  nlua_call_typval("vim._core.help", "escape_subject", tv_args, &rettv);
343  if (rettv.v_type != VAR_STRING || rettv.vval.v_string == NULL) {
344    tv_clear(&rettv);
345    return FAIL;
346  }
347  xstrlcpy(IObuff, rettv.vval.v_string, sizeof(IObuff));
348  tv_clear(&rettv);
349
350  *matches = NULL;
351  *num_matches = 0;
352  int flags = TAG_HELP | TAG_REGEXP | TAG_NAMES | TAG_VERBOSE | TAG_NO_TAGFUNC;
353  if (keep_lang) {
354    flags |= TAG_KEEP_LANG;
355  }
356  if (find_tags(IObuff, num_matches, matches, flags, MAXCOL, NULL) == OK
357      && *num_matches > 0) {
358    // Sort the matches found on the heuristic number that is after the
359    // tag name.
360    qsort((void *)(*matches), (size_t)(*num_matches),
361          sizeof(char *), help_compare);
362    // Delete more than TAG_MANY to reduce the size of the listing.
363    while (*num_matches > TAG_MANY) {
364      xfree((*matches)[--*num_matches]);
365    }
366  }
367  return OK;
368}
369
370/// Cleanup matches for help tags:
371/// Remove "@ab" if the top of 'helplang' is "ab" and the language of the first
372/// tag matches it.  Otherwise remove "@en" if "en" is the only language.
373void cleanup_help_tags(int num_file, char **file)
374{
375  char buf[4];
376  char *p = buf;
377
378  if (p_hlg[0] != NUL && (p_hlg[0] != 'e' || p_hlg[1] != 'n')) {
379    *p++ = '@';
380    *p++ = p_hlg[0];
381    *p++ = p_hlg[1];
382  }
383  *p = NUL;
384
385  for (int i = 0; i < num_file; i++) {
386    int len = (int)strlen(file[i]) - 3;
387    if (len <= 0) {
388      continue;
389    }
390    if (strcmp(file[i] + len, "@en") == 0) {
391      // Sorting on priority means the same item in another language may
392      // be anywhere.  Search all items for a match up to the "@en".
393      int j;
394      for (j = 0; j < num_file; j++) {
395        if (j != i
396            && (int)strlen(file[j]) == len + 3
397            && strncmp(file[i], file[j], (size_t)len + 1) == 0) {
398          break;
399        }
400      }
401      if (j == num_file) {
402        // item only exists with @en, remove it
403        file[i][len] = NUL;
404      }
405    }
406  }
407
408  if (*buf != NUL) {
409    for (int i = 0; i < num_file; i++) {
410      int len = (int)strlen(file[i]) - 3;
411      if (len <= 0) {
412        continue;
413      }
414      if (strcmp(file[i] + len, buf) == 0) {
415        // remove the default language
416        file[i][len] = NUL;
417      }
418    }
419  }
420}
421
422/// Called when starting to edit a buffer for a help file.
423void prepare_help_buffer(void)
424{
425  curbuf->b_help = true;
426  set_option_direct(kOptBuftype, STATIC_CSTR_AS_OBJ("help"), OPT_LOCAL, 0);
427
428  // Always set these options after jumping to a help tag, because the
429  // user may have an autocommand that gets in the way.
430  // Accept all ASCII chars for keywords, except ' ', '*', '"', '|', and
431  // latin1 word characters (for translated help files).
432  // Only set it when needed, buf_init_chartab() is some work.
433  char *p = "!-~,^*,^|,^\",192-255";
434  if (strcmp(curbuf->b_p_isk, p) != 0) {
435    set_option_direct(kOptIskeyword, CSTR_AS_OBJ(p), OPT_LOCAL, 0);
436    check_buf_options(curbuf);
437    buf_init_isk_chartab(curbuf);
438  }
439
440  // Don't use the global foldmethod.
441  set_option_direct(kOptFoldmethod, STATIC_CSTR_AS_OBJ("manual"), OPT_LOCAL, 0);
442
443  curbuf->b_p_ts = 8;         // 'tabstop' is 8.
444  curwin->w_p_list = false;   // No list mode.
445
446  curbuf->b_p_ma = false;     // Not modifiable.
447  curbuf->b_p_bin = false;    // Reset 'bin' before reading file.
448  curwin->w_p_nu = 0;         // No line numbers.
449  curwin->w_p_rnu = 0;        // No relative line numbers.
450  RESET_BINDING(curwin);      // No scroll or cursor binding.
451  curwin->w_p_arab = false;   // No arabic mode.
452  curwin->w_p_rl = false;     // Help window is left-to-right.
453  curwin->w_p_fen = false;    // No folding in the help window.
454  curwin->w_p_diff = false;   // No 'diff'.
455  curwin->w_p_spell = false;  // No spell checking.
456
457  set_buflisted(false);
458}
459
460/// Populate *local-additions* in help.txt
461void get_local_additions(void)
462{
463  typval_T no_args[] = { { .v_type = VAR_UNKNOWN } };
464  nlua_call_typval("vim._core.help", "local_additions", no_args, NULL);
465}
466
467/// ":exusage"
468void ex_exusage(exarg_T *eap)
469{
470  do_cmdline_cmd("help ex-cmd-index");
471}
472
473/// ":viusage"
474void ex_viusage(exarg_T *eap)
475{
476  do_cmdline_cmd("help normal-index");
477}
478
479/// ":helptags"
480void ex_helptags(exarg_T *eap)
481{
482  bool add_help_tags = false;
483
484  // Check for ++t in ":helptags ++t {dir}".
485  if (strncmp(eap->arg, "++t", 3) == 0 && ascii_iswhite(eap->arg[3])) {
486    add_help_tags = true;
487    eap->arg = skipwhite(eap->arg + 3);
488  }
489
490  typval_T tv_args[] = {
491    { .v_type = VAR_STRING, .vval.v_string = eap->arg },
492    { .v_type = VAR_BOOL, .vval.v_bool = add_help_tags ? kBoolVarTrue : kBoolVarFalse },
493    { .v_type = VAR_UNKNOWN },
494  };
495  if (strcmp(eap->arg, "ALL") == 0) {
496    tv_args[0] = (typval_T){ .v_type = VAR_SPECIAL, .vval.v_special = kSpecialVarNull };
497  }
498  nlua_call_typval("vim._core.help", "gen_tags", tv_args, NULL);
499}