robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3b00ddb601
master
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 ={ 50Neovim ='Nvim' , 51NeoVim ='Nvim' , 52neovim ='Nvim' , 53lua ='Lua' , 54VimL ='Vimscript' , 55vimL ='Vimscript' , 56viml ='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 ={ 130matchit ='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 ) 160local f =io . open ( fname , 'w' ) 161if not f then 162error (( 'failed to write: %s' ): format ( f )) 163else 164f : write ( text ) 165f : close () 166end 167end 168 169---@type fun(s: string): string 170local function html_esc ( s ) 171local html_entity = 172{ [ '&' ] ='&' , [ '<' ] ='<' , [ '>' ] ='>' , [ '{' ] ='{' , [ '}' ] ='}' } 173return ( 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 ) 180return ( 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 ) 187return ( 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: ' ( ) 193return vim . fn . substitute ( 194vim . 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 ) 202local text ='' 203for w in vim . gsplit ( s , '[ \t]+' ) do 204text =( '%s %s%s' ): format ( text , vim . fn . toupper ( w : sub ( 1 , 1 )), w : sub ( 2 )) 205end 206return text 207end 208 209local function to_heading_tag ( text ) 210-- Prepend "_" to avoid conflicts with actual :help tags. 211return text and string . format ( '_%s' , vim . fn . tolower (( text : gsub ( '%s+' , '-' )))) or 'unknown' 212end 213 214local function basename_noext ( f ) 215return vim . fs . basename ( f : gsub ( '%.txt' , '' )) 216end 217 218local function is_blank ( s ) 219return not not s : find ( [[^[\t ]*$]] ) 220end 221 222---@type fun(s: string, dir?:0|1|2): string 223local function trim ( s , dir ) 224return 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 ) 235local removed_chars ='' 236local 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 244return 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 ) 249if 250-- First line is always noise. 251( noise_lines ~= nil and vim . tbl_count ( noise_lines ) == 0 ) 252or line : find ( 'Type .*gO.* to see the table of contents' ) 253-- Title line of traditional :help pages. 254-- Example: "NVIM REFERENCE MANUAL by ..." 255or line : find ( [[^%s*N?VIM[ \t]*REFERENCE[ \t]*MANUAL]] ) 256-- First line of traditional :help pages. 257-- Example: "*api.txt* Nvim" 258or 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:" 261or line : find ( '^%s*vim?%:.*ft=help' ) 262or line : find ( '^%s*vim?%:.*filetype=help' ) 263or line : find ( '[*>]local%-additions[*<]' ) 264then 265-- table.insert(stats.noise_lines, getbuflinestr(root, opt.buf, 0)) 266table . insert ( noise_lines or {} , line ) 267return true 268end 269return 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 ) 278local this_url =string . format ( 'https://neovim.io/doc/user/%s' , vim . fs . basename ( to_fname )) 279local 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) 288return 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 ) 298local this_url =string . format ( 'https://neovim.io/doc/user/%s' , vim . fs . basename ( to_fname )) 299local 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) 310return bug_url 311end 312 313--- Gets a "foo" name from a "foo.txt" helpfile name. 314local function get_helppage_html ( f , with_extension ) 315if not f then 316return nil 317end 318-- Special case: help.txt is the "main landing page" of :help files, not index.txt. 319if f == 'index.txt' then 320return with_extension and 'vimindex.html' or 'vimindex/' 321elseif f == 'help.txt' then 322-- Hugo needs an `_index.html` (note the underscore) file to recognize it as section 323return with_extension and '_index.html' or '' 324end 325 326return ( 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 ) 333local _ , indent =vim . text . indent ( 0 , s , { expandtab =8 } ) 334return indent 335end 336 337--- Removes the common indent level, after expanding tabs to 8 spaces. 338local function trim_indent ( s ) 339return ( 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 ) 347local line1 , _ , line2 , _ =node : range () 348line1 =line1 - offset 349line2 =line2 + offset 350local lines =vim . fn . getbufline ( bufnr , line1 + 1 , line2 + 1 ) 351return 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 ) 360local line1 , c1 , line2 , _ =node : range () 361---@type string 362local raw =vim . fn . getbufline ( bufnr , line1 + 1 , line2 + 1 )[ 1 ] 363local text_before =raw : sub ( 1 , c1 ) 364local leading_ws =text_before : match ( '%s+$' ) or '' 365return leading_ws 366end 367 368local function get_tagname ( node , bufnr ) 369local text =vim . treesitter . get_node_text ( node , bufnr ) 370local tag =( node : type () == 'optionlink' or node : parent (): type () == 'optionlink' ) 371and ( "'%s'" ): format ( text ) 372or text 373local helpfile =vim . fs . basename ( tagmap [ tag ]) or nil -- "api.txt" 374local helppage =get_helppage_html ( helpfile ) -- "api.html" 375return helppage , tag 376end 377 378--- Returns true if the given invalid tagname is a false positive. 379local function ignore_invalid ( s ) 380return not not ( 381exclude_invalid [ s ] 382-- Strings like |~/====| appear in various places and the parser thinks they are links, but they 383-- are just table borders. 384or s : find ( '===' ) 385or s : find ( '%-%-%-' ) 386) 387end 388 389local function ignore_parse_error ( fname , s ) 390if ignore_errors [ vim . fs . basename ( fname )] then 391return true 392end 393-- Ignore parse errors for unclosed tag. 394-- This is common in vimdocs and is treated as plaintext by :help. 395return s : find ( "^[`'|*]" ) 396end 397 398---@param node TSNode 399local function has_ancestor ( node , ancestor_name ) 400local p =node ---@type TSNode? 401while p do 402p =p : parent () 403if not p or p : type () == 'help_file' then 404break 405elseif p : type () == ancestor_name then 406return true 407end 408end 409return false 410end 411 412--- Gets the first matching child node matching `name`. 413---@param node TSNode 414local function first ( node , name ) 415for c , _ in node : iter_children () do 416if c : named () and c : type () == name then 417return c 418end 419end 420return nil 421end 422 423--- Gets the last child of `node`, or nil. 424---@param node TSNode 425local function last ( node ) 426local n =node : child_count () 427return 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). 434local prev =n : prev_sibling () 435and ( n : prev_sibling (). named and n : prev_sibling (): named ()) 436and n : prev_sibling (): type () 437or nil 438-- Next sibling kind (string). 439local next_ =n : next_sibling () 440and ( n : next_sibling (). named and n : next_sibling (): named ()) 441and n : next_sibling (): type () 442or nil 443return prev , next_ 444end 445 446local function validate_link ( node , bufnr , fname ) 447local helppage , tagname =get_tagname ( node : child ( 1 ), bufnr ) 448local ignored =false 449if not tagmap [ tagname ] then 450ignored =has_ancestor ( node , 'column_heading' ) or node : has_error () or ignore_invalid ( tagname ) 451if not ignored then 452invalid_links [ tagname ] =vim . fs . basename ( fname ) 453end 454end 455return helppage , tagname , ignored 456end 457 458local function validate_url ( text , fname , check_unreachable ) 459fname =vim . fs . basename ( fname ) 460local ignored =ignore_errors [ fname ] or exclude_invalid_urls [ text ] 461if ignored then 462return true 463end 464if check_unreachable then 465vim . net . request ( text , { retry =2 } , function ( err , _ ) 466if err then 467invalid_urls [ text ] =fname 468end 469pending_urls =pending_urls - 1 470end ) 471pending_urls =pending_urls + 1 472else 473if text : find ( 'http%:' ) then 474invalid_urls [ text ] =fname 475end 476end 477return 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 ) 487level =level or 0 488 489local function node_text ( node ) 490return vim . treesitter . get_node_text ( node or root , opt . buf ) 491end 492 493local text =trim ( node_text ()) 494local node_name =( root . named and root : named ()) and root : type () or nil 495-- Parent kind (string). 496local parent =root : parent () and root : parent (): type () or nil 497local toplevel =level < 1 498-- local prev, next_ = get_prev_next(root) 499local prev_text =root : prev_sibling () and node_text ( root : prev_sibling ()) or nil 500local next_text =root : next_sibling () and node_text ( root : next_sibling ()) or nil 501 502if root : child_count () > 0 then 503for node , _ in root : iter_children () do 504if node : named () then 505visit_validate ( node , level + 1 , lang_tree , opt , stats ) 506end 507end 508end 509 510if node_name == 'ERROR' then 511if ignore_parse_error ( opt . fname , text ) then 512return 513end 514-- Store the raw text to give context to the error report. 515local sample_text =not toplevel and getbuflinestr ( root , opt . buf , 0 ) or '[top level!]' 516-- Flatten the sample text to a single, truncated line. 517sample_text =vim . trim ( sample_text ): gsub ( '[\t\n]' , ' ' ): sub ( 1 , 80 ) 518table . insert ( stats . parse_errors , sample_text ) 519elseif 520( node_name == 'word' or node_name == 'uppercase_name' ) 521and ( not vim . tbl_contains ( { 'codespan' , 'taglink' , 'tag' } , parent )) 522then 523local text_nopunct =vim . fn . trim ( text , '.,' , 0 ) -- Ignore some punctuation. 524local fname_basename =assert ( vim . fs . basename ( opt . fname --[[ @as string ]] )) 525if spell_dict [ text_nopunct ] then 526local should_ignore =( 527spell_ignore_files [ fname_basename ] == true 528or vim . tbl_contains ( 529( spell_ignore_files [ fname_basename ] or {} ) --[[ @as string[] ]] , 530text_nopunct 531) 532or ( spell_punc [ next_text ] or spell_punc [ prev_text ]) 533) 534if not should_ignore then 535invalid_spelling [ text_nopunct ] =invalid_spelling [ text_nopunct ] or {} 536invalid_spelling [ text_nopunct ][ fname_basename ] =node_text ( root : parent ()) 537end 538end 539elseif node_name == 'url' then 540local fixed_url , _ =fix_url ( trim ( text )) 541validate_url ( fixed_url , opt . fname , opt . request_urls ) 542elseif node_name == 'taglink' or node_name == 'optionlink' then 543local _ , _ , _ =validate_link ( root , opt . buf , opt . fname ) 544end 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. 555if string . sub ( next_node_text , 1 , 1 ) == '\t' then 556text =text .. ' ' 557end 558return 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 ) 574level =level or 0 575 576local function node_text ( node , ws_ ) 577node =node or root 578ws_ =( ws_ == nil or ws_ == true ) and getws ( node , opt . buf ) or '' 579return string . format ( '%s%s' , ws_ , vim . treesitter . get_node_text ( node , opt . buf )) 580end 581 582-- Gets leading whitespace of `node`. 583local function ws ( node ) 584node =node or root 585local 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 ? 588if ws_ == '' then 589ws_ =vim . treesitter . get_node_text ( node , opt . buf ): match ( '^%s+' ) or '' 590end 591return ws_ 592end 593 594local node_name =( root . named and root : named ()) and root : type () or nil 595local prev , next_ =get_prev_next ( root ) 596-- Parent kind (string). 597local parent =root : parent () and root : parent (): type () or nil 598 599local text ='' 600local trimmed ---@type string 601if root : named_child_count () == 0 or node_name == 'ERROR' then 602text =node_text () 603trimmed =html_esc ( trim ( text )) 604text =html_esc ( text ) 605else 606-- Process children and join them with whitespace. 607for node , _ in root : iter_children () do 608if node : named () then 609local r =ts_node_to_html ( node , level + 1 , lang_tree , headings , opt , stats ) 610text =string . format ( '%s%s' , text , r ) 611end 612end 613trimmed =trim ( text ) 614end 615 616if node_name == 'help_file' then -- root node 617return text 618elseif node_name == 'url' then 619local fixed_url , removed_chars =fix_url ( trimmed ) 620return ( '%s<a href="%s">%s</a>%s' ): format ( ws (), fixed_url , fixed_url , removed_chars ) 621elseif node_name == 'word' or node_name == 'uppercase_name' then 622return text 623elseif node_name == 'note' then 624return ( '<b>%s</b>' ): format ( text ) 625elseif node_name == 'h1' or node_name == 'h2' or node_name == 'h3' then 626if is_noise ( text , stats . noise_lines ) then 627return '' -- Discard common "noise" lines. 628end 629-- Remove tags from ToC text. 630local heading_node =first ( root , 'heading' ) 631local hname =trim ( node_text ( heading_node ): gsub ( '%*.*%*' , '' )) 632if not heading_node or hname == '' then 633return '' -- Spurious "===" or "---" in the help doc. 634end 635 636-- Generate an anchor id from the heading text. 637local tagname =to_heading_tag ( hname ) 638if node_name == 'h1' or # headings == 0 then 639---@type nvim.gen_help_html.heading 640local heading ={ name =hname , subheadings ={} , tag =tagname } 641headings [ # headings + 1 ] =heading 642else 643table . insert ( 644headings [ # headings ]. subheadings , 645{ name =hname , subheadings ={} , tag =tagname } 646) 647end 648local el =node_name == 'h1' and 'h2' or 'h3' 649return ( '<%s id="%s" class="help-heading">%s</%s>\n' ): format ( el , tagname , trimmed , el ) 650elseif node_name == 'heading' then 651return trimmed 652elseif node_name == 'column_heading' or node_name == 'column_name' then 653if root : has_error () then 654return text 655end 656return ( '<div class="help-column_heading">%s</div>' ): format ( text ) 657elseif node_name == 'block' then 658if is_blank ( text ) then 659return '' 660end 661 662-- Conjoin list-item blocks: merge adjacent blocks that form a contiguous list. 663local prev_block =root : prev_sibling () 664local next_block =root : next_sibling () 665local prev_last =prev_block and prev_block : type () == 'block' and last ( prev_block ) 666local next_first =next_block and next_block : type () == 'block' and next_block : child ( 0 ) 667local continues_list =root : child ( 0 ) 668and root : child ( 0 ): type () == 'line_li' 669and prev_last 670and prev_last : type () == 'line_li' 671local list_continues =last ( root ) 672and last ( root ): type () == 'line_li' 673and next_first 674and next_first : type () == 'line_li' 675if continues_list and list_continues then 676return text 677elseif continues_list then 678-- Last continuation block: close the wrapper opened by the first block. 679if opt . old then 680return ( '%s</div>\n' ): format ( trim ( text , 2 )) 681end 682return string . format ( '%s\n</div>\n' , text ) 683elseif list_continues then 684-- First block of a list that continues: open wrapper but don't close. 685if opt . old then 686return ( '<div class="old-help-para">%s' ): format ( trim ( text , 2 )) 687end 688return string . format ( '<div class="help-para">\n%s' , text ) 689end 690 691if 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. 694return ( '<div class="old-help-para">%s</div>\n' ): format ( trim ( text , 2 )) 695end 696return string . format ( '<div class="help-para">\n%s\n</div>\n' , text ) 697elseif node_name == 'line' then 698if 699( parent ~= 'codeblock' and parent ~= 'code' ) 700and ( is_blank ( text ) or is_noise ( text , stats . noise_lines )) 701then 702return '' -- Discard common "noise" lines. 703end 704-- XXX: Avoid newlines (too much whitespace) after block elements in old (preformatted) layout. 705local div =opt . old 706and root : child ( 0 ) 707and vim . list_contains ( { 'column_heading' , 'h1' , 'h2' , 'h3' } , root : child ( 0 ): type ()) 708return string . format ( '%s%s' , div and trim ( text ) or text , div and '' or '\n' ) 709elseif parent == 'line_li' and node_name == 'prefix' then 710return '' 711elseif node_name == 'line_li' then 712local prefix =first ( root , 'prefix' ) 713local numli =prefix and trim ( node_text ( prefix )): match ( '%d' ) -- Numbered listitem? 714local sib =root : prev_sibling () 715local prev_li =sib and sib : type () == 'line_li' 716local cssclass =numli and 'help-li-num' or 'help-li' 717 718-- Conjoin list items separated by blank lines (wrapped in separate blocks). 719if not prev_li then 720local parent_block =root : parent () 721local prev_block =parent_block and parent_block : prev_sibling () 722local prev_last =prev_block and prev_block : type () == 'block' and last ( prev_block ) 723if prev_last and prev_last : type () == 'line_li' then 724prev_li =true 725sib =prev_last 726end 727end 728 729if not prev_li then 730opt . indent =1 731-- Track the leading whitespace for each indent level so that we can dedent 732-- to the correct level later. 733opt . indent_ws ={ ws () } 734else 735opt . indent_ws =opt . indent_ws or { ws () } 736local sib_ws =ws ( sib ) 737local this_ws =ws () 738if get_indent ( node_text ()) == 0 then 739opt . indent =1 740opt . indent_ws ={ this_ws } 741elseif this_ws > sib_ws then 742-- Previous sibling is logically the _parent_ if it is indented less. 743opt . indent =opt . indent + 1 744opt . indent_ws [ opt . indent ] =this_ws 745elseif 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. 748while opt . indent > 1 and ( opt . indent_ws [ opt . indent ] or '' ) > this_ws do 749opt . indent_ws [ opt . indent ] =nil 750opt . indent =opt . indent - 1 751end 752opt . indent_ws [ opt . indent ] =this_ws 753end 754end 755local margin =opt . indent == 1 and '' or ( 'margin-left: %drem;' ): format (( 1.5 * opt . indent )) 756 757return string . format ( '<div class="%s" style="%s">%s</div>' , cssclass , margin , text ) 758elseif node_name == 'taglink' or node_name == 'optionlink' then 759local helppage , tagname , ignored =validate_link ( root , opt . buf , opt . fname ) 760if ignored or not helppage then 761return html_esc ( node_text ( root )) 762end 763local s =( '%s<a href="/doc/user/%s#%s">%s</a>' ): format ( 764ws (), 765helppage , 766url_encode ( tagname ), 767html_esc ( tagname ) 768) 769if opt . old and node_name == 'taglink' then 770s =fix_tab_after_conceal ( s , node_text ( root : next_sibling ())) 771end 772return s 773elseif vim . list_contains ( { 'codespan' , 'keycode' } , node_name ) then 774if root : has_error () then 775return text 776end 777local s =( '%s<code>%s</code>' ): format ( ws (), trimmed ) 778if opt . old and node_name == 'codespan' then 779s =fix_tab_after_conceal ( s , node_text ( root : next_sibling ())) 780end 781return s 782elseif node_name == 'argument' then 783return ( '%s<code>%s</code>' ): format ( ws (), trim ( node_text ( root ))) 784elseif node_name == 'codeblock' then 785return text 786elseif node_name == 'language' then 787language =node_text ( root ) 788return '' 789elseif node_name == 'code' then -- Highlighted codeblock (child). 790if is_blank ( text ) then 791return '' 792end 793local code ---@type string 794if language then 795code =( '<pre><code class="language-%s">%s</code></pre>' ): format ( 796language , 797trim ( trim_indent ( text ), 2 ) 798) 799language =nil 800else 801code =( '<pre>%s</pre>' ): format ( trim ( trim_indent ( text ), 2 )) 802end 803return code 804elseif node_name == 'tag' then -- anchor, h4 pseudo-heading 805if root : has_error () then 806return text 807end 808local in_heading =vim . list_contains ( { 'h1' , 'h2' , 'h3' } , parent ) 809local h4 =not in_heading and not next_ and get_indent ( node_text ()) > 8 -- h4 pseudo-heading 810local cssclass =h4 and 'help-tag-right' or 'help-tag' 811local tagname =node_text ( root : child ( 1 ), false ) 812if vim . tbl_count ( stats . first_tags ) < 2 then 813-- Force the first 2 tags in the doc to be anchored at the main heading. 814table . insert ( stats . first_tags , tagname ) 815return '' 816end 817local el ='span' 818local encoded_tagname =url_encode ( tagname ) 819local s =( '%s<%s id="%s" class="%s"><a href="#%s">%s</a></%s>' ): format ( 820ws (), 821el , 822encoded_tagname , 823cssclass , 824encoded_tagname , 825trimmed , 826el 827) 828if opt . old then 829s =fix_tab_after_conceal ( s , node_text ( root : next_sibling ())) 830end 831 832if 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> 836return string . format ( '<span class="help-heading-tags">%s' , s ) 837elseif in_heading and next_ == nil then 838-- End the <span> container for tags in a heading. 839return string . format ( '%s</span>' , s ) 840end 841return s .. ( h4 and '<br>' or '' ) -- HACK: <br> avoids h4 pseudo-heading mushing with text. 842elseif node_name == 'delimiter' or node_name == 'modeline' then 843return '' 844elseif node_name == 'ERROR' then 845if ignore_parse_error ( opt . fname , trimmed ) then 846return text 847end 848 849-- Store the raw text to give context to the bug report. 850local sample_text =level > 0 and getbuflinestr ( root , opt . buf , 3 ) or '[top level!]' 851table . insert ( stats . parse_errors , sample_text ) 852return ( '<a class="parse-error" target="_blank" title="Report bug... (parse error)" href="%s">%s</a>' ): format ( 853get_bug_url_vimdoc ( opt . fname , opt . to_fname , sample_text ), 854trimmed 855) 856else -- Unknown token. 857local sample_text =level > 0 and getbuflinestr ( root , opt . buf , 3 ) or '[top level!]' 858return ( '<a class="unknown-token" target="_blank" title="Report bug... (unhandled token "%s")" href="%s">%s</a>' ): format ( 859node_name , 860get_bug_url_nvim ( opt . fname , opt . to_fname , sample_text , node_name ), 861trimmed 862), 863( 'unknown-token:"%s"' ): format ( node_name ) 864end 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 ) 874local function node_text ( node , ws_ ) 875node =node or root 876ws_ =( ws_ == nil or ws_ == true ) and getws ( node , opt . buf ) or '' 877return string . format ( '%s%s' , ws_ , vim . treesitter . get_node_text ( node , opt . buf )) 878end 879 880-- Gets leading whitespace of `node`. 881local function ws ( node ) 882node =node or root 883local 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 ? 886if ws_ == '' then 887ws_ =vim . treesitter . get_node_text ( node , opt . buf ): match ( '^%s+' ) or '' 888end 889return ws_ 890end 891 892local node_name =( root . named and root : named ()) and root : type () or nil 893local prev , next_ =get_prev_next ( root ) 894-- Parent kind (string). 895local parent =root : parent () and root : parent (): type () or nil 896 897local text ='' 898local trimmed ---@type string 899if root : named_child_count () == 0 or node_name == 'ERROR' then 900text =node_text () 901trimmed =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 906if parent ~= 'url' then 907text =typ_esc ( text ) 908end 909else 910-- Process children and join them with whitespace. 911for node , _ in root : iter_children () do 912if node : named () then 913local r =ts_node_to_typ ( node , level + 1 , lang_tree , opt , stats ) 914text =string . format ( '%s%s' , text , r ) 915end 916end 917trimmed =trim ( text ) 918end 919 920if node_name == 'help_file' then -- root node 921return text 922elseif node_name == 'url' then 923local fixed_url , removed_chars =fix_url ( trimmed ) 924return ( '%s#link("%s")%s' ): format ( ws (), typ_str_esc ( fixed_url ), removed_chars ) 925elseif node_name == 'word' or node_name == 'uppercase_name' then 926return text 927elseif node_name == 'note' then 928return ( '*%s*' ): format ( text ) 929elseif node_name == 'h1' or node_name == 'h2' or node_name == 'h3' then 930if is_noise ( text , stats . noise_lines ) then 931return '' -- Discard common "noise" lines. 932end 933-- Remove tags from ToC text. 934local heading_node =first ( root , 'heading' ) 935local hname =trim ( node_text ( heading_node ): gsub ( '%*.*%*' , '' )) 936if not heading_node or hname == '' then 937return '' -- Spurious "===" or "---" in the help doc. 938end 939 940local heading_level =tonumber ( string . sub ( node_name , - 1 )) 941if not heading_level then 942(( 'Cannot parse heading level from node name %s' ): format ( node_name )) 943return '' 944end 945return ( '%s %s' ): format ( string . rep ( '=' , heading_level ), trimmed ) 946elseif node_name == 'heading' then 947return trimmed 948elseif node_name == 'column_heading' then 949if root : has_error () then 950return text 951end 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 956return ( '```\n%s\n```\n' ): format ( trimmed ) 957elseif node_name == 'block' then 958if is_blank ( text ) then 959return '' 960end 961return ( '%s\n' ): format ( text ) 962elseif node_name == 'line' then 963if 964( parent ~= 'codeblock' and parent ~= 'code' ) 965and ( is_blank ( text ) or is_noise ( text , stats . noise_lines )) 966then 967return '' -- Discard common "noise" lines. 968end 969-- XXX: Avoid newlines (too much whitespace) after block elements in old (preformatted) layout. 970local old_after_block =opt . old 971and root : child ( 0 ) 972and vim . list_contains ( { 'column_heading' , 'h1' , 'h2' , 'h3' } , root : child ( 0 ): type ()) 973 974if parent == 'codeblock' or parent == 'code' then 975return text 976elseif old_after_block then 977return trim ( text ) 978else 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) 981return string . format ( '%s \\ \n' , text ) 982end 983elseif parent == 'line_li' and node_name == 'prefix' then 984return '' 985elseif node_name == 'line_li' then 986-- Just writing the text - indentation needs improvements 987return text 988elseif 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. 994return ( ' #underline[%s]' ): format ( text ) 995elseif vim . list_contains ( { 'codespan' , 'keycode' } , node_name ) then 996if root : has_error () then 997return text 998end 999return ( '%s`%s`' ): format ( ws (), trimmed ) 1000elseif node_name == 'argument' then 1001return ( '%s`%s`' ): format ( ws (), trim ( node_text ( root ))) 1002elseif node_name == 'codeblock' then 1003return text 1004elseif node_name == 'language' then 1005language =node_text ( root ) 1006return '' 1007elseif node_name == 'code' then -- Highlighted codeblock (child). 1008if is_blank ( text ) then 1009return '' 1010end 1011local code ---@type string 1012if language then 1013code =( '```%s\n%s\n```' ): format ( language , trim ( trim_indent ( text ), 2 )) 1014language =nil 1015else 1016code =( '\n```\n%s\n```\n' ): format ( trim ( trim_indent ( text ), 2 )) 1017end 1018return code 1019elseif node_name == 'tag' then -- anchor, h4 pseudo-heading 1020if root : has_error () then 1021return text 1022end 1023local in_heading =vim . list_contains ( { 'h1' , 'h2' , 'h3' } , parent ) 1024local tagname =node_text ( root : child ( 1 ), false ) 1025-- NOTE: the <%s> syntax doesn't work because it terminates the heading 1026local s =( '%s%s #label("%s")' ): format ( ws (), text , typ_str_esc ( tagname )) 1027if opt . old then 1028s =fix_tab_after_conceal ( s , node_text ( root : next_sibling ())) 1029end 1030 1031if 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) 1035return ( ' #h(1fr) %s' ): format ( s ) 1036end 1037return s 1038elseif node_name == 'delimiter' then 1039return '\n' 1040elseif node_name == 'modeline' then 1041return '' 1042else -- Unknown token. 1043local sample_text =level > 0 and getbuflinestr ( root , opt . buf , 3 ) or '[top level!]' 1044if node_name == 'ERROR' then 1045if ignore_parse_error ( opt . fname , trimmed ) then 1046return text 1047end 1048table . insert ( stats . parse_errors , sample_text ) 1049end 1050(( 'Unexpected token %s: %s' ): format ( node_name , sample_text )) 1051return '' 1052end 1053end 1054 1055--- @param dir string e.g. '$VIMRUNTIME/doc' 1056--- @param include string[]|nil 1057--- @return string[] 1058local function get_helpfiles ( dir , include ) 1059local rv ={} 1060for f , type in vim . fs . dir ( dir ) do 1061if 1062vim . endswith ( f , '.txt' ) 1063and type == 'file' 1064and ( not include or vim . list_contains ( include , f )) 1065then 1066local fullpath =vim . fn . fnamemodify (( '%s/%s' ): format ( dir , f ), ':p' ) 1067table . insert ( rv , fullpath ) 1068end 1069end 1070return 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> 1078local m ={} 1079-- Load a random help file to convince taglist() to do its job. 1080vim . cmd ( string . format ( 'split %s/api.txt' , help_dir )) 1081vim . cmd ( 'lcd %:p:h' ) 1082local tags =vim . fn . taglist ( '.*' ) --[[ @as {name: string, filename: string}[] ]] 1083for _ , item in ipairs ( tags ) do 1084if vim . endswith ( item . filename , '.txt' ) then 1085m [ item . name ] =item . filename 1086end 1087end 1088vim . cmd ( 'q!' ) 1089 1090return m 1091end 1092 1093--- Populates the helptags map. 1094local function get_helptags ( help_dir ) 1095local m =_get_helptags ( help_dir ) 1096 1097--- XXX: Append tags from netrw, until we remove it... 1098local netrwtags =_get_helptags ( vim . fs . normalize ( '$VIMRUNTIME/pack/dist/opt/netrw/doc/' )) 1099m =vim . tbl_extend ( 'keep' , m , netrwtags ) 1100 1101return 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 () 1106if not vim . o . runtimepath : find ( 'build/lib/nvim/' ) then 1107vim . cmd [[set runtimepath^=./build/lib/nvim/]] 1108end 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 ) 1117local buf ---@type integer 1118 1119if text then 1120vim . cmd ( 'split new' ) -- Text contents. 1121vim . api . nvim_put ( vim . split ( text , '\n' ), '' , false , false ) 1122vim . cmd ( 'setfiletype help' ) 1123buf =vim . api . nvim_get_current_buf () 1124elseif type ( fname ) == 'string' then 1125vim . cmd ( 'split ' .. vim . fn . fnameescape ( fname )) -- Filename. 1126buf =vim . api . nvim_get_current_buf () 1127else 1128-- Left for debugging 1129---@diagnostic disable-next-line: no-unknown 1130buf =fname 1131vim . cmd ( 'sbuffer ' .. tostring ( fname )) -- Buffer number. 1132end 1133local lang_tree =assert ( vim . treesitter . get_parser ( buf , nil )) 1134lang_tree : parse () 1135return 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 ) 1146local stats ={ 1147parse_errors ={} , 1148} 1149local lang_tree , buf =parse_buf ( fname , nil ) 1150for _ , tree in ipairs ( lang_tree : trees ()) do 1151visit_validate ( tree : root (), 0 , tree , { 1152buf =buf , 1153fname =fname , 1154request_urls =request_urls , 1155} , stats ) 1156end 1157lang_tree : destroy () 1158vim . cmd . close () 1159return 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 ) 1172local stats ={ 1173noise_lines ={} , 1174parse_errors ={} , 1175first_tags ={} , -- Track the first few tags in doc. 1176} 1177local lang_tree , buf =parse_buf ( fname , text ) 1178---@type nvim.gen_help_html.heading[] 1179local headings ={} -- Headings (for ToC). 2-dimensional: h1 contains h2/h3. 1180local title =to_titlecase ( basename_noext ( fname )) 1181 1182local main ='' 1183for _ , tree in ipairs ( lang_tree : trees ()) do 1184main =main 1185.. ( 1186ts_node_to_html ( 1187tree : root (), 11880 , 1189tree , 1190headings , 1191{ buf =buf , old =old , fname =fname , to_fname =to_fname , indent =1 } , 1192stats 1193) 1194) 1195end 1196 1197local frontmatter =vim . json . encode ( { 1198title =title , 1199layout ='single' , -- Hugo-specific, to make _index.html the same as the other pages 1200aliases ={ -- Hugo-specific, make /api.html redirect to /api/ 1201vim . fs . joinpath ( '/doc/user' , vim . fs . basename ( to_fname )), 1202} , 1203params ={ 1204firstTag1 =stats . first_tags [ 1 ] or '' , 1205firstTag2 =stats . first_tags [ 2 ] or '' , 1206basename =vim . fs . basename ( fname ), 1207commit =commit , 1208parseErrors =# stats . parse_errors , 1209bugUrl =get_bug_url_nvim ( fname , to_fname , 'TODO' , nil ), 1210noiseLines =html_esc ( table . concat ( stats . noise_lines , '\n' )), 1211noiseLinesCount =# stats . noise_lines , 1212headings =headings , 1213} , 1214} , { indent =' ' , sort_keys =true } ) 1215 1216local html =( '%s\n%s' ): format ( frontmatter , main ) 1217 1218vim . cmd ( 'q!' ) 1219lang_tree : destroy () 1220return 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 ) 1234local stats ={ 1235noise_lines ={} , 1236parse_errors ={} , 1237} 1238local lang_tree , buf =parse_buf ( fname , text ) 1239local title =to_titlecase ( basename_noext ( fname )) 1240 1241local typ =( '= %s\n' ): format ( typ_esc ( trim ( title ))) 1242for _ , tree in ipairs ( lang_tree : trees ()) do 1243typ =typ 1244.. ( 1245ts_node_to_typ ( 1246tree : root (), 12470 , 1248tree , 1249{ buf =buf , old =old , fname =fname , to_fname =to_fname , indent =1 } , 1250stats 1251) 1252) 1253end 1254 1255-- Add page break at the bottom, so that merging .typ files before conversion 1256-- results in page breaks in the right places 1257local page_break ='#pagebreak()' 1258typ =( '%s\n%s' ): format ( typ , page_break ) 1259 1260vim . cmd ( 'q!' ) 1261lang_tree : destroy () 1262return 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 ) 1269assert ( tagmap , '`tagmap` not generated yet' ) 1270local t ={} ---@type table<string, string> 1271for tag , f in pairs ( tagmap ) do 1272-- "foo.txt" 1273local helpfile =vim . fs . basename ( f ) 1274-- "foo.html" 1275local htmlpage =assert ( get_helppage_html ( helpfile )) 1276-- "foo.html#tag" 1277t [ tag ] =( '%s#%s' ): format ( htmlpage , url_encode ( tag )) 1278end 1279tofile ( fname , vim . json . encode ( t , { indent =' ' , sort_keys =true } )) 1280end 1281 1282local function gen_helptag_html ( fname ) 1283local frontmatter =vim . json . encode ( { 1284title ='Helptag redirect' , 1285layout ='helptag' , 1286aliases ={ vim . fs . basename ( fname ) } , 1287} , { indent =' ' , sort_keys =true } ) 1288tofile ( fname , frontmatter ) 1289end 1290 1291-- Testing 1292 1293local function ok ( cond , expected , actual , message ) 1294assert ( 1295( not expected and not actual ) or ( expected and actual ), 1296'if "expected" is given, "actual" is also required' 1297) 1298if expected then 1299assert ( 1300cond , 1301( '%sexpected %s, got: %s' ): format ( 1302message and ( message .. '\n' ) or '' , 1303vim . inspect ( expected ), 1304vim . inspect ( actual ) 1305) 1306) 1307else 1308assert ( cond ) 1309end 1310 1311return true 1312end 1313local function eq ( expected , actual , message ) 1314return ok ( vim . deep_equal ( expected , actual ), expected , actual , message ) 1315end 1316 1317function M . _test () 1318tagmap =get_helptags ( '$VIMRUNTIME/doc' ) 1319helpfiles =get_helpfiles ( vim . fs . normalize ( '$VIMRUNTIME/doc' )) 1320 1321ok ( vim . tbl_count ( tagmap ) > 3000 , '>3000' , vim . tbl_count ( tagmap )) 1322ok ( 1323vim . endswith ( tagmap [ 'vim.diagnostic.set()' ], 'diagnostic.txt' ), 1324tagmap [ 'vim.diagnostic.set()' ], 1325'diagnostic.txt' 1326) 1327ok ( vim . endswith ( tagmap [ '%:s' ], 'cmdline.txt' ), tagmap [ '%:s' ], 'cmdline.txt' ) 1328ok ( is_noise ( [[vim:tw=78:isk=!-~,^*,^\|,^\":ts=8:noet:ft=help:norl:]] )) 1329ok ( is_noise ( [[ NVIM REFERENCE MANUAL by Thiago de Arruda ]] )) 1330ok ( not is_noise ( [[vim:tw=78]] )) 1331 1332eq ( 0 , get_indent ( 'a' )) 1333eq ( 1 , get_indent ( ' a' )) 1334eq ( 2 , get_indent ( ' a\n b\n c\n' )) 1335eq ( 5 , get_indent ( ' a\n \n b\n c\n d\n e\n' )) 1336eq ( 1337'a\n \n b\n c\n d\n e\n' , 1338trim_indent ( ' a\n \n b\n c\n d\n e\n' ) 1339) 1340 1341local fixed_url , removed_chars =fix_url ( 'https://example.com).' ) 1342eq ( 'https://example.com' , fixed_url ) 1343eq ( ').' , removed_chars ) 1344fixed_url , removed_chars =fix_url ( 'https://example.com.)' ) 1345eq ( 'https://example.com.' , fixed_url ) 1346eq ( ')' , removed_chars ) 1347fixed_url , removed_chars =fix_url ( 'https://example.com.' ) 1348eq ( 'https://example.com' , fixed_url ) 1349eq ( '.' , removed_chars ) 1350fixed_url , removed_chars =fix_url ( 'https://example.com)' ) 1351eq ( 'https://example.com' , fixed_url ) 1352eq ( ')' , removed_chars ) 1353fixed_url , removed_chars =fix_url ( 'https://example.com' ) 1354eq ( 'https://example.com' , fixed_url ) 1355eq ( '' , removed_chars ) 1356 1357( '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 ) 1369local helpfile_tag =( helpfile : gsub ( '%.txt$' , '' )): gsub ( '_' , '-' ) -- "dev_tools.txt" => "dev-tools" 1370local redirect_from =redirects [ helpfile ] 1371if not redirect_from then 1372return false 1373end 1374 1375local redirect_text =vim . text 1376. indent ( 13770 , 1378[[ 1379*%s* Nvim 1380 1381Document moved to: |%s| 1382 1383============================================================================== 1384Document moved 1385 1386Document moved to: |%s| 1387 1388============================================================================== 1389vim:tw=78:ts=8:ft=help:norl: 1390]] 1391) 1392: format ( redirect_from , helpfile_tag , helpfile_tag , helpfile_tag , helpfile_tag , helpfile_tag ) 1393local redirect_to_fname =get_helppage_html ( redirect_from , true ) 1394local redirect_to =( '%s/%s' ): format ( to_dir , redirect_to_fname ) 1395local redirect_html , _ = 1396gen_one_html ( redirect_from , redirect_text , redirect_to , false , commit or '?' ) 1397assert ( 1398redirect_html : find ( vim . pesc ( helpfile_tag )), 1399( 'not found in redirect html: %s' ): format ( helpfile_tag ) 1400) 1401tofile ( redirect_to , redirect_html ) 1402 1403(( 'generated (redirect) : %-15s => %s' ): format ( redirect_from , vim . fs . basename ( to_fname ))) 1404return 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 ) 1427vim . validate ( 'output_format' , output_format , 'string' ) 1428vim . validate ( 'help_dir' , help_dir , function ( d ) 1429return vim . fn . isdirectory ( vim . fs . normalize ( d )) == 1 1430end , 'valid directory' ) 1431vim . validate ( 'to_dir' , to_dir , 'string' ) 1432vim . validate ( 'include' , include , 'table' , true ) 1433vim . validate ( 'commit' , commit , 'string' , true ) 1434vim . validate ( 'parser_path' , parser_path , function ( f ) 1435return vim . fn . filereadable ( vim . fs . normalize ( f )) == 1 1436end , true , 'valid vimdoc.{so,dll,dylib} filepath' ) 1437 1438local err_count =0 1439local redirects_count =0 1440ensure_runtimepath () 1441 1442parser_path =parser_path and vim . fs . normalize ( parser_path ) or nil 1443if 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 1447vim . treesitter . language . add ( 'vimdoc' , { path =parser_path } ) 1448end 1449 1450tagmap =get_helptags ( vim . fs . normalize ( help_dir )) 1451helpfiles =get_helpfiles ( help_dir , include ) 1452to_dir =vim . fs . normalize ( to_dir ) 1453 1454(( 'output dir: %s\n\n' ): format ( to_dir )) 1455vim . fn . mkdir ( to_dir , 'p' ) 1456 1457if output_format == 'html' then 1458-- NOTE: Better for Hugo to be in static/, but works fine with contents/ as to_dir 1459gen_helptags_json (( '%s/helptags.json' ): format ( to_dir )) 1460gen_helptag_html (( '%s/helptag.html' ): format ( to_dir )) 1461end 1462 1463-- Map output formats to the function that outputs one file in that format 1464local generators ={ 1465html =gen_one_html , 1466typ =gen_one_typ , 1467} 1468local gen_one =generators [ output_format ] 1469 1470for _ , f in ipairs ( helpfiles ) do 1471-- "foo.txt" 1472local helpfile =vim . fs . basename ( f ) 1473 1474local to_fname ='' 1475if output_format == 'html' then 1476-- "to/dir/foo.html" 1477to_fname =( '%s/%s' ): format ( to_dir , get_helppage_html ( helpfile , true )) 1478else 1479to_fname =( '%s/%s.%s' ): format ( to_dir , helpfile : gsub ( '.txt' , '' ), output_format ) 1480end 1481 1482local converted_help , stats =gen_one ( f , nil , to_fname , not new_layout [ helpfile ], commit or '?' ) 1483tofile ( to_fname , converted_help ) 1484( 1485( 'generated (%-2s errors): %-15s => %s' ): format ( 1486# stats . parse_errors , 1487helpfile , 1488vim . fs . basename ( to_fname ) 1489) 1490) 1491 1492if output_format == 'html' then 1493local generated =gen_redirect_pages ( commit , helpfile , to_dir , to_fname ) 1494if generated then 1495redirects_count =redirects_count + 1 1496end 1497end 1498 1499err_count =err_count + # stats . parse_errors 1500end 1501 1502(( '\ngenerated %d pages' ): format ( # helpfiles + redirects_count )) 1503(( 'total errors: %d' ): format ( err_count )) 1504-- Why aren't the netrw tags found in neovim/docs/ CI? 1505(( 'invalid tags: %s' ): format ( vim . inspect ( invalid_links ))) 1506 1507if output_format == 'html' then 1508eq ( redirects_count , include and redirects_count or vim . tbl_count ( redirects )) -- sanity check 1509(( 'redirects: %d' ): format ( redirects_count )) 1510end 1511 1512( '\n' ) 1513 1514--- @type nvim.gen_help_html.gen_result 1515return { 1516helpfiles =helpfiles , 1517err_count =err_count , 1518invalid_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 ) 1538vim . validate ( 'help_dir' , help_dir , function ( d ) 1539return vim . fn . isdirectory ( vim . fs . normalize ( d )) == 1 1540end , 'valid directory' ) 1541vim . validate ( 'include' , include , 'table' , true ) 1542vim . validate ( 'parser_path' , parser_path , function ( f ) 1543return vim . fn . filereadable ( vim . fs . normalize ( f )) == 1 1544end , true , 'valid vimdoc.{so,dll,dylib} filepath' ) 1545local err_count =0 ---@type integer 1546local files_to_errors ={} ---@type table<string, string[]> 1547ensure_runtimepath () 1548 1549parser_path =parser_path and vim . fs . normalize ( parser_path ) or nil 1550if 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 1554vim . treesitter . language . add ( 'vimdoc' , { path =parser_path } ) 1555end 1556 1557tagmap =get_helptags ( vim . fs . normalize ( help_dir )) 1558helpfiles =get_helpfiles ( help_dir , include ) 1559 1560for _ , f in ipairs ( helpfiles ) do 1561local helpfile =vim . fs . basename ( f ) 1562local rv =validate_one ( f , request_urls ) 1563(( 'validated (%-4s errors): %s' ): format ( # rv . parse_errors , helpfile )) 1564if # rv . parse_errors > 0 then 1565files_to_errors [ helpfile ] =rv . parse_errors 1566vim . (( '%s' ): format ( vim . iter ( rv . parse_errors ): fold ( '' , function ( s , v ) 1567return s .. '\n ' .. v 1568end ))) 1569end 1570err_count =err_count + # rv . parse_errors 1571end 1572 1573-- Requests are async, wait for them to finish. 1574-- TODO(yochem): `:cancel()` tasks after #36146 1575vim . wait ( 20000 , function () 1576return pending_urls <= 0 1577end ) 1578ok ( pending_urls <= 0 , 'pending url checks' , pending_urls ) 1579 1580---@type nvim.gen_help_html.validate_result 1581return { 1582helpfiles =# helpfiles , 1583err_count =err_count , 1584parse_errors =files_to_errors , 1585invalid_links =invalid_links , 1586invalid_urls =invalid_urls , 1587invalid_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 ) 1601help_dir =vim . fs . normalize ( help_dir or '$VIMRUNTIME/doc' ) 1602( 'doc path = ' .. vim . uv . fs_realpath ( help_dir )) 1603 1604local rv =M . validate ( help_dir , nil , nil , request_urls ) 1605 1606-- Check that we actually found helpfiles. 1607ok ( rv . helpfiles > 100 , '>100 :help files' , rv . helpfiles ) 1608 1609eq ( {} , rv . parse_errors , 'no parse errors' ) 1610eq ( 0 , rv . err_count , 'no parse errors' ) 1611eq ( {} , rv . invalid_links , 'invalid tags in :help docs' ) 1612eq ( {} , rv . invalid_urls , 'invalid URLs in :help docs' ) 1613eq ( 1614{} , 1615rv . 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 ) 1627local tmpdir =vim . fs . dirname ( vim . fn . tempname ()) 1628help_dir =vim . fs . normalize ( help_dir or '$VIMRUNTIME/doc' ) 1629( 'doc path = ' .. vim . uv . fs_realpath ( help_dir )) 1630 1631-- Because gen() is slow (~30s), this test is limited to a few files. 1632local input ={ 'api.txt' , 'index.txt' , 'nvim.txt' } 1633local rv =M . gen ( 'html' , help_dir , tmpdir , input ) 1634eq ( # input , # rv . helpfiles ) 1635eq ( 0 , rv . err_count , 'parse errors in :help docs' ) 1636eq ( {} , rv . invalid_links , 'invalid tags in :help docs' ) 1637end 1638 1639return M