helptoc.vim (47382B)
1 vim9script noclear 2 3 # the Vim HelpTOC plugin, creates a table of contents in a popup 4 # Maintainer: Vim project 5 # Original Author: @lacygoill 6 # Latest Change: 2026 Aug 31 7 # 8 # Config {{{1 9 # g:helptoc {{{2 10 # Create the g:helptoc dict (used to specify the shell_prompt and other 11 # options) when it does not exist 12 g:helptoc = exists('g:helptoc') ? g:helptoc : {} 13 14 # Set the initial shell_prompt pattern matching a default bash prompt 15 g:helptoc.shell_prompt = get(g:helptoc, 'shell_prompt', '^\w\+@\w\+:\f\+\$\s') 16 17 # Track the prior prompt (used to reset b:toc if 'shell_prompt' changes) 18 g:helptoc.prior_shell_prompt = g:helptoc.shell_prompt 19 20 def UpdateUserSettings() #{{{2 21 22 if g:helptoc.shell_prompt != g:helptoc.prior_shell_prompt 23 # invalidate cache: user config has changed 24 unlet! b:toc 25 # reset the prior prompt to the new prompt 26 g:helptoc.prior_shell_prompt = g:helptoc.shell_prompt 27 endif 28 29 # helptoc popup presentation options{{{ 30 # Enable users to choose whether, in toc and help text popups, to have: 31 # - border (default [], which is a border, so is usually wanted) 32 # - borderchars (default single box drawing; use [] for Vim's defaults) 33 # - borderhighlight (default [], but a user may prefer something else) 34 # - close (default 'none'; mouse users may prefer 'button') 35 # - drag (default true, which is a popup_menu's default) 36 # - scrollbar (default false; for long tocs/HELP_TEXT true may be better) 37 # For example, in a Vim9 script .vimrc, these settings will produce tocs 38 # with borders that have the same highlight group as the inactive 39 # statusline, a scrollbar, and an 'X' close button: 40 # g:helptoc.popup_borderchars = get(g:helptoc, 'popup_borderchars', [' ']) 41 # g:helptoc.popup_borderhighlight = get(g:helptoc, 42 # 'popup_borderhighlight', ['StatusLineNC']) 43 # g:helptoc.popup_close = get(g:helptoc, 'popup_close', 'button') 44 # g:helptoc.popup_scrollbar = get(g:helptoc, 'popup_scrollbar', true) 45 # }}} 46 g:helptoc.popup_border = get(g:helptoc, 'popup_border', []) 47 g:helptoc.popup_borderchars = get(g:helptoc, 'popup_borderchars', 48 ['─', '│', '─', '│', '┌', '┐', '┘', '└']) 49 g:helptoc.popup_borderhighlight = get(g:helptoc, 'popup_borderhighlight', 50 []) 51 g:helptoc.popup_drag = get(g:helptoc, 'popup_drag', true) 52 g:helptoc.popup_close = get(g:helptoc, 'popup_close', 'none') 53 g:helptoc.popup_scrollbar = get(g:helptoc, 'popup_scrollbar', false) 54 # For sanitized tocs, allow the user to specify the level indicator 55 g:helptoc.level_indicator = get(g:helptoc, 'level_indicator', '| ') 56 enddef 57 58 UpdateUserSettings() 59 60 # Syntax {{{1 61 62 # Used by sanitized tocs (asciidoc, html, markdown, tex, vim, and xhtml) 63 def SanitizedTocSyntax(): void 64 silent execute "syntax match helptocLevel _^\\(" .. 65 g:helptoc.level_indicator .. "\\)*_ contained" 66 silent execute "syntax region helptocText start=_^\\(" .. 67 g:helptoc.level_indicator .. "\\)*_ end=_$_ contains=helptocLevel" 68 highlight link helptocText Normal 69 highlight link helptocLevel NonText 70 enddef 71 72 # Init {{{1 73 # Constants {{{2 74 # HELP_TEXT {{{3 75 const HELP_TEXT: list<string> =<< trim END 76 normal commands in help window 77 ────────────────────────────── 78 ? hide this help window 79 <C-J> scroll down one line 80 <C-K> scroll up one line 81 82 normal commands in TOC menu 83 ─────────────────────────── 84 j select next entry 85 k select previous entry 86 J same as j, and jump to corresponding line in main buffer 87 K same as k, and jump to corresponding line in main buffer 88 c select nearest entry from cursor position in main buffer 89 g select first entry 90 G select last entry 91 H collapse one level 92 L expand one level 93 p print selected entry on command-line 94 95 P same as p but automatically, whenever selection changes 96 press multiple times to toggle feature on/off 97 98 q quit menu 99 z redraw menu with selected entry at center 100 + increase width of popup menu 101 - decrease width of popup menu 102 / look for given text with fuzzy algorithm 103 ? show help window 104 105 <C-D> scroll down half a page 106 <C-U> scroll up half a page 107 s split window, and jump to selected entry 108 <PageUp> scroll down a whole page 109 <PageDown> scroll up a whole page 110 <Home> select first entry 111 <End> select last entry 112 113 title meaning 114 ───────────── 115 example: 12/34 (5/6) 116 broken down: 117 118 12 index of selected entry 119 34 index of last entry 120 5 index of deepest level currently visible 121 6 index of maximum possible level 122 123 tip 124 ─── 125 after inserting a pattern to look for with the / command, 126 if you press <Esc> instead of <CR>, you can then get 127 more context for each remaining entry by pressing J or K 128 END 129 130 # UPTOINC_H {{{3 131 const UPTOINC_H: string = '\v\c^%(%([<][^h][^>]*[>])|\s)*[<]h' 132 133 # MATCH_ENTRY {{{3 134 const MATCH_ENTRY: dict<dict<func: bool>> = { 135 136 help: {}, 137 138 # This lets the user get a TOC when piping `info(1)` to Vim:{{{ 139 # 140 # $ info coreutils | vim - 141 #}}} 142 # But it assumes that they have some heuristics to set the `info` filetype.{{{ 143 # 144 # Possibly by inspecting the first line from `scripts.vim`: 145 # 146 # if getline(1) =~ '^File: .*\.info, Node: .*, \%(Next\|Prev\): .*, Up: \|This is the top of the INFO tree.' 147 # setfiletype info 148 # endif 149 #}}} 150 info: { 151 1: (l: string, nextline): bool => l =~ '^\d\+\%(\.\d\+\)\+ ' && nextline =~ '^=\+$', 152 2: (l: string, nextline): bool => l =~ '^\d\+\%(\.\d\+\)\+ ' && nextline =~ '^-\+$', 153 }, 154 155 # For asciidoc, these patterns should match: 156 # https://docs.asciidoctor.org/asciidoc/latest/sections/titles-and-levels/ 157 asciidoc: { 158 1: (l: string, _): bool => l =~ '\v^%(\=|#)\s', 159 2: (l: string, _): bool => l =~ '\v^%(\={2}|#{2})\s', 160 3: (l: string, _): bool => l =~ '\v^%(\={3}|#{3})\s', 161 4: (l: string, _): bool => l =~ '\v^%(\={4}|#{4})\s', 162 5: (l: string, _): bool => l =~ '\v^%(\={5}|#{5})\s', 163 6: (l: string, _): bool => l =~ '\v^%(\={6}|#{6})\s', 164 }, 165 166 html: { 167 1: (l: string, _): bool => l =~ $"{UPTOINC_H}1", 168 2: (l: string, _): bool => l =~ $"{UPTOINC_H}2", 169 3: (l: string, _): bool => l =~ $"{UPTOINC_H}3", 170 4: (l: string, _): bool => l =~ $"{UPTOINC_H}4", 171 5: (l: string, _): bool => l =~ $"{UPTOINC_H}5", 172 6: (l: string, _): bool => l =~ $"{UPTOINC_H}6", 173 }, 174 175 man: { 176 1: (l: string, _): bool => l =~ '^\S', 177 2: (l: string, _): bool => l =~ '\v^%( {3})=\S', 178 3: (l: string, _): bool => l =~ '\v^\s+%(%(\+|-)\S+,\s+)*(\+|-)\S+' 179 }, 180 181 # For markdown, these patterns should match: 182 # https://spec.commonmark.org/0.31.2/#atx-headings and 183 # https://spec.commonmark.org/0.31.2/#setext-headings 184 markdown: { 185 1: (l: string, nextline: string): bool => 186 (l =~ '\v^ {0,3}#%(\s|$)' || nextline =~ '\v^ {0,3}\=+$') && 187 l =~ '\S', 188 2: (l: string, nextline: string): bool => 189 (l =~ '\v^ {0,3}##%(\s|$)' || nextline =~ '\v^ {0,3}-+$') && 190 l =~ '\S', 191 3: (l: string, _): bool => l =~ '\v {0,3}#{3}%(\s|$)', 192 4: (l: string, _): bool => l =~ '\v {0,3}#{4}%(\s|$)', 193 5: (l: string, _): bool => l =~ '\v {0,3}#{5}%(\s|$)', 194 6: (l: string, _): bool => l =~ '\v {0,3}#{6}%(\s|$)', 195 }, 196 197 terminal: { 198 1: (l: string, _): bool => l =~ g:helptoc.shell_prompt 199 }, 200 201 # For LaTeX, this should meet 202 # https://mirrors.rit.edu/CTAN/info/latex2e-help-texinfo/latex2e.pdf 203 # including: 204 # para 6.3: 205 # \section{Heading} 206 # \section[Alternative ToC Heading]{Heading} 207 # para 25.1.2: 208 # \section*{Not for the TOC heading} 209 # \addcontentsline{toc}{section}{Alternative ToC Heading} 210 tex: { 211 1: (l: string, _): bool => l =~ '^[\\]\(\%(part\|chapter\)' .. 212 '\%([\u005B{]\)\|addcontentsline{toc}{\%(part\|chapter\)\)', 213 2: (l: string, _): bool => l =~ '^[\\]\%(section' .. 214 '\%([\u005B{]\)\|addcontentsline{toc}{section}\)', 215 3: (l: string, _): bool => l =~ '^[\\]\%(subsection' .. 216 '\%([\u005B{]\)\|addcontentsline{toc}{subsection}\)', 217 4: (l: string, _): bool => l =~ '^[\\]\%(subsubsection' .. 218 '\%([\u005B{]\)\|addcontentsline{toc}{subsubsection}\)', 219 }, 220 221 vim: { 222 1: (l: string, _): bool => l =~ '\v\{{3}1', 223 2: (l: string, _): bool => l =~ '\v\{{3}2', 224 3: (l: string, _): bool => l =~ '\v\{{3}3', 225 4: (l: string, _): bool => l =~ '\v\{{3}4', 226 5: (l: string, _): bool => l =~ '\v\{{3}5', 227 6: (l: string, _): bool => l =~ '\v\{{3}6', 228 }, 229 230 xhtml: { 231 1: (l: string, _): bool => l =~ $"{UPTOINC_H}1", 232 2: (l: string, _): bool => l =~ $"{UPTOINC_H}2", 233 3: (l: string, _): bool => l =~ $"{UPTOINC_H}3", 234 4: (l: string, _): bool => l =~ $"{UPTOINC_H}4", 235 5: (l: string, _): bool => l =~ $"{UPTOINC_H}5", 236 6: (l: string, _): bool => l =~ $"{UPTOINC_H}6", 237 } 238 } 239 240 # HELP_RULERS {{{3 241 const HELP_RULERS: dict<string> = { 242 '=': '^=\{40,}$', 243 '-': '^-\{40,}', 244 } 245 const HELP_RULER: string = HELP_RULERS->values()->join('\|') 246 247 # HELP_TAG {{{3 248 # The regex is copied from the help syntax plugin 249 const HELP_TAG: string = '\*[#-)!+-~]\+\*\%(\s\|$\)\@=' 250 251 # Adapted from `$VIMRUNTIME/syntax/help.vim`.{{{ 252 # 253 # The original regex is: 254 # 255 # ^[-A-Z .][-A-Z0-9 .()_]*\ze\(\s\+\*\|$\) 256 # 257 # Allowing a space or a hyphen at the start can give false positives, and is 258 # useless, so we don't allow them. 259 #}}} 260 261 # HELP_HEADLINE {{{3 262 const HELP_HEADLINE: string = '^\C[A-Z.][-A-Z0-9 .()_]*\%(\s\+\*+\@!\|$\)' 263 # ^--^ 264 # To prevent some false positives under `:help feature-list`. 265 # Others {{{2 266 var lvls: dict<number> 267 def InitHelpLvls() 268 lvls = { 269 '*01.1*': 0, 270 '1.': 0, 271 '1.2': 0, 272 '1.2.3': 0, 273 'header ~': 0, 274 HEADLINE: 0, 275 tag: 0, 276 } 277 enddef 278 279 var fuzzy_entries: list<dict<any>> 280 var help_winid: number 281 var print_entry: bool 282 var selected_entry_match: number 283 284 # Interface {{{1 285 export def Open() #{{{2 286 g:helptoc.type = GetType() 287 if !MATCH_ENTRY->has_key(g:helptoc.type) 288 return 289 endif 290 if g:helptoc.type == 'terminal' && win_gettype() == 'popup' 291 # trying to deal with a popup menu on top of a popup terminal seems 292 # too tricky for now 293 echomsg 'does not work in a popup window; only in a regular window' 294 return 295 endif 296 297 UpdateUserSettings() 298 299 # invalidate the cache if the buffer's contents has changed 300 if exists('b:toc') && &filetype != 'man' 301 if b:toc.changedtick != b:changedtick 302 # in a terminal buffer, `b:changedtick` does not change 303 || g:helptoc.type == 'terminal' && line('$') > b:toc.linecount 304 unlet! b:toc 305 endif 306 endif 307 308 if !exists('b:toc') 309 SetToc() 310 endif 311 312 var winpos: list<number> = winnr()->win_screenpos() 313 var height: number = winheight(0) - 2 314 var width: number = winwidth(0) 315 b:toc.width = b:toc.width ?? width / 3 316 # the popup needs enough space to display the help message in its title 317 if b:toc.width < 30 318 b:toc.width = 30 319 endif 320 # Is `popup_menu()` OK with a list of dictionaries?{{{ 321 # 322 # Yes, see `:help popup_create-arguments`. 323 # Although, it expects dictionaries with the keys `text` and `props`. 324 # But we use dictionaries with the keys `text` and `lnum`. 325 # IOW, we abuse the feature which lets us use text properties in a popup. 326 #}}} 327 var winid: number = GetTocEntries() 328 ->popup_menu({ 329 line: winpos[0], 330 col: winpos[1] + width - 1, 331 pos: 'topright', 332 highlight: g:helptoc.type == 'terminal' ? 'Terminal' : 'Normal', 333 minheight: height, 334 maxheight: height, 335 minwidth: b:toc.width, 336 maxwidth: b:toc.width, 337 filter: Filter, 338 callback: Callback, 339 border: g:helptoc.popup_border, 340 borderchars: g:helptoc.popup_borderchars, 341 borderhighlight: g:helptoc.popup_borderhighlight, 342 close: g:helptoc.popup_close, 343 drag: g:helptoc.popup_drag, 344 scrollbar: g:helptoc.popup_scrollbar, 345 }) 346 # Specify filetypes using sanitized toc syntax{{{ 347 # Those filetypes have a normalized toc structure. The top level is 348 # unprefixed and levels 2 to 6 are prefixed, by default, with a vertical 349 # line and space for each level below 1: 350 # Level 1 351 # | Level 2 352 # ... 353 # | | | | | Level 6 }}} 354 final SanitizedTocSyntaxTypes: list<string> = 355 ['asciidoc', 'html', 'markdown', 'tex', 'vim', 'xhtml'] 356 if index(SanitizedTocSyntaxTypes, g:helptoc.type) != -1 357 # Specified types' toc popups use a common syntax 358 Win_execute(winid, 'SanitizedTocSyntax()') 359 else 360 # Other types' toc popups use the same syntax as the buffer itself 361 Win_execute(winid, [$'ownsyntax {&filetype}', '&l:conceallevel = 3']) 362 endif 363 # In a help file, we might reduce some noisy tags to a trailing asterisk. 364 # Hide those. 365 if g:helptoc.type == 'help' 366 matchadd('Conceal', '\*$', 0, -1, {window: winid}) 367 endif 368 SelectNearestEntryFromCursor(winid) 369 370 # Can't set the title before jumping to the relevant line, otherwise the 371 # indicator in the title might be wrong 372 SetTitle(winid) 373 enddef 374 375 # Core {{{1 376 def SetToc() #{{{2 377 # Lambdas: 378 # CHARACTER_REFERENCES_TO_CHARACTERS {{{3 379 # These are used for AsciiDoc, Markdown, and [X]HTML, all of which allow 380 # for decimal, hexadecimal, and XML predefined entities. 381 # Decimal character references: e.g., § to § 382 # Hexadecimal character references: e.g., § to § 383 # XML predefined entities to chars: e.g., < to < 384 # All HTML5 named character references could be handled, though is that 385 # warranted for the few that may appear in a toc entry, especially when 386 # they are often mnemonic? Future: A common Vim dict/enum could be useful? 387 const CHARACTER_REFERENCES_TO_CHARACTERS = (text: string): string => 388 text->substitute('\v\�*([1-9]\d{0,6});', 389 '\=nr2char(str2nr(submatch(1), 10), 1)', 'g') 390 ->substitute('\c\v\�*([1-9a-f][[:xdigit:]]{1,5});', 391 '\=nr2char(str2nr(submatch(1), 16), 1)', 'g') 392 ->substitute('\C&', '\="\u0026"', 'g') 393 ->substitute('\C'', "\u0027", 'g') 394 ->substitute('\C>', "\u003E", 'g') 395 ->substitute('\C<', "\u003C", 'g') 396 ->substitute('\C"', "\u0022", 'g') 397 398 # SANITIZE_ASCIIDOC {{{3 399 # 1 - Substitute the = or # heading markup with the level indicator 400 # 2 - Substitute XML predefined, dec, and hex char refs in the entry 401 # AsciiDoc recommends only using named char refs defined in XML: 402 # https://docs.asciidoctor.org/asciidoc/latest/subs/replacements/ 403 const SANITIZE_ASCIIDOC = (text: string): string => 404 text->substitute('\v^(\={1,6}|#{1,6})\s+', 405 '\=repeat(g:helptoc.level_indicator, len(submatch(1)) - 1)', '') 406 ->CHARACTER_REFERENCES_TO_CHARACTERS() 407 408 # SANITIZE_HTML {{{3 409 # 1 - Remove any leading spaces or tabs 410 # 2 - Remove any <!--HTML comments--> 411 # 3 - Remove any <?processing_instructions?> 412 # 4 - Remove any leading tags (and any blanks) other than <h1 to <h6 413 # 5 - Remove any persisting leading blanks 414 # 6 - Handle empty XHTML headings, e.g., <h6 /> 415 # 7 - Remove trailing content following the </h[1-6]> 416 # 8 - Remove the <h1 417 # 9 - Substitute the h2 to h6 heading tags with level indicator/level 418 # 10 - Remove intra-heading tags like <em>, </em>, <strong>, etc. 419 # 11 - Substitute XML predefined, dec and hex character references 420 const SANITIZE_HTML = (text: string): string => 421 text->substitute('^\s*', '', '') 422 ->substitute('[<]!--.\{-}--[>]', '', 'g') 423 ->substitute('[<]?[^?]\+?[>]', '', 'g') 424 ->substitute('\v%([<][^Hh][^1-6]?[^>][>])*\s*', '', '') 425 ->substitute('^\s\+', '', '') 426 ->substitute('\v[<][Hh]([1-6])\s*[/][>].*', 427 '\=repeat(g:helptoc.level_indicator, ' .. 428 'str2nr(submatch(1)) - 1) ' .. 429 '.. "[Empty heading " .. submatch(1) .. "]"', '') 430 ->substitute('[<][/][Hh][1-6][>].*$', '', '') 431 ->substitute('[<][Hh]1[^>]*[>]', '', '') 432 ->substitute('\v[<][Hh]([2-6])[^>]*[>]', 433 '\=repeat(g:helptoc.level_indicator, ' .. 434 'str2nr(submatch(1)) - 1)', '') 435 ->substitute('[<][/]\?[[:alpha:]][^>]*[>]', '', 'g') 436 ->CHARACTER_REFERENCES_TO_CHARACTERS() 437 438 # SANITIZE_MARKDOWN #{{{3 439 # 1 - Hyperlink incl image, e.g. [](\uri), to Vim... 440 # 2 - Hyperlink [text](/uri) to text 441 # 3 - Substitute the # ATX heading markup with the level indicator/level 442 # The omitted markup reflects CommonMark Spec: 443 # https://spec.commonmark.org/0.31.2/#atx-headings 444 # 4 - Substitute decimal, hexadecimal, and XML predefined char refs 445 const SANITIZE_MARKDOWN = (text: string): string => 446 text->substitute('\v[\u005B][\u005D]' 447 .. '[(][^)]+[)][\u005D][(][^)]+[)]', '\1', '') 448 ->substitute('\v[\u005B]([^\u005D]+)[\u005D][(][^)]+[)]', 449 '\1', '') 450 ->substitute('\v^ {0,3}(#{1,6})\s*', 451 '\=repeat(g:helptoc.level_indicator, len(submatch(1)) - 1)', 452 '') 453 ->CHARACTER_REFERENCES_TO_CHARACTERS() 454 455 # SANITIZE_TERMINAL {{{3 456 # Omit the prompt, which may be very long and otherwise just adds clutter 457 const SANITIZE_TERMINAL = (text: string): string => 458 text->substitute('^' .. g:helptoc.shell_prompt, '', '') 459 460 # SANITIZE_TEX #{{{3 461 # 1 - Use any [toc-title] overrides to move its content into the 462 # {heading} instead of the (non-ToC) heading's text 463 # 2 - Replace \part{ or \addcontentsline{toc}{part} with '[PART] ' 464 # 3 - Omit \chapter{ or \addcontentsline{toc}{chapter} 465 # 4 - Omit \section{ or \addcontentsline{toc}{section} 466 # 5 - Omit \subsection{ or \addcontentsline{toc}{subsection} 467 # 6 - Omit \subsubsection{ or \addcontentsline{toc}{subsubsection} 468 # 7 - Omit the trailing } 469 # 8 - Unescape common escaped characters &%$_#{}~^\ 470 const SANITIZE_TEX = (text: string): string => 471 text->substitute('\v^[\\](part|chapter|%(sub){0,2}section)' .. 472 '[\u005B]([^\u005D]+).*', '\\\1{\2}', '') 473 ->substitute('^[\\]\(part\|addcontentsline{toc}{part}\){', 474 '[PART] ', '') 475 ->substitute('^[\\]\(chapter\|addcontentsline{toc}{chapter}\){', 476 '', '') 477 ->substitute('^[\\]\(section\|addcontentsline{toc}{section}\){', 478 '\=g:helptoc.level_indicator', '') 479 ->substitute('^[\\]\(subsection\|' .. 480 'addcontentsline{toc}{subsection}\){', 481 '\=repeat(g:helptoc.level_indicator, 2)', '') 482 ->substitute('^[\\]\(subsubsection\|' .. 483 'addcontentsline{toc}{subsubsection}\){', 484 '\=repeat(g:helptoc.level_indicator, 3)', '') 485 ->substitute('}[^}]*$', '', '') 486 ->substitute('\\\([&%$_#{}~\\^]\)', '\1', 'g') 487 488 # SANITIZE_VIM {{{3 489 # #1 - Omit leading Vim9 script # or Vim script " markers and blanks 490 # #2 - Omit numbered 3x { markers 491 const SANITIZE_VIM = (text: string): string => 492 text->substitute('\v^[#[:blank:]"]*(.+)\ze[{]{3}([1-6])', 493 '\=submatch(2) == "1" ? submatch(1) : ' .. 494 'repeat(g:helptoc.level_indicator, str2nr(submatch(2)) - 1)' .. 495 ' .. submatch(1)', 'g') 496 ->substitute('[#[:blank:]"]*{\{3}[1-6]', '', '') 497 #}}}3 498 499 final toc: dict<any> = {entries: []} 500 toc.changedtick = b:changedtick 501 if !toc->has_key('width') 502 toc.width = 0 503 endif 504 # We cache the toc in `b:toc` to get better performance.{{{ 505 # 506 # Without caching, when we press `H`, `L`, `H`, `L`, ... quickly for a few 507 # seconds, there is some lag if we then try to move with `j` and `k`. 508 # This can only be perceived in big man pages like with `:Man ffmpeg-all`. 509 #}}} 510 b:toc = toc 511 512 if g:helptoc.type == 'help' 513 SetTocHelp() 514 return 515 endif 516 517 if g:helptoc.type == 'terminal' 518 b:toc.linecount = line('$') 519 endif 520 521 var curline: string = getline(1) 522 var nextline: string 523 var lvl_and_test: list<list<any>> = MATCH_ENTRY 524 ->get(g:helptoc.type, {}) 525 ->items() 526 ->sort((l: list<any>, ll: list<any>): number => 527 l[0]->str2nr() - ll[0]->str2nr()) 528 529 var skip_next: bool = false 530 var skip_fence: bool = false 531 532 # Non-help headings processing 533 for lnum: number in range(1, line('$')) 534 if skip_next 535 skip_next = false 536 curline = nextline 537 continue 538 endif 539 540 nextline = getline(lnum + 1) 541 542 # Special handling for markdown filetype using setext headings 543 if g:helptoc.type == 'markdown' 544 # ignore fenced codeblock lines 545 if curline =~ '^```.' 546 skip_fence = true 547 elseif curline =~ '^```$' 548 skip_fence = !skip_fence 549 endif 550 if skip_fence 551 curline = nextline 552 continue 553 endif 554 # Check for setext formatted headings (= or - underlined) 555 if nextline =~ '^\s\{0,3}=\+$' && curline =~ '\S' 556 # Level 1 heading (one or more =, up to three spaces preceding) 557 b:toc.entries->add({ 558 lnum: lnum, 559 lvl: 1, 560 text: SANITIZE_MARKDOWN('# ' .. trim(curline)), 561 }) 562 skip_next = true 563 curline = nextline 564 continue 565 elseif nextline =~ '^\s\{0,3}-\+$' && curline =~ '\S' 566 # Level 2 heading (one or more -, up to three spaces preceding) 567 b:toc.entries->add({ 568 lnum: lnum, 569 lvl: 2, 570 text: SANITIZE_MARKDOWN('## ' .. trim(curline)), 571 }) 572 skip_next = true 573 curline = nextline 574 continue 575 endif 576 endif 577 578 # Regular processing for markdown ATX-style headings + other filetypes 579 for [lvl: string, IsEntry: func: bool] in lvl_and_test 580 if IsEntry(curline, nextline) 581 if g:helptoc.type == 'asciidoc' 582 curline = curline->SANITIZE_ASCIIDOC() 583 elseif g:helptoc.type == 'html' || g:helptoc.type == 'xhtml' 584 curline = curline->SANITIZE_HTML() 585 elseif g:helptoc.type == 'markdown' 586 curline = curline->SANITIZE_MARKDOWN() 587 elseif g:helptoc.type == 'terminal' 588 curline = curline->SANITIZE_TERMINAL() 589 elseif g:helptoc.type == 'tex' 590 curline = curline->SANITIZE_TEX() 591 elseif g:helptoc.type == 'vim' 592 curline = curline->SANITIZE_VIM() 593 endif 594 b:toc.entries->add({ 595 lnum: lnum, 596 lvl: lvl->str2nr(), 597 text: curline, 598 }) 599 break 600 endif 601 endfor 602 curline = nextline 603 endfor 604 605 InitMaxAndCurLvl() 606 enddef 607 608 def SetTocHelp() #{{{2 609 var main_ruler: string 610 for line: string in getline(1, '$') 611 if line =~ HELP_RULER 612 main_ruler = line =~ '=' ? HELP_RULERS['='] : HELP_RULERS['-'] 613 break 614 endif 615 endfor 616 617 var prevline: string 618 var curline: string = getline(1) 619 var nextline: string 620 var in_list: bool 621 var last_numbered_entry: number 622 InitHelpLvls() 623 for lnum: number in range(1, line('$')) 624 nextline = getline(lnum + 1) 625 626 if main_ruler != '' && curline =~ main_ruler 627 last_numbered_entry = 0 628 # The information gathered in `lvls` might not be applicable to 629 # all the main sections of a help file. Let's reset it whenever 630 # we find a ruler. 631 InitHelpLvls() 632 endif 633 634 # Do not assume that a list ends on an empty line. 635 # See the list at `:help gdb` for a counter-example. 636 if in_list 637 && curline !~ '^\d\+.\s' 638 && curline !~ '^\s*$' 639 && curline !~ '^[<[:blank:]]' 640 in_list = false 641 endif 642 643 if prevline =~ '^\d\+\.\s' 644 && curline !~ '^\s*$' 645 && curline !~ $'^\s*{HELP_TAG}' 646 in_list = true 647 endif 648 649 # 1. 650 if prevline =~ '^\d\+\.\s' 651 # Let's assume that the start of a main entry is always followed by an 652 # empty line, or a line starting with a tag 653 && (curline =~ '^>\=\s*$' || curline =~ $'^\s*{HELP_TAG}') 654 # ignore a numbered line in a list 655 && !in_list 656 var current_numbered_entry: number = prevline 657 ->matchstr('^\d\+\ze\.\s') 658 ->str2nr() 659 if current_numbered_entry > last_numbered_entry 660 AddEntryInTocHelp('1.', lnum - 1, prevline) 661 last_numbered_entry = prevline 662 ->matchstr('^\d\+\ze\.\s') 663 ->str2nr() 664 endif 665 endif 666 667 # 1.2 668 if curline =~ '^\d\+\.\d\+\s' 669 if curline =~ $'\%({HELP_TAG}\s*\|\~\)$' 670 || (prevline =~ $'^\s*{HELP_TAG}' || nextline =~ $'^\s*{HELP_TAG}') 671 || (prevline =~ HELP_RULER || nextline =~ HELP_RULER) 672 || (prevline =~ '^\s*$' && nextline =~ '^\s*$') 673 AddEntryInTocHelp('1.2', lnum, curline) 674 endif 675 # 1.2.3 676 elseif curline =~ '^\s\=\d\+\.\d\+\.\d\+\s' 677 AddEntryInTocHelp('1.2.3', lnum, curline) 678 endif 679 680 # HEADLINE 681 if curline =~ HELP_HEADLINE 682 && curline !~ '^CTRL-' 683 && prevline->IsSpecialHelpLine() 684 && (nextline ->IsSpecialHelpLine() 685 || nextline =~ '^\s*(\|^\t\|^N[oO][tT][eE]:') 686 AddEntryInTocHelp('HEADLINE', lnum, curline) 687 endif 688 689 # header ~ 690 if curline =~ '\~$' 691 && curline =~ '\w' 692 && curline !~ '^[[:blank:]<]\|\t\|---+---\|^NOTE:' 693 && curline !~ '^\d\+\.\%(\d\+\%(\.\d\+\)\=\)\=\s' 694 && prevline !~ $'^\s*{HELP_TAG}' 695 && prevline !~ '\~$' 696 && nextline !~ '\~$' 697 AddEntryInTocHelp('header ~', lnum, curline) 698 endif 699 700 # *some_tag* 701 if curline =~ HELP_TAG 702 AddEntryInTocHelp('tag', lnum, curline) 703 endif 704 705 # In the Vim user manual, a main section is a special case.{{{ 706 # 707 # It's not a simple numbered section: 708 # 709 # 01.1 710 # 711 # It's used as a tag: 712 # 713 # *01.1* Two manuals 714 # ^ ^ 715 #}}} 716 if prevline =~ main_ruler && curline =~ '^\*\d\+\.\d\+\*' 717 AddEntryInTocHelp('*01.1*', lnum, curline) 718 endif 719 720 [prevline, curline] = [curline, nextline] 721 endfor 722 723 # let's ignore the tag on the first line (not really interesting) 724 if b:toc.entries->get(0, {})->get('lnum') == 1 725 b:toc.entries->remove(0) 726 endif 727 728 # let's also ignore anything before the first `1.` line 729 var i: number = b:toc.entries 730 ->copy() 731 ->map((_, entry: dict<any>) => entry.text) 732 ->match('^\s*1\.\s') 733 if i > 0 734 b:toc.entries->remove(0, i - 1) 735 endif 736 737 InitMaxAndCurLvl() 738 739 # set level of tag entries to the deepest level 740 var has_tag: bool = b:toc.entries 741 ->copy() 742 ->map((_, entry: dict<any>) => entry.text) 743 ->match(HELP_TAG) >= 0 744 if has_tag 745 ++b:toc.maxlvl 746 endif 747 b:toc.entries 748 ->map((_, entry: dict<any>) => entry.lvl == 0 749 ? entry->extend({lvl: b:toc.maxlvl}) 750 : entry) 751 752 # fix indentation 753 var min_lvl: number = b:toc.entries 754 ->copy() 755 ->map((_, entry: dict<any>) => entry.lvl) 756 ->min() 757 for entry: dict<any> in b:toc.entries 758 entry.text = entry.text 759 ->substitute('^\s*', () => 760 repeat(' ', (entry.lvl - min_lvl) * 3), '') 761 endfor 762 enddef 763 764 def AddEntryInTocHelp(type: string, lnum: number, line: string) #{{{2 765 # don't add a duplicate entry 766 if lnum == b:toc.entries->get(-1, {})->get('lnum') 767 # For a numbered line containing a tag, *do* add an entry. 768 # But only for its numbered prefix, not for its tag. 769 # The former is the line's most meaningful representation. 770 if b:toc.entries->get(-1, {})->get('type') == 'tag' 771 b:toc.entries->remove(-1) 772 else 773 return 774 endif 775 endif 776 777 var text: string = line 778 if type == 'tag' 779 var tags: list<string> 780 text->substitute(HELP_TAG, () => !!tags->add(submatch(0)), 'g') 781 text = tags 782 # we ignore errors and warnings because those are meaningless in 783 # a TOC where no context is available 784 ->filter((_, tag: string): bool => tag !~ '\*[EW]\d\+\*') 785 ->join() 786 if text !~ HELP_TAG 787 return 788 endif 789 endif 790 791 var maxlvl: number = lvls->values()->max() 792 if type == 'tag' 793 lvls[type] = 0 794 elseif type == '1.2' 795 lvls[type] = lvls[type] ?? lvls->get('1.', maxlvl) + 1 796 elseif type == '1.2.3' 797 lvls[type] = lvls[type] ?? lvls->get('1.2', maxlvl) + 1 798 else 799 lvls[type] = lvls[type] ?? maxlvl + 1 800 endif 801 802 # Ignore noisy tags.{{{ 803 # 804 # 14. Linking groups *:hi-link* *:highlight-link* *E412* *E413* 805 # ^----------------------------------------^ 806 # ^\s*\d\+\.\%(\d\+\.\=\)*\s\+.\{-}\zs\*.* 807 # --- 808 # 809 # We don't use conceal because then, `matchfuzzypos()` could match 810 # concealed characters, which would be confusing. 811 #}}} 812 # MAKING YOUR OWN SYNTAX FILES *mysyntaxfile* 813 # ^------------^ 814 # ^\s*[A-Z].\{-}\*\zs.* 815 # 816 var after_HEADLINE: string = '^\s*[A-Z].\{-}\*\zs.*' 817 # 14. Linking groups *:hi-link* *:highlight-link* *E412* *E413* 818 # ^----------------------------------------^ 819 # ^\s*\d\+\.\%(\d\+\.\=\)*\s\+.\{-}\*\zs.* 820 var after_numbered: string = '^\s*\d\+\.\%(\d\+\.\=\)*\s\+.\{-}\*\zs.*' 821 # 01.3 Using the Vim tutor *tutor* *vimtutor* 822 # ^----------------^ 823 var after_numbered_tutor: string = '^\*\d\+\.\%(\d\+\.\=\)*.\{-}\t\*\zs.*' 824 var noisy_tags: string = 825 $'{after_HEADLINE}\|{after_numbered}\|{after_numbered_tutor}' 826 text = text->substitute(noisy_tags, '', '') 827 # We don't remove the trailing asterisk, because the help syntax plugin 828 # might need it to highlight some headlines. 829 830 b:toc.entries->add({ 831 lnum: lnum, 832 lvl: lvls[type], 833 text: text, 834 type: type, 835 }) 836 enddef 837 838 def InitMaxAndCurLvl() #{{{2 839 b:toc.maxlvl = b:toc.entries 840 ->copy() 841 ->map((_, entry: dict<any>) => entry.lvl) 842 ->max() 843 b:toc.curlvl = b:toc.maxlvl 844 enddef 845 846 def Popup_settext(winid: number, entries: list<dict<any>>) #{{{2 847 var text: list<any> 848 # When we fuzzy search the toc, the dictionaries in `entries` contain a 849 # `props` key, to highlight each matched character individually. 850 # We don't want to process those dictionaries further. 851 # The processing should already have been done by the caller. 852 if entries->get(0, {})->has_key('props') 853 text = entries 854 else 855 text = entries 856 ->copy() 857 ->map((_, entry: dict<any>): string => entry.text) 858 endif 859 popup_settext(winid, text) 860 SetTitle(winid) 861 redraw 862 enddef 863 864 def SetTitle(winid: number) #{{{2 865 var curlnum: number 866 var lastlnum: number = line('$', winid) 867 var is_empty: bool = lastlnum == 1 868 && winid->winbufnr()->getbufoneline(1) == '' 869 if is_empty 870 [curlnum, lastlnum] = [0, 0] 871 else 872 curlnum = line('.', winid) 873 endif 874 var newtitle: string = printf(' %*d/%d (%d/%d)', 875 len(lastlnum), curlnum, 876 lastlnum, 877 b:toc.curlvl, 878 b:toc.maxlvl, 879 ) 880 881 var width: number = winid->popup_getoptions().minwidth 882 newtitle = printf('%s%*s', 883 newtitle, 884 width - newtitle->strlen(), 885 'press ? for help ') 886 887 popup_setoptions(winid, {title: newtitle}) 888 enddef 889 890 def SelectNearestEntryFromCursor(winid: number) #{{{2 891 var lnum: number = line('.') 892 if lnum == 1 893 Win_execute(winid, 'normal! 1G') 894 return 895 endif 896 897 if lnum == line('$') 898 Win_execute(winid, 'normal! G') 899 return 900 endif 901 902 var collapsed_entries: list<dict<any>> = b:toc.entries 903 ->deepcopy() 904 ->filter((_, entry: dict<any>): bool => entry.lvl <= b:toc.curlvl) 905 var firstline: number = collapsed_entries 906 ->reverse() 907 ->indexof((_, entry: dict<any>): bool => entry.lnum <= lnum) 908 firstline = len(collapsed_entries) - firstline 909 910 if firstline <= 0 911 return 912 endif 913 Win_execute(winid, $'normal! {firstline}Gzz') 914 enddef 915 916 def Filter(winid: number, key: string): bool #{{{2 917 # support various normal commands for moving/scrolling 918 if [ 919 'j', 'J', 'k', 'K', "\<Down>", "\<Up>", "\<C-N>", "\<C-P>", 920 "\<C-D>", "\<C-U>", 921 "\<PageUp>", "\<PageDown>", 922 'g', 'G', "\<Home>", "\<End>", 923 'z' 924 ]->index(key) >= 0 925 var scroll_cmd: string = { 926 J: 'j', 927 K: 'k', 928 g: '1G', 929 "\<Home>": '1G', 930 "\<End>": 'G', 931 z: 'zz' 932 }->get(key, key) 933 934 var old_lnum: number = line('.', winid) 935 Win_execute(winid, $'normal! {scroll_cmd}') 936 var new_lnum: number = line('.', winid) 937 938 if print_entry 939 PrintEntry(winid) 940 endif 941 942 # wrap around the edges 943 if new_lnum == old_lnum 944 scroll_cmd = { 945 j: '1G', 946 J: '1G', 947 k: 'G', 948 K: 'G', 949 "\<Down>": '1G', 950 "\<Up>": 'G', 951 "\<C-N>": '1G', 952 "\<C-P>": 'G', 953 }->get(key, '') 954 if !scroll_cmd->empty() 955 Win_execute(winid, $'normal! {scroll_cmd}') 956 endif 957 endif 958 959 # move the cursor to the corresponding line in the main buffer 960 if key == 'J' || key == 'K' 961 var lnum: number = GetBufLnum(winid) 962 execute $'normal! 0{lnum}zt' 963 # Install a match in the regular buffer to highlight the position 964 # of the entry in the latter 965 MatchDelete() 966 selected_entry_match = matchaddpos('IncSearch', [lnum], 0, -1) 967 endif 968 SetTitle(winid) 969 970 return true 971 endif 972 973 if key == 'c' 974 SelectNearestEntryFromCursor(winid) 975 return true 976 endif 977 978 # when we press `p`, print the selected line (useful when it's truncated) 979 if key == 'p' 980 PrintEntry(winid) 981 return true 982 endif 983 984 # same thing, but automatically 985 if key == 'P' 986 print_entry = !print_entry 987 if print_entry 988 PrintEntry(winid) 989 else 990 echo '' 991 endif 992 return true 993 endif 994 995 if key == 'q' 996 popup_close(winid, -1) 997 return true 998 endif 999 1000 if key == '?' 1001 ToggleHelp(winid) 1002 return true 1003 endif 1004 1005 # scroll help window 1006 if key == "\<C-J>" || key == "\<C-K>" 1007 var scroll_cmd: string = {"\<C-J>": 'j', "\<C-K>": 'k'}->get(key, key) 1008 if scroll_cmd == 'j' && line('.', help_winid) == line('$', help_winid) 1009 scroll_cmd = '1G' 1010 elseif scroll_cmd == 'k' && line('.', help_winid) == 1 1011 scroll_cmd = 'G' 1012 endif 1013 Win_execute(help_winid, $'normal! {scroll_cmd}') 1014 return true 1015 endif 1016 1017 # split main window 1018 if key == 's' 1019 split 1020 return popup_filter_menu(winid, "\<CR>") 1021 endif 1022 1023 # increase/decrease the popup's width 1024 if key == '+' || key == '-' 1025 var width: number = winid->popup_getoptions().minwidth 1026 if key == '-' && width == 1 1027 || key == '+' && winid->popup_getpos().col == 1 1028 return true 1029 endif 1030 width = width + (key == '+' ? 1 : -1) 1031 # remember the last width if we close and re-open the TOC later 1032 b:toc.width = width 1033 popup_setoptions(winid, {minwidth: width, maxwidth: width}) 1034 return true 1035 endif 1036 1037 if key == 'H' && b:toc.curlvl > 1 1038 || key == 'L' && b:toc.curlvl < b:toc.maxlvl 1039 CollapseOrExpand(winid, key) 1040 return true 1041 endif 1042 1043 if key == '/' 1044 # This is probably what the user expects if they've started a first 1045 # fuzzy search, press Escape, then start a new one. 1046 DisplayNonFuzzyToc(winid) 1047 1048 [{ 1049 group: 'HelpToc', 1050 event: 'CmdlineChanged', 1051 pattern: '@', 1052 cmd: $'FuzzySearch({winid})', 1053 replace: true, 1054 }, 1055 { 1056 group: 'HelpToc', 1057 event: 'CmdlineLeave', 1058 pattern: '@', 1059 cmd: 'TearDown()', 1060 replace: true, 1061 }]->autocmd_add() 1062 1063 # Need to evaluate `winid` right now{{{ 1064 # with an `eval`'ed and `execute()`'ed heredoc because: 1065 # 1066 # - the mappings can only access the script-local namespace 1067 # - `winid` is in the function namespace; not in the script-local one 1068 #}}} 1069 var input_mappings: list<string> =<< trim eval END 1070 cnoremap <buffer><nowait> <Down> <ScriptCmd>Filter({winid}, 'j')<CR> 1071 cnoremap <buffer><nowait> <Up> <ScriptCmd>Filter({winid}, 'k')<CR> 1072 cnoremap <buffer><nowait> <C-N> <ScriptCmd>Filter({winid}, 'j')<CR> 1073 cnoremap <buffer><nowait> <C-P> <ScriptCmd>Filter({winid}, 'k')<CR> 1074 END 1075 input_mappings->execute() 1076 1077 var look_for: string 1078 try 1079 popup_setoptions(winid, {mapping: true}) 1080 look_for = input('look for: ', '', $'custom,{Complete->string()}') 1081 | redraw 1082 | echo '' 1083 catch /Vim:Interrupt/ 1084 TearDown() 1085 finally 1086 popup_setoptions(winid, {mapping: false}) 1087 endtry 1088 return look_for == '' ? true : popup_filter_menu(winid, "\<CR>") 1089 endif 1090 1091 return popup_filter_menu(winid, key) 1092 enddef 1093 1094 def FuzzySearch(winid: number) #{{{2 1095 var look_for: string = getcmdline() 1096 if look_for == '' 1097 DisplayNonFuzzyToc(winid) 1098 return 1099 endif 1100 1101 # We match against *all* entries; not just the currently visible ones. 1102 # Rationale: If we use a (fuzzy) search, we're probably lost. We don't 1103 # know where the info is. 1104 var matches: list<list<any>> = b:toc.entries 1105 ->copy() 1106 ->matchfuzzypos(look_for, {key: 'text'}) 1107 1108 fuzzy_entries = matches->get(0, [])->copy() 1109 var pos: list<list<number>> = matches->get(1, []) 1110 1111 var text: list<dict<any>> 1112 if !has('textprop') 1113 text = matches->get(0, []) 1114 else 1115 var buf: number = winid->winbufnr() 1116 if prop_type_get('help-fuzzy-toc', {bufnr: buf}) == {} 1117 prop_type_add('help-fuzzy-toc', { 1118 bufnr: buf, 1119 combine: false, 1120 highlight: 'IncSearch', 1121 }) 1122 endif 1123 text = matches 1124 ->get(0, []) 1125 ->map((i: number, match: dict<any>) => ({ 1126 text: match.text, 1127 props: pos[i]->copy()->map((_, cp: number) => ({ 1128 col: byteidx(match.text, cp) + 1, 1129 length: byteidx(match.text, cp + 1) - byteidx(match.text, cp), 1130 type: 'help-fuzzy-toc', 1131 }))})) 1132 endif 1133 Win_execute(winid, 'normal! 1Gzt') 1134 Popup_settext(winid, text) 1135 enddef 1136 1137 def DisplayNonFuzzyToc(winid: number) #{{{2 1138 fuzzy_entries = null_list 1139 Popup_settext(winid, GetTocEntries()) 1140 enddef 1141 1142 def PrintEntry(winid: number) #{{{2 1143 echo GetTocEntries()[line('.', winid) - 1]['text'] 1144 enddef 1145 1146 def CollapseOrExpand(winid: number, key: string) #{{{2 1147 # Must be saved before we reset the popup contents, so we can 1148 # automatically select the least unexpected entry in the updated popup. 1149 var buf_lnum: number = GetBufLnum(winid) 1150 1151 # find the nearest lower level for which the contents of the TOC changes 1152 if key == 'H' 1153 while b:toc.curlvl > 1 1154 var old: list<dict<any>> = GetTocEntries() 1155 --b:toc.curlvl 1156 var new: list<dict<any>> = GetTocEntries() 1157 # In `:help`, there are only entries in levels 3. 1158 # We don't want to collapse to level 2, nor 1. 1159 # It would clear the TOC which is confusing. 1160 if new->empty() 1161 ++b:toc.curlvl 1162 break 1163 endif 1164 var did_change: bool = new != old 1165 if did_change || b:toc.curlvl == 1 1166 break 1167 endif 1168 endwhile 1169 # find the nearest upper level for which the contents of the TOC changes 1170 else 1171 while b:toc.curlvl < b:toc.maxlvl 1172 var old: list<dict<any>> = GetTocEntries() 1173 ++b:toc.curlvl 1174 var did_change: bool = GetTocEntries() != old 1175 if did_change || b:toc.curlvl == b:toc.maxlvl 1176 break 1177 endif 1178 endwhile 1179 endif 1180 1181 # Update the popup contents 1182 var toc_entries: list<dict<any>> = GetTocEntries() 1183 Popup_settext(winid, toc_entries) 1184 1185 # Try to select the same entry; if it's no longer visible, select its 1186 # direct parent. 1187 var toc_lnum: number = 0 1188 for entry: dict<any> in toc_entries 1189 if entry.lnum > buf_lnum 1190 break 1191 endif 1192 ++toc_lnum 1193 endfor 1194 Win_execute(winid, $'normal! {toc_lnum ?? 1}Gzz') 1195 enddef 1196 1197 def MatchDelete() #{{{2 1198 if selected_entry_match == 0 1199 return 1200 endif 1201 1202 selected_entry_match->matchdelete() 1203 selected_entry_match = 0 1204 enddef 1205 1206 def Callback(winid: number, choice: number) #{{{2 1207 MatchDelete() 1208 1209 if help_winid != 0 1210 help_winid->popup_close() 1211 help_winid = 0 1212 endif 1213 1214 if choice == -1 1215 fuzzy_entries = null_list 1216 return 1217 endif 1218 if choice == -2 # Button X is clicked (when close: 'button') 1219 return 1220 endif 1221 1222 var lnum: number = GetTocEntries() 1223 ->get(choice - 1, {}) 1224 ->get('lnum') 1225 1226 fuzzy_entries = null_list 1227 1228 if lnum == 0 1229 return 1230 endif 1231 1232 # Moving the cursor with `normal! 123G` instead of `cursor()` adds an 1233 # entry in the jumplist (which is useful if you want to come back where 1234 # you were). 1235 execute $'normal! {lnum}Gzvzt' 1236 enddef 1237 1238 def ToggleHelp(menu_winid: number) #{{{2 1239 # Show/hide HELP_TEXT in a second popup when '?' is typed{{{ 1240 # (when a helptoc popup is open). A scrollbar on this popup makes sense 1241 # because it is very long and, even if it's not used for scrolling, works 1242 # well as an indicator of how far through the HELP_TEXT popup you are. }}} 1243 if help_winid == 0 1244 var height: number = [HELP_TEXT->len(), winheight(0) * 2 / 3]->min() 1245 var longest_line: number = HELP_TEXT 1246 ->copy() 1247 ->map((_, line: string) => line->strcharlen()) 1248 ->max() 1249 var width: number = [longest_line, winwidth(0) - 4]->min() 1250 var zindex: number = popup_getoptions(menu_winid).zindex 1251 ++zindex 1252 help_winid = HELP_TEXT->popup_create({ 1253 pos: 'center', 1254 minheight: height, 1255 maxheight: height, 1256 minwidth: width, 1257 maxwidth: width, 1258 highlight: &buftype == 'terminal' ? 'Terminal' : 'Normal', 1259 zindex: zindex, 1260 border: g:helptoc.popup_border, 1261 borderchars: g:helptoc.popup_borderchars, 1262 borderhighlight: g:helptoc.popup_borderhighlight, 1263 close: g:helptoc.popup_close, 1264 scrollbar: true, 1265 }) 1266 1267 setwinvar(help_winid, '&cursorline', true) 1268 setwinvar(help_winid, '&linebreak', true) 1269 matchadd('Special', '^<\S\+\|^\S\{,2} \@=', 0, -1, 1270 {window: help_winid}) 1271 matchadd('Number', '\d\+', 0, -1, {window: help_winid}) 1272 for lnum: number in HELP_TEXT->len()->range() 1273 if HELP_TEXT[lnum] =~ '^─\+$' 1274 matchaddpos('Title', [lnum], 0, -1, {window: help_winid}) 1275 endif 1276 endfor 1277 1278 else 1279 if IsVisible(help_winid) 1280 popup_hide(help_winid) 1281 else 1282 popup_show(help_winid) 1283 endif 1284 endif 1285 enddef 1286 1287 def Win_execute(winid: number, cmd: any) #{{{2 1288 # wrapper around `win_execute()` to enforce a redraw, which might be necessary 1289 # whenever we change the cursor position 1290 win_execute(winid, cmd) 1291 redraw 1292 enddef 1293 1294 def TearDown() #{{{2 1295 autocmd_delete([{group: 'HelpToc'}]) 1296 cunmap <buffer> <Down> 1297 cunmap <buffer> <Up> 1298 cunmap <buffer> <C-N> 1299 cunmap <buffer> <C-P> 1300 enddef 1301 # Util {{{1 1302 def GetType(): string #{{{2 1303 return &buftype == 'terminal' ? 'terminal' : &filetype 1304 enddef 1305 1306 def GetTocEntries(): list<dict<any>> #{{{2 1307 return fuzzy_entries ?? b:toc.entries 1308 ->copy() 1309 ->filter((_, entry: dict<any>): bool => entry.lvl <= b:toc.curlvl) 1310 enddef 1311 1312 def GetBufLnum(winid: number): number #{{{2 1313 var toc_lnum: number = line('.', winid) 1314 return GetTocEntries() 1315 ->get(toc_lnum - 1, {}) 1316 ->get('lnum') 1317 enddef 1318 1319 def IsVisible(win: number): bool #{{{2 1320 return win->popup_getpos()->get('visible') 1321 enddef 1322 1323 def IsSpecialHelpLine(line: string): bool #{{{2 1324 return line =~ '^[<>]\=\s*$' 1325 || line =~ '^\s*\*' 1326 || line =~ HELP_RULER 1327 || line =~ HELP_HEADLINE 1328 enddef 1329 1330 def Complete(..._): string #{{{2 1331 return b:toc.entries 1332 ->copy() 1333 ->map((_, entry: dict<any>) => 1334 entry.text->trim(' ~')->substitute('*', '', 'g')) 1335 ->filter((_, text: string): bool => text =~ '^[-a-zA-Z0-9_() ]\+$') 1336 ->sort() 1337 ->uniq() 1338 ->join("\n") 1339 enddef #}}}2 1340 #}}}1 1341 # vim:et:ft=vim:fdm=marker: