gen_help_html.lua 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. --- Converts Nvim :help files to HTML. Validates |tag| links and document syntax (parser errors).
  2. --
  3. -- USAGE (For CI/local testing purposes): Simply `make lintdoc` or `scripts/lintdoc.lua`, which
  4. -- basically does the following:
  5. -- 1. :helptags ALL
  6. -- 2. nvim -V1 -es +"lua require('scripts.gen_help_html').run_validate()" +q
  7. -- 3. nvim -V1 -es +"lua require('scripts.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('scripts.gen_help_html').gen('./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 (VALIDATE):
  17. -- 1. nvim -V1 -es +"lua require('scripts.gen_help_html').validate('./runtime/doc')" +q
  18. -- - validate() is 10x faster than gen(), so it is used in CI.
  19. --
  20. -- SELF-TEST MODE:
  21. -- 1. nvim -V1 -es +"lua require('scripts.gen_help_html')._test()" +q
  22. --
  23. -- NOTES:
  24. -- * This script is used by the automation repo: https://github.com/neovim/doc
  25. -- * :helptags checks for duplicate tags, whereas this script checks _links_ (to tags).
  26. -- * gen() and validate() are the primary (programmatic) entrypoints. validate() only exists
  27. -- because gen() is too slow (~1 min) to run in per-commit CI.
  28. -- * visit_node() is the core function used by gen() to traverse the document tree and produce HTML.
  29. -- * visit_validate() is the core function used by validate().
  30. -- * Files in `new_layout` will be generated with a "flow" layout instead of preformatted/fixed-width layout.
  31. local tagmap = nil ---@type table<string, string>
  32. local helpfiles = nil ---@type string[]
  33. local invalid_links = {} ---@type table<string, any>
  34. local invalid_urls = {} ---@type table<string, any>
  35. local invalid_spelling = {} ---@type table<string, table<string, string>>
  36. local spell_dict = {
  37. Neovim = 'Nvim',
  38. NeoVim = 'Nvim',
  39. neovim = 'Nvim',
  40. lua = 'Lua',
  41. VimL = 'Vimscript',
  42. vimL = 'Vimscript',
  43. viml = 'Vimscript',
  44. ['tree-sitter'] = 'treesitter',
  45. ['Tree-sitter'] = 'Treesitter',
  46. }
  47. --- specify the list of keywords to ignore (i.e. allow), or true to disable spell check completely.
  48. --- @type table<string, true|string[]>
  49. local spell_ignore_files = {
  50. ['backers.txt'] = true,
  51. ['news.txt'] = { 'tree-sitter' }, -- in news, may refer to the upstream "tree-sitter" library
  52. ['news-0.10.txt'] = { 'tree-sitter' },
  53. }
  54. local language = nil
  55. local M = {}
  56. -- These files are generated with "flow" layout (non fixed-width, wrapped text paragraphs).
  57. -- All other files are "legacy" files which require fixed-width layout.
  58. local new_layout = {
  59. ['api.txt'] = true,
  60. ['lsp.txt'] = true,
  61. ['channel.txt'] = true,
  62. ['deprecated.txt'] = true,
  63. ['develop.txt'] = true,
  64. ['dev_style.txt'] = true,
  65. ['dev_theme.txt'] = true,
  66. ['dev_tools.txt'] = true,
  67. ['dev_vimpatch.txt'] = true,
  68. ['editorconfig.txt'] = true,
  69. ['faq.txt'] = true,
  70. ['lua.txt'] = true,
  71. ['luaref.txt'] = true,
  72. ['news.txt'] = true,
  73. ['news-0.9.txt'] = true,
  74. ['news-0.10.txt'] = true,
  75. ['nvim.txt'] = true,
  76. ['provider.txt'] = true,
  77. ['tui.txt'] = true,
  78. ['ui.txt'] = true,
  79. ['vim_diff.txt'] = true,
  80. }
  81. -- Map of new:old pages, to redirect renamed pages.
  82. local redirects = {
  83. ['tui'] = 'term',
  84. ['terminal'] = 'nvim_terminal_emulator',
  85. }
  86. -- TODO: These known invalid |links| require an update to the relevant docs.
  87. local exclude_invalid = {
  88. ["'string'"] = 'eval.txt',
  89. Query = 'treesitter.txt',
  90. matchit = 'vim_diff.txt',
  91. ['set!'] = 'treesitter.txt',
  92. }
  93. -- False-positive "invalid URLs".
  94. local exclude_invalid_urls = {
  95. ['http://'] = 'usr_23.txt',
  96. ['http://.'] = 'usr_23.txt',
  97. ['http://aspell.net/man-html/Affix-Compression.html'] = 'spell.txt',
  98. ['http://aspell.net/man-html/Phonetic-Code.html'] = 'spell.txt',
  99. ['http://canna.sourceforge.jp/'] = 'mbyte.txt',
  100. ['http://gnuada.sourceforge.net'] = 'ft_ada.txt',
  101. ['http://lua-users.org/wiki/StringLibraryTutorial'] = 'lua.txt',
  102. ['http://michael.toren.net/code/'] = 'pi_tar.txt',
  103. ['http://papp.plan9.de'] = 'syntax.txt',
  104. ['http://wiki.services.openoffice.org/wiki/Dictionaries'] = 'spell.txt',
  105. ['http://www.adapower.com'] = 'ft_ada.txt',
  106. ['http://www.jclark.com/'] = 'quickfix.txt',
  107. ['http://oldblog.antirez.com/post/redis-and-scripting.html'] = 'faq.txt',
  108. }
  109. -- Deprecated, brain-damaged files that I don't care about.
  110. local ignore_errors = {
  111. ['pi_netrw.txt'] = true,
  112. ['backers.txt'] = true,
  113. }
  114. local function tofile(fname, text)
  115. local f = io.open(fname, 'w')
  116. if not f then
  117. error(('failed to write: %s'):format(f))
  118. else
  119. f:write(text)
  120. f:close()
  121. end
  122. end
  123. ---@type fun(s: string): string
  124. local function html_esc(s)
  125. return (s:gsub('&', '&amp;'):gsub('<', '&lt;'):gsub('>', '&gt;'))
  126. end
  127. local function url_encode(s)
  128. -- Credit: tpope / vim-unimpaired
  129. -- NOTE: these chars intentionally *not* escaped: ' ( )
  130. return vim.fn.substitute(
  131. vim.fn.iconv(s, 'latin1', 'utf-8'),
  132. [=[[^A-Za-z0-9()'_.~-]]=],
  133. [=[\="%".printf("%02X",char2nr(submatch(0)))]=],
  134. 'g'
  135. )
  136. end
  137. local function expandtabs(s)
  138. return s:gsub('\t', (' '):rep(8)) --[[ @as string ]]
  139. end
  140. local function to_titlecase(s)
  141. local text = ''
  142. for w in vim.gsplit(s, '[ \t]+') do
  143. text = ('%s %s%s'):format(text, vim.fn.toupper(w:sub(1, 1)), w:sub(2))
  144. end
  145. return text
  146. end
  147. local function to_heading_tag(text)
  148. -- Prepend "_" to avoid conflicts with actual :help tags.
  149. return text and string.format('_%s', vim.fn.tolower((text:gsub('%s+', '-')))) or 'unknown'
  150. end
  151. local function basename_noext(f)
  152. return vim.fs.basename(f:gsub('%.txt', ''))
  153. end
  154. local function is_blank(s)
  155. return not not s:find([[^[\t ]*$]])
  156. end
  157. ---@type fun(s: string, dir?:0|1|2): string
  158. local function trim(s, dir)
  159. return vim.fn.trim(s, '\r\t\n ', dir or 0)
  160. end
  161. --- Removes common punctuation from URLs.
  162. ---
  163. --- TODO: fix this in the parser instead... https://github.com/neovim/tree-sitter-vimdoc
  164. ---
  165. --- @param url string
  166. --- @return string, string (fixed_url, removed_chars) where `removed_chars` is in the order found in the input.
  167. local function fix_url(url)
  168. local removed_chars = ''
  169. local fixed_url = url
  170. -- Remove up to one of each char from end of the URL, in this order.
  171. for _, c in ipairs({ '.', ')' }) do
  172. if fixed_url:sub(-1) == c then
  173. removed_chars = c .. removed_chars
  174. fixed_url = fixed_url:sub(1, -2)
  175. end
  176. end
  177. return fixed_url, removed_chars
  178. end
  179. --- Checks if a given line is a "noise" line that doesn't look good in HTML form.
  180. local function is_noise(line, noise_lines)
  181. if
  182. -- First line is always noise.
  183. (noise_lines ~= nil and vim.tbl_count(noise_lines) == 0)
  184. or line:find('Type .*gO.* to see the table of contents')
  185. -- Title line of traditional :help pages.
  186. -- Example: "NVIM REFERENCE MANUAL by ..."
  187. or line:find([[^%s*N?VIM[ \t]*REFERENCE[ \t]*MANUAL]])
  188. -- First line of traditional :help pages.
  189. -- Example: "*api.txt* Nvim"
  190. or line:find('%s*%*?[a-zA-Z]+%.txt%*?%s+N?[vV]im%s*$')
  191. -- modeline
  192. -- Example: "vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl:"
  193. or line:find('^%s*vim?%:.*ft=help')
  194. or line:find('^%s*vim?%:.*filetype=help')
  195. or line:find('[*>]local%-additions[*<]')
  196. then
  197. -- table.insert(stats.noise_lines, getbuflinestr(root, opt.buf, 0))
  198. table.insert(noise_lines or {}, line)
  199. return true
  200. end
  201. return false
  202. end
  203. --- Creates a github issue URL at neovim/tree-sitter-vimdoc with prefilled content.
  204. --- @return string
  205. local function get_bug_url_vimdoc(fname, to_fname, sample_text)
  206. local this_url = string.format('https://neovim.io/doc/user/%s', vim.fs.basename(to_fname))
  207. local bug_url = (
  208. 'https://github.com/neovim/tree-sitter-vimdoc/issues/new?labels=bug&title=parse+error%3A+'
  209. .. vim.fs.basename(fname)
  210. .. '+&body=Found+%60tree-sitter-vimdoc%60+parse+error+at%3A+'
  211. .. this_url
  212. .. '%0D%0DContext%3A%0D%0D%60%60%60%0D'
  213. .. url_encode(sample_text)
  214. .. '%0D%60%60%60'
  215. )
  216. return bug_url
  217. end
  218. --- Creates a github issue URL at neovim/neovim with prefilled content.
  219. --- @return string
  220. local function get_bug_url_nvim(fname, to_fname, sample_text, token_name)
  221. local this_url = string.format('https://neovim.io/doc/user/%s', vim.fs.basename(to_fname))
  222. local bug_url = (
  223. 'https://github.com/neovim/neovim/issues/new?labels=bug&title=user+docs+HTML%3A+'
  224. .. vim.fs.basename(fname)
  225. .. '+&body=%60gen_help_html.lua%60+problem+at%3A+'
  226. .. this_url
  227. .. '%0D'
  228. .. (token_name and '+unhandled+token%3A+%60' .. token_name .. '%60' or '')
  229. .. '%0DContext%3A%0D%0D%60%60%60%0D'
  230. .. url_encode(sample_text)
  231. .. '%0D%60%60%60'
  232. )
  233. return bug_url
  234. end
  235. --- Gets a "foo.html" name from a "foo.txt" helpfile name.
  236. local function get_helppage(f)
  237. if not f then
  238. return nil
  239. end
  240. -- Special case: help.txt is the "main landing page" of :help files, not index.txt.
  241. if f == 'index.txt' then
  242. return 'vimindex.html'
  243. elseif f == 'help.txt' then
  244. return 'index.html'
  245. end
  246. return (f:gsub('%.txt$', '')) .. '.html'
  247. end
  248. --- Counts leading spaces (tab=8) to decide the indent size of multiline text.
  249. ---
  250. --- Blank lines (empty or whitespace-only) are ignored.
  251. local function get_indent(s)
  252. local min_indent = nil
  253. for line in vim.gsplit(s, '\n') do
  254. if line and not is_blank(line) then
  255. local ws = expandtabs(line:match('^%s+') or '')
  256. min_indent = (not min_indent or ws:len() < min_indent) and ws:len() or min_indent
  257. end
  258. end
  259. return min_indent or 0
  260. end
  261. --- Removes the common indent level, after expanding tabs to 8 spaces.
  262. local function trim_indent(s)
  263. local indent_size = get_indent(s)
  264. local trimmed = ''
  265. for line in vim.gsplit(s, '\n') do
  266. line = expandtabs(line)
  267. trimmed = ('%s%s\n'):format(trimmed, line:sub(indent_size + 1))
  268. end
  269. return trimmed:sub(1, -2)
  270. end
  271. --- Gets raw buffer text in the node's range (+/- an offset), as a newline-delimited string.
  272. ---@param node TSNode
  273. ---@param bufnr integer
  274. ---@param offset integer
  275. local function getbuflinestr(node, bufnr, offset)
  276. local line1, _, line2, _ = node:range()
  277. line1 = line1 - offset
  278. line2 = line2 + offset
  279. local lines = vim.fn.getbufline(bufnr, line1 + 1, line2 + 1)
  280. return table.concat(lines, '\n')
  281. end
  282. --- Gets the whitespace just before `node` from the raw buffer text.
  283. --- Needed for preformatted `old` lines.
  284. ---@param node TSNode
  285. ---@param bufnr integer
  286. ---@return string
  287. local function getws(node, bufnr)
  288. local line1, c1, line2, _ = node:range()
  289. ---@type string
  290. local raw = vim.fn.getbufline(bufnr, line1 + 1, line2 + 1)[1]
  291. local text_before = raw:sub(1, c1)
  292. local leading_ws = text_before:match('%s+$') or ''
  293. return leading_ws
  294. end
  295. local function get_tagname(node, bufnr)
  296. local text = vim.treesitter.get_node_text(node, bufnr)
  297. local tag = (node:type() == 'optionlink' or node:parent():type() == 'optionlink')
  298. and ("'%s'"):format(text)
  299. or text
  300. local helpfile = vim.fs.basename(tagmap[tag]) or nil -- "api.txt"
  301. local helppage = get_helppage(helpfile) -- "api.html"
  302. return helppage, tag
  303. end
  304. --- Returns true if the given invalid tagname is a false positive.
  305. local function ignore_invalid(s)
  306. return not not (
  307. exclude_invalid[s]
  308. -- Strings like |~/====| appear in various places and the parser thinks they are links, but they
  309. -- are just table borders.
  310. or s:find('===')
  311. or s:find('%-%-%-')
  312. )
  313. end
  314. local function ignore_parse_error(fname, s)
  315. if ignore_errors[vim.fs.basename(fname)] then
  316. return true
  317. end
  318. -- Ignore parse errors for unclosed tag.
  319. -- This is common in vimdocs and is treated as plaintext by :help.
  320. return s:find("^[`'|*]")
  321. end
  322. ---@param node TSNode
  323. local function has_ancestor(node, ancestor_name)
  324. local p = node ---@type TSNode?
  325. while p do
  326. p = p:parent()
  327. if not p or p:type() == 'help_file' then
  328. break
  329. elseif p:type() == ancestor_name then
  330. return true
  331. end
  332. end
  333. return false
  334. end
  335. --- Gets the first matching child node matching `name`.
  336. ---@param node TSNode
  337. local function first(node, name)
  338. for c, _ in node:iter_children() do
  339. if c:named() and c:type() == name then
  340. return c
  341. end
  342. end
  343. return nil
  344. end
  345. local function validate_link(node, bufnr, fname)
  346. local helppage, tagname = get_tagname(node:child(1), bufnr)
  347. local ignored = false
  348. if not tagmap[tagname] then
  349. ignored = has_ancestor(node, 'column_heading') or node:has_error() or ignore_invalid(tagname)
  350. if not ignored then
  351. invalid_links[tagname] = vim.fs.basename(fname)
  352. end
  353. end
  354. return helppage, tagname, ignored
  355. end
  356. --- TODO: port the logic from scripts/check_urls.vim
  357. local function validate_url(text, fname)
  358. local ignored = false
  359. if ignore_errors[vim.fs.basename(fname)] then
  360. ignored = true
  361. elseif text:find('http%:') and not exclude_invalid_urls[text] then
  362. invalid_urls[text] = vim.fs.basename(fname)
  363. end
  364. return ignored
  365. end
  366. --- Traverses the tree at `root` and checks that |tag| links point to valid helptags.
  367. ---@param root TSNode
  368. ---@param level integer
  369. ---@param lang_tree TSTree
  370. ---@param opt table
  371. ---@param stats table
  372. local function visit_validate(root, level, lang_tree, opt, stats)
  373. level = level or 0
  374. local node_name = (root.named and root:named()) and root:type() or nil
  375. -- Parent kind (string).
  376. local parent = root:parent() and root:parent():type() or nil
  377. local toplevel = level < 1
  378. local function node_text(node)
  379. return vim.treesitter.get_node_text(node or root, opt.buf)
  380. end
  381. local text = trim(node_text())
  382. if root:child_count() > 0 then
  383. for node, _ in root:iter_children() do
  384. if node:named() then
  385. visit_validate(node, level + 1, lang_tree, opt, stats)
  386. end
  387. end
  388. end
  389. if node_name == 'ERROR' then
  390. if ignore_parse_error(opt.fname, text) then
  391. return
  392. end
  393. -- Store the raw text to give context to the error report.
  394. local sample_text = not toplevel and getbuflinestr(root, opt.buf, 0) or '[top level!]'
  395. -- Flatten the sample text to a single, truncated line.
  396. sample_text = vim.trim(sample_text):gsub('[\t\n]', ' '):sub(1, 80)
  397. table.insert(stats.parse_errors, sample_text)
  398. elseif
  399. (node_name == 'word' or node_name == 'uppercase_name')
  400. and (not vim.tbl_contains({ 'codespan', 'taglink', 'tag' }, parent))
  401. then
  402. local text_nopunct = vim.fn.trim(text, '.,', 0) -- Ignore some punctuation.
  403. local fname_basename = assert(vim.fs.basename(opt.fname))
  404. if spell_dict[text_nopunct] then
  405. local should_ignore = (
  406. spell_ignore_files[fname_basename] == true
  407. or vim.tbl_contains(
  408. (spell_ignore_files[fname_basename] or {}) --[[ @as string[] ]],
  409. text_nopunct
  410. )
  411. )
  412. if not should_ignore then
  413. invalid_spelling[text_nopunct] = invalid_spelling[text_nopunct] or {}
  414. invalid_spelling[text_nopunct][fname_basename] = node_text(root:parent())
  415. end
  416. end
  417. elseif node_name == 'url' then
  418. local fixed_url, _ = fix_url(trim(text))
  419. validate_url(fixed_url, opt.fname)
  420. elseif node_name == 'taglink' or node_name == 'optionlink' then
  421. local _, _, _ = validate_link(root, opt.buf, opt.fname)
  422. end
  423. end
  424. -- Fix tab alignment issues caused by concealed characters like |, `, * in tags
  425. -- and code blocks.
  426. ---@param text string
  427. ---@param next_node_text string
  428. local function fix_tab_after_conceal(text, next_node_text)
  429. -- Vim tabs take into account the two concealed characters even though they
  430. -- are invisible, so we need to add back in the two spaces if this is
  431. -- followed by a tab to make the tab alignment to match Vim's behavior.
  432. if string.sub(next_node_text, 1, 1) == '\t' then
  433. text = text .. ' '
  434. end
  435. return text
  436. end
  437. ---@class (exact) nvim.gen_help_html.heading
  438. ---@field name string
  439. ---@field subheadings nvim.gen_help_html.heading[]
  440. ---@field tag string
  441. -- Generates HTML from node `root` recursively.
  442. ---@param root TSNode
  443. ---@param level integer
  444. ---@param lang_tree TSTree
  445. ---@param headings nvim.gen_help_html.heading[]
  446. ---@param opt table
  447. ---@param stats table
  448. local function visit_node(root, level, lang_tree, headings, opt, stats)
  449. level = level or 0
  450. local node_name = (root.named and root:named()) and root:type() or nil
  451. -- Previous sibling kind (string).
  452. local prev = root:prev_sibling()
  453. and (root:prev_sibling().named and root:prev_sibling():named())
  454. and root:prev_sibling():type()
  455. or nil
  456. -- Next sibling kind (string).
  457. local next_ = root:next_sibling()
  458. and (root:next_sibling().named and root:next_sibling():named())
  459. and root:next_sibling():type()
  460. or nil
  461. -- Parent kind (string).
  462. local parent = root:parent() and root:parent():type() or nil
  463. -- Gets leading whitespace of `node`.
  464. local function ws(node)
  465. node = node or root
  466. local ws_ = getws(node, opt.buf)
  467. -- XXX: first node of a (line) includes whitespace, even after
  468. -- https://github.com/neovim/tree-sitter-vimdoc/pull/31 ?
  469. if ws_ == '' then
  470. ws_ = vim.treesitter.get_node_text(node, opt.buf):match('^%s+') or ''
  471. end
  472. return ws_
  473. end
  474. local function node_text(node, ws_)
  475. node = node or root
  476. ws_ = (ws_ == nil or ws_ == true) and getws(node, opt.buf) or ''
  477. return string.format('%s%s', ws_, vim.treesitter.get_node_text(node, opt.buf))
  478. end
  479. local text = ''
  480. local trimmed ---@type string
  481. if root:named_child_count() == 0 or node_name == 'ERROR' then
  482. text = node_text()
  483. trimmed = html_esc(trim(text))
  484. text = html_esc(text)
  485. else
  486. -- Process children and join them with whitespace.
  487. for node, _ in root:iter_children() do
  488. if node:named() then
  489. local r = visit_node(node, level + 1, lang_tree, headings, opt, stats)
  490. text = string.format('%s%s', text, r)
  491. end
  492. end
  493. trimmed = trim(text)
  494. end
  495. if node_name == 'help_file' then -- root node
  496. return text
  497. elseif node_name == 'url' then
  498. local fixed_url, removed_chars = fix_url(trimmed)
  499. return ('%s<a href="%s">%s</a>%s'):format(ws(), fixed_url, fixed_url, removed_chars)
  500. elseif node_name == 'word' or node_name == 'uppercase_name' then
  501. return text
  502. elseif node_name == 'note' then
  503. return ('<b>%s</b>'):format(text)
  504. elseif node_name == 'h1' or node_name == 'h2' or node_name == 'h3' then
  505. if is_noise(text, stats.noise_lines) then
  506. return '' -- Discard common "noise" lines.
  507. end
  508. -- Remove tags from ToC text.
  509. local heading_node = first(root, 'heading')
  510. local hname = trim(node_text(heading_node):gsub('%*.*%*', ''))
  511. if not heading_node or hname == '' then
  512. return '' -- Spurious "===" or "---" in the help doc.
  513. end
  514. -- Generate an anchor id from the heading text.
  515. local tagname = to_heading_tag(hname)
  516. if node_name == 'h1' or #headings == 0 then
  517. ---@type nvim.gen_help_html.heading
  518. local heading = { name = hname, subheadings = {}, tag = tagname }
  519. headings[#headings + 1] = heading
  520. else
  521. table.insert(
  522. headings[#headings].subheadings,
  523. { name = hname, subheadings = {}, tag = tagname }
  524. )
  525. end
  526. local el = node_name == 'h1' and 'h2' or 'h3'
  527. return ('<%s id="%s" class="help-heading">%s</%s>\n'):format(el, tagname, trimmed, el)
  528. elseif node_name == 'heading' then
  529. return trimmed
  530. elseif node_name == 'column_heading' or node_name == 'column_name' then
  531. if root:has_error() then
  532. return text
  533. end
  534. return ('<div class="help-column_heading">%s</div>'):format(text)
  535. elseif node_name == 'block' then
  536. if is_blank(text) then
  537. return ''
  538. end
  539. if opt.old then
  540. -- XXX: Treat "old" docs as preformatted: they use indentation for layout.
  541. -- Trim trailing newlines to avoid too much whitespace between divs.
  542. return ('<div class="old-help-para">%s</div>\n'):format(trim(text, 2))
  543. end
  544. return string.format('<div class="help-para">\n%s\n</div>\n', text)
  545. elseif node_name == 'line' then
  546. if
  547. (parent ~= 'codeblock' or parent ~= 'code')
  548. and (is_blank(text) or is_noise(text, stats.noise_lines))
  549. then
  550. return '' -- Discard common "noise" lines.
  551. end
  552. -- XXX: Avoid newlines (too much whitespace) after block elements in old (preformatted) layout.
  553. local div = opt.old
  554. and root:child(0)
  555. and vim.list_contains({ 'column_heading', 'h1', 'h2', 'h3' }, root:child(0):type())
  556. return string.format('%s%s', div and trim(text) or text, div and '' or '\n')
  557. elseif node_name == 'line_li' then
  558. local sib = root:prev_sibling()
  559. local prev_li = sib and sib:type() == 'line_li'
  560. if not prev_li then
  561. opt.indent = 1
  562. else
  563. -- The previous listitem _sibling_ is _logically_ the _parent_ if it is indented less.
  564. local parent_indent = get_indent(node_text(sib))
  565. local this_indent = get_indent(node_text())
  566. if this_indent > parent_indent then
  567. opt.indent = opt.indent + 1
  568. elseif this_indent < parent_indent then
  569. opt.indent = math.max(1, opt.indent - 1)
  570. end
  571. end
  572. local margin = opt.indent == 1 and '' or ('margin-left: %drem;'):format((1.5 * opt.indent))
  573. return string.format('<div class="help-li" style="%s">%s</div>', margin, text)
  574. elseif node_name == 'taglink' or node_name == 'optionlink' then
  575. local helppage, tagname, ignored = validate_link(root, opt.buf, opt.fname)
  576. if ignored then
  577. return text
  578. end
  579. local s = ('%s<a href="%s#%s">%s</a>'):format(
  580. ws(),
  581. helppage,
  582. url_encode(tagname),
  583. html_esc(tagname)
  584. )
  585. if opt.old and node_name == 'taglink' then
  586. s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
  587. end
  588. return s
  589. elseif vim.list_contains({ 'codespan', 'keycode' }, node_name) then
  590. if root:has_error() then
  591. return text
  592. end
  593. local s = ('%s<code>%s</code>'):format(ws(), trimmed)
  594. if opt.old and node_name == 'codespan' then
  595. s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
  596. end
  597. return s
  598. elseif node_name == 'argument' then
  599. return ('%s<code>{%s}</code>'):format(ws(), text)
  600. elseif node_name == 'codeblock' then
  601. return text
  602. elseif node_name == 'language' then
  603. language = node_text(root)
  604. return ''
  605. elseif node_name == 'code' then -- Highlighted codeblock (child).
  606. if is_blank(text) then
  607. return ''
  608. end
  609. local code ---@type string
  610. if language then
  611. code = ('<pre><code class="language-%s">%s</code></pre>'):format(
  612. language,
  613. trim(trim_indent(text), 2)
  614. )
  615. language = nil
  616. else
  617. code = ('<pre>%s</pre>'):format(trim(trim_indent(text), 2))
  618. end
  619. return code
  620. elseif node_name == 'tag' then -- anchor, h4 pseudo-heading
  621. if root:has_error() then
  622. return text
  623. end
  624. local in_heading = vim.list_contains({ 'h1', 'h2', 'h3' }, parent)
  625. local h4 = not in_heading and not next_ and get_indent(node_text()) > 8 -- h4 pseudo-heading
  626. local cssclass = h4 and 'help-tag-right' or 'help-tag'
  627. local tagname = node_text(root:child(1), false)
  628. if vim.tbl_count(stats.first_tags) < 2 then
  629. -- Force the first 2 tags in the doc to be anchored at the main heading.
  630. table.insert(stats.first_tags, tagname)
  631. return ''
  632. end
  633. local el = 'span'
  634. local encoded_tagname = url_encode(tagname)
  635. local s = ('%s<%s id="%s" class="%s"><a href="#%s">%s</a></%s>'):format(
  636. ws(),
  637. el,
  638. encoded_tagname,
  639. cssclass,
  640. encoded_tagname,
  641. trimmed,
  642. el
  643. )
  644. if opt.old then
  645. s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
  646. end
  647. if in_heading and prev ~= 'tag' then
  648. -- Start the <span> container for tags in a heading.
  649. -- This makes "justify-content:space-between" right-align the tags.
  650. -- <h2>foo bar<span>tag1 tag2</span></h2>
  651. return string.format('<span class="help-heading-tags">%s', s)
  652. elseif in_heading and next_ == nil then
  653. -- End the <span> container for tags in a heading.
  654. return string.format('%s</span>', s)
  655. end
  656. return s .. (h4 and '<br>' or '') -- HACK: <br> avoids h4 pseudo-heading mushing with text.
  657. elseif node_name == 'delimiter' or node_name == 'modeline' then
  658. return ''
  659. elseif node_name == 'ERROR' then
  660. if ignore_parse_error(opt.fname, trimmed) then
  661. return text
  662. end
  663. -- Store the raw text to give context to the bug report.
  664. local sample_text = level > 0 and getbuflinestr(root, opt.buf, 3) or '[top level!]'
  665. table.insert(stats.parse_errors, sample_text)
  666. return ('<a class="parse-error" target="_blank" title="Report bug... (parse error)" href="%s">%s</a>'):format(
  667. get_bug_url_vimdoc(opt.fname, opt.to_fname, sample_text),
  668. trimmed
  669. )
  670. else -- Unknown token.
  671. local sample_text = level > 0 and getbuflinestr(root, opt.buf, 3) or '[top level!]'
  672. return ('<a class="unknown-token" target="_blank" title="Report bug... (unhandled token "%s")" href="%s">%s</a>'):format(
  673. node_name,
  674. get_bug_url_nvim(opt.fname, opt.to_fname, sample_text, node_name),
  675. trimmed
  676. ),
  677. ('unknown-token:"%s"'):format(node_name)
  678. end
  679. end
  680. --- @param dir string e.g. '$VIMRUNTIME/doc'
  681. --- @param include string[]|nil
  682. --- @return string[]
  683. local function get_helpfiles(dir, include)
  684. local rv = {}
  685. for f, type in vim.fs.dir(dir) do
  686. if
  687. vim.endswith(f, '.txt')
  688. and type == 'file'
  689. and (not include or vim.list_contains(include, f))
  690. then
  691. local fullpath = vim.fn.fnamemodify(('%s/%s'):format(dir, f), ':p')
  692. table.insert(rv, fullpath)
  693. end
  694. end
  695. return rv
  696. end
  697. --- Populates the helptags map.
  698. local function get_helptags(help_dir)
  699. local m = {}
  700. -- Load a random help file to convince taglist() to do its job.
  701. vim.cmd(string.format('split %s/api.txt', help_dir))
  702. vim.cmd('lcd %:p:h')
  703. for _, item in ipairs(vim.fn.taglist('.*')) do
  704. if vim.endswith(item.filename, '.txt') then
  705. m[item.name] = item.filename
  706. end
  707. end
  708. vim.cmd('q!')
  709. return m
  710. end
  711. --- Use the vimdoc parser defined in the build, not whatever happens to be installed on the system.
  712. local function ensure_runtimepath()
  713. if not vim.o.runtimepath:find('build/lib/nvim/') then
  714. vim.cmd [[set runtimepath^=./build/lib/nvim/]]
  715. end
  716. end
  717. --- Opens `fname` (or `text`, if given) in a buffer and gets a treesitter parser for the buffer contents.
  718. ---
  719. --- @param fname string :help file to parse
  720. --- @param text string? :help file contents
  721. --- @param parser_path string? path to non-default vimdoc.so
  722. --- @return vim.treesitter.LanguageTree, integer (lang_tree, bufnr)
  723. local function parse_buf(fname, text, parser_path)
  724. local buf ---@type integer
  725. if text then
  726. vim.cmd('split new') -- Text contents.
  727. vim.api.nvim_put(vim.split(text, '\n'), '', false, false)
  728. vim.cmd('setfiletype help')
  729. -- vim.treesitter.language.add('vimdoc')
  730. buf = vim.api.nvim_get_current_buf()
  731. elseif type(fname) == 'string' then
  732. vim.cmd('split ' .. vim.fn.fnameescape(fname)) -- Filename.
  733. buf = vim.api.nvim_get_current_buf()
  734. else
  735. -- Left for debugging
  736. ---@diagnostic disable-next-line: no-unknown
  737. buf = fname
  738. vim.cmd('sbuffer ' .. tostring(fname)) -- Buffer number.
  739. end
  740. if parser_path then
  741. vim.treesitter.language.add('vimdoc', { path = parser_path })
  742. end
  743. local lang_tree = assert(vim.treesitter.get_parser(buf, nil, { error = false }))
  744. return lang_tree, buf
  745. end
  746. --- Validates one :help file `fname`:
  747. --- - checks that |tag| links point to valid helptags.
  748. --- - recursively counts parse errors ("ERROR" nodes)
  749. ---
  750. --- @param fname string help file to validate
  751. --- @param parser_path string? path to non-default vimdoc.so
  752. --- @return { invalid_links: number, parse_errors: string[] }
  753. local function validate_one(fname, parser_path)
  754. local stats = {
  755. parse_errors = {},
  756. }
  757. local lang_tree, buf = parse_buf(fname, nil, parser_path)
  758. for _, tree in ipairs(lang_tree:trees()) do
  759. visit_validate(tree:root(), 0, tree, { buf = buf, fname = fname }, stats)
  760. end
  761. lang_tree:destroy()
  762. vim.cmd.close()
  763. return stats
  764. end
  765. --- Generates HTML from one :help file `fname` and writes the result to `to_fname`.
  766. ---
  767. --- @param fname string Source :help file.
  768. --- @param text string|nil Source :help file contents, or nil to read `fname`.
  769. --- @param to_fname string Destination .html file
  770. --- @param old boolean Preformat paragraphs (for old :help files which are full of arbitrary whitespace)
  771. --- @param parser_path string? path to non-default vimdoc.so
  772. ---
  773. --- @return string html
  774. --- @return table stats
  775. local function gen_one(fname, text, to_fname, old, commit, parser_path)
  776. local stats = {
  777. noise_lines = {},
  778. parse_errors = {},
  779. first_tags = {}, -- Track the first few tags in doc.
  780. }
  781. local lang_tree, buf = parse_buf(fname, text, parser_path)
  782. ---@type nvim.gen_help_html.heading[]
  783. local headings = {} -- Headings (for ToC). 2-dimensional: h1 contains h2/h3.
  784. local title = to_titlecase(basename_noext(fname))
  785. local html = ([[
  786. <!DOCTYPE html>
  787. <html>
  788. <head>
  789. <meta charset="utf-8">
  790. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  791. <meta name="viewport" content="width=device-width, initial-scale=1">
  792. <meta name="description" content="Neovim user documentation">
  793. <!-- algolia docsearch https://docsearch.algolia.com/docs/docsearch-v3/ -->
  794. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@3" />
  795. <link rel="preconnect" href="https://X185E15FPG-dsn.algolia.net" crossorigin />
  796. <link href="/css/bootstrap.min.css" rel="stylesheet">
  797. <link href="/css/main.css" rel="stylesheet">
  798. <link href="help.css" rel="stylesheet">
  799. <link href="/highlight/styles/neovim.min.css" rel="stylesheet">
  800. <script src="/highlight/highlight.min.js"></script>
  801. <script>hljs.highlightAll();</script>
  802. <title>%s - Neovim docs</title>
  803. </head>
  804. <body>
  805. ]]):format(title)
  806. local logo_svg = [[
  807. <svg xmlns="http://www.w3.org/2000/svg" role="img" width="173" height="50" viewBox="0 0 742 214" aria-label="Neovim">
  808. <title>Neovim</title>
  809. <defs>
  810. <linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="a">
  811. <stop stop-color="#16B0ED" stop-opacity=".8" offset="0%" />
  812. <stop stop-color="#0F59B2" stop-opacity=".837" offset="100%" />
  813. </linearGradient>
  814. <linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="b">
  815. <stop stop-color="#7DB643" offset="0%" />
  816. <stop stop-color="#367533" offset="100%" />
  817. </linearGradient>
  818. <linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="c">
  819. <stop stop-color="#88C649" stop-opacity=".8" offset="0%" />
  820. <stop stop-color="#439240" stop-opacity=".84" offset="100%" />
  821. </linearGradient>
  822. </defs>
  823. <g fill="none" fill-rule="evenodd">
  824. <path
  825. d="M.027 45.459L45.224-.173v212.171L.027 166.894V45.459z"
  826. fill="url(#a)"
  827. transform="translate(1 1)"
  828. />
  829. <path
  830. d="M129.337 45.89L175.152-.149l-.928 212.146-45.197-45.104.31-121.005z"
  831. fill="url(#b)"
  832. transform="matrix(-1 0 0 1 305 1)"
  833. />
  834. <path
  835. d="M45.194-.137L162.7 179.173l-32.882 32.881L12.25 33.141 45.194-.137z"
  836. fill="url(#c)"
  837. transform="translate(1 1)"
  838. />
  839. <path
  840. d="M46.234 84.032l-.063 7.063-36.28-53.563 3.36-3.422 32.983 49.922z"
  841. fill-opacity=".13"
  842. fill="#000"
  843. />
  844. <g fill="#444">
  845. <path
  846. d="M227 154V64.44h4.655c1.55 0 2.445.75 2.685 2.25l.806 13.502c4.058-5.16 8.786-9.316 14.188-12.466 5.4-3.15 11.413-4.726 18.037-4.726 4.893 0 9.205.781 12.935 2.34 3.729 1.561 6.817 3.811 9.264 6.751 2.448 2.942 4.297 6.48 5.55 10.621 1.253 4.14 1.88 8.821 1.88 14.042V154h-8.504V96.754c0-8.402-1.91-14.987-5.729-19.757-3.82-4.771-9.667-7.156-17.544-7.156-5.851 0-11.28 1.516-16.292 4.545-5.013 3.032-9.489 7.187-13.427 12.467V154H227zM350.624 63c5.066 0 9.755.868 14.069 2.605 4.312 1.738 8.052 4.268 11.219 7.592s5.638 7.412 7.419 12.264C385.11 90.313 386 95.883 386 102.17c0 1.318-.195 2.216-.588 2.696-.393.48-1.01.719-1.851.719h-64.966v1.70c0 6.708.784 12.609 2.353 17.7 1.567 5.09 3.8 9.357 6.695 12.802 2.895 3.445 6.393 6.034 10.495 7.771 4.1 1.738 8.686 2.606 13.752 2.606 4.524 0 8.446-.494 11.762-1.483 3.317-.988 6.108-2.097 8.37-3.324 2.261-1.227 4.056-2.336 5.383-3.324 1.326-.988 2.292-1.482 2.895-1.482.784 0 1.388.3 1.81.898l2.352 2.875c-1.448 1.797-3.362 3.475-5.745 5.031-2.383 1.558-5.038 2.891-7.962 3.998-2.926 1.109-6.062 1.991-9.41 2.65a52.21 52.21 0 01-10.088.989c-6.152 0-11.762-1.064-16.828-3.19-5.067-2.125-9.415-5.225-13.043-9.298-3.63-4.074-6.435-9.06-8.415-14.96C310.99 121.655 310 114.9 310 107.294c0-6.408.92-12.323 2.76-17.744 1.84-5.421 4.493-10.093 7.961-14.016 3.467-3.922 7.72-6.991 12.758-9.209C338.513 64.11 344.229 63 350.624 63zm.573 6c-4.696 0-8.904.702-12.623 2.105-3.721 1.404-6.936 3.421-9.65 6.053-2.713 2.631-4.908 5.79-6.586 9.474S319.55 94.439 319 99h60c0-4.679-.672-8.874-2.013-12.588-1.343-3.712-3.232-6.856-5.67-9.43-2.44-2.571-5.367-4.545-8.782-5.92-3.413-1.374-7.192-2.062-11.338-2.062zM435.546 63c6.526 0 12.368 1.093 17.524 3.28 5.154 2.186 9.5 5.286 13.04 9.298 3.538 4.013 6.238 8.85 8.099 14.51 1.861 5.66 2.791 11.994 2.791 19.002 0 7.008-.932 13.327-2.791 18.957-1.861 5.631-4.561 10.452-8.099 14.465-3.54 4.012-7.886 7.097-13.04 9.254-5.156 2.156-10.998 3.234-17.524 3.234-6.529 0-12.369-1.078-17.525-3.234-5.155-2.157-9.517-5.242-13.085-9.254-3.57-4.013-6.285-8.836-8.145-14.465-1.861-5.63-2.791-11.95-2.791-18.957 0-7.008.93-13.342 2.791-19.002 1.861-5.66 4.576-10.496 8.145-14.51 3.568-4.012 7.93-7.112 13.085-9.299C423.177 64.094 429.017 63 435.546 63zm-.501 86c5.341 0 10.006-.918 13.997-2.757 3.99-1.838 7.32-4.474 9.992-7.909 2.67-3.435 4.664-7.576 5.986-12.428 1.317-4.85 1.98-10.288 1.98-16.316 0-5.965-.66-11.389-1.98-16.27-1.322-4.88-3.316-9.053-5.986-12.519-2.67-3.463-6-6.13-9.992-7.999-3.991-1.867-8.657-2.802-13.997-2.802s-10.008.935-13.997 2.802c-3.991 1.87-7.322 4.536-9.992 8-2.671 3.465-4.68 7.637-6.03 12.518-1.35 4.881-2.026 10.305-2.026 16.27 0 6.026.675 11.465 2.025 16.316 1.35 4.852 3.36 8.993 6.031 12.428 2.67 3.435 6 6.07 9.992 7.91 3.99 1.838 8.656 2.756 13.997 2.756z"
  847. fill="currentColor"
  848. />
  849. <path
  850. d="M530.57 152h-20.05L474 60h18.35c1.61 0 2.967.39 4.072 1.166 1.103.778 1.865 1.763 2.283 2.959l17.722 49.138a92.762 92.762 0 012.551 8.429c.686 2.751 1.298 5.5 1.835 8.25.537-2.75 1.148-5.499 1.835-8.25a77.713 77.713 0 012.64-8.429l18.171-49.138c.417-1.196 1.164-2.181 2.238-2.96 1.074-.776 2.356-1.165 3.849-1.165H567l-36.43 92zM572 61h23v92h-23zM610 153V60.443h13.624c2.887 0 4.78 1.354 5.682 4.06l1.443 6.856a52.7 52.7 0 015.097-4.962 32.732 32.732 0 015.683-3.879 30.731 30.731 0 016.496-2.57c2.314-.632 4.855-.948 7.624-.948 5.832 0 10.63 1.579 14.39 4.736 3.758 3.157 6.57 7.352 8.434 12.585 1.444-3.068 3.248-5.698 5.413-7.894 2.165-2.194 4.541-3.984 7.127-5.367a32.848 32.848 0 018.254-3.068 39.597 39.597 0 018.796-.992c5.111 0 9.653.783 13.622 2.345 3.97 1.565 7.307 3.849 10.014 6.857 2.706 3.007 4.766 6.675 6.18 11.005C739.29 83.537 740 88.5 740 94.092V153h-22.284V94.092c0-5.894-1.294-10.329-3.878-13.306-2.587-2.977-6.376-4.465-11.368-4.465-2.286 0-4.404.391-6.358 1.172a15.189 15.189 0 00-5.144 3.383c-1.473 1.474-2.631 3.324-3.474 5.548-.842 2.225-1.263 4.781-1.263 7.668V153h-22.37V94.092c0-6.194-1.249-10.704-3.744-13.532-2.497-2.825-6.18-4.24-11.051-4.24-3.19 0-6.18.798-8.976 2.391-2.799 1.593-5.399 3.775-7.804 6.54V153H610zM572 30h23v19h-23z"
  851. fill="currentColor"
  852. fill-opacity=".8"
  853. />
  854. </g>
  855. </g>
  856. </svg>
  857. ]]
  858. local main = ''
  859. for _, tree in ipairs(lang_tree:trees()) do
  860. main = main
  861. .. (
  862. visit_node(
  863. tree:root(),
  864. 0,
  865. tree,
  866. headings,
  867. { buf = buf, old = old, fname = fname, to_fname = to_fname, indent = 1 },
  868. stats
  869. )
  870. )
  871. end
  872. main = ([[
  873. <header class="container">
  874. <nav class="navbar navbar-expand-lg">
  875. <div class="container-fluid">
  876. <a href="/" class="navbar-brand" aria-label="logo">
  877. <!--TODO: use <img src="….svg"> here instead. Need one that has green lettering instead of gray. -->
  878. %s
  879. <!--<img src="https://neovim.io/logos/neovim-logo.svg" width="173" height="50" alt="Neovim" />-->
  880. </a>
  881. <div id="docsearch"></div> <!-- algolia docsearch https://docsearch.algolia.com/docs/docsearch-v3/ -->
  882. </div>
  883. </nav>
  884. </header>
  885. <div class="container golden-grid help-body">
  886. <div class="col-wide">
  887. <a name="%s" href="#%s"><h1 id="%s">%s</h1></a>
  888. <p>
  889. <i>
  890. Nvim <code>:help</code> pages, <a href="https://github.com/neovim/neovim/blob/master/scripts/gen_help_html.lua">generated</a>
  891. from <a href="https://github.com/neovim/neovim/blob/master/runtime/doc/%s">source</a>
  892. using the <a href="https://github.com/neovim/tree-sitter-vimdoc">tree-sitter-vimdoc</a> parser.
  893. </i>
  894. </p>
  895. <hr/>
  896. %s
  897. </div>
  898. ]]):format(
  899. logo_svg,
  900. stats.first_tags[1] or '',
  901. stats.first_tags[2] or '',
  902. stats.first_tags[2] or '',
  903. title,
  904. vim.fs.basename(fname),
  905. main
  906. )
  907. ---@type string
  908. local toc = [[
  909. <div class="col-narrow toc">
  910. <div><a href="index.html">Main</a></div>
  911. <div><a href="vimindex.html">Commands index</a></div>
  912. <div><a href="quickref.html">Quick reference</a></div>
  913. <hr/>
  914. ]]
  915. local n = 0 -- Count of all headings + subheadings.
  916. for _, h1 in ipairs(headings) do
  917. n = n + 1 + #h1.subheadings
  918. end
  919. for _, h1 in ipairs(headings) do
  920. ---@type string
  921. toc = toc .. ('<div class="help-toc-h1"><a href="#%s">%s</a>\n'):format(h1.tag, h1.name)
  922. if n < 30 or #headings < 10 then -- Show subheadings only if there aren't too many.
  923. for _, h2 in ipairs(h1.subheadings) do
  924. toc = toc
  925. .. ('<div class="help-toc-h2"><a href="#%s">%s</a></div>\n'):format(h2.tag, h2.name)
  926. end
  927. end
  928. toc = toc .. '</div>'
  929. end
  930. toc = toc .. '</div>\n'
  931. local bug_url = get_bug_url_nvim(fname, to_fname, 'TODO', nil)
  932. local bug_link = string.format('(<a href="%s" target="_blank">report docs bug...</a>)', bug_url)
  933. local footer = ([[
  934. <footer>
  935. <div class="container flex">
  936. <div class="generator-stats">
  937. Generated at %s from <code><a href="https://github.com/neovim/neovim/commit/%s">%s</a></code>
  938. </div>
  939. <div class="generator-stats">
  940. parse_errors: %d %s | <span title="%s">noise_lines: %d</span>
  941. </div>
  942. <div>
  943. <!-- algolia docsearch https://docsearch.algolia.com/docs/docsearch-v3/ -->
  944. <script src="https://cdn.jsdelivr.net/npm/@docsearch/js@3"></script>
  945. <script type="module">
  946. docsearch({
  947. container: '#docsearch',
  948. appId: 'X185E15FPG',
  949. apiKey: 'b5e6b2f9c636b2b471303205e59832ed',
  950. indexName: 'nvim',
  951. });
  952. </script>
  953. </footer>
  954. ]]):format(
  955. os.date('%Y-%m-%d %H:%M'),
  956. commit,
  957. commit:sub(1, 7),
  958. #stats.parse_errors,
  959. bug_link,
  960. html_esc(table.concat(stats.noise_lines, '\n')),
  961. #stats.noise_lines
  962. )
  963. html = ('%s%s%s</div>\n%s</body>\n</html>\n'):format(html, main, toc, footer)
  964. vim.cmd('q!')
  965. lang_tree:destroy()
  966. return html, stats
  967. end
  968. local function gen_css(fname)
  969. local css = [[
  970. :root {
  971. --code-color: #004b4b;
  972. --tag-color: #095943;
  973. }
  974. @media (prefers-color-scheme: dark) {
  975. :root {
  976. --code-color: #00c243;
  977. --tag-color: #00b7b7;
  978. }
  979. }
  980. @media (min-width: 40em) {
  981. .toc {
  982. position: fixed;
  983. left: 67%;
  984. }
  985. .golden-grid {
  986. display: grid;
  987. grid-template-columns: 65% auto;
  988. grid-gap: 1em;
  989. }
  990. }
  991. @media (max-width: 40em) {
  992. .golden-grid {
  993. /* Disable grid for narrow viewport (mobile phone). */
  994. display: block;
  995. }
  996. }
  997. .toc {
  998. /* max-width: 12rem; */
  999. height: 85%; /* Scroll if there are too many items. https://github.com/neovim/neovim.github.io/issues/297 */
  1000. overflow: auto; /* Scroll if there are too many items. https://github.com/neovim/neovim.github.io/issues/297 */
  1001. }
  1002. .toc > div {
  1003. text-overflow: ellipsis;
  1004. overflow: hidden;
  1005. white-space: nowrap;
  1006. }
  1007. html {
  1008. scroll-behavior: auto;
  1009. }
  1010. body {
  1011. font-size: 18px;
  1012. line-height: 1.5;
  1013. }
  1014. h1, h2, h3, h4, h5 {
  1015. font-family: sans-serif;
  1016. border-bottom: 1px solid var(--tag-color); /*rgba(0, 0, 0, .9);*/
  1017. }
  1018. h3, h4, h5 {
  1019. border-bottom-style: dashed;
  1020. }
  1021. .help-column_heading {
  1022. color: var(--code-color);
  1023. }
  1024. .help-body {
  1025. padding-bottom: 2em;
  1026. }
  1027. .help-line {
  1028. /* font-family: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace; */
  1029. }
  1030. .help-li {
  1031. white-space: normal;
  1032. display: list-item;
  1033. margin-left: 1.5rem; /* padding-left: 1rem; */
  1034. }
  1035. .help-para {
  1036. padding-top: 10px;
  1037. padding-bottom: 10px;
  1038. }
  1039. .old-help-para {
  1040. padding-top: 10px;
  1041. padding-bottom: 10px;
  1042. /* Tabs are used for alignment in old docs, so we must match Vim's 8-char expectation. */
  1043. tab-size: 8;
  1044. white-space: pre-wrap;
  1045. font-size: 16px;
  1046. font-family: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace;
  1047. word-wrap: break-word;
  1048. }
  1049. .old-help-para pre, .old-help-para pre:hover {
  1050. /* Text following <pre> is already visually separated by the linebreak. */
  1051. margin-bottom: 0;
  1052. /* Long lines that exceed the textwidth should not be wrapped (no "pre-wrap").
  1053. Since text may overflow horizontally, we make the contents to be scrollable
  1054. (only if necessary) to prevent overlapping with the navigation bar at the right. */
  1055. white-space: pre;
  1056. overflow-x: auto;
  1057. }
  1058. /* TODO: should this rule be deleted? help tags are rendered as <code> or <span>, not <a> */
  1059. a.help-tag, a.help-tag:focus, a.help-tag:hover {
  1060. color: inherit;
  1061. text-decoration: none;
  1062. }
  1063. .help-tag {
  1064. color: var(--tag-color);
  1065. }
  1066. /* Tag pseudo-header common in :help docs. */
  1067. .help-tag-right {
  1068. color: var(--tag-color);
  1069. margin-left: auto;
  1070. margin-right: 0;
  1071. float: right;
  1072. display: block;
  1073. }
  1074. .help-tag a,
  1075. .help-tag-right a {
  1076. color: inherit;
  1077. }
  1078. .help-tag a:not(:hover),
  1079. .help-tag-right a:not(:hover) {
  1080. text-decoration: none;
  1081. }
  1082. h1 .help-tag, h2 .help-tag, h3 .help-tag {
  1083. font-size: smaller;
  1084. }
  1085. .help-heading {
  1086. white-space: normal;
  1087. display: flex;
  1088. flex-flow: row wrap;
  1089. justify-content: space-between;
  1090. gap: 0 15px;
  1091. }
  1092. /* The (right-aligned) "tags" part of a section heading. */
  1093. .help-heading-tags {
  1094. margin-right: 10px;
  1095. }
  1096. .help-toc-h1 {
  1097. }
  1098. .help-toc-h2 {
  1099. margin-left: 1em;
  1100. }
  1101. .parse-error {
  1102. background-color: red;
  1103. }
  1104. .unknown-token {
  1105. color: black;
  1106. background-color: yellow;
  1107. }
  1108. code {
  1109. color: var(--code-color);
  1110. font-size: 16px;
  1111. }
  1112. pre {
  1113. /* Tabs are used in codeblocks only for indentation, not alignment, so we can aggressively shrink them. */
  1114. tab-size: 2;
  1115. white-space: pre-wrap;
  1116. line-height: 1.3; /* Important for ascii art. */
  1117. overflow: visible;
  1118. /* font-family: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace; */
  1119. font-size: 16px;
  1120. margin-top: 10px;
  1121. }
  1122. pre:last-child {
  1123. margin-bottom: 0;
  1124. }
  1125. pre:hover {
  1126. overflow: visible;
  1127. }
  1128. .generator-stats {
  1129. color: gray;
  1130. font-size: smaller;
  1131. }
  1132. ]]
  1133. tofile(fname, css)
  1134. end
  1135. -- Testing
  1136. local function ok(cond, expected, actual, message)
  1137. assert(
  1138. (not expected and not actual) or (expected and actual),
  1139. 'if "expected" is given, "actual" is also required'
  1140. )
  1141. if expected then
  1142. assert(
  1143. cond,
  1144. ('%sexpected %s, got: %s'):format(
  1145. message and (message .. '\n') or '',
  1146. vim.inspect(expected),
  1147. vim.inspect(actual)
  1148. )
  1149. )
  1150. return cond
  1151. else
  1152. return assert(cond)
  1153. end
  1154. end
  1155. local function eq(expected, actual, message)
  1156. return ok(vim.deep_equal(expected, actual), expected, actual, message)
  1157. end
  1158. function M._test()
  1159. tagmap = get_helptags('$VIMRUNTIME/doc')
  1160. helpfiles = get_helpfiles(vim.fs.normalize('$VIMRUNTIME/doc'))
  1161. ok(vim.tbl_count(tagmap) > 3000, '>3000', vim.tbl_count(tagmap))
  1162. ok(
  1163. vim.endswith(tagmap['vim.diagnostic.set()'], 'diagnostic.txt'),
  1164. tagmap['vim.diagnostic.set()'],
  1165. 'diagnostic.txt'
  1166. )
  1167. ok(vim.endswith(tagmap['%:s'], 'cmdline.txt'), tagmap['%:s'], 'cmdline.txt')
  1168. ok(is_noise([[vim:tw=78:isk=!-~,^*,^\|,^\":ts=8:noet:ft=help:norl:]]))
  1169. ok(is_noise([[ NVIM REFERENCE MANUAL by Thiago de Arruda ]]))
  1170. ok(not is_noise([[vim:tw=78]]))
  1171. eq(0, get_indent('a'))
  1172. eq(1, get_indent(' a'))
  1173. eq(2, get_indent(' a\n b\n c\n'))
  1174. eq(5, get_indent(' a\n \n b\n c\n d\n e\n'))
  1175. eq(
  1176. 'a\n \n b\n c\n d\n e\n',
  1177. trim_indent(' a\n \n b\n c\n d\n e\n')
  1178. )
  1179. local fixed_url, removed_chars = fix_url('https://example.com).')
  1180. eq('https://example.com', fixed_url)
  1181. eq(').', removed_chars)
  1182. fixed_url, removed_chars = fix_url('https://example.com.)')
  1183. eq('https://example.com.', fixed_url)
  1184. eq(')', removed_chars)
  1185. fixed_url, removed_chars = fix_url('https://example.com.')
  1186. eq('https://example.com', fixed_url)
  1187. eq('.', removed_chars)
  1188. fixed_url, removed_chars = fix_url('https://example.com)')
  1189. eq('https://example.com', fixed_url)
  1190. eq(')', removed_chars)
  1191. fixed_url, removed_chars = fix_url('https://example.com')
  1192. eq('https://example.com', fixed_url)
  1193. eq('', removed_chars)
  1194. print('all tests passed.\n')
  1195. end
  1196. --- @class nvim.gen_help_html.gen_result
  1197. --- @field helpfiles string[] list of generated HTML files, from the source docs {include}
  1198. --- @field err_count integer number of parse errors in :help docs
  1199. --- @field invalid_links table<string, any>
  1200. --- Generates HTML from :help docs located in `help_dir` and writes the result in `to_dir`.
  1201. ---
  1202. --- Example:
  1203. ---
  1204. --- gen('$VIMRUNTIME/doc', '/path/to/neovim.github.io/_site/doc/', {'api.txt', 'autocmd.txt', 'channel.txt'}, nil)
  1205. ---
  1206. --- @param help_dir string Source directory containing the :help files. Must run `make helptags` first.
  1207. --- @param to_dir string Target directory where the .html files will be written.
  1208. --- @param include string[]|nil Process only these filenames. Example: {'api.txt', 'autocmd.txt', 'channel.txt'}
  1209. ---
  1210. --- @return nvim.gen_help_html.gen_result result
  1211. function M.gen(help_dir, to_dir, include, commit, parser_path)
  1212. vim.validate('help_dir', help_dir, function(d)
  1213. return vim.fn.isdirectory(vim.fs.normalize(d)) == 1
  1214. end, 'valid directory')
  1215. vim.validate('to_dir', to_dir, 'string')
  1216. vim.validate('include', include, 'table', true)
  1217. vim.validate('commit', commit, 'string', true)
  1218. vim.validate('parser_path', parser_path, function(f)
  1219. return vim.fn.filereadable(vim.fs.normalize(f)) == 1
  1220. end, true, 'valid vimdoc.{so,dll} filepath')
  1221. local err_count = 0
  1222. local redirects_count = 0
  1223. ensure_runtimepath()
  1224. tagmap = get_helptags(vim.fs.normalize(help_dir))
  1225. helpfiles = get_helpfiles(help_dir, include)
  1226. to_dir = vim.fs.normalize(to_dir)
  1227. parser_path = parser_path and vim.fs.normalize(parser_path) or nil
  1228. print(('output dir: %s\n\n'):format(to_dir))
  1229. vim.fn.mkdir(to_dir, 'p')
  1230. gen_css(('%s/help.css'):format(to_dir))
  1231. for _, f in ipairs(helpfiles) do
  1232. -- "foo.txt"
  1233. local helpfile = vim.fs.basename(f)
  1234. -- "to/dir/foo.html"
  1235. local to_fname = ('%s/%s'):format(to_dir, get_helppage(helpfile))
  1236. local html, stats =
  1237. gen_one(f, nil, to_fname, not new_layout[helpfile], commit or '?', parser_path)
  1238. tofile(to_fname, html)
  1239. print(
  1240. ('generated (%-2s errors): %-15s => %s'):format(
  1241. #stats.parse_errors,
  1242. helpfile,
  1243. vim.fs.basename(to_fname)
  1244. )
  1245. )
  1246. -- Generate redirect pages for renamed help files.
  1247. local helpfile_tag = (helpfile:gsub('%.txt$', ''))
  1248. local redirect_from = redirects[helpfile_tag]
  1249. if redirect_from then
  1250. local redirect_text = ([[
  1251. *%s* Nvim
  1252. This document moved to: |%s|
  1253. ==============================================================================
  1254. This document moved to: |%s|
  1255. This document moved to: |%s|
  1256. ==============================================================================
  1257. vim:tw=78:ts=8:ft=help:norl:
  1258. ]]):format(
  1259. redirect_from,
  1260. helpfile_tag,
  1261. helpfile_tag,
  1262. helpfile_tag,
  1263. helpfile_tag,
  1264. helpfile_tag
  1265. )
  1266. local redirect_to = ('%s/%s'):format(to_dir, get_helppage(redirect_from))
  1267. local redirect_html, _ =
  1268. gen_one(redirect_from, redirect_text, redirect_to, false, commit or '?', parser_path)
  1269. assert(redirect_html:find(helpfile_tag))
  1270. tofile(redirect_to, redirect_html)
  1271. print(
  1272. ('generated (redirect) : %-15s => %s'):format(
  1273. redirect_from .. '.txt',
  1274. vim.fs.basename(to_fname)
  1275. )
  1276. )
  1277. redirects_count = redirects_count + 1
  1278. end
  1279. err_count = err_count + #stats.parse_errors
  1280. end
  1281. print(('\ngenerated %d html pages'):format(#helpfiles + redirects_count))
  1282. print(('total errors: %d'):format(err_count))
  1283. print(('invalid tags: %s'):format(vim.inspect(invalid_links)))
  1284. assert(#(include or {}) > 0 or redirects_count == vim.tbl_count(redirects)) -- sanity check
  1285. print(('redirects: %d'):format(redirects_count))
  1286. print('\n')
  1287. --- @type nvim.gen_help_html.gen_result
  1288. return {
  1289. helpfiles = helpfiles,
  1290. err_count = err_count,
  1291. invalid_links = invalid_links,
  1292. }
  1293. end
  1294. --- @class nvim.gen_help_html.validate_result
  1295. --- @field helpfiles integer number of generated helpfiles
  1296. --- @field err_count integer number of parse errors
  1297. --- @field parse_errors table<string, string[]>
  1298. --- @field invalid_links table<string, any> invalid tags in :help docs
  1299. --- @field invalid_urls table<string, any> invalid URLs in :help docs
  1300. --- @field invalid_spelling table<string, table<string, string>> invalid spelling in :help docs
  1301. --- Validates all :help files found in `help_dir`:
  1302. --- - checks that |tag| links point to valid helptags.
  1303. --- - recursively counts parse errors ("ERROR" nodes)
  1304. ---
  1305. --- This is 10x faster than gen(), for use in CI.
  1306. ---
  1307. --- @return nvim.gen_help_html.validate_result result
  1308. function M.validate(help_dir, include, parser_path)
  1309. vim.validate('help_dir', help_dir, function(d)
  1310. return vim.fn.isdirectory(vim.fs.normalize(d)) == 1
  1311. end, 'valid directory')
  1312. vim.validate('include', include, 'table', true)
  1313. vim.validate('parser_path', parser_path, function(f)
  1314. return vim.fn.filereadable(vim.fs.normalize(f)) == 1
  1315. end, true, 'valid vimdoc.{so,dll} filepath')
  1316. local err_count = 0 ---@type integer
  1317. local files_to_errors = {} ---@type table<string, string[]>
  1318. ensure_runtimepath()
  1319. tagmap = get_helptags(vim.fs.normalize(help_dir))
  1320. helpfiles = get_helpfiles(help_dir, include)
  1321. parser_path = parser_path and vim.fs.normalize(parser_path) or nil
  1322. for _, f in ipairs(helpfiles) do
  1323. local helpfile = vim.fs.basename(f)
  1324. local rv = validate_one(f, parser_path)
  1325. print(('validated (%-4s errors): %s'):format(#rv.parse_errors, helpfile))
  1326. if #rv.parse_errors > 0 then
  1327. files_to_errors[helpfile] = rv.parse_errors
  1328. vim.print(('%s'):format(vim.iter(rv.parse_errors):fold('', function(s, v)
  1329. return s .. '\n ' .. v
  1330. end)))
  1331. end
  1332. err_count = err_count + #rv.parse_errors
  1333. end
  1334. ---@type nvim.gen_help_html.validate_result
  1335. return {
  1336. helpfiles = #helpfiles,
  1337. err_count = err_count,
  1338. parse_errors = files_to_errors,
  1339. invalid_links = invalid_links,
  1340. invalid_urls = invalid_urls,
  1341. invalid_spelling = invalid_spelling,
  1342. }
  1343. end
  1344. --- Validates vimdoc files on $VIMRUNTIME. and print human-readable error messages if fails.
  1345. ---
  1346. --- If this fails, try these steps (in order):
  1347. --- 1. Fix/cleanup the :help docs.
  1348. --- 2. Fix the parser: https://github.com/neovim/tree-sitter-vimdoc
  1349. --- 3. File a parser bug, and adjust the tolerance of this test in the meantime.
  1350. ---
  1351. --- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc'
  1352. function M.run_validate(help_dir)
  1353. help_dir = vim.fs.normalize(help_dir or '$VIMRUNTIME/doc')
  1354. print('doc path = ' .. vim.uv.fs_realpath(help_dir))
  1355. local rv = M.validate(help_dir)
  1356. -- Check that we actually found helpfiles.
  1357. ok(rv.helpfiles > 100, '>100 :help files', rv.helpfiles)
  1358. eq({}, rv.parse_errors, 'no parse errors')
  1359. eq(0, rv.err_count, 'no parse errors')
  1360. eq({}, rv.invalid_links, 'invalid tags in :help docs')
  1361. eq({}, rv.invalid_urls, 'invalid URLs in :help docs')
  1362. eq(
  1363. {},
  1364. rv.invalid_spelling,
  1365. 'invalid spelling in :help docs (see spell_dict in scripts/gen_help_html.lua)'
  1366. )
  1367. end
  1368. --- Test-generates HTML from docs.
  1369. ---
  1370. --- 1. Test that gen_help_html.lua actually works.
  1371. --- 2. Test that parse errors did not increase wildly. Because we explicitly test only a few
  1372. --- :help files, we can be precise about the tolerances here.
  1373. --- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc'
  1374. function M.test_gen(help_dir)
  1375. local tmpdir = vim.fs.dirname(vim.fn.tempname())
  1376. help_dir = vim.fs.normalize(help_dir or '$VIMRUNTIME/doc')
  1377. print('doc path = ' .. vim.uv.fs_realpath(help_dir))
  1378. -- Because gen() is slow (~30s), this test is limited to a few files.
  1379. local input = { 'help.txt', 'index.txt', 'nvim.txt' }
  1380. local rv = M.gen(help_dir, tmpdir, input)
  1381. eq(#input, #rv.helpfiles)
  1382. eq(0, rv.err_count, 'parse errors in :help docs')
  1383. eq({}, rv.invalid_links, 'invalid tags in :help docs')
  1384. end
  1385. return M