robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
56.0 KiB1639 linesraw
1--- Converts Nvim :help files to alternate formats (HTML or Typst).
2--- Validates |tag| links and document syntax (parser errors).
3--
4-- USAGE (For CI/local testing purposes): Simply `make lintdoc`, which basically does the following:
5--   1. :helptags ALL
6--   2. nvim -V1 -es +"lua require('src.gen.gen_help_html').run_validate()" +q
7--   3. nvim -V1 -es +"lua require('src.gen.gen_help_html').test_gen()" +q
8--
9-- USAGE (GENERATE HTML):
10--   1. `:helptags ALL` first; this script depends on vim.fn.taglist().
11--   2. nvim -V1 -es --clean +"lua require('src.gen.gen_help_html').gen('html', './runtime/doc', 'target/dir/')" +q
12--      - Read the docstring at gen().
13--   3. cd target/dir/ && jekyll serve --host 0.0.0.0
14--   4. Visit http://localhost:4000/…/help.txt.html
15--
16-- USAGE (GENERATE PDF VIA TYPST):
17--   1. `:helptags ALL`
18--   2. mkdir usr_manual pdf_docs
19--   3. cp runtime/doc/usr_*.txt usr_manual/
20--   4. nvim -V1 -es --clean +"lua require('src.gen.gen_help_html').gen('typ', './usr_manual', 'pdf_docs')" +q
21--   5. mv pdf_docs/usr_toc.typ pdf_docs/user_manual.typ && cat pdf_docs/usr_*.typ >> pdf_docs/user_manual.typ
22--   6. typst compile pdf_docs/user_manual.typ
23--   7. open pdf_docs/user_manual.pdf
24--
25-- USAGE (VALIDATE):
26--   1. nvim -V1 -es +"lua require('src.gen.gen_help_html').validate('./runtime/doc')" +q
27--      - validate() is 10x faster than gen(), so it is used in CI.
28--   2. Check for unreachable URLs:
29--      nvim -V1 -es +"lua require('src.gen.gen_help_html').validate('./runtime/doc', true)" +q
30--
31-- SELF-TEST MODE:
32--   1. nvim -V1 -es +"lua require('src.gen.gen_help_html')._test()" +q
33--
34-- NOTES:
35--   * This script is used by the website repo: https://github.com/neovim/neovim.github.io
36--   * :helptags checks for duplicate tags, whereas this script checks _links_ (to tags).
37--   * gen() and validate() are the primary (programmatic) entrypoints. validate() only exists
38--     because gen() is too slow (~1 min) to run in per-commit CI.
39--   * ts_node_to_html() is the core function used by gen() to traverse the document tree and produce HTML.
40--   * visit_validate() is the core function used by validate().
41--   * Files in `new_layout` will be generated with a "flow" layout instead of preformatted/fixed-width layout.
42--
43local pending_urls = 0
44local tagmap = nil ---@type table<string, string>
45local helpfiles = nil ---@type string[]
46local invalid_links = {} ---@type table<string, any>
47local invalid_urls = {} ---@type table<string, any>
48local invalid_spelling = {} ---@type table<string, table<string, string>>
49local spell_dict = {
50  Neovim = 'Nvim',
51  NeoVim = 'Nvim',
52  neovim = 'Nvim',
53  lua = 'Lua',
54  VimL = 'Vimscript',
55  vimL = 'Vimscript',
56  viml = 'Vimscript',
57  ['tree-sitter'] = 'treesitter',
58  ['Tree-sitter'] = 'Treesitter',
59}
60--- specify the list of keywords to ignore (i.e. allow), or true to disable spell check completely.
61--- @type table<string, true|string[]>
62local spell_ignore_files = {
63  ['credits.txt'] = { 'Neovim' },
64  ['news.txt'] = { 'tree-sitter' }, -- in news, may refer to the upstream "tree-sitter" library
65  ['news-0.10.txt'] = { 'tree-sitter' },
66}
67--- Punctuation that indicates a word is part of a path, module name, etc.
68--- Example: ".lua" is likely part of a filename, thus we don't want to enforce its spelling.
69local spell_punc = {
70  ['.'] = true,
71  ['/'] = true,
72}
73local language = nil
74
75local M = {}
76
77-- These files are generated with "flow" layout (non fixed-width, wrapped text paragraphs).
78-- All other files are "legacy" files which require fixed-width layout.
79local new_layout = {
80  ['api.txt'] = true,
81  ['channel.txt'] = true,
82  ['deprecated.txt'] = true,
83  ['dev.txt'] = true,
84  ['dev_arch.txt'] = true,
85  ['dev_style.txt'] = true,
86  ['dev_test.txt'] = true,
87  ['dev_theme.txt'] = true,
88  ['dev_tools.txt'] = true,
89  ['dev_vimpatch.txt'] = true,
90  ['diagnostic.txt'] = true,
91  ['faq.txt'] = true,
92  ['gui.txt'] = true,
93  ['help.txt'] = true,
94  ['intro.txt'] = true,
95  ['job_control.txt'] = true,
96  ['lsp.txt'] = true,
97  ['lua-bit.txt'] = true,
98  ['lua-guide.txt'] = true,
99  ['lua-plugin.txt'] = true,
100  ['lua.txt'] = true,
101  ['luaref.txt'] = true,
102  ['news-0.10.txt'] = true,
103  ['news-0.11.txt'] = true,
104  ['news-0.12.txt'] = true,
105  ['news-0.9.txt'] = true,
106  ['news.txt'] = true,
107  ['nvim.txt'] = true,
108  ['pack.txt'] = true,
109  ['provider.txt'] = true,
110  ['starting.txt'] = true,
111  ['terminal.txt'] = true,
112  ['tui.txt'] = true,
113  ['ui.txt'] = true,
114  ['vim_diff.txt'] = true,
115}
116
117-- Map of new-page:old-page, to redirect renamed pages.
118local redirects = {
119  ['api-ui-events.txt'] = 'ui.txt',
120  ['credits.txt'] = 'backers.txt',
121  ['dev.txt'] = 'develop.txt',
122  ['dev_tools.txt'] = 'debug.txt',
123  ['plugins.txt'] = 'editorconfig.txt',
124  ['terminal.txt'] = 'nvim_terminal_emulator.txt',
125  ['tui.txt'] = 'term.txt',
126}
127
128-- TODO: These known invalid |links| require an update to the relevant docs.
129local exclude_invalid = {
130  matchit = 'vim_diff.txt',
131}
132
133-- False-positive "invalid URLs".
134local exclude_invalid_urls = {
135  ['http://aspell.net/man-html/Affix-Compression.html'] = 'spell.txt',
136  ['http://aspell.net/man-html/Phonetic-Code.html'] = 'spell.txt',
137  ['http://lua-users.org/wiki/StringLibraryTutorial'] = 'lua.txt',
138  ['http://michael.toren.net/code/'] = 'pi_tar.txt',
139  ['http://oldblog.antirez.com/post/redis-and-scripting.html'] = 'faq.txt',
140  ['http://papp.plan9.de'] = 'syntax.txt',
141  ['http://vimcasts.org'] = 'intro.txt',
142  ['http://wiki.services.openoffice.org/wiki/Dictionaries'] = 'spell.txt',
143  ['http://www.adapower.com'] = 'ft_ada.txt',
144  ['http://www.jclark.com/'] = 'quickfix.txt',
145
146  -- Can't be accessed by GitHub runners:
147  ['https://cacm.acm.org/research/a-look-at-the-design-of-lua/'] = 'faq.txt',
148  ['https://linux.die.net/man/2/poll'] = 'luvref.txt',
149  ['https://www.kuwasha.net'] = 'uganda.txt',
150  ['https://www.kuwasha.net/'] = 'uganda.txt',
151}
152
153-- Deprecated, brain-damaged files that I don't care about.
154local ignore_errors = {
155  ['pi_netrw.txt'] = true,
156  ['credits.txt'] = true,
157}
158
159local function tofile(fname, text)
160  local f = io.open(fname, 'w')
161  if not f then
162    error(('failed to write: %s'):format(f))
163  else
164    f:write(text)
165    f:close()
166  end
167end
168
169---@type fun(s: string): string
170local function html_esc(s)
171  local html_entity =
172    { ['&'] = '&amp;', ['<'] = '&lt;', ['>'] = '&gt;', ['{'] = '&#123;', ['}'] = '&#125;' }
173  return (s and string.gsub(s, '[&<>{}]', html_entity) or nil)
174end
175
176--- Escapes a string to make it valid Typst markup.
177--- @param s string?
178--- @return string
179local function typ_esc(s)
180  return (s and string.gsub(s, '([%[%]@#\\/<*`_^$])', '\\%1') or '')
181end
182
183--- Escapes a string for use in a Typst string literal, e.g. `#label("…")`.
184--- @param s string?
185--- @return string
186local function typ_str_esc(s)
187  return (s and string.gsub(s, '([\\"])', '\\%1') or '')
188end
189
190local function url_encode(s)
191  -- Credit: tpope / vim-unimpaired
192  -- NOTE: these chars intentionally *not* escaped: ' ( )
193  return vim.fn.substitute(
194    vim.fn.iconv(s, 'latin1', 'utf-8'),
195    [=[[^A-Za-z0-9()'_.~-]]=],
196    [=[\="%".printf("%02X",char2nr(submatch(0)))]=],
197    'g'
198  )
199end
200
201local function to_titlecase(s)
202  local text = ''
203  for w in vim.gsplit(s, '[ \t]+') do
204    text = ('%s %s%s'):format(text, vim.fn.toupper(w:sub(1, 1)), w:sub(2))
205  end
206  return text
207end
208
209local function to_heading_tag(text)
210  -- Prepend "_" to avoid conflicts with actual :help tags.
211  return text and string.format('_%s', vim.fn.tolower((text:gsub('%s+', '-')))) or 'unknown'
212end
213
214local function basename_noext(f)
215  return vim.fs.basename(f:gsub('%.txt', ''))
216end
217
218local function is_blank(s)
219  return not not s:find([[^[\t ]*$]])
220end
221
222---@type fun(s: string, dir?:0|1|2): string
223local function trim(s, dir)
224  return vim.fn.trim(s, '\r\t\n ', dir or 0)
225end
226
227--- Removes common punctuation from URLs.
228---
229--- NOTE: this is currently a no-op, since known issues were fixed in the parser:
230--- https://github.com/neovim/tree-sitter-vimdoc/pull/157
231---
232--- @param url string
233--- @return string, string (fixed_url, removed_chars) where `removed_chars` is in the order found in the input.
234local function fix_url(url)
235  local removed_chars = ''
236  local fixed_url = url
237  -- Remove up to one of each char from end of the URL, in this order.
238  -- for _, c in ipairs({ '.', ')', ',' }) do
239  --   if fixed_url:sub(-1) == c then
240  --     removed_chars = c .. removed_chars
241  --     fixed_url = fixed_url:sub(1, -2)
242  --   end
243  -- end
244  return fixed_url, removed_chars
245end
246
247--- Checks if a given line is a "noise" line that doesn't look good in non-vimdoc formats.
248local function is_noise(line, noise_lines)
249  if
250    -- First line is always noise.
251    (noise_lines ~= nil and vim.tbl_count(noise_lines) == 0)
252    or line:find('Type .*gO.* to see the table of contents')
253    -- Title line of traditional :help pages.
254    -- Example: "NVIM REFERENCE MANUAL    by ..."
255    or line:find([[^%s*N?VIM[ \t]*REFERENCE[ \t]*MANUAL]])
256    -- First line of traditional :help pages.
257    -- Example: "*api.txt*    Nvim"
258    or line:find('%s*%*?[a-zA-Z]+%.txt%*?%s+N?[vV]im%s*$')
259    -- modeline
260    -- Example: "vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl:"
261    or line:find('^%s*vim?%:.*ft=help')
262    or line:find('^%s*vim?%:.*filetype=help')
263    or line:find('[*>]local%-additions[*<]')
264  then
265    -- table.insert(stats.noise_lines, getbuflinestr(root, opt.buf, 0))
266    table.insert(noise_lines or {}, line)
267    return true
268  end
269  return false
270end
271
272--- Creates a github issue URL at neovim/tree-sitter-vimdoc with prefilled content.
273--- @param fname string
274--- @param to_fname string
275--- @param sample_text string
276--- @return string
277local function get_bug_url_vimdoc(fname, to_fname, sample_text)
278  local this_url = string.format('https://neovim.io/doc/user/%s', vim.fs.basename(to_fname))
279  local bug_url = (
280    'https://github.com/neovim/tree-sitter-vimdoc/issues/new?labels=bug&title=parse+error%3A+'
281    .. vim.fs.basename(fname)
282    .. '+&body=Found+%60tree-sitter-vimdoc%60+parse+error+at%3A+'
283    .. this_url
284    .. '%0D%0DContext%3A%0D%0D%60%60%60%0D'
285    .. url_encode(sample_text)
286    .. '%0D%60%60%60'
287  )
288  return bug_url
289end
290
291--- Creates a github issue URL at neovim/neovim with prefilled content.
292--- @param fname string
293--- @param to_fname string
294--- @param sample_text string
295--- @param token_name? string
296--- @return string
297local function get_bug_url_nvim(fname, to_fname, sample_text, token_name)
298  local this_url = string.format('https://neovim.io/doc/user/%s', vim.fs.basename(to_fname))
299  local bug_url = (
300    'https://github.com/neovim/neovim/issues/new?labels=bug&title=user+docs+HTML%3A+'
301    .. vim.fs.basename(fname)
302    .. '+&body=%60gen_help_html.lua%60+problem+at%3A+'
303    .. this_url
304    .. '%0D'
305    .. (token_name and '+unhandled+token%3A+%60' .. token_name .. '%60' or '')
306    .. '%0DContext%3A%0D%0D%60%60%60%0D'
307    .. url_encode(sample_text)
308    .. '%0D%60%60%60'
309  )
310  return bug_url
311end
312
313--- Gets a "foo" name from a "foo.txt" helpfile name.
314local function get_helppage_html(f, with_extension)
315  if not f then
316    return nil
317  end
318  -- Special case: help.txt is the "main landing page" of :help files, not index.txt.
319  if f == 'index.txt' then
320    return with_extension and 'vimindex.html' or 'vimindex/'
321  elseif f == 'help.txt' then
322    -- Hugo needs an `_index.html` (note the underscore) file to recognize it as section
323    return with_extension and '_index.html' or ''
324  end
325
326  return (f:gsub('%.txt$', '')) .. (with_extension and '.html' or '/')
327end
328
329--- Counts leading spaces (tab=8) to decide the indent size of multiline text.
330---
331--- Blank lines (empty or whitespace-only) are ignored.
332local function get_indent(s)
333  local _, indent = vim.text.indent(0, s, { expandtab = 8 })
334  return indent
335end
336
337--- Removes the common indent level, after expanding tabs to 8 spaces.
338local function trim_indent(s)
339  return (vim.text.indent(0, s, { expandtab = 8 }))
340end
341
342--- Gets raw buffer text in the node's range (+/- an offset), as a newline-delimited string.
343---@param node TSNode
344---@param bufnr integer
345---@param offset integer
346local function getbuflinestr(node, bufnr, offset)
347  local line1, _, line2, _ = node:range()
348  line1 = line1 - offset
349  line2 = line2 + offset
350  local lines = vim.fn.getbufline(bufnr, line1 + 1, line2 + 1)
351  return table.concat(lines, '\n')
352end
353
354--- Gets the whitespace just before `node` from the raw buffer text.
355--- Needed for preformatted `old` lines.
356---@param node TSNode
357---@param bufnr integer
358---@return string
359local function getws(node, bufnr)
360  local line1, c1, line2, _ = node:range()
361  ---@type string
362  local raw = vim.fn.getbufline(bufnr, line1 + 1, line2 + 1)[1]
363  local text_before = raw:sub(1, c1)
364  local leading_ws = text_before:match('%s+$') or ''
365  return leading_ws
366end
367
368local function get_tagname(node, bufnr)
369  local text = vim.treesitter.get_node_text(node, bufnr)
370  local tag = (node:type() == 'optionlink' or node:parent():type() == 'optionlink')
371      and ("'%s'"):format(text)
372    or text
373  local helpfile = vim.fs.basename(tagmap[tag]) or nil -- "api.txt"
374  local helppage = get_helppage_html(helpfile) -- "api.html"
375  return helppage, tag
376end
377
378--- Returns true if the given invalid tagname is a false positive.
379local function ignore_invalid(s)
380  return not not (
381    exclude_invalid[s]
382    -- Strings like |~/====| appear in various places and the parser thinks they are links, but they
383    -- are just table borders.
384    or s:find('===')
385    or s:find('%-%-%-')
386  )
387end
388
389local function ignore_parse_error(fname, s)
390  if ignore_errors[vim.fs.basename(fname)] then
391    return true
392  end
393  -- Ignore parse errors for unclosed tag.
394  -- This is common in vimdocs and is treated as plaintext by :help.
395  return s:find("^[`'|*]")
396end
397
398---@param node TSNode
399local function has_ancestor(node, ancestor_name)
400  local p = node ---@type TSNode?
401  while p do
402    p = p:parent()
403    if not p or p:type() == 'help_file' then
404      break
405    elseif p:type() == ancestor_name then
406      return true
407    end
408  end
409  return false
410end
411
412--- Gets the first matching child node matching `name`.
413---@param node TSNode
414local function first(node, name)
415  for c, _ in node:iter_children() do
416    if c:named() and c:type() == name then
417      return c
418    end
419  end
420  return nil
421end
422
423--- Gets the last child of `node`, or nil.
424---@param node TSNode
425local function last(node)
426  local n = node:child_count()
427  return n > 0 and node:child(n - 1) or nil
428end
429
430--- Gets the kind and node text of the previous and next siblings of node `n`.
431--- @param n any node
432local function get_prev_next(n)
433  -- Previous sibling kind (string).
434  local prev = n:prev_sibling()
435      and (n:prev_sibling().named and n:prev_sibling():named())
436      and n:prev_sibling():type()
437    or nil
438  -- Next sibling kind (string).
439  local next_ = n:next_sibling()
440      and (n:next_sibling().named and n:next_sibling():named())
441      and n:next_sibling():type()
442    or nil
443  return prev, next_
444end
445
446local function validate_link(node, bufnr, fname)
447  local helppage, tagname = get_tagname(node:child(1), bufnr)
448  local ignored = false
449  if not tagmap[tagname] then
450    ignored = has_ancestor(node, 'column_heading') or node:has_error() or ignore_invalid(tagname)
451    if not ignored then
452      invalid_links[tagname] = vim.fs.basename(fname)
453    end
454  end
455  return helppage, tagname, ignored
456end
457
458local function validate_url(text, fname, check_unreachable)
459  fname = vim.fs.basename(fname)
460  local ignored = ignore_errors[fname] or exclude_invalid_urls[text]
461  if ignored then
462    return true
463  end
464  if check_unreachable then
465    vim.net.request(text, { retry = 2 }, function(err, _)
466      if err then
467        invalid_urls[text] = fname
468      end
469      pending_urls = pending_urls - 1
470    end)
471    pending_urls = pending_urls + 1
472  else
473    if text:find('http%:') then
474      invalid_urls[text] = fname
475    end
476  end
477  return false
478end
479
480--- Traverses the tree at `root` and checks that |tag| links point to valid helptags.
481---@param root TSNode
482---@param level integer
483---@param lang_tree TSTree
484---@param opt table
485---@param stats table
486local function visit_validate(root, level, lang_tree, opt, stats)
487  level = level or 0
488
489  local function node_text(node)
490    return vim.treesitter.get_node_text(node or root, opt.buf)
491  end
492
493  local text = trim(node_text())
494  local node_name = (root.named and root:named()) and root:type() or nil
495  -- Parent kind (string).
496  local parent = root:parent() and root:parent():type() or nil
497  local toplevel = level < 1
498  -- local prev, next_ = get_prev_next(root)
499  local prev_text = root:prev_sibling() and node_text(root:prev_sibling()) or nil
500  local next_text = root:next_sibling() and node_text(root:next_sibling()) or nil
501
502  if root:child_count() > 0 then
503    for node, _ in root:iter_children() do
504      if node:named() then
505        visit_validate(node, level + 1, lang_tree, opt, stats)
506      end
507    end
508  end
509
510  if node_name == 'ERROR' then
511    if ignore_parse_error(opt.fname, text) then
512      return
513    end
514    -- Store the raw text to give context to the error report.
515    local sample_text = not toplevel and getbuflinestr(root, opt.buf, 0) or '[top level!]'
516    -- Flatten the sample text to a single, truncated line.
517    sample_text = vim.trim(sample_text):gsub('[\t\n]', ' '):sub(1, 80)
518    table.insert(stats.parse_errors, sample_text)
519  elseif
520    (node_name == 'word' or node_name == 'uppercase_name')
521    and (not vim.tbl_contains({ 'codespan', 'taglink', 'tag' }, parent))
522  then
523    local text_nopunct = vim.fn.trim(text, '.,', 0) -- Ignore some punctuation.
524    local fname_basename = assert(vim.fs.basename(opt.fname --[[ @as string ]]))
525    if spell_dict[text_nopunct] then
526      local should_ignore = (
527        spell_ignore_files[fname_basename] == true
528        or vim.tbl_contains(
529          (spell_ignore_files[fname_basename] or {}) --[[ @as string[] ]],
530          text_nopunct
531        )
532        or (spell_punc[next_text] or spell_punc[prev_text])
533      )
534      if not should_ignore then
535        invalid_spelling[text_nopunct] = invalid_spelling[text_nopunct] or {}
536        invalid_spelling[text_nopunct][fname_basename] = node_text(root:parent())
537      end
538    end
539  elseif node_name == 'url' then
540    local fixed_url, _ = fix_url(trim(text))
541    validate_url(fixed_url, opt.fname, opt.request_urls)
542  elseif node_name == 'taglink' or node_name == 'optionlink' then
543    local _, _, _ = validate_link(root, opt.buf, opt.fname)
544  end
545end
546
547-- Fix tab alignment issues caused by concealed characters like |, `, * in tags
548-- and code blocks.
549---@param text string
550---@param next_node_text string
551local function fix_tab_after_conceal(text, next_node_text)
552  -- Vim tabs take into account the two concealed characters even though they
553  -- are invisible, so we need to add back in the two spaces if this is
554  -- followed by a tab to make the tab alignment to match Vim's behavior.
555  if string.sub(next_node_text, 1, 1) == '\t' then
556    text = text .. '  '
557  end
558  return text
559end
560
561---@class (exact) nvim.gen_help_html.heading
562---@field name string
563---@field subheadings nvim.gen_help_html.heading[]
564---@field tag string
565
566-- Generates HTML from node `root` recursively.
567---@param root TSNode
568---@param level integer
569---@param lang_tree TSTree
570---@param headings nvim.gen_help_html.heading[]
571---@param opt table
572---@param stats table
573local function ts_node_to_html(root, level, lang_tree, headings, opt, stats)
574  level = level or 0
575
576  local function node_text(node, ws_)
577    node = node or root
578    ws_ = (ws_ == nil or ws_ == true) and getws(node, opt.buf) or ''
579    return string.format('%s%s', ws_, vim.treesitter.get_node_text(node, opt.buf))
580  end
581
582  -- Gets leading whitespace of `node`.
583  local function ws(node)
584    node = node or root
585    local ws_ = getws(node, opt.buf)
586    -- XXX: first node of a (line) includes whitespace, even after
587    -- https://github.com/neovim/tree-sitter-vimdoc/pull/31 ?
588    if ws_ == '' then
589      ws_ = vim.treesitter.get_node_text(node, opt.buf):match('^%s+') or ''
590    end
591    return ws_
592  end
593
594  local node_name = (root.named and root:named()) and root:type() or nil
595  local prev, next_ = get_prev_next(root)
596  -- Parent kind (string).
597  local parent = root:parent() and root:parent():type() or nil
598
599  local text = ''
600  local trimmed ---@type string
601  if root:named_child_count() == 0 or node_name == 'ERROR' then
602    text = node_text()
603    trimmed = html_esc(trim(text))
604    text = html_esc(text)
605  else
606    -- Process children and join them with whitespace.
607    for node, _ in root:iter_children() do
608      if node:named() then
609        local r = ts_node_to_html(node, level + 1, lang_tree, headings, opt, stats)
610        text = string.format('%s%s', text, r)
611      end
612    end
613    trimmed = trim(text)
614  end
615
616  if node_name == 'help_file' then -- root node
617    return text
618  elseif node_name == 'url' then
619    local fixed_url, removed_chars = fix_url(trimmed)
620    return ('%s<a href="%s">%s</a>%s'):format(ws(), fixed_url, fixed_url, removed_chars)
621  elseif node_name == 'word' or node_name == 'uppercase_name' then
622    return text
623  elseif node_name == 'note' then
624    return ('<b>%s</b>'):format(text)
625  elseif node_name == 'h1' or node_name == 'h2' or node_name == 'h3' then
626    if is_noise(text, stats.noise_lines) then
627      return '' -- Discard common "noise" lines.
628    end
629    -- Remove tags from ToC text.
630    local heading_node = first(root, 'heading')
631    local hname = trim(node_text(heading_node):gsub('%*.*%*', ''))
632    if not heading_node or hname == '' then
633      return '' -- Spurious "===" or "---" in the help doc.
634    end
635
636    -- Generate an anchor id from the heading text.
637    local tagname = to_heading_tag(hname)
638    if node_name == 'h1' or #headings == 0 then
639      ---@type nvim.gen_help_html.heading
640      local heading = { name = hname, subheadings = {}, tag = tagname }
641      headings[#headings + 1] = heading
642    else
643      table.insert(
644        headings[#headings].subheadings,
645        { name = hname, subheadings = {}, tag = tagname }
646      )
647    end
648    local el = node_name == 'h1' and 'h2' or 'h3'
649    return ('<%s id="%s" class="help-heading">%s</%s>\n'):format(el, tagname, trimmed, el)
650  elseif node_name == 'heading' then
651    return trimmed
652  elseif node_name == 'column_heading' or node_name == 'column_name' then
653    if root:has_error() then
654      return text
655    end
656    return ('<div class="help-column_heading">%s</div>'):format(text)
657  elseif node_name == 'block' then
658    if is_blank(text) then
659      return ''
660    end
661
662    -- Conjoin list-item blocks: merge adjacent blocks that form a contiguous list.
663    local prev_block = root:prev_sibling()
664    local next_block = root:next_sibling()
665    local prev_last = prev_block and prev_block:type() == 'block' and last(prev_block)
666    local next_first = next_block and next_block:type() == 'block' and next_block:child(0)
667    local continues_list = root:child(0)
668      and root:child(0):type() == 'line_li'
669      and prev_last
670      and prev_last:type() == 'line_li'
671    local list_continues = last(root)
672      and last(root):type() == 'line_li'
673      and next_first
674      and next_first:type() == 'line_li'
675    if continues_list and list_continues then
676      return text
677    elseif continues_list then
678      -- Last continuation block: close the wrapper opened by the first block.
679      if opt.old then
680        return ('%s</div>\n'):format(trim(text, 2))
681      end
682      return string.format('%s\n</div>\n', text)
683    elseif list_continues then
684      -- First block of a list that continues: open wrapper but don't close.
685      if opt.old then
686        return ('<div class="old-help-para">%s'):format(trim(text, 2))
687      end
688      return string.format('<div class="help-para">\n%s', text)
689    end
690
691    if opt.old then
692      -- XXX: Treat "old" docs as preformatted: they use indentation for layout.
693      --      Trim trailing newlines to avoid too much whitespace between divs.
694      return ('<div class="old-help-para">%s</div>\n'):format(trim(text, 2))
695    end
696    return string.format('<div class="help-para">\n%s\n</div>\n', text)
697  elseif node_name == 'line' then
698    if
699      (parent ~= 'codeblock' and parent ~= 'code')
700      and (is_blank(text) or is_noise(text, stats.noise_lines))
701    then
702      return '' -- Discard common "noise" lines.
703    end
704    -- XXX: Avoid newlines (too much whitespace) after block elements in old (preformatted) layout.
705    local div = opt.old
706      and root:child(0)
707      and vim.list_contains({ 'column_heading', 'h1', 'h2', 'h3' }, root:child(0):type())
708    return string.format('%s%s', div and trim(text) or text, div and '' or '\n')
709  elseif parent == 'line_li' and node_name == 'prefix' then
710    return ''
711  elseif node_name == 'line_li' then
712    local prefix = first(root, 'prefix')
713    local numli = prefix and trim(node_text(prefix)):match('%d') -- Numbered listitem?
714    local sib = root:prev_sibling()
715    local prev_li = sib and sib:type() == 'line_li'
716    local cssclass = numli and 'help-li-num' or 'help-li'
717
718    -- Conjoin list items separated by blank lines (wrapped in separate blocks).
719    if not prev_li then
720      local parent_block = root:parent()
721      local prev_block = parent_block and parent_block:prev_sibling()
722      local prev_last = prev_block and prev_block:type() == 'block' and last(prev_block)
723      if prev_last and prev_last:type() == 'line_li' then
724        prev_li = true
725        sib = prev_last
726      end
727    end
728
729    if not prev_li then
730      opt.indent = 1
731      -- Track the leading whitespace for each indent level so that we can dedent
732      -- to the correct level later.
733      opt.indent_ws = { ws() }
734    else
735      opt.indent_ws = opt.indent_ws or { ws() }
736      local sib_ws = ws(sib)
737      local this_ws = ws()
738      if get_indent(node_text()) == 0 then
739        opt.indent = 1
740        opt.indent_ws = { this_ws }
741      elseif this_ws > sib_ws then
742        -- Previous sibling is logically the _parent_ if it is indented less.
743        opt.indent = opt.indent + 1
744        opt.indent_ws[opt.indent] = this_ws
745      elseif this_ws < sib_ws then
746        -- Dedent: pop indent levels whose tracked whitespace is deeper than the
747        -- current item, so we return to the correct ancestor level.
748        while opt.indent > 1 and (opt.indent_ws[opt.indent] or '') > this_ws do
749          opt.indent_ws[opt.indent] = nil
750          opt.indent = opt.indent - 1
751        end
752        opt.indent_ws[opt.indent] = this_ws
753      end
754    end
755    local margin = opt.indent == 1 and '' or ('margin-left: %drem;'):format((1.5 * opt.indent))
756
757    return string.format('<div class="%s" style="%s">%s</div>', cssclass, margin, text)
758  elseif node_name == 'taglink' or node_name == 'optionlink' then
759    local helppage, tagname, ignored = validate_link(root, opt.buf, opt.fname)
760    if ignored or not helppage then
761      return html_esc(node_text(root))
762    end
763    local s = ('%s<a href="/doc/user/%s#%s">%s</a>'):format(
764      ws(),
765      helppage,
766      url_encode(tagname),
767      html_esc(tagname)
768    )
769    if opt.old and node_name == 'taglink' then
770      s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
771    end
772    return s
773  elseif vim.list_contains({ 'codespan', 'keycode' }, node_name) then
774    if root:has_error() then
775      return text
776    end
777    local s = ('%s<code>%s</code>'):format(ws(), trimmed)
778    if opt.old and node_name == 'codespan' then
779      s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
780    end
781    return s
782  elseif node_name == 'argument' then
783    return ('%s<code>%s</code>'):format(ws(), trim(node_text(root)))
784  elseif node_name == 'codeblock' then
785    return text
786  elseif node_name == 'language' then
787    language = node_text(root)
788    return ''
789  elseif node_name == 'code' then -- Highlighted codeblock (child).
790    if is_blank(text) then
791      return ''
792    end
793    local code ---@type string
794    if language then
795      code = ('<pre><code class="language-%s">%s</code></pre>'):format(
796        language,
797        trim(trim_indent(text), 2)
798      )
799      language = nil
800    else
801      code = ('<pre>%s</pre>'):format(trim(trim_indent(text), 2))
802    end
803    return code
804  elseif node_name == 'tag' then -- anchor, h4 pseudo-heading
805    if root:has_error() then
806      return text
807    end
808    local in_heading = vim.list_contains({ 'h1', 'h2', 'h3' }, parent)
809    local h4 = not in_heading and not next_ and get_indent(node_text()) > 8 -- h4 pseudo-heading
810    local cssclass = h4 and 'help-tag-right' or 'help-tag'
811    local tagname = node_text(root:child(1), false)
812    if vim.tbl_count(stats.first_tags) < 2 then
813      -- Force the first 2 tags in the doc to be anchored at the main heading.
814      table.insert(stats.first_tags, tagname)
815      return ''
816    end
817    local el = 'span'
818    local encoded_tagname = url_encode(tagname)
819    local s = ('%s<%s id="%s" class="%s"><a href="#%s">%s</a></%s>'):format(
820      ws(),
821      el,
822      encoded_tagname,
823      cssclass,
824      encoded_tagname,
825      trimmed,
826      el
827    )
828    if opt.old then
829      s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
830    end
831
832    if in_heading and prev ~= 'tag' then
833      -- Start the <span> container for tags in a heading.
834      -- This makes "justify-content:space-between" right-align the tags.
835      --    <h2>foo bar<span>tag1 tag2</span></h2>
836      return string.format('<span class="help-heading-tags">%s', s)
837    elseif in_heading and next_ == nil then
838      -- End the <span> container for tags in a heading.
839      return string.format('%s</span>', s)
840    end
841    return s .. (h4 and '<br>' or '') -- HACK: <br> avoids h4 pseudo-heading mushing with text.
842  elseif node_name == 'delimiter' or node_name == 'modeline' then
843    return ''
844  elseif node_name == 'ERROR' then
845    if ignore_parse_error(opt.fname, trimmed) then
846      return text
847    end
848
849    -- Store the raw text to give context to the bug report.
850    local sample_text = level > 0 and getbuflinestr(root, opt.buf, 3) or '[top level!]'
851    table.insert(stats.parse_errors, sample_text)
852    return ('<a class="parse-error" target="_blank" title="Report bug... (parse error)" href="%s">%s</a>'):format(
853      get_bug_url_vimdoc(opt.fname, opt.to_fname, sample_text),
854      trimmed
855    )
856  else -- Unknown token.
857    local sample_text = level > 0 and getbuflinestr(root, opt.buf, 3) or '[top level!]'
858    return ('<a class="unknown-token" target="_blank" title="Report bug... (unhandled token "%s")" href="%s">%s</a>'):format(
859      node_name,
860      get_bug_url_nvim(opt.fname, opt.to_fname, sample_text, node_name),
861      trimmed
862    ),
863      ('unknown-token:"%s"'):format(node_name)
864  end
865end
866
867-- Generate Typst from node `root` recursively.
868---@param root TSNode
869---@param level integer
870---@param lang_tree TSTree
871---@param opt table
872---@param stats table
873local function ts_node_to_typ(root, level, lang_tree, opt, stats)
874  local function node_text(node, ws_)
875    node = node or root
876    ws_ = (ws_ == nil or ws_ == true) and getws(node, opt.buf) or ''
877    return string.format('%s%s', ws_, vim.treesitter.get_node_text(node, opt.buf))
878  end
879
880  -- Gets leading whitespace of `node`.
881  local function ws(node)
882    node = node or root
883    local ws_ = getws(node, opt.buf)
884    -- XXX: first node of a (line) includes whitespace, even after
885    -- https://github.com/neovim/tree-sitter-vimdoc/pull/31 ?
886    if ws_ == '' then
887      ws_ = vim.treesitter.get_node_text(node, opt.buf):match('^%s+') or ''
888    end
889    return ws_
890  end
891
892  local node_name = (root.named and root:named()) and root:type() or nil
893  local prev, next_ = get_prev_next(root)
894  -- Parent kind (string).
895  local parent = root:parent() and root:parent():type() or nil
896
897  local text = ''
898  local trimmed ---@type string
899  if root:named_child_count() == 0 or node_name == 'ERROR' then
900    text = node_text()
901    trimmed = typ_esc(trim(text))
902
903    -- A URL is a "word" directly under a "url"
904    -- We don't want any typ escaping there, as typ won't try to parse the
905    -- value as a command
906    if parent ~= 'url' then
907      text = typ_esc(text)
908    end
909  else
910    -- Process children and join them with whitespace.
911    for node, _ in root:iter_children() do
912      if node:named() then
913        local r = ts_node_to_typ(node, level + 1, lang_tree, opt, stats)
914        text = string.format('%s%s', text, r)
915      end
916    end
917    trimmed = trim(text)
918  end
919
920  if node_name == 'help_file' then -- root node
921    return text
922  elseif node_name == 'url' then
923    local fixed_url, removed_chars = fix_url(trimmed)
924    return ('%s#link("%s")%s'):format(ws(), typ_str_esc(fixed_url), removed_chars)
925  elseif node_name == 'word' or node_name == 'uppercase_name' then
926    return text
927  elseif node_name == 'note' then
928    return ('*%s*'):format(text)
929  elseif node_name == 'h1' or node_name == 'h2' or node_name == 'h3' then
930    if is_noise(text, stats.noise_lines) then
931      return '' -- Discard common "noise" lines.
932    end
933    -- Remove tags from ToC text.
934    local heading_node = first(root, 'heading')
935    local hname = trim(node_text(heading_node):gsub('%*.*%*', ''))
936    if not heading_node or hname == '' then
937      return '' -- Spurious "===" or "---" in the help doc.
938    end
939
940    local heading_level = tonumber(string.sub(node_name, -1))
941    if not heading_level then
942      print(('Cannot parse heading level from node name %s'):format(node_name))
943      return ''
944    end
945    return ('%s %s'):format(string.rep('=', heading_level), trimmed)
946  elseif node_name == 'heading' then
947    return trimmed
948  elseif node_name == 'column_heading' then
949    if root:has_error() then
950      return text
951    end
952    -- In help files column_heading is used for a lot more than column headings.
953    -- Sometimes it's some sort of title (see usr_toc.txt), and sometimes it's
954    -- some example text that really should be a code block (see usr_02.txt)
955    -- Using a raw block allows us to match all use cases fairly well
956    return ('```\n%s\n```\n'):format(trimmed)
957  elseif node_name == 'block' then
958    if is_blank(text) then
959      return ''
960    end
961    return ('%s\n'):format(text)
962  elseif node_name == 'line' then
963    if
964      (parent ~= 'codeblock' and parent ~= 'code')
965      and (is_blank(text) or is_noise(text, stats.noise_lines))
966    then
967      return '' -- Discard common "noise" lines.
968    end
969    -- XXX: Avoid newlines (too much whitespace) after block elements in old (preformatted) layout.
970    local old_after_block = opt.old
971      and root:child(0)
972      and vim.list_contains({ 'column_heading', 'h1', 'h2', 'h3' }, root:child(0):type())
973
974    if parent == 'codeblock' or parent == 'code' then
975      return text
976    elseif old_after_block then
977      return trim(text)
978    else
979      -- It would be nice to let the text flow when possible
980      -- But many lines do need an explicit line break (e.g. in the ToC)
981      return string.format('%s \\ \n', text)
982    end
983  elseif parent == 'line_li' and node_name == 'prefix' then
984    return ''
985  elseif node_name == 'line_li' then
986    -- Just writing the text - indentation needs improvements
987    return text
988  elseif node_name == 'taglink' or node_name == 'optionlink' then
989    -- Links are just text for now, because dealing with broken links is
990    -- difficult. Broken links are expected when generating a PDF of the user
991    -- manual, since all links to the reference don't have a destination.
992    -- Ideally, links with invalid destinations would be allowed and just be
993    -- normal text.
994    return (' #underline[%s]'):format(text)
995  elseif vim.list_contains({ 'codespan', 'keycode' }, node_name) then
996    if root:has_error() then
997      return text
998    end
999    return ('%s`%s`'):format(ws(), trimmed)
1000  elseif node_name == 'argument' then
1001    return ('%s`%s`'):format(ws(), trim(node_text(root)))
1002  elseif node_name == 'codeblock' then
1003    return text
1004  elseif node_name == 'language' then
1005    language = node_text(root)
1006    return ''
1007  elseif node_name == 'code' then -- Highlighted codeblock (child).
1008    if is_blank(text) then
1009      return ''
1010    end
1011    local code ---@type string
1012    if language then
1013      code = ('```%s\n%s\n```'):format(language, trim(trim_indent(text), 2))
1014      language = nil
1015    else
1016      code = ('\n```\n%s\n```\n'):format(trim(trim_indent(text), 2))
1017    end
1018    return code
1019  elseif node_name == 'tag' then -- anchor, h4 pseudo-heading
1020    if root:has_error() then
1021      return text
1022    end
1023    local in_heading = vim.list_contains({ 'h1', 'h2', 'h3' }, parent)
1024    local tagname = node_text(root:child(1), false)
1025    -- NOTE: the <%s> syntax doesn't work because it terminates the heading
1026    local s = ('%s%s #label("%s")'):format(ws(), text, typ_str_esc(tagname))
1027    if opt.old then
1028      s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
1029    end
1030
1031    if in_heading and prev ~= 'tag' then
1032      -- Add fractional spacing to right-align the tags in a heading
1033      -- TODO those right-aligned tags should also be styled differently
1034      -- (i.e. not like a header)
1035      return (' #h(1fr) %s'):format(s)
1036    end
1037    return s
1038  elseif node_name == 'delimiter' then
1039    return '\n'
1040  elseif node_name == 'modeline' then
1041    return ''
1042  else -- Unknown token.
1043    local sample_text = level > 0 and getbuflinestr(root, opt.buf, 3) or '[top level!]'
1044    if node_name == 'ERROR' then
1045      if ignore_parse_error(opt.fname, trimmed) then
1046        return text
1047      end
1048      table.insert(stats.parse_errors, sample_text)
1049    end
1050    print(('Unexpected token %s: %s'):format(node_name, sample_text))
1051    return ''
1052  end
1053end
1054
1055--- @param dir string e.g. '$VIMRUNTIME/doc'
1056--- @param include string[]|nil
1057--- @return string[]
1058local function get_helpfiles(dir, include)
1059  local rv = {}
1060  for f, type in vim.fs.dir(dir) do
1061    if
1062      vim.endswith(f, '.txt')
1063      and type == 'file'
1064      and (not include or vim.list_contains(include, f))
1065    then
1066      local fullpath = vim.fn.fnamemodify(('%s/%s'):format(dir, f), ':p')
1067      table.insert(rv, fullpath)
1068    end
1069  end
1070  return rv
1071end
1072
1073--- Populates the helptags map.
1074--- @param help_dir string
1075--- @return table<string, string>
1076local function _get_helptags(help_dir)
1077  ---@type table<string, string>
1078  local m = {}
1079  -- Load a random help file to convince taglist() to do its job.
1080  vim.cmd(string.format('split %s/api.txt', help_dir))
1081  vim.cmd('lcd %:p:h')
1082  local tags = vim.fn.taglist('.*') --[[ @as {name: string, filename: string}[] ]]
1083  for _, item in ipairs(tags) do
1084    if vim.endswith(item.filename, '.txt') then
1085      m[item.name] = item.filename
1086    end
1087  end
1088  vim.cmd('q!')
1089
1090  return m
1091end
1092
1093--- Populates the helptags map.
1094local function get_helptags(help_dir)
1095  local m = _get_helptags(help_dir)
1096
1097  --- XXX: Append tags from netrw, until we remove it...
1098  local netrwtags = _get_helptags(vim.fs.normalize('$VIMRUNTIME/pack/dist/opt/netrw/doc/'))
1099  m = vim.tbl_extend('keep', m, netrwtags)
1100
1101  return m
1102end
1103
1104--- Use the vimdoc parser defined in the build, not whatever happens to be installed on the system.
1105local function ensure_runtimepath()
1106  if not vim.o.runtimepath:find('build/lib/nvim/') then
1107    vim.cmd [[set runtimepath^=./build/lib/nvim/]]
1108  end
1109end
1110
1111--- Opens `fname` (or `text`, if given) in a buffer and gets a treesitter parser for the buffer contents.
1112---
1113--- @param fname string :help file to parse
1114--- @param text string? :help file contents
1115--- @return vim.treesitter.LanguageTree, integer (lang_tree, bufnr)
1116local function parse_buf(fname, text)
1117  local buf ---@type integer
1118
1119  if text then
1120    vim.cmd('split new') -- Text contents.
1121    vim.api.nvim_put(vim.split(text, '\n'), '', false, false)
1122    vim.cmd('setfiletype help')
1123    buf = vim.api.nvim_get_current_buf()
1124  elseif type(fname) == 'string' then
1125    vim.cmd('split ' .. vim.fn.fnameescape(fname)) -- Filename.
1126    buf = vim.api.nvim_get_current_buf()
1127  else
1128    -- Left for debugging
1129    ---@diagnostic disable-next-line: no-unknown
1130    buf = fname
1131    vim.cmd('sbuffer ' .. tostring(fname)) -- Buffer number.
1132  end
1133  local lang_tree = assert(vim.treesitter.get_parser(buf, nil))
1134  lang_tree:parse()
1135  return lang_tree, buf
1136end
1137
1138--- Validates one :help file `fname`:
1139---  - checks that |tag| links point to valid helptags.
1140---  - recursively counts parse errors ("ERROR" nodes)
1141---
1142--- @param fname string help file to validate
1143--- @param request_urls boolean? whether to make requests to the URLs
1144--- @return { invalid_links: number, parse_errors: string[] }
1145local function validate_one(fname, request_urls)
1146  local stats = {
1147    parse_errors = {},
1148  }
1149  local lang_tree, buf = parse_buf(fname, nil)
1150  for _, tree in ipairs(lang_tree:trees()) do
1151    visit_validate(tree:root(), 0, tree, {
1152      buf = buf,
1153      fname = fname,
1154      request_urls = request_urls,
1155    }, stats)
1156  end
1157  lang_tree:destroy()
1158  vim.cmd.close()
1159  return stats
1160end
1161
1162--- Generates HTML from one :help file `fname`.
1163---
1164--- @param fname string Source :help file.
1165--- @param text string|nil Source :help file contents, or nil to read `fname`.
1166--- @param to_fname string Destination .html file
1167--- @param old boolean Preformat paragraphs (for old :help files which are full of arbitrary whitespace)
1168---
1169--- @return string html
1170--- @return table stats
1171local function gen_one_html(fname, text, to_fname, old, commit)
1172  local stats = {
1173    noise_lines = {},
1174    parse_errors = {},
1175    first_tags = {}, -- Track the first few tags in doc.
1176  }
1177  local lang_tree, buf = parse_buf(fname, text)
1178  ---@type nvim.gen_help_html.heading[]
1179  local headings = {} -- Headings (for ToC). 2-dimensional: h1 contains h2/h3.
1180  local title = to_titlecase(basename_noext(fname))
1181
1182  local main = ''
1183  for _, tree in ipairs(lang_tree:trees()) do
1184    main = main
1185      .. (
1186        ts_node_to_html(
1187          tree:root(),
1188          0,
1189          tree,
1190          headings,
1191          { buf = buf, old = old, fname = fname, to_fname = to_fname, indent = 1 },
1192          stats
1193        )
1194      )
1195  end
1196
1197  local frontmatter = vim.json.encode({
1198    title = title,
1199    layout = 'single', -- Hugo-specific, to make _index.html the same as the other pages
1200    aliases = { -- Hugo-specific, make /api.html redirect to /api/
1201      vim.fs.joinpath('/doc/user', vim.fs.basename(to_fname)),
1202    },
1203    params = {
1204      firstTag1 = stats.first_tags[1] or '',
1205      firstTag2 = stats.first_tags[2] or '',
1206      basename = vim.fs.basename(fname),
1207      commit = commit,
1208      parseErrors = #stats.parse_errors,
1209      bugUrl = get_bug_url_nvim(fname, to_fname, 'TODO', nil),
1210      noiseLines = html_esc(table.concat(stats.noise_lines, '\n')),
1211      noiseLinesCount = #stats.noise_lines,
1212      headings = headings,
1213    },
1214  }, { indent = '  ', sort_keys = true })
1215
1216  local html = ('%s\n%s'):format(frontmatter, main)
1217
1218  vim.cmd('q!')
1219  lang_tree:destroy()
1220  return html, stats
1221end
1222
1223--- Generates Typst from one :help file `fname`.
1224---
1225--- @param fname string Source :help file.
1226--- @param text string|nil Source :help file contents, or nil to read `fname`.
1227--- @param to_fname string Destination .typ file
1228--- @param old boolean Preformat paragraphs (for old :help files which are full of arbitrary whitespace)
1229--- @param commit string|nil Unused.
1230---
1231--- @return string Typst output
1232--- @return table stats
1233local function gen_one_typ(fname, text, to_fname, old, commit)
1234  local stats = {
1235    noise_lines = {},
1236    parse_errors = {},
1237  }
1238  local lang_tree, buf = parse_buf(fname, text)
1239  local title = to_titlecase(basename_noext(fname))
1240
1241  local typ = ('= %s\n'):format(typ_esc(trim(title)))
1242  for _, tree in ipairs(lang_tree:trees()) do
1243    typ = typ
1244      .. (
1245        ts_node_to_typ(
1246          tree:root(),
1247          0,
1248          tree,
1249          { buf = buf, old = old, fname = fname, to_fname = to_fname, indent = 1 },
1250          stats
1251        )
1252      )
1253  end
1254
1255  -- Add page break at the bottom, so that merging .typ files before conversion
1256  -- results in page breaks in the right places
1257  local page_break = '#pagebreak()'
1258  typ = ('%s\n%s'):format(typ, page_break)
1259
1260  vim.cmd('q!')
1261  lang_tree:destroy()
1262  return typ, stats
1263end
1264
1265--- Generates a JSON map of tags to URL-encoded `filename#anchor` locations.
1266---
1267---@param fname string
1268local function gen_helptags_json(fname)
1269  assert(tagmap, '`tagmap` not generated yet')
1270  local t = {} ---@type table<string, string>
1271  for tag, f in pairs(tagmap) do
1272    -- "foo.txt"
1273    local helpfile = vim.fs.basename(f)
1274    -- "foo.html"
1275    local htmlpage = assert(get_helppage_html(helpfile))
1276    -- "foo.html#tag"
1277    t[tag] = ('%s#%s'):format(htmlpage, url_encode(tag))
1278  end
1279  tofile(fname, vim.json.encode(t, { indent = '  ', sort_keys = true }))
1280end
1281
1282local function gen_helptag_html(fname)
1283  local frontmatter = vim.json.encode({
1284    title = 'Helptag redirect',
1285    layout = 'helptag',
1286    aliases = { vim.fs.basename(fname) },
1287  }, { indent = '  ', sort_keys = true })
1288  tofile(fname, frontmatter)
1289end
1290
1291-- Testing
1292
1293local function ok(cond, expected, actual, message)
1294  assert(
1295    (not expected and not actual) or (expected and actual),
1296    'if "expected" is given, "actual" is also required'
1297  )
1298  if expected then
1299    assert(
1300      cond,
1301      ('%sexpected %s, got: %s'):format(
1302        message and (message .. '\n') or '',
1303        vim.inspect(expected),
1304        vim.inspect(actual)
1305      )
1306    )
1307  else
1308    assert(cond)
1309  end
1310
1311  return true
1312end
1313local function eq(expected, actual, message)
1314  return ok(vim.deep_equal(expected, actual), expected, actual, message)
1315end
1316
1317function M._test()
1318  tagmap = get_helptags('$VIMRUNTIME/doc')
1319  helpfiles = get_helpfiles(vim.fs.normalize('$VIMRUNTIME/doc'))
1320
1321  ok(vim.tbl_count(tagmap) > 3000, '>3000', vim.tbl_count(tagmap))
1322  ok(
1323    vim.endswith(tagmap['vim.diagnostic.set()'], 'diagnostic.txt'),
1324    tagmap['vim.diagnostic.set()'],
1325    'diagnostic.txt'
1326  )
1327  ok(vim.endswith(tagmap['%:s'], 'cmdline.txt'), tagmap['%:s'], 'cmdline.txt')
1328  ok(is_noise([[vim:tw=78:isk=!-~,^*,^\|,^\":ts=8:noet:ft=help:norl:]]))
1329  ok(is_noise([[          NVIM  REFERENCE  MANUAL     by  Thiago  de  Arruda      ]]))
1330  ok(not is_noise([[vim:tw=78]]))
1331
1332  eq(0, get_indent('a'))
1333  eq(1, get_indent(' a'))
1334  eq(2, get_indent('  a\n  b\n  c\n'))
1335  eq(5, get_indent('     a\n      \n        b\n      c\n      d\n      e\n'))
1336  eq(
1337    'a\n        \n   b\n c\n d\n e\n',
1338    trim_indent('     a\n             \n        b\n      c\n      d\n      e\n')
1339  )
1340
1341  local fixed_url, removed_chars = fix_url('https://example.com).')
1342  eq('https://example.com', fixed_url)
1343  eq(').', removed_chars)
1344  fixed_url, removed_chars = fix_url('https://example.com.)')
1345  eq('https://example.com.', fixed_url)
1346  eq(')', removed_chars)
1347  fixed_url, removed_chars = fix_url('https://example.com.')
1348  eq('https://example.com', fixed_url)
1349  eq('.', removed_chars)
1350  fixed_url, removed_chars = fix_url('https://example.com)')
1351  eq('https://example.com', fixed_url)
1352  eq(')', removed_chars)
1353  fixed_url, removed_chars = fix_url('https://example.com')
1354  eq('https://example.com', fixed_url)
1355  eq('', removed_chars)
1356
1357  print('all tests passed.\n')
1358end
1359
1360--- Generate redirect pages for renamed help files.
1361
1362--- @param commit string?
1363--- @param helpfile string Name of the help file being generated
1364--- @param to_dir string Target directory where the output files will be written.
1365--- @param to_fname string Name of the already-generated page in the new location
1366---
1367--- @return boolean Whether a redirect page has been generated
1368local function gen_redirect_pages(commit, helpfile, to_dir, to_fname)
1369  local helpfile_tag = (helpfile:gsub('%.txt$', '')):gsub('_', '-') -- "dev_tools.txt" => "dev-tools"
1370  local redirect_from = redirects[helpfile]
1371  if not redirect_from then
1372    return false
1373  end
1374
1375  local redirect_text = vim.text
1376    .indent(
1377      0,
1378      [[
1379      *%s*      Nvim
1380
1381      Document moved to: |%s|
1382
1383      ==============================================================================
1384      Document moved
1385
1386      Document moved to: |%s|
1387
1388      ==============================================================================
1389        vim:tw=78:ts=8:ft=help:norl:
1390      ]]
1391    )
1392    :format(redirect_from, helpfile_tag, helpfile_tag, helpfile_tag, helpfile_tag, helpfile_tag)
1393  local redirect_to_fname = get_helppage_html(redirect_from, true)
1394  local redirect_to = ('%s/%s'):format(to_dir, redirect_to_fname)
1395  local redirect_html, _ =
1396    gen_one_html(redirect_from, redirect_text, redirect_to, false, commit or '?')
1397  assert(
1398    redirect_html:find(vim.pesc(helpfile_tag)),
1399    ('not found in redirect html: %s'):format(helpfile_tag)
1400  )
1401  tofile(redirect_to, redirect_html)
1402
1403  print(('generated (redirect) : %-15s => %s'):format(redirect_from, vim.fs.basename(to_fname)))
1404  return true
1405end
1406
1407--- @class nvim.gen_help_html.gen_result
1408--- @field helpfiles string[] list of generated HTML files, from the source docs {include}
1409--- @field err_count integer number of parse errors in :help docs
1410--- @field invalid_links table<string, any>
1411
1412--- Generates HTML from :help docs located in `help_dir` and writes the result in `to_dir`.
1413---
1414--- Example:
1415---
1416---   gen('$VIMRUNTIME/doc', '/path/to/neovim.github.io/_site/doc/', {'api.txt', 'autocmd.txt', 'channel.txt'}, nil)
1417---
1418--- @param output_format string Currently only "html"
1419--- @param help_dir string Source directory containing the :help files. Must run `make helptags` first.
1420--- @param to_dir string Target directory where the output files will be written.
1421--- @param include string[]|nil Process only these filenames. Example: {'api.txt', 'autocmd.txt', 'channel.txt'}
1422--- @param commit string?
1423--- @param parser_path string? path to non-default vimdoc.so/dylib/dll
1424---
1425--- @return nvim.gen_help_html.gen_result result
1426function M.gen(output_format, help_dir, to_dir, include, commit, parser_path)
1427  vim.validate('output_format', output_format, 'string')
1428  vim.validate('help_dir', help_dir, function(d)
1429    return vim.fn.isdirectory(vim.fs.normalize(d)) == 1
1430  end, 'valid directory')
1431  vim.validate('to_dir', to_dir, 'string')
1432  vim.validate('include', include, 'table', true)
1433  vim.validate('commit', commit, 'string', true)
1434  vim.validate('parser_path', parser_path, function(f)
1435    return vim.fn.filereadable(vim.fs.normalize(f)) == 1
1436  end, true, 'valid vimdoc.{so,dll,dylib} filepath')
1437
1438  local err_count = 0
1439  local redirects_count = 0
1440  ensure_runtimepath()
1441
1442  parser_path = parser_path and vim.fs.normalize(parser_path) or nil
1443  if parser_path then
1444    -- XXX: Delete the installed .so files first, else this won't work :(
1445    --    /usr/local/lib/nvim/parser/vimdoc.so
1446    --    ./build/lib/nvim/parser/vimdoc.so
1447    vim.treesitter.language.add('vimdoc', { path = parser_path })
1448  end
1449
1450  tagmap = get_helptags(vim.fs.normalize(help_dir))
1451  helpfiles = get_helpfiles(help_dir, include)
1452  to_dir = vim.fs.normalize(to_dir)
1453
1454  print(('output dir: %s\n\n'):format(to_dir))
1455  vim.fn.mkdir(to_dir, 'p')
1456
1457  if output_format == 'html' then
1458    -- NOTE: Better for Hugo to be in static/, but works fine with contents/ as to_dir
1459    gen_helptags_json(('%s/helptags.json'):format(to_dir))
1460    gen_helptag_html(('%s/helptag.html'):format(to_dir))
1461  end
1462
1463  -- Map output formats to the function that outputs one file in that format
1464  local generators = {
1465    html = gen_one_html,
1466    typ = gen_one_typ,
1467  }
1468  local gen_one = generators[output_format]
1469
1470  for _, f in ipairs(helpfiles) do
1471    -- "foo.txt"
1472    local helpfile = vim.fs.basename(f)
1473
1474    local to_fname = ''
1475    if output_format == 'html' then
1476      -- "to/dir/foo.html"
1477      to_fname = ('%s/%s'):format(to_dir, get_helppage_html(helpfile, true))
1478    else
1479      to_fname = ('%s/%s.%s'):format(to_dir, helpfile:gsub('.txt', ''), output_format)
1480    end
1481
1482    local converted_help, stats = gen_one(f, nil, to_fname, not new_layout[helpfile], commit or '?')
1483    tofile(to_fname, converted_help)
1484    print(
1485      ('generated (%-2s errors): %-15s => %s'):format(
1486        #stats.parse_errors,
1487        helpfile,
1488        vim.fs.basename(to_fname)
1489      )
1490    )
1491
1492    if output_format == 'html' then
1493      local generated = gen_redirect_pages(commit, helpfile, to_dir, to_fname)
1494      if generated then
1495        redirects_count = redirects_count + 1
1496      end
1497    end
1498
1499    err_count = err_count + #stats.parse_errors
1500  end
1501
1502  print(('\ngenerated %d pages'):format(#helpfiles + redirects_count))
1503  print(('total errors: %d'):format(err_count))
1504  -- Why aren't the netrw tags found in neovim/docs/ CI?
1505  print(('invalid tags: %s'):format(vim.inspect(invalid_links)))
1506
1507  if output_format == 'html' then
1508    eq(redirects_count, include and redirects_count or vim.tbl_count(redirects)) -- sanity check
1509    print(('redirects: %d'):format(redirects_count))
1510  end
1511
1512  print('\n')
1513
1514  --- @type nvim.gen_help_html.gen_result
1515  return {
1516    helpfiles = helpfiles,
1517    err_count = err_count,
1518    invalid_links = invalid_links,
1519  }
1520end
1521
1522--- @class nvim.gen_help_html.validate_result
1523--- @field helpfiles integer number of generated helpfiles
1524--- @field err_count integer number of parse errors
1525--- @field parse_errors table<string, string[]>
1526--- @field invalid_links table<string, any> invalid tags in :help docs
1527--- @field invalid_urls table<string, any> invalid URLs in :help docs
1528--- @field invalid_spelling table<string, table<string, string>> invalid spelling in :help docs
1529
1530--- Validates all :help files found in `help_dir`:
1531---  - checks that |tag| links point to valid helptags.
1532---  - recursively counts parse errors ("ERROR" nodes)
1533---
1534--- This is 10x faster than gen(), for use in CI.
1535---
1536--- @return nvim.gen_help_html.validate_result result
1537function M.validate(help_dir, include, parser_path, request_urls)
1538  vim.validate('help_dir', help_dir, function(d)
1539    return vim.fn.isdirectory(vim.fs.normalize(d)) == 1
1540  end, 'valid directory')
1541  vim.validate('include', include, 'table', true)
1542  vim.validate('parser_path', parser_path, function(f)
1543    return vim.fn.filereadable(vim.fs.normalize(f)) == 1
1544  end, true, 'valid vimdoc.{so,dll,dylib} filepath')
1545  local err_count = 0 ---@type integer
1546  local files_to_errors = {} ---@type table<string, string[]>
1547  ensure_runtimepath()
1548
1549  parser_path = parser_path and vim.fs.normalize(parser_path) or nil
1550  if parser_path then
1551    -- XXX: Delete the installed .so files first, else this won't work :(
1552    --    /usr/local/lib/nvim/parser/vimdoc.so
1553    --    ./build/lib/nvim/parser/vimdoc.so
1554    vim.treesitter.language.add('vimdoc', { path = parser_path })
1555  end
1556
1557  tagmap = get_helptags(vim.fs.normalize(help_dir))
1558  helpfiles = get_helpfiles(help_dir, include)
1559
1560  for _, f in ipairs(helpfiles) do
1561    local helpfile = vim.fs.basename(f)
1562    local rv = validate_one(f, request_urls)
1563    print(('validated (%-4s errors): %s'):format(#rv.parse_errors, helpfile))
1564    if #rv.parse_errors > 0 then
1565      files_to_errors[helpfile] = rv.parse_errors
1566      vim.print(('%s'):format(vim.iter(rv.parse_errors):fold('', function(s, v)
1567        return s .. '\n    ' .. v
1568      end)))
1569    end
1570    err_count = err_count + #rv.parse_errors
1571  end
1572
1573  -- Requests are async, wait for them to finish.
1574  -- TODO(yochem): `:cancel()` tasks after #36146
1575  vim.wait(20000, function()
1576    return pending_urls <= 0
1577  end)
1578  ok(pending_urls <= 0, 'pending url checks', pending_urls)
1579
1580  ---@type nvim.gen_help_html.validate_result
1581  return {
1582    helpfiles = #helpfiles,
1583    err_count = err_count,
1584    parse_errors = files_to_errors,
1585    invalid_links = invalid_links,
1586    invalid_urls = invalid_urls,
1587    invalid_spelling = invalid_spelling,
1588  }
1589end
1590
1591--- Validates vimdoc files in $VIMRUNTIME, and prints error messages on failure.
1592---
1593--- If this fails, try these steps (in order):
1594--- 1. Fix/cleanup the :help docs.
1595--- 2. Fix the parser: https://github.com/neovim/tree-sitter-vimdoc
1596--- 3. File a parser bug, and adjust the tolerance of this test in the meantime.
1597---
1598--- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc'
1599--- @param request_urls? boolean make network requests to check if the URLs are reachable.
1600function M.run_validate(help_dir, request_urls)
1601  help_dir = vim.fs.normalize(help_dir or '$VIMRUNTIME/doc')
1602  print('doc path = ' .. vim.uv.fs_realpath(help_dir))
1603
1604  local rv = M.validate(help_dir, nil, nil, request_urls)
1605
1606  -- Check that we actually found helpfiles.
1607  ok(rv.helpfiles > 100, '>100 :help files', rv.helpfiles)
1608
1609  eq({}, rv.parse_errors, 'no parse errors')
1610  eq(0, rv.err_count, 'no parse errors')
1611  eq({}, rv.invalid_links, 'invalid tags in :help docs')
1612  eq({}, rv.invalid_urls, 'invalid URLs in :help docs')
1613  eq(
1614    {},
1615    rv.invalid_spelling,
1616    'invalid spelling in :help docs (see spell_dict in src/gen/gen_help_html.lua)'
1617  )
1618end
1619
1620--- Test-generates HTML from docs.
1621---
1622--- 1. Test that gen_help_html.lua actually works.
1623--- 2. Test that parse errors did not increase wildly. Because we explicitly test only a few
1624---    :help files, we can be precise about the tolerances here.
1625--- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc'
1626function M.test_gen(help_dir)
1627  local tmpdir = vim.fs.dirname(vim.fn.tempname())
1628  help_dir = vim.fs.normalize(help_dir or '$VIMRUNTIME/doc')
1629  print('doc path = ' .. vim.uv.fs_realpath(help_dir))
1630
1631  -- Because gen() is slow (~30s), this test is limited to a few files.
1632  local input = { 'api.txt', 'index.txt', 'nvim.txt' }
1633  local rv = M.gen('html', help_dir, tmpdir, input)
1634  eq(#input, #rv.helpfiles)
1635  eq(0, rv.err_count, 'parse errors in :help docs')
1636  eq({}, rv.invalid_links, 'invalid tags in :help docs')
1637end
1638
1639return M