vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

2html.vim (74479B)


      1 vim9script
      2 # Vim syntax support file
      3 # Maintainer: Ben Fritz <fritzophrenic@gmail.com>
      4 # Last Change: 2026-05-22
      5 #
      6 # Additional contributors:
      7 #
      8 #             Original by Bram Moolenaar <Bram@vim.org>
      9 #             Modified by David Ne\v{c}as (Yeti) <yeti@physics.muni.cz>
     10 #             XHTML support by Panagiotis Issaris <takis@lumumba.luc.ac.be>
     11 #             Made w3 compliant by Edd Barrett <vext01@gmail.com>
     12 #             Added html_font. Edd Barrett <vext01@gmail.com>
     13 #             Progress bar based off code from "progressbar widget" plugin by
     14 #               Andreas Politz, heavily modified:
     15 #               http://www.vim.org/scripts/script.php?script_id=2006
     16 #             Converted to Vim9 by Mao-Yining Vim PR #19915
     17 #
     18 #             See git change logs for more!
     19 
     20 # Transform a file into HTML, using the current syntax highlighting.
     21 
     22 var ls_sav = &laststatus
     23 var ei_sav = &eventignore
     24 set eventignore+=FileType
     25 
     26 var lnum: number
     27 var end = line('$')
     28 var trim_tmp: list<string>
     29 
     30 # Font
     31 var htmlfont: string
     32 if exists("g:html_font")
     33   if type(g:html_font) == type([])
     34     htmlfont = "'" .. join(g:html_font, "','") .. "', monospace"
     35   else
     36     htmlfont = "'" .. g:html_font .. "', monospace"
     37   endif
     38 else
     39   htmlfont = "monospace"
     40 endif
     41 
     42 var settings = tohtml#GetUserSettings()
     43 
     44 var html5: number
     45 if settings.use_xhtml
     46   html5 = 0
     47 elseif settings.use_css && !settings.no_pre
     48   html5 = 1
     49 else
     50   html5 = 0
     51 endif
     52 
     53 const FOLDED_ID  = hlID("Folded")
     54 const FOLD_C_ID  = hlID("FoldColumn")
     55 const LINENR_ID  = hlID('LineNr')
     56 const DIFF_D_ID  = hlID("DiffDelete")
     57 const DIFF_A_ID  = hlID("DiffAdd")
     58 const DIFF_C_ID  = hlID("DiffChange")
     59 const DIFF_T_ID  = hlID("DiffText")
     60 const CONCEAL_ID = hlID('Conceal')
     61 
     62 # Whitespace
     63 var whitespace: string
     64 if settings.pre_wrap
     65   whitespace = "white-space: pre-wrap; "
     66 else
     67   whitespace = ""
     68 endif
     69 
     70 var unselInputType: string
     71 if !empty(settings.prevent_copy)
     72   if settings.no_invalid
     73     # User has decided they don't want invalid markup. Still works in
     74     # OpenOffice, and for text editors, but when pasting into Microsoft Word the
     75     # input elements get pasted too and they cannot be deleted (at least not
     76     # easily).
     77     unselInputType = ""
     78   else
     79     # Prevent from copy-pasting the input elements into Microsoft Word where
     80     # they cannot be deleted easily by deliberately inserting invalid markup.
     81     unselInputType = " type='invalid_input_type'"
     82   endif
     83 endif
     84 
     85 # When gui colors are not supported, we can only guess the colors.
     86 # TODO - is this true anymore? Is there a way to ask the terminal what colors
     87 # each number means or read them from some file?
     88 var whatterm: string
     89 var cterm_color: dict<string>
     90 if &termguicolors || has("gui_running")
     91   whatterm = "gui"
     92 else
     93   whatterm = "cterm"
     94   if &t_Co == '8'
     95     cterm_color = {
     96       0: "#808080", 1: "#ff6060", 2: "#00ff00", 3: "#ffff00",
     97       4: "#8080ff", 5: "#ff40ff", 6: "#00ffff", 7: "#ffffff"
     98     }
     99   else
    100     cterm_color = {
    101       0: "#000000", 1: "#c00000", 2: "#008000", 3: "#804000",
    102       4: "#0000c0", 5: "#c000c0", 6: "#008080", 7: "#c0c0c0",
    103       8: "#808080", 9: "#ff6060", 10: "#00ff00", 11: "#ffff00",
    104       12: "#8080ff", 13: "#ff40ff", 14: "#00ffff", 15: "#ffffff"
    105     }
    106 
    107     # Colors for 88 and 256 come from xterm.
    108     if &t_Co == '88'
    109       extend(cterm_color, {
    110 	16: "#000000", 17: "#00008b", 18: "#0000cd", 19: "#0000ff",
    111 	20: "#008b00", 21: "#008b8b", 22: "#008bcd", 23: "#008bff",
    112 	24: "#00cd00", 25: "#00cd8b", 26: "#00cdcd", 27: "#00cdff",
    113 	28: "#00ff00", 29: "#00ff8b", 30: "#00ffcd", 31: "#00ffff",
    114 	32: "#8b0000", 33: "#8b008b", 34: "#8b00cd", 35: "#8b00ff",
    115 	36: "#8b8b00", 37: "#8b8b8b", 38: "#8b8bcd", 39: "#8b8bff",
    116 	40: "#8bcd00", 41: "#8bcd8b", 42: "#8bcdcd", 43: "#8bcdff",
    117 	44: "#8bff00", 45: "#8bff8b", 46: "#8bffcd", 47: "#8bffff",
    118 	48: "#cd0000", 49: "#cd008b", 50: "#cd00cd", 51: "#cd00ff",
    119 	52: "#cd8b00", 53: "#cd8b8b", 54: "#cd8bcd", 55: "#cd8bff",
    120 	56: "#cdcd00", 57: "#cdcd8b", 58: "#cdcdcd", 59: "#cdcdff",
    121 	60: "#cdff00", 61: "#cdff8b", 62: "#cdffcd", 63: "#cdffff",
    122 	64: "#ff0000"
    123       })
    124       extend(cterm_color, {
    125 	65: "#ff008b", 66: "#ff00cd", 67: "#ff00ff", 68: "#ff8b00",
    126 	69: "#ff8b8b", 70: "#ff8bcd", 71: "#ff8bff", 72: "#ffcd00",
    127 	73: "#ffcd8b", 74: "#ffcdcd", 75: "#ffcdff", 76: "#ffff00",
    128 	77: "#ffff8b", 78: "#ffffcd", 79: "#ffffff", 80: "#2e2e2e",
    129 	81: "#5c5c5c", 82: "#737373", 83: "#8b8b8b", 84: "#a2a2a2",
    130 	85: "#b9b9b9", 86: "#d0d0d0", 87: "#e7e7e7"
    131       })
    132     elseif &t_Co == '256'
    133       extend(cterm_color, {
    134 	16: "#000000", 17: "#00005f", 18: "#000087", 19: "#0000af",
    135 	20: "#0000d7", 21: "#0000ff", 22: "#005f00", 23: "#005f5f",
    136 	24: "#005f87", 25: "#005faf", 26: "#005fd7", 27: "#005fff",
    137 	28: "#008700", 29: "#00875f", 30: "#008787", 31: "#0087af",
    138 	32: "#0087d7", 33: "#0087ff", 34: "#00af00", 35: "#00af5f",
    139 	36: "#00af87", 37: "#00afaf", 38: "#00afd7", 39: "#00afff",
    140 	40: "#00d700", 41: "#00d75f", 42: "#00d787", 43: "#00d7af",
    141 	44: "#00d7d7", 45: "#00d7ff", 46: "#00ff00", 47: "#00ff5f",
    142 	48: "#00ff87", 49: "#00ffaf", 50: "#00ffd7", 51: "#00ffff",
    143 	52: "#5f0000", 53: "#5f005f", 54: "#5f0087", 55: "#5f00af",
    144 	56: "#5f00d7", 57: "#5f00ff", 58: "#5f5f00", 59: "#5f5f5f",
    145 	60: "#5f5f87", 61: "#5f5faf", 62: "#5f5fd7", 63: "#5f5fff",
    146 	64: "#5f8700"
    147       })
    148       extend(cterm_color, {
    149 	65: "#5f875f", 66: "#5f8787", 67: "#5f87af", 68: "#5f87d7",
    150 	69: "#5f87ff", 70: "#5faf00", 71: "#5faf5f", 72: "#5faf87",
    151 	73: "#5fafaf", 74: "#5fafd7", 75: "#5fafff", 76: "#5fd700",
    152 	77: "#5fd75f", 78: "#5fd787", 79: "#5fd7af", 80: "#5fd7d7",
    153 	81: "#5fd7ff", 82: "#5fff00", 83: "#5fff5f", 84: "#5fff87",
    154 	85: "#5fffaf", 86: "#5fffd7", 87: "#5fffff", 88: "#870000",
    155 	89: "#87005f", 90: "#870087", 91: "#8700af", 92: "#8700d7",
    156 	93: "#8700ff", 94: "#875f00", 95: "#875f5f", 96: "#875f87",
    157 	97: "#875faf", 98: "#875fd7", 99: "#875fff", 100: "#878700",
    158 	101: "#87875f", 102: "#878787", 103: "#8787af", 104: "#8787d7",
    159 	105: "#8787ff", 106: "#87af00", 107: "#87af5f", 108: "#87af87",
    160 	109: "#87afaf", 110: "#87afd7", 111: "#87afff", 112: "#87d700"
    161       })
    162       extend(cterm_color, {
    163 	113: "#87d75f", 114: "#87d787", 115: "#87d7af", 116: "#87d7d7",
    164 	117: "#87d7ff", 118: "#87ff00", 119: "#87ff5f", 120: "#87ff87",
    165 	121: "#87ffaf", 122: "#87ffd7", 123: "#87ffff", 124: "#af0000",
    166 	125: "#af005f", 126: "#af0087", 127: "#af00af", 128: "#af00d7",
    167 	129: "#af00ff", 130: "#af5f00", 131: "#af5f5f", 132: "#af5f87",
    168 	133: "#af5faf", 134: "#af5fd7", 135: "#af5fff", 136: "#af8700",
    169 	137: "#af875f", 138: "#af8787", 139: "#af87af", 140: "#af87d7",
    170 	141: "#af87ff", 142: "#afaf00", 143: "#afaf5f", 144: "#afaf87",
    171 	145: "#afafaf", 146: "#afafd7", 147: "#afafff", 148: "#afd700",
    172 	149: "#afd75f", 150: "#afd787", 151: "#afd7af", 152: "#afd7d7",
    173 	153: "#afd7ff", 154: "#afff00", 155: "#afff5f", 156: "#afff87",
    174 	157: "#afffaf", 158: "#afffd7"
    175       })
    176       extend(cterm_color, {
    177 	159: "#afffff", 160: "#d70000", 161: "#d7005f", 162: "#d70087",
    178 	163: "#d700af", 164: "#d700d7", 165: "#d700ff", 166: "#d75f00",
    179 	167: "#d75f5f", 168: "#d75f87", 169: "#d75faf", 170: "#d75fd7",
    180 	171: "#d75fff", 172: "#d78700", 173: "#d7875f", 174: "#d78787",
    181 	175: "#d787af", 176: "#d787d7", 177: "#d787ff", 178: "#d7af00",
    182 	179: "#d7af5f", 180: "#d7af87", 181: "#d7afaf", 182: "#d7afd7",
    183 	183: "#d7afff", 184: "#d7d700", 185: "#d7d75f", 186: "#d7d787",
    184 	187: "#d7d7af", 188: "#d7d7d7", 189: "#d7d7ff", 190: "#d7ff00",
    185 	191: "#d7ff5f", 192: "#d7ff87", 193: "#d7ffaf", 194: "#d7ffd7",
    186 	195: "#d7ffff", 196: "#ff0000", 197: "#ff005f", 198: "#ff0087",
    187 	199: "#ff00af", 200: "#ff00d7", 201: "#ff00ff", 202: "#ff5f00",
    188 	203: "#ff5f5f", 204: "#ff5f87"
    189       })
    190       extend(cterm_color, {
    191 	205: "#ff5faf", 206: "#ff5fd7", 207: "#ff5fff", 208: "#ff8700",
    192 	209: "#ff875f", 210: "#ff8787", 211: "#ff87af", 212: "#ff87d7",
    193 	213: "#ff87ff", 214: "#ffaf00", 215: "#ffaf5f", 216: "#ffaf87",
    194 	217: "#ffafaf", 218: "#ffafd7", 219: "#ffafff", 220: "#ffd700",
    195 	221: "#ffd75f", 222: "#ffd787", 223: "#ffd7af", 224: "#ffd7d7",
    196 	225: "#ffd7ff", 226: "#ffff00", 227: "#ffff5f", 228: "#ffff87",
    197 	229: "#ffffaf", 230: "#ffffd7", 231: "#ffffff", 232: "#080808",
    198 	233: "#121212", 234: "#1c1c1c", 235: "#262626", 236: "#303030",
    199 	237: "#3a3a3a", 238: "#444444", 239: "#4e4e4e", 240: "#585858",
    200 	241: "#626262", 242: "#6c6c6c", 243: "#767676", 244: "#808080",
    201 	245: "#8a8a8a", 246: "#949494", 247: "#9e9e9e", 248: "#a8a8a8",
    202 	249: "#b2b2b2", 250: "#bcbcbc", 251: "#c6c6c6", 252: "#d0d0d0",
    203 	253: "#dadada", 254: "#e4e4e4", 255: "#eeeeee"
    204       })
    205     endif
    206   endif
    207 endif
    208 
    209 # Return good color specification: in GUI no transformation is done, in
    210 # terminal return RGB values of known colors and empty string for unknown
    211 if whatterm == "gui"
    212   def HtmlColor(color: string): string
    213     return color
    214   enddef
    215 else
    216   def HtmlColor(color: string): string
    217     if has_key(cterm_color, color)
    218       return cterm_color[color]
    219     else
    220       return ""
    221     endif
    222   enddef
    223 endif
    224 
    225 # Find out the background and foreground color for use later
    226 var fgc = HtmlColor(synIDattr(synIDtrans(hlID("Normal")), "fg#", whatterm))
    227 var bgc = HtmlColor(synIDattr(synIDtrans(hlID("Normal")), "bg#", whatterm))
    228 if fgc == ""
    229   fgc = (&background == "dark" ? "#ffffff" : "#000000")
    230 endif
    231 if bgc == ""
    232   bgc = (&background == "dark" ? "#000000" : "#ffffff")
    233 endif
    234 
    235 if !settings.use_css
    236   # Return opening HTML tag for given highlight id
    237   def HtmlOpening(id: number, extra_attrs: string): string
    238     var a = ""
    239     var translated_ID = synIDtrans(id)
    240     if synIDattr(translated_ID, "inverse") == '1'
    241       # For inverse, we always must set both colors (and exchange them)
    242       var x = HtmlColor(synIDattr(translated_ID, "fg#", whatterm))
    243       a ..= '<span ' .. extra_attrs .. 'style="background-color: ' .. (x != "" ? x : fgc) .. '">'
    244       x = HtmlColor(synIDattr(translated_ID, "bg#", whatterm))
    245       a ..= '<font color="' .. (x != "" ? x : bgc) .. '">'
    246     else
    247       var x = HtmlColor(synIDattr(translated_ID, "bg#", whatterm))
    248       if x != ""
    249 	a ..= '<span ' .. extra_attrs .. 'style="background-color: ' .. x .. '">'
    250       elseif !empty(extra_attrs)
    251 	a ..= '<span ' .. extra_attrs .. '>'
    252       endif
    253       x = HtmlColor(synIDattr(translated_ID, "fg#", whatterm))
    254       if x != "" | a ..= '<font color="' .. x .. '">' | endif
    255     endif
    256     if synIDattr(translated_ID, "bold") == '1' | a ..= "<b>" | endif
    257     if synIDattr(translated_ID, "italic") == '1' | a ..= "<i>" | endif
    258     if synIDattr(translated_ID, "underline") == '1' | a ..= "<u>" | endif
    259     return a
    260   enddef
    261 
    262   # Return closing HTML tag for given highlight id
    263   def HtmlClosing(id: number, has_extra_attrs: bool): string
    264     var a = ""
    265     var translated_ID = synIDtrans(id)
    266     if synIDattr(translated_ID, "underline") == '1' | a ..= "</u>" | endif
    267     if synIDattr(translated_ID, "italic") == '1' | a ..= "</i>" | endif
    268     if synIDattr(translated_ID, "bold") == '1' | a ..= "</b>" | endif
    269     if synIDattr(translated_ID, "inverse") == '1'
    270       a ..= '</font></span>'
    271     else
    272       var x = HtmlColor(synIDattr(translated_ID, "fg#", whatterm))
    273       if x != "" | a ..= '</font>' | endif
    274       x = HtmlColor(synIDattr(translated_ID, "bg#", whatterm))
    275       if x != "" || has_extra_attrs | a ..= '</span>' | endif
    276     endif
    277     return a
    278   enddef
    279 endif
    280 
    281 # Use a different function for formatting based on user options. This way we
    282 # can avoid a lot of logic during the actual execution.
    283 #
    284 # Build the function line by line containing only what is needed for the options
    285 # in use for maximum code sharing with minimal branch logic for greater speed.
    286 if settings.use_css
    287   # save CSS to a list of rules to add to the output at the end of processing
    288 
    289   # Note, 'exec' commands do not recognize line continuations, so must concatenate
    290   # lines rather than continue them.
    291   var wrapperfunc_lines: list<string>
    292   # first, get the style names we need
    293   wrapperfunc_lines =<< trim eval ENDLET
    294     def BuildStyleWrapper(style_id: number, diff_style_id: number, extra_attrs: string, text: string, make_unselectable: bool, unformatted: string): string
    295       var style_name = synIDattr(style_id, "name", whatterm)
    296       var saved_style: string
    297   ENDLET
    298   if &diff
    299     trim_tmp =<< trim eval ENDLET
    300       var diff_style_name = synIDattr(diff_style_id, "name", whatterm)
    301     ENDLET
    302     wrapperfunc_lines += trim_tmp
    303 
    304     # Add normal groups and diff groups to separate lists so we can order them to
    305     # allow diff highlight to override normal highlight
    306 
    307     # if primary style IS a diff style, grab it from the diff cache instead
    308     # (always succeeds because we pre-populate it)
    309     trim_tmp =<< trim eval ENDLET
    310       if style_id == DIFF_D_ID || style_id == DIFF_A_ID || style_id == DIFF_C_ID || style_id == DIFF_T_ID
    311 	saved_style = get(diffstylelist, style_id)
    312       else
    313     ENDLET
    314     wrapperfunc_lines += trim_tmp
    315   endif
    316 
    317   # get primary style info from cache or build it on the fly if not found
    318   trim_tmp =<< trim ENDLET
    319     if has_key(stylelist, style_id)
    320 	saved_style = stylelist[style_id]
    321     else
    322 	saved_style = CSS1(style_id)
    323 	if !empty(saved_style)
    324 	    saved_style = "." .. style_name .. " { " .. saved_style .. "}"
    325 	endif
    326 	stylelist[style_id] = saved_style
    327     endif
    328   ENDLET
    329   wrapperfunc_lines += trim_tmp
    330   if &diff
    331     trim_tmp =<< trim eval ENDLET
    332       endif
    333     ENDLET
    334     wrapperfunc_lines += trim_tmp
    335   endif
    336   # Ignore this comment, just bypassing a highlighting issue: if
    337 
    338   # Build the wrapper tags around the text. It turns out that caching these
    339   # gives pretty much zero performance gain and adds a lot of logic.
    340 
    341   trim_tmp =<< trim eval ENDLET
    342       if saved_style == "" && empty(extra_attrs)
    343   ENDLET
    344   wrapperfunc_lines += trim_tmp
    345   if &diff
    346     trim_tmp =<< trim eval ENDLET
    347 	if diff_style_id <= 0
    348     ENDLET
    349     wrapperfunc_lines += trim_tmp
    350   endif
    351   # no surroundings if neither primary nor diff style has any info
    352   trim_tmp =<< trim eval ENDLET
    353 	  return text
    354   ENDLET
    355   wrapperfunc_lines += trim_tmp
    356   if &diff
    357     # no primary style, but diff style
    358     trim_tmp =<< trim ENDLET
    359 	else
    360 	  return $'<span class="{diff_style_name}">{text}</span>'
    361 	endif
    362     ENDLET
    363     wrapperfunc_lines += trim_tmp
    364   endif
    365   # Ignore this comment, just bypassing a highlighting issue: if
    366 
    367   # open tag for non-empty primary style
    368   trim_tmp =<< trim eval ENDLET
    369       else
    370   ENDLET
    371   wrapperfunc_lines += trim_tmp
    372   # non-empty primary style. handle either empty or non-empty diff style.
    373   #
    374   # separate the two classes by a space to apply them both if there is a diff
    375   # style name, unless the primary style is empty, then just use the diff style
    376   # name
    377   var diffstyle: string
    378   if &diff
    379     diffstyle = '(diff_style_id <= 0 ? "" : " " .. diff_style_name) .. '
    380   else
    381     diffstyle = ''
    382   endif
    383   if settings.prevent_copy == ""
    384     trim_tmp =<< trim eval ENDLET
    385 	return "<span " .. extra_attrs .. 'class="' .. style_name .. {diffstyle}'">' .. text .. "</span>"
    386     ENDLET
    387     wrapperfunc_lines += trim_tmp
    388   else
    389     # New method: use generated content in the CSS. The only thing needed here
    390     # is a span with no content, with an attribute holding the desired text.
    391     #
    392     # Old method: use an <input> element when text is unsectable. This is still
    393     # used in conditional comments for Internet Explorer, where the new method
    394     # doesn't work.
    395     #
    396     # Wrap the <input> in a <span> to allow fixing the stupid bug in some fonts
    397     # which cause browsers to display a 1px gap between lines when these
    398     # <input>s have a background color (maybe not really a bug, this isn't
    399     # well-defined)
    400     #
    401     # use strwidth, because we care only about how many character boxes are
    402     # needed to size the input, we don't care how many characters (including
    403     # separately counted composing chars, from strchars()) or bytes (from
    404     # len())the string contains. strdisplaywidth() is not needed because none of
    405     # the unselectable groups can contain tab characters (fold column, fold
    406     # text, line number).
    407     #
    408     # Note, if maxlength property needs to be added in the future, it will need
    409     # to use strchars(), because HTML specifies that the maxlength parameter
    410     # uses the number of unique codepoints for its limit.
    411     trim_tmp =<< trim eval ENDLET
    412 	if make_unselectable
    413 	  var return_span = "<span " .. extra_attrs .. 'class="' .. style_name .. {diffstyle}'"'
    414     ENDLET
    415     wrapperfunc_lines += trim_tmp
    416     if settings.use_input_for_pc !=# 'all'
    417       trim_tmp =<< trim eval ENDLET
    418 	  return_span ..= " data-" .. style_name .. '-content="' .. text .. '"'
    419       ENDLET
    420       wrapperfunc_lines += trim_tmp
    421     endif
    422     trim_tmp =<< trim eval ENDLET
    423 	  return_span ..= '>'
    424     ENDLET
    425     wrapperfunc_lines += trim_tmp
    426     if settings.use_input_for_pc !=# 'none'
    427       trim_tmp =<< trim eval ENDLET
    428 	  return_span ..= '<input' .. unselInputType .. ' class="' .. style_name .. {diffstyle}'"'
    429 	  return_span ..= ' value="' .. substitute(unformatted, '\s\+$', "", "") .. '"'
    430 	  return_span ..= " onselect='this.blur(); return false;'"
    431 	  return_span ..= " onmousedown='this.blur(); return false;'"
    432 	  return_span ..= " onclick='this.blur(); return false;'"
    433 	  return_span ..= " readonly='readonly'"
    434 	  return_span ..= ' size="' .. strwidth(unformatted) .. '"'
    435 	  return_span ..= (settings.use_xhtml ? '/>' : '>')
    436       ENDLET
    437       wrapperfunc_lines += trim_tmp
    438     endif
    439     trim_tmp =<< trim eval ENDLET
    440 	  return return_span .. '</span>'
    441 	else
    442 	  return "<span " .. extra_attrs .. 'class="' .. style_name .. {diffstyle}'">' .. text .. "</span>"
    443 	endif
    444     ENDLET
    445     wrapperfunc_lines += trim_tmp
    446   endif
    447   trim_tmp =<< trim eval ENDLET
    448       endif
    449     enddef
    450   ENDLET
    451   wrapperfunc_lines += trim_tmp
    452 
    453   # create the function we built line by line above
    454   execute join(wrapperfunc_lines, "\n")
    455 else
    456   # Non-CSS method just needs the wrapper.
    457   #
    458   # Functions used to get opening/closing automatically return null strings if
    459   # no styles exist.
    460   if &diff
    461     def BuildStyleWrapper(style_id: number, diff_style_id: number, extra_attrs: string, text: string, unusedarg: bool, unusedarg2: string): string
    462       var diff_opening: string
    463       var diff_closing: string
    464       if diff_style_id > 0
    465 	diff_opening = HtmlOpening(diff_style_id, "")
    466 	diff_closing = HtmlClosing(diff_style_id, false)
    467       endif
    468       return HtmlOpening(style_id, extra_attrs) .. diff_opening .. text .. diff_closing .. HtmlClosing(style_id, !empty(extra_attrs))
    469     enddef
    470   else
    471     def BuildStyleWrapper(style_id: number, diff_style_id: number, extra_attrs: string, text: string, unusedarg: bool, unusedarg2: string): string
    472       return HtmlOpening(style_id, extra_attrs) .. text .. HtmlClosing(style_id, !empty(extra_attrs))
    473     enddef
    474   endif
    475 endif
    476 
    477 var diff_mode = &diff
    478 
    479 # Return HTML valid characters enclosed in a span of class style_name with
    480 # unprintable characters expanded and double spaces replaced as necessary.
    481 #
    482 # TODO: eliminate unneeded logic like done for BuildStyleWrapper
    483 def HtmlFormat(text: string, style_id: number, diff_style_id: number, extra_attrs: string, make_unselectable: bool): string
    484   # Replace unprintable characters
    485   var unformatted = strtrans(text)
    486 
    487   var formatted = unformatted
    488 
    489   # Replace the reserved html characters
    490   formatted = substitute(formatted, '&', '\&amp;',  'g')
    491   formatted = substitute(formatted, '<', '\&lt;',   'g')
    492   formatted = substitute(formatted, '>', '\&gt;',   'g')
    493   formatted = substitute(formatted, '"', '\&quot;', 'g')
    494   # &apos; is not valid in HTML but it is in XHTML, so just use the numeric
    495   # reference for it instead. Needed because it could appear in quotes
    496   # especially if unselectable regions is turned on.
    497   formatted = substitute(formatted, '"', '\&#0039;', 'g')
    498 
    499   # Replace a "form feed" character with HTML to do a page break
    500   # TODO: need to prevent this in unselectable areas? Probably it should never
    501   # BE in an unselectable area...
    502   formatted = substitute(formatted, "\x0c", '<hr class="PAGE-BREAK">', 'g')
    503 
    504   # Replace double spaces, leading spaces, and trailing spaces if needed
    505   if ' ' != HtmlSpace
    506     formatted = substitute(formatted, '  ', HtmlSpace .. HtmlSpace, 'g')
    507     formatted = substitute(formatted, '^ ', HtmlSpace, 'g')
    508     formatted = substitute(formatted, ' \+$', HtmlSpace, 'g')
    509   endif
    510 
    511   # Enclose in the correct format
    512   return BuildStyleWrapper(style_id, diff_style_id, extra_attrs, formatted, make_unselectable, unformatted)
    513 enddef
    514 
    515 # set up functions to call HtmlFormat in certain ways based on whether the
    516 # element is supposed to be unselectable or not
    517 if settings.prevent_copy =~# 'n'
    518   if settings.number_lines
    519     if settings.line_ids
    520       def HtmlFormat_n(text: string, style_id: number, diff_style_id: number, lnr: number): string
    521 	if lnr > 0
    522 	  return HtmlFormat(text, style_id, diff_style_id, 'id="' .. (exists('g:html_diff_win_num') ? 'W' .. g:html_diff_win_num : "") .. 'L' .. lnr .. settings.id_suffix .. '" ', true)
    523 	else
    524 	  return HtmlFormat(text, style_id, diff_style_id, "", true)
    525 	endif
    526       enddef
    527     else
    528       def HtmlFormat_n(text: string, style_id: number, diff_style_id: number, lnr: number): string
    529 	return HtmlFormat(text, style_id, diff_style_id, "", true)
    530       enddef
    531     endif
    532   elseif settings.line_ids
    533     # if lines are not being numbered the only reason this function gets called
    534     # is to put the line IDs on each line; "text" will be empty but lnr will
    535     # always be non-zero, however we don't want to use the <input> because that
    536     # won't work as nice for empty text
    537     def HtmlFormat_n(text: string, style_id: number, diff_style_id: number, lnr: number): string
    538       return HtmlFormat(text, style_id, diff_style_id, 'id="' .. (exists('g:html_diff_win_num') ? 'W' .. g:html_diff_win_num : "") .. 'L' .. lnr .. settings.id_suffix .. '" ', false)
    539     enddef
    540   endif
    541 else
    542   if settings.line_ids
    543     def HtmlFormat_n(text: string, style_id: number, diff_style_id: number, lnr: number): string
    544       if lnr > 0
    545 	return HtmlFormat(text, style_id, diff_style_id, 'id="' .. (exists('g:html_diff_win_num') ? 'W' .. g:html_diff_win_num : "") .. 'L' .. lnr .. settings.id_suffix .. '" ', false)
    546       else
    547 	return HtmlFormat(text, style_id, diff_style_id, "", false)
    548       endif
    549     enddef
    550   else
    551     def HtmlFormat_n(text: string, style_id: number, diff_style_id: number, lnr: number): string
    552       return HtmlFormat(text, style_id, diff_style_id, "", false)
    553     enddef
    554   endif
    555 endif
    556 
    557 if settings.prevent_copy =~# 'd'
    558   def HtmlFormat_d(text: string, style_id: number, diff_style_id: number): string
    559     return HtmlFormat(text, style_id, diff_style_id, "", true)
    560   enddef
    561 else
    562   def HtmlFormat_d(text: string, style_id: number, diff_style_id: number): string
    563     return HtmlFormat(text, style_id, diff_style_id, "", false)
    564   enddef
    565 endif
    566 if settings.prevent_copy =~# 'f'
    567   if settings.use_input_for_pc ==# 'none'
    568     # If not using the method at all, define functions that will simply
    569     # space-pad to the desired width inside the generated content (note that
    570     # the FoldColumn definition includes a whitespace:pre rule)
    571     def FoldColumn_build(char: string, len: number, numfill: number, char2: string, class: string, click: string): string
    572       return "<a href='#' class='" .. class .. "' onclick='" .. click .. "' data-FoldColumn-content='" ..
    573 	repeat(char, len) .. char2 .. repeat(' ', numfill) ..
    574 	"'></a>"
    575     enddef
    576     def FoldColumn_fill(): string
    577       return HtmlFormat(repeat(' ', foldcolumn), FOLD_C_ID, 0, "", true)
    578     enddef
    579   else
    580     # Note the <input> elements for fill spaces will have a single space for
    581     # content, to allow active cursor CSS selection to work.
    582     #
    583     # Wrap the whole thing in a span for the 1px padding workaround for gaps.
    584     #
    585     # Build the function line by line containing only what is needed for the
    586     # options in use for maximum code sharing with minimal branch logic for
    587     # greater speed.
    588     #
    589     # Note, 'exec' commands do not recognize line continuations, so must
    590     # concatenate lines rather than continue them.
    591     var build_fun_lines: list<string> = []
    592     build_fun_lines =<< trim ENDLET
    593       def FoldColumn_build(char: string, len: number, numfill: number, char2: string, class: string, click: string): string
    594 	var input_open = "<input readonly='readonly'" .. unselInputType
    595 	input_open ..= " onselect='this.blur(); return false;'"
    596 	input_open ..= " onmousedown='this.blur(); " .. click .. " return false;'"
    597 	input_open ..= " onclick='return false;' size='"
    598 	input_open ..= string(len + (empty(char2) ? 0 : 1) + numfill) .. "' "
    599 	var common_attrs = "class='FoldColumn' value='"
    600 	var input_close = settings.use_xhtml ? "' />" : "'>"
    601 	var return_span = "<span class='" .. class .. "'>"
    602 	return_span ..= input_open .. common_attrs .. repeat(char, len) .. char2
    603 	return_span ..= input_close
    604     ENDLET
    605     if settings.use_input_for_pc ==# 'fallback'
    606       trim_tmp =<< trim ENDLET
    607 	return_span ..= "<a href='#' class='FoldColumn' onclick='" .. click .. "'"
    608 	return_span ..= " data-FoldColumn-content='"
    609 	return_span ..= repeat(char, len) .. char2 .. repeat(' ', numfill)
    610 	return_span ..= "'></a>"
    611       ENDLET
    612       build_fun_lines += trim_tmp
    613     endif
    614     trim_tmp =<< trim ENDLET
    615 	return_span ..= "</span>"
    616 	return return_span
    617       enddef
    618     ENDLET
    619     build_fun_lines += trim_tmp
    620     execute join(build_fun_lines, "\n")
    621 
    622     def FoldColumn_fill(): string
    623       return FoldColumn_build(' ', foldcolumn, 0, '', 'FoldColumn', '')
    624     enddef
    625   endif
    626 else
    627   # For normal fold columns, simply space-pad to the desired width (note that
    628   # the FoldColumn definition includes a whitespace:pre rule)
    629   def FoldColumn_build(char: string, len: number, numfill: number, char2: string, class: string, click: string): string
    630     return "<a href='#' class='" .. class .. "' onclick='" .. click .. "'>" ..
    631       repeat(char, len) .. char2 .. repeat(' ', numfill) ..
    632       "</a>"
    633   enddef
    634   def FoldColumn_fill(): string
    635     return HtmlFormat(repeat(' ', foldcolumn), FOLD_C_ID, 0, "", false)
    636   enddef
    637 endif
    638 if settings.prevent_copy =~# 't'
    639   # put an extra empty span at the end for dynamic folds, so the linebreak can
    640   # be surrounded. Otherwise do it as normal.
    641   #
    642   # TODO: isn't there a better way to do this, than placing it here and using a
    643   # substitute later?
    644   if settings.dynamic_folds
    645     def HtmlFormat_t(text: string, style_id: number, diff_style_id: number): string
    646       return HtmlFormat(text, style_id, diff_style_id, "", true) ..
    647 	HtmlFormat("", style_id, 0, "", false)
    648     enddef
    649   else
    650     def HtmlFormat_t(text: string, style_id: number, diff_style_id: number): string
    651       return HtmlFormat(text, style_id, diff_style_id, "", true)
    652     enddef
    653   endif
    654 else
    655   def HtmlFormat_t(text: string, style_id: number, diff_style_id: number): string
    656     return HtmlFormat(text, style_id, diff_style_id, "", false)
    657   enddef
    658 endif
    659 
    660 # Return CSS style describing given highlight id (can be empty)
    661 def CSS1(id: number): string
    662   var a = ""
    663   var translated_ID = synIDtrans(id)
    664   if synIDattr(translated_ID, "inverse") == '1'
    665     # For inverse, we always must set both colors (and exchange them)
    666     var x = HtmlColor(synIDattr(translated_ID, "bg#", whatterm))
    667     a ..= "color: " .. (x != "" ? x : bgc) .. "; "
    668     x = HtmlColor(synIDattr(translated_ID, "fg#", whatterm))
    669     a ..= "background-color: " .. (x != "" ? x : fgc) .. "; "
    670   else
    671     var x = HtmlColor(synIDattr(translated_ID, "fg#", whatterm))
    672     if x != "" | a ..= "color: " .. x .. "; " | endif
    673     x = HtmlColor(synIDattr(translated_ID, "bg#", whatterm))
    674     if x != ""
    675       a ..= "background-color: " .. x .. "; "
    676       # stupid hack because almost every browser seems to have at least one font
    677       # which shows 1px gaps between lines which have background
    678       a ..= "padding-bottom: 1px; "
    679     elseif (translated_ID == FOLDED_ID || translated_ID == LINENR_ID || translated_ID == FOLD_C_ID) && !empty(settings.prevent_copy)
    680       # input elements default to a different color than the rest of the page
    681       a ..= "background-color: " .. bgc .. "; "
    682     endif
    683   endif
    684   if synIDattr(translated_ID, "bold") == '1' | a ..= "font-weight: bold; " | endif
    685   if synIDattr(translated_ID, "italic") == '1' | a ..= "font-style: italic; " | endif
    686   if synIDattr(translated_ID, "underline") == '1' | a ..= "text-decoration: underline; " | endif
    687   return a
    688 enddef
    689 
    690 if settings.dynamic_folds
    691   # compares two folds as stored in our list of folds
    692   # A fold is "less" than another if it starts at an earlier line number,
    693   # or ends at a later line number, ties broken by fold level
    694   def FoldCompare(f1: dict<any>, f2: dict<any>): number
    695     if f1.firstline != f2.firstline
    696       # put it before if it starts earlier
    697       return f1.firstline - f2.firstline
    698     elseif f1.lastline != f2.lastline
    699       # put it before if it ends later
    700       return f2.lastline - f1.lastline
    701     else
    702       # if folds begin and end on the same lines, put lowest fold level first
    703       return f1.level - f2.level
    704     endif
    705   enddef
    706 endif
    707 
    708 
    709 # Set some options to make it work faster.
    710 # Don't report changes for :substitute, there will be many of them.
    711 # Don't change other windows; turn off scroll bind temporarily
    712 var old_title = &title
    713 var old_icon = &icon
    714 var old_et = &l:et
    715 var old_bind = &l:scrollbind
    716 var old_report = &report
    717 var old_search = @/
    718 var old_more = &more
    719 set notitle noicon
    720 setlocal et
    721 set nomore
    722 set report=1000000
    723 setlocal noscrollbind
    724 
    725 var current_syntax: string
    726 if exists(':ownsyntax') == 2 && exists('w:current_syntax')
    727   current_syntax = w:current_syntax
    728 elseif exists('b:current_syntax')
    729   current_syntax = b:current_syntax
    730 else
    731   current_syntax = 'none'
    732 endif
    733 
    734 if current_syntax == ''
    735   current_syntax = 'none'
    736 endif
    737 
    738 # If the user is sourcing this script directly then the plugin version isn't
    739 # known because the main plugin script didn't load. In the usual case where the
    740 # user still has the full Vim runtime installed, or has this full plugin
    741 # installed in a package or something, then we can extract the version from the
    742 # main plugin file at it's usual spot relative to this file. Otherwise the user
    743 # is assembling their runtime piecemeal and we have no idea what versions of
    744 # other files may be present so don't even try to make a guess or assume the
    745 # presence of other specific files with specific meaning.
    746 #
    747 # We don't want to actually source the main plugin file here because the user
    748 # may have a good reason not to (e.g. they define their own TOhtml command or
    749 # something).
    750 #
    751 # If this seems way too complicated and convoluted, it is. Probably I should
    752 # have put the version information in the autoload file from the start. But the
    753 # version has been in the global variable for so long that changing it could
    754 # break a lot of user scripts.
    755 var pluginversion: string
    756 if exists("g:loaded_2html_plugin")
    757   pluginversion = g:loaded_2html_plugin
    758 else
    759   if !exists("g:unloaded_tohtml_plugin")
    760     var main_plugin_path = expand("<sfile>:p:h:h") .. "/plugin/tohtml.vim"
    761     if filereadable(main_plugin_path)
    762       var plugin_lines = readfile(main_plugin_path, "", 20)
    763       filter(plugin_lines, (_, val) => val =~ "loaded_2html_plugin = ")
    764       if empty(plugin_lines)
    765 	g:unloaded_tohtml_plugin = "unknown"
    766       else
    767 	g:unloaded_tohtml_plugin = substitute(plugin_lines[0], '.*loaded_2html_plugin = \([''"]\)\(\%(\1\@!.\)\+\)\1', '\2', '')
    768       endif
    769     else
    770       g:unloaded_tohtml_plugin = "unknown"
    771     endif
    772   endif
    773   pluginversion = g:unloaded_tohtml_plugin
    774 endif
    775 
    776 # Split window to create a buffer with the HTML file.
    777 var orgbufnr = winbufnr(0)
    778 var origwin_stl = &l:stl
    779 if expand("%") == ""
    780   if exists('g:html_diff_win_num')
    781     execute 'new Untitled_win' .. g:html_diff_win_num .. '.' .. (settings.use_xhtml ? 'xhtml' : 'html')
    782   else
    783     execute 'new Untitled.' .. (settings.use_xhtml ? 'xhtml' : 'html')
    784   endif
    785 else
    786   execute 'new %.' .. (settings.use_xhtml ? 'xhtml' : 'html')
    787 endif
    788 
    789 # Resize the new window to very small in order to make it draw faster
    790 var old_winheight = winheight(0)
    791 var old_winfixheight = &l:winfixheight
    792 if old_winheight > 2
    793   resize 1 # leave enough room to view one line at a time
    794   norm! G
    795   norm! zt
    796 endif
    797 setlocal winfixheight
    798 
    799 var newwin_stl = &l:stl
    800 
    801 # on the new window, set the least time-consuming fold method
    802 var old_fen = &foldenable
    803 setlocal foldmethod=manual
    804 setlocal nofoldenable
    805 
    806 var newwin = winnr()
    807 var orgwin = bufwinnr(orgbufnr)
    808 
    809 setlocal modifiable
    810 :%d
    811 var old_paste = &paste
    812 set paste
    813 var old_magic = &magic
    814 set magic
    815 
    816 # set the fileencoding to match the charset we'll be using
    817 &l:fileencoding = settings.vim_encoding
    818 
    819 # According to http://www.w3.org/TR/html4/charset.html#doc-char-set, the byte
    820 # order mark is highly recommend on the web when using multibyte encodings. But,
    821 # it is not a good idea to include it on UTF-8 files. Otherwise, let Vim
    822 # determine when it is actually inserted.
    823 if settings.vim_encoding == 'utf-8'
    824   setlocal nobomb
    825 else
    826   setlocal bomb
    827 endif
    828 
    829 var lines = []
    830 
    831 var tag_close: string
    832 if settings.use_xhtml
    833   if settings.encoding != ""
    834     add(lines, "<?xml version=\"1.0\" encoding=\"" .. settings.encoding .. "\"?>")
    835   else
    836     add(lines, "<?xml version=\"1.0\"?>")
    837   endif
    838   tag_close = ' />'
    839 else
    840   tag_close = '>'
    841 endif
    842 
    843 var HtmlSpace = ' '
    844 var LeadingSpace = ' '
    845 var HtmlEndline = ''
    846 if settings.no_pre
    847   HtmlEndline = '<br' .. tag_close
    848   LeadingSpace = settings.use_xhtml ? '&#160;' : '&nbsp;'
    849   HtmlSpace = '\' .. LeadingSpace
    850 endif
    851 
    852 # HTML header, with the title and generator ;-). Left free space for the CSS,
    853 # to be filled at the end.
    854 if !settings.no_doc
    855   extend(lines, [
    856     "<html>",
    857     "<head>"])
    858   # include encoding as close to the top as possible, but only if not already
    859   # contained in XML information (to avoid haggling over content type)
    860   if settings.encoding != "" && !settings.use_xhtml
    861     if html5
    862       add(lines, '<meta charset="' .. settings.encoding .. '"' .. tag_close)
    863     else
    864       add(lines, "<meta http-equiv=\"content-type\" content=\"text/html; charset=" .. settings.encoding .. '"' .. tag_close)
    865     endif
    866   endif
    867   extend(lines, [
    868     ("<title>" .. expand("%:p:~") .. "</title>"),
    869     ($'<meta name="Generator" content="Vim/{v:version / 100}.{v:version % 100}"{tag_close}'),
    870     ("<meta name=\"plugin-version\" content=\"" .. pluginversion .. '"' .. tag_close)
    871   ])
    872   add(lines, '<meta name="syntax" content="' .. current_syntax .. '"' .. tag_close)
    873   add(lines, '<meta name="settings" content="' ..
    874     join(filter(keys(settings), (_, k) => {
    875       var v = settings[k]
    876       if type(v) == v:t_number
    877 	return v != 0
    878       elseif type(v) == v:t_bool
    879 	return !empty(v)
    880       else
    881 	return false
    882       endif
    883     }), ',') ..
    884     ',prevent_copy=' .. settings.prevent_copy ..
    885     ',use_input_for_pc=' .. settings.use_input_for_pc ..
    886     '"' .. tag_close)
    887   add(lines, '<meta name="colorscheme" content="' ..
    888     (exists('g:colors_name')
    889     ? g:colors_name
    890     : 'none') .. '"' .. tag_close)
    891 
    892   if settings.use_css
    893     extend(lines, [
    894       "<style" .. (html5 ? "" : " type=\"text/css\"") .. ">",
    895       settings.use_xhtml ? "" : "<!--"])
    896     var ieonly: list<string> = []
    897     if settings.dynamic_folds
    898       if settings.hover_unfold
    899 	# if we are doing hover_unfold, use css 2 with css 1 fallback for IE6
    900 	extend(lines, [
    901 	  ".FoldColumn { text-decoration: none; white-space: pre; }",
    902 	  "",
    903 	  "body * { margin: 0; padding: 0; }", "",
    904 	  ".open-fold   > span.Folded { display: none;  }",
    905 	  ".open-fold   > .fulltext   { display: inline; }",
    906 	  ".closed-fold > .fulltext   { display: none;  }",
    907 	  ".closed-fold > span.Folded { display: inline; }",
    908 	  "",
    909 	  ".open-fold   > .toggle-open   { display: none;   }",
    910 	  ".open-fold   > .toggle-closed { display: inline; }",
    911 	  ".closed-fold > .toggle-open   { display: inline; }",
    912 	  ".closed-fold > .toggle-closed { display: none;   }",
    913 	  "", "",
    914 	  '/* opening a fold while hovering won''t be supported by IE6 and other',
    915 	  "similar browsers, but it should fail gracefully. */",
    916 	  ".closed-fold:hover > .fulltext      { display: inline; }",
    917 	  ".closed-fold:hover > .toggle-filler { display: none; }",
    918 	  ".closed-fold:hover > .Folded        { display: none; }"])
    919 	# TODO: IE6 is REALLY old and I can't even test it anymore. Maybe we
    920 	# should remove this? Leave it in for now, it was working at one point,
    921 	# and doesn't affect any modern browsers. Even newer IE versions should
    922 	# support the above code and ignore the following.
    923 	ieonly = [
    924 	  "<!--[if lt IE 7]><style type=\"text/css\">",
    925 	  ".open-fold   .fulltext      { display: inline; }",
    926 	  ".open-fold   span.Folded    { display: none; }",
    927 	  ".open-fold   .toggle-open   { display: none; }",
    928 	  ".open-fold   .toggle-closed { display: inline; }",
    929 	  "",
    930 	  ".closed-fold .fulltext      { display: none; }",
    931 	  ".closed-fold span.Folded    { display: inline; }",
    932 	  ".closed-fold .toggle-open   { display: inline; }",
    933 	  ".closed-fold .toggle-closed { display: none; }",
    934 	  "</style>",
    935 	  "<![endif]-->",
    936 	]
    937       else
    938 	# if we aren't doing hover_unfold, use CSS 1 only
    939 	extend(lines, [
    940 	  ".FoldColumn { text-decoration: none; white-space: pre; }",
    941 	  ".open-fold   .fulltext      { display: inline; }",
    942 	  ".open-fold   span.Folded    { display: none; }",
    943 	  ".open-fold   .toggle-open   { display: none; }",
    944 	  ".open-fold   .toggle-closed { display: inline; }",
    945 	  "",
    946 	  ".closed-fold .fulltext      { display: none; }",
    947 	  ".closed-fold span.Folded    { display: inline; }",
    948 	  ".closed-fold .toggle-open   { display: inline; }",
    949 	  ".closed-fold .toggle-closed { display: none; }",
    950 	])
    951       endif
    952     endif
    953     # else we aren't doing any dynamic folding, no need for any special rules
    954 
    955     extend(lines, [
    956       settings.use_xhtml ? "" : '-->',
    957       "</style>",
    958     ])
    959     extend(lines, ieonly)
    960   endif
    961 
    962   var uses_script = settings.dynamic_folds || settings.line_ids
    963 
    964   # insert script tag if needed
    965   if uses_script
    966     extend(lines, [
    967       "",
    968       "<script" .. (html5 ? "" : " type='text/javascript'") .. ">",
    969       settings.use_xhtml ? '//<![CDATA[' : "<!--"])
    970   endif
    971 
    972   # insert javascript to toggle folds open and closed
    973   if settings.dynamic_folds
    974     extend(lines, [
    975       "",
    976       "function toggleFold(objID)",
    977       "{",
    978       "  var fold;",
    979       "  fold = document.getElementById(objID);",
    980       "  if (fold.className == 'closed-fold')",
    981       "  {",
    982       "    fold.className = 'open-fold';",
    983       "  }",
    984       "  else if (fold.className == 'open-fold')",
    985       "  {",
    986       "    fold.className = 'closed-fold';",
    987       "  }",
    988       "}"
    989     ])
    990   endif
    991 
    992   if settings.line_ids
    993     # insert javascript to get IDs from line numbers, and to open a fold before
    994     # jumping to any lines contained therein
    995     extend(lines, [
    996       "",
    997       "/* function to open any folds containing a jumped-to line before jumping to it */",
    998       "function JumpToLine()",
    999       "{",
   1000       "  var lineNum;",
   1001       "  lineNum = window.location.hash;",
   1002       "  lineNum = lineNum.substr(1); /* strip off '#' */",
   1003       "",
   1004     "  if (lineNum.indexOf('L') == -1) {",
   1005     "    lineNum = 'L'+lineNum;",
   1006     "  }",
   1007     "  var lineElem = document.getElementById(lineNum);"
   1008     ])
   1009 
   1010     if settings.dynamic_folds
   1011       extend(lines, [
   1012 	"",
   1013       "  /* navigate upwards in the DOM tree to open all folds containing the line */",
   1014       "  var node = lineElem;",
   1015       "  while (node && node.id != 'vimCodeElement" .. settings.id_suffix .. "')",
   1016       "  {",
   1017       "    if (node.className == 'closed-fold')",
   1018       "    {",
   1019       "      node.className = 'open-fold';",
   1020       "    }",
   1021       "    node = node.parentNode;",
   1022       "  }",
   1023       ])
   1024     endif
   1025     extend(lines, [
   1026       "  /* Always jump to new location even if the line was hidden inside a fold, or",
   1027       "   * we corrected the raw number to a line ID.",
   1028       "   */",
   1029       "  if (lineElem) {",
   1030       "    lineElem.scrollIntoView(true);",
   1031       "  }",
   1032       "  return true;",
   1033       "}",
   1034       "if ('onhashchange' in window) {",
   1035       "  window.onhashchange = JumpToLine;",
   1036       "}"
   1037     ])
   1038   endif
   1039 
   1040   # insert script closing tag if needed
   1041   if uses_script
   1042     extend(lines, [
   1043       '',
   1044       settings.use_xhtml ? '//]]>' : '-->',
   1045       "</script>"
   1046     ])
   1047   endif
   1048 
   1049   extend(lines, ["</head>",
   1050     "<body" .. (settings.line_ids ? " onload='JumpToLine();'" : "") .. ">"])
   1051 endif
   1052 
   1053 if settings.no_pre
   1054   # if we're not using CSS we use a font tag which can't have a div inside
   1055   if settings.use_css
   1056     extend(lines, ["<div id='vimCodeElement" .. settings.id_suffix .. "'>"])
   1057   endif
   1058 else
   1059   extend(lines, ["<pre id='vimCodeElement" .. settings.id_suffix .. "'>"])
   1060 endif
   1061 
   1062 execute $":{orgwin}wincmd w"
   1063 
   1064 # caches of style data
   1065 # initialize to include line numbers if using them
   1066 var stylelist: dict<string>
   1067 if settings.number_lines
   1068   stylelist = { [LINENR_ID]: ".LineNr { " .. CSS1(LINENR_ID) .. "}" }
   1069 else
   1070   stylelist = {}
   1071 endif
   1072 var diffstylelist: dict<string> = {
   1073   [DIFF_A_ID]: ".DiffAdd { " .. CSS1(DIFF_A_ID) .. "}",
   1074   [DIFF_C_ID]: ".DiffChange { " .. CSS1(DIFF_C_ID) .. "}",
   1075   [DIFF_D_ID]: ".DiffDelete { " .. CSS1(DIFF_D_ID) .. "}",
   1076   [DIFF_T_ID]: ".DiffText { " .. CSS1(DIFF_T_ID) .. "}"
   1077 }
   1078 
   1079 var last_colors_name: string
   1080 # set up progress bar in the status line
   1081 # ProgressBar Indicator
   1082 # Progressbar specific functions
   1083 def SetProgbarColor()
   1084   if hlID("TOhtmlProgress") != 0
   1085     hi! link TOhtmlProgress_auto TOhtmlProgress
   1086   elseif hlID("TOhtmlProgress_auto") == 0 ||
   1087       last_colors_name == null_string || !exists("g:colors_name") ||
   1088       g:colors_name != last_colors_name
   1089     last_colors_name = exists("g:colors_name") ? g:colors_name : "none"
   1090 
   1091     var diffatr = synIDattr(synIDtrans(hlID("DiffDelete")), "reverse", whatterm) == '1' ? "fg#" : "bg#"
   1092     var stlatr = synIDattr(synIDtrans(hlID("StatusLine")), "reverse", whatterm) == '1' ? "fg#" : "bg#"
   1093 
   1094     var progbar_color = synIDattr(synIDtrans(hlID("DiffDelete")), diffatr, whatterm)
   1095     var stl_color = synIDattr(synIDtrans(hlID("StatusLine")), stlatr, whatterm)
   1096 
   1097     if empty(progbar_color)
   1098       progbar_color = synIDattr(synIDtrans(hlID("DiffDelete")), "reverse", whatterm) == '1' ? fgc : bgc
   1099     endif
   1100     if empty(stl_color)
   1101       stl_color = synIDattr(synIDtrans(hlID("StatusLine")), "reverse", whatterm) == '1' ? fgc : bgc
   1102     endif
   1103 
   1104     if progbar_color == stl_color
   1105       if whatterm == 'cterm'
   1106 	var nr = str2nr(progbar_color)
   1107 	if nr >= (str2nr(&t_Co) / 2)
   1108 	  nr -= 1
   1109 	else
   1110 	  nr += 1
   1111 	endif
   1112 	progbar_color = string(nr)
   1113       else
   1114 	var rgb = map(matchlist(progbar_color, '#\zs\x\x\ze\(\x\x\)\(\x\x\)')[: 2], (_, v) => str2nr(v, 16))
   1115 	var avg = (rgb[0] + rgb[1] + rgb[2]) / 3
   1116 	if avg >= 128
   1117 	  var avg_new = avg
   1118 	  while avg - avg_new < 0x15
   1119 	    rgb = map(rgb, (_, v) => v * 3 / 4)
   1120 	    avg_new = (rgb[0] + rgb[1] + rgb[2]) / 3
   1121 	  endwhile
   1122 	else
   1123 	  var avg_new = avg
   1124 	  while avg_new - avg < 0x15
   1125 	    rgb = map(rgb, (_, v) => min([max([v, 4]) * 5 / 4, 255]))
   1126 	    avg_new = (rgb[0] + rgb[1] + rgb[2]) / 3
   1127 	  endwhile
   1128 	endif
   1129 	progbar_color = printf("#%02x%02x%02x", rgb[0], rgb[1], rgb[2])
   1130       endif
   1131       echomsg "diff detected progbar color set to" progbar_color
   1132     endif
   1133     execute "hi TOhtmlProgress_auto" whatterm .. "bg=" .. progbar_color
   1134   endif
   1135 enddef
   1136 
   1137 class ProgressBar #{{{
   1138   public var title: string
   1139   public var max_value: number
   1140   public var winnr: number
   1141   public var cur_value: number = 0
   1142   public var items: dict<any>
   1143   public var last_value: number = 0
   1144   public var needs_redraw: number = 0
   1145   public var pb_len: number = 0
   1146   public var max_len: number = 0
   1147   public var progress_ticks: list<number> = []
   1148   var subtractedlen: number
   1149 
   1150   def new(title: string, max_value: number, winnr: number)
   1151     this.title = title .. ' '
   1152     this.max_value = max_value
   1153     this.winnr = winnr
   1154 
   1155     this.items = {
   1156       'title': { 'color': 'Statusline' },
   1157       'bar': { 'color': 'Statusline', 'fillcolor': 'TOhtmlProgress_auto', 'bg': 'Statusline' },
   1158       'counter': { 'color': 'Statusline' }
   1159     }
   1160     # Note that you must use len(split) instead of len() if you want to use
   1161     # unicode in title.
   1162     #
   1163     # Subtract 3 for spacing around the title.
   1164     # Subtract 4 for the percentage display.
   1165     # Subtract 2 for spacing before this.
   1166     # Subtract 2 more for the '|' on either side of the progress bar
   1167     this.subtractedlen = len(split(this.title, '\zs')) + 3 + 4 + 2 + 2
   1168     set laststatus=2
   1169   enddef
   1170 
   1171   def Paint()
   1172     # Recalculate widths.
   1173     var max_len = winwidth(this.winnr)
   1174     var pb_len = 0
   1175     var cur_value: number
   1176 
   1177     def CalculateTicks(len: number)
   1178       if len <= 0
   1179 	pb_len = 100
   1180       else
   1181 	pb_len = len
   1182       endif
   1183       this.progress_ticks = range(pb_len + 1)->map((_, v) => v * this.max_value / pb_len)
   1184     enddef
   1185 
   1186     # always true on first call because of initial value of this.max_len
   1187     if max_len != this.max_len
   1188       this.max_len = max_len
   1189 
   1190       # Progressbar length
   1191       pb_len = max_len - this.subtractedlen
   1192 
   1193       CalculateTicks(pb_len)
   1194 
   1195       this.needs_redraw = 1
   1196       cur_value = 0
   1197       this.pb_len = pb_len
   1198     else
   1199       # start searching at the last found index to make the search for the
   1200       # appropriate tick value normally take 0 or 1 comparisons
   1201       cur_value = this.last_value
   1202       pb_len = this.pb_len
   1203     endif
   1204 
   1205     var cur_val_max = pb_len > 0 ? pb_len : 100
   1206 
   1207     # find the current progress bar position based on precalculated thresholds
   1208     while cur_value < cur_val_max && this.cur_value > this.progress_ticks[cur_value]
   1209       cur_value += 1
   1210     endwhile
   1211 
   1212     # update progress bar
   1213     if this.last_value != cur_value || this.needs_redraw || this.cur_value == this.max_value
   1214       this.needs_redraw = 1
   1215       this.last_value = cur_value
   1216 
   1217       var t_color  = this.items.title.color
   1218       var b_fcolor = this.items.bar.fillcolor
   1219       var b_color  = this.items.bar.color
   1220       var c_color  = this.items.counter.color
   1221 
   1222       var stl =  $"%#{t_color}#%-( {this.title} %)%#{b_color}#" ..
   1223 	(pb_len > 0 ? $'|%#{b_fcolor}#%-({repeat(" ", cur_value)}%)%#{b_color}#{repeat(" ", pb_len - cur_value)}|' : (''))
   1224 	.. $"%=%#{c_color}#%( {printf("%3.d ", 100 * this.cur_value / this.max_value)}%% %)"
   1225       setwinvar(this.winnr, '&stl', stl)
   1226     endif
   1227   enddef
   1228 
   1229   def Incr(delta: number = 1)
   1230     this.cur_value += delta
   1231     # if we were making a general-purpose progress bar, we'd need to limit to a
   1232     # lower limit as well, but since we always increment with a positive value
   1233     # in this script, we only need limit the upper value
   1234     this.cur_value = (this.cur_value > this.max_value ? this.max_value : this.cur_value)
   1235     this.Paint()
   1236   enddef
   1237 endclass #}}}
   1238 
   1239 var pgb: ProgressBar
   1240 if !settings.no_progress
   1241   if settings.dynamic_folds
   1242     # to process folds we make two passes through each line
   1243     pgb = ProgressBar.new("Processing folds:", line('$') * 2, orgwin)
   1244   endif
   1245 
   1246   SetProgbarColor()
   1247 endif
   1248 
   1249 var build_fun_lines: list<string>
   1250 build_fun_lines =<< trim ENDLET
   1251   def Add_diff_fill(_lnum: number)
   1252     var filler = diff_filler(_lnum)
   1253     if filler > 0
   1254       var to_insert = filler
   1255       while to_insert > 0
   1256 	var new = repeat(difffillchar, 3)
   1257 
   1258 	if to_insert > 2 && to_insert < filler && !settings.whole_filler
   1259 	  new = new .. " " .. filler .. " inserted lines "
   1260 	  to_insert = 2
   1261 	endif
   1262 ENDLET
   1263 if !settings.no_pre
   1264   trim_tmp =<< trim ENDLET
   1265 	# HTML line wrapping is off--go ahead and fill to the margin
   1266 	# TODO: what about when CSS wrapping is turned on?
   1267 	new = new .. repeat(difffillchar, &columns - strlen(new) - margin)
   1268   ENDLET
   1269   build_fun_lines += trim_tmp
   1270 else
   1271   trim_tmp =<< trim ENDLET
   1272 	new = new .. repeat(difffillchar, 3)
   1273   ENDLET
   1274   build_fun_lines += trim_tmp
   1275 endif
   1276 trim_tmp =<< trim ENDLET
   1277 	new = HtmlFormat_d(new, DIFF_D_ID, 0)
   1278 ENDLET
   1279 build_fun_lines += trim_tmp
   1280 if settings.number_lines
   1281   trim_tmp =<< trim ENDLET
   1282 	# Indent if line numbering is on. Indent gets style of line number
   1283 	# column.
   1284 	new = HtmlFormat_n(repeat(' ', margin), LINENR_ID, 0, 0) .. new
   1285   ENDLET
   1286   build_fun_lines += trim_tmp
   1287 endif
   1288 if settings.dynamic_folds && !settings.no_foldcolumn
   1289   trim_tmp =<< trim ENDLET
   1290 	if foldcolumn > 0
   1291 	  # Indent for foldcolumn if there is one. Assume it's empty, there should
   1292 	  # not be a fold for deleted lines in diff mode.
   1293 	  new = FoldColumn_fill() .. new
   1294 	endif
   1295   ENDLET
   1296   build_fun_lines += trim_tmp
   1297 endif
   1298 # Ignore this comment, just bypassing a highlighting issue: if
   1299 trim_tmp =<< trim ENDLET
   1300 	add(lines, new .. HtmlEndline)
   1301 	to_insert -= 1
   1302       endwhile
   1303     endif
   1304   enddef
   1305 ENDLET
   1306 build_fun_lines += trim_tmp
   1307 execute join(build_fun_lines, "\n")
   1308 
   1309 # First do some preprocessing for dynamic folding. Do this for the entire file
   1310 # so we don't accidentally start within a closed fold or something.
   1311 var allfolds: list<any> = []
   1312 
   1313 var foldcolumn: number
   1314 if settings.dynamic_folds
   1315   def ProcessFolds()
   1316     lnum = 1
   1317     end = line('$')
   1318     # save the fold text and set it to the default so we can find fold levels
   1319     var foldtext_save = &foldtext
   1320     setlocal foldtext&
   1321 
   1322     # we will set the foldcolumn in the html to the greater of the maximum fold
   1323     # level and the current foldcolumn setting
   1324     foldcolumn = &foldcolumn
   1325 
   1326     # get all info needed to describe currently closed folds
   1327     while lnum <= end
   1328       if foldclosed(lnum) == lnum
   1329 	# default fold text has '+-' and then a number of dashes equal to fold
   1330 	# level, so subtract 2 from index of first non-dash after the dashes
   1331 	# in order to get the fold level of the current fold
   1332 	var level = match(foldtextresult(lnum), '+-*\zs[^-]') - 2
   1333 	# store fold info for later use
   1334 	var newfold = {firstline: lnum, lastline: foldclosedend(lnum), level: level, type: "closed-fold"}
   1335 	add(allfolds, newfold)
   1336 	# open the fold so we can find any contained folds
   1337 	execute $":{lnum}foldopen"
   1338       else
   1339 	if !settings.no_progress
   1340 	  pgb.Incr()
   1341 	  if pgb.needs_redraw
   1342 	    redrawstatus
   1343 	    pgb.needs_redraw = 0
   1344 	  endif
   1345 	endif
   1346 	lnum = lnum + 1
   1347       endif
   1348     endwhile
   1349 
   1350     # close all folds to get info for originally open folds
   1351     silent! :%foldclose!
   1352     lnum = 1
   1353 
   1354     # the originally open folds will be all folds we encounter that aren't
   1355     # already in the list of closed folds
   1356     while lnum <= end
   1357       if foldclosed(lnum) == lnum
   1358 	# default fold text has '+-' and then a number of dashes equal to fold
   1359 	# level, so subtract 2 from index of first non-dash after the dashes
   1360 	# in order to get the fold level of the current fold
   1361 	var level = match(foldtextresult(lnum), '+-*\zs[^-]') - 2
   1362 	var newfold = {firstline: lnum, lastline: foldclosedend(lnum), level: level, type: "closed-fold"}
   1363 	# only add the fold if we don't already have it
   1364 	if empty(allfolds) || index(allfolds, newfold) == -1
   1365 	  newfold.type = "open-fold"
   1366 	  add(allfolds, newfold)
   1367 	endif
   1368 	# open the fold so we can find any contained folds
   1369 	execute $":{lnum}foldopen"
   1370       else
   1371 	if !settings.no_progress
   1372 	  pgb.Incr()
   1373 	  if pgb.needs_redraw
   1374 	    redrawstatus
   1375 	    pgb.needs_redraw = 0
   1376 	  endif
   1377 	endif
   1378 	lnum = lnum + 1
   1379       endif
   1380     endwhile
   1381 
   1382     # sort the folds so that we only ever need to look at the first item in the
   1383     # list of folds
   1384     sort(allfolds, FoldCompare)
   1385 
   1386     &l:foldtext = foldtext_save
   1387 
   1388     # close all folds again so we can get the fold text as we go
   1389     silent! :%foldclose!
   1390 
   1391     # Go through and remove folds we don't need to (or cannot) process in the
   1392     # current conversion range
   1393     #
   1394     # If a fold is removed which contains other folds, which are included, we need
   1395     # to adjust the level of the included folds as used by the conversion logic
   1396     # (avoiding special cases is good)
   1397     #
   1398     # Note any time we remove a fold, either all of the included folds are in it,
   1399     # or none of them, because we only remove a fold if neither its start nor its
   1400     # end are within the conversion range.
   1401     var leveladjust = 0
   1402     for afold in allfolds
   1403       var removed = 0
   1404       if exists("g:html_start_line") && exists("g:html_end_line")
   1405 	if afold.firstline < g:html_start_line
   1406 	  if afold.lastline <= g:html_end_line && afold.lastline >= g:html_start_line
   1407 	    # if a fold starts before the range to convert but stops within the
   1408 	    # range, we need to include it. Make it start on the first converted
   1409 	    # line.
   1410 	    afold.firstline = g:html_start_line
   1411 	  else
   1412 	    # if the fold lies outside the range or the start and stop enclose
   1413 	    # the entire range, don't bother parsing it
   1414 	    remove(allfolds, index(allfolds, afold))
   1415 	    removed = 1
   1416 	    if afold.lastline > g:html_end_line
   1417 	      leveladjust += 1
   1418 	    endif
   1419 	  endif
   1420 	elseif afold.firstline > g:html_end_line
   1421 	  # If the entire fold lies outside the range we need to remove it.
   1422 	  remove(allfolds, index(allfolds, afold))
   1423 	  removed = 1
   1424 	endif
   1425       elseif exists("g:html_start_line")
   1426 	if afold.firstline < g:html_start_line
   1427 	  # if there is no last line, but there is a first line, the end of the
   1428 	  # fold will always lie within the region of interest, so keep it
   1429 	  afold.firstline = g:html_start_line
   1430 	endif
   1431       elseif exists("g:html_end_line")
   1432 	# if there is no first line we default to the first line in the buffer so
   1433 	# the fold start will always be included if the fold itself is included.
   1434 	# If however the entire fold lies outside the range we need to remove it.
   1435 	if afold.firstline > g:html_end_line
   1436 	  remove(allfolds, index(allfolds, afold))
   1437 	  removed = 1
   1438 	endif
   1439       endif
   1440       if !removed
   1441 	afold.level -= leveladjust
   1442 	if afold.level + 1 > foldcolumn
   1443 	  foldcolumn = afold.level + 1
   1444 	endif
   1445       endif
   1446     endfor
   1447 
   1448     # if we've removed folds containing the conversion range from processing,
   1449     # getting foldtext as we go won't know to open the removed folds, so the
   1450     # foldtext would be wrong; open them now.
   1451     #
   1452     # Note that only when a start and an end line is specified will a fold
   1453     # containing the current range ever be removed.
   1454     while leveladjust > 0
   1455       execute $":{g:html_start_line}foldopen"
   1456       leveladjust -= 1
   1457     endwhile
   1458   enddef
   1459   ProcessFolds()
   1460 endif
   1461 
   1462 # Now loop over all lines in the original text to convert to html.
   1463 # Use html_start_line and html_end_line if they are set.
   1464 if exists("g:html_start_line")
   1465   lnum = g:html_start_line
   1466   if lnum < 1 || lnum > line("$")
   1467     lnum = 1
   1468   endif
   1469 else
   1470   lnum = 1
   1471 endif
   1472 if exists("g:html_end_line")
   1473   end = g:html_end_line
   1474   if end < lnum || end > line("$")
   1475     end = line("$")
   1476   endif
   1477 else
   1478   end = line("$")
   1479 endif
   1480 
   1481 # stack to keep track of all the folds containing the current line
   1482 var foldstack: list<any> = []
   1483 
   1484 if !settings.no_progress
   1485   pgb = ProgressBar.new("Processing lines:", end - lnum + 1, orgwin)
   1486 endif
   1487 
   1488 var margin: number
   1489 if settings.number_lines
   1490   margin = strlen(end) + 1
   1491 else
   1492   margin = 0
   1493 endif
   1494 
   1495 var foldfillchar: string
   1496 var charidx: number
   1497 if has('folding') && !settings.ignore_folding
   1498   charidx = matchend(&fillchars, 'fold:')
   1499   if charidx >= 0
   1500     foldfillchar = &fillchars[charidx(&fillchars, charidx)]
   1501   endif
   1502   if foldfillchar->empty()
   1503     foldfillchar = '-'
   1504   endif
   1505 endif
   1506 var difffillchar: string
   1507 charidx = matchend(&fillchars, 'diff:')
   1508 if charidx >= 0
   1509   difffillchar = &fillchars[charidx(&fillchars, charidx)]
   1510 endif
   1511 if difffillchar->empty()
   1512   difffillchar = '-'
   1513 endif
   1514 
   1515 var foldId = 0
   1516 var old_isprint: string
   1517 if !settings.expand_tabs
   1518   # If keeping tabs, add them to printable characters so we keep them when
   1519   # formatting text (strtrans() doesn't replace printable chars)
   1520   old_isprint = &isprint
   1521   setlocal isprint+=9
   1522 endif
   1523 
   1524 def ProcessLines()
   1525   var all_lines = getline(lnum, end)
   1526   var start_lnum = lnum
   1527 
   1528   while lnum <= end
   1529 
   1530     # If there are filler lines for diff mode, show these above the line.
   1531     Add_diff_fill(lnum)
   1532 
   1533     # Start the line with the line number.
   1534     var numcol: string
   1535     if settings.number_lines
   1536       numcol = repeat(' ', margin - 1 - strlen(lnum)) .. lnum .. ' '
   1537     endif
   1538 
   1539     var new: string
   1540 
   1541     if has('folding') && !settings.ignore_folding && foldclosed(lnum) > -1 && !settings.dynamic_folds
   1542       #
   1543       # This is the beginning of a folded block (with no dynamic folding)
   1544       new = foldtextresult(lnum)
   1545       if !settings.no_pre
   1546 	# HTML line wrapping is off--go ahead and fill to the margin
   1547 	new ..= repeat(foldfillchar, &columns - strlen(new))
   1548       endif
   1549 
   1550       # put numcol in a separate group for sake of unselectable text
   1551       new = (settings.number_lines ? HtmlFormat_n(numcol, FOLDED_ID, 0, lnum) : "") .. HtmlFormat_t(new, FOLDED_ID, 0)
   1552 
   1553       # Skip to the end of the fold
   1554       var new_lnum = foldclosedend(lnum)
   1555 
   1556       if !settings.no_progress
   1557 	pgb.Incr(new_lnum - lnum)
   1558       endif
   1559 
   1560       lnum = new_lnum
   1561 
   1562     else
   1563       #
   1564       # A line that is not folded, or doing dynamic folding.
   1565       #
   1566       var line = all_lines[lnum - start_lnum]
   1567       var len = strlen(line)
   1568 
   1569       if settings.dynamic_folds
   1570 	# First insert a closing for any open folds that end on this line
   1571 	while !empty(foldstack) && get(foldstack, 0).lastline == lnum - 1
   1572 	  new ..= "</span></span>"
   1573 	  remove(foldstack, 0)
   1574 	endwhile
   1575 
   1576 	# Now insert an opening for any new folds that start on this line
   1577 	var firstfold = 1
   1578 	while !empty(allfolds) && get(allfolds, 0).firstline == lnum
   1579 	  foldId = foldId + 1
   1580 	  new ..= "<span id='"
   1581 	  new ..= (exists('g:html_diff_win_num') ? "win" .. g:html_diff_win_num : "")
   1582 	  new ..= "fold" .. foldId .. settings.id_suffix .. "' class='" .. allfolds[0].type .. "'>"
   1583 
   1584 
   1585 	  # Unless disabled, add a fold column for the opening line of a fold.
   1586 	  #
   1587 	  # Note that dynamic folds require using css so we just use css to take
   1588 	  # care of the leading spaces rather than using &nbsp; in the case of
   1589 	  # html_no_pre to make it easier
   1590 	  if !settings.no_foldcolumn
   1591 	    # add fold column that can open the new fold
   1592 	    if allfolds[0].level > 1 && firstfold
   1593 	      new ..= FoldColumn_build('|', allfolds[0].level - 1, 0, "",
   1594 		'toggle-open FoldColumn', 'javascript:toggleFold("fold' .. foldstack[0].id .. settings.id_suffix .. '");')
   1595 	    endif
   1596 	    # add the filler spaces separately from the '+' char so that it can be
   1597 	    # shown/hidden separately during a hover unfold
   1598 	    new ..= FoldColumn_build("+", 1, 0, "",
   1599 	      'toggle-open FoldColumn', 'javascript:toggleFold("fold' .. foldId .. settings.id_suffix .. '");')
   1600 	    # If this is not the last fold we're opening on this line, we need
   1601 	    # to keep the filler spaces hidden if the fold is opened by mouse
   1602 	    # hover. If it is the last fold to open in the line, we shouldn't hide
   1603 	    # them, so don't apply the toggle-filler class.
   1604 	    new ..= FoldColumn_build(" ", 1, foldcolumn - allfolds[0].level - 1, "",
   1605 	      'toggle-open FoldColumn' .. (get(allfolds, 1, {firstline: 0}).firstline == lnum ? " toggle-filler" : ""),
   1606 	      'javascript:toggleFold("fold' .. foldId .. settings.id_suffix .. '");')
   1607 
   1608 	    # add fold column that can close the new fold
   1609 	    # only add extra blank space if we aren't opening another fold on the
   1610 	    # same line
   1611 	    var extra_space: number
   1612 	    if get(allfolds, 1, {firstline: 0}).firstline != lnum
   1613 	      extra_space = foldcolumn - allfolds[0].level
   1614 	    else
   1615 	      extra_space = 0
   1616 	    endif
   1617 	    if firstfold
   1618 	      # the first fold in a line has '|' characters from folds opened in
   1619 	      # previous lines, before the '-' for this fold
   1620 	      new ..= FoldColumn_build('|', allfolds[0].level - 1, extra_space, '-',
   1621 		'toggle-closed FoldColumn', 'javascript:toggleFold("fold' .. foldId .. settings.id_suffix .. '");')
   1622 	    else
   1623 	      # any subsequent folds in the line only add a single '-'
   1624 	      new ..= FoldColumn_build("-", 1, extra_space, "",
   1625 		'toggle-closed FoldColumn', 'javascript:toggleFold("fold' .. foldId .. settings.id_suffix .. '");')
   1626 	    endif
   1627 	    firstfold = 0
   1628 	  endif
   1629 
   1630 	  # Add fold text, moving the span ending to the next line so collapsing
   1631 	  # of folds works correctly.
   1632 	  # Put numcol in a separate group for sake of unselectable text.
   1633 	  new ..= (settings.number_lines ? HtmlFormat_n(numcol, FOLDED_ID, 0, 0) : "") .. substitute(HtmlFormat_t(foldtextresult(lnum), FOLDED_ID, 0), '</span>', HtmlEndline .. '\n\0', '')
   1634 	  new ..= "<span class='fulltext'>"
   1635 
   1636 	  # open the fold now that we have the fold text to allow retrieval of
   1637 	  # fold text for subsequent folds
   1638 	  execute $":{lnum}foldopen"
   1639 	  insert(foldstack, remove(allfolds, 0), 0)
   1640 	  foldstack[0].id = foldId
   1641 	endwhile
   1642 
   1643 	# Unless disabled, add a fold column for other lines.
   1644 	#
   1645 	# Note that dynamic folds require using css so we just use css to take
   1646 	# care of the leading spaces rather than using &nbsp; in the case of
   1647 	# html_no_pre to make it easier
   1648 	if !settings.no_foldcolumn
   1649 	  if empty(foldstack)
   1650 	    # add the empty foldcolumn for unfolded lines if there is a fold
   1651 	    # column at all
   1652 	    if foldcolumn > 0
   1653 	      new = new .. FoldColumn_fill()
   1654 	    endif
   1655 	  else
   1656 	    # add the fold column for folds not on the opening line
   1657 	    if get(foldstack, 0).firstline < lnum
   1658 	      new = new .. FoldColumn_build('|', foldstack[0].level, foldcolumn - foldstack[0].level, "",
   1659 		'FoldColumn', 'javascript:toggleFold("fold' .. foldstack[0].id .. settings.id_suffix .. '");')
   1660 	    endif
   1661 	  endif
   1662 	endif
   1663       endif
   1664 
   1665       # Now continue with the unfolded line text
   1666       if settings.number_lines
   1667 	new ..= HtmlFormat_n(numcol, LINENR_ID, 0, lnum)
   1668       elseif settings.line_ids
   1669 	new ..= HtmlFormat_n("", LINENR_ID, 0, lnum)
   1670       endif
   1671 
   1672       # Get the diff attribute, if any.
   1673       var diffattr = diff_hlID(lnum, 1)
   1674 
   1675       # initialize conceal info to act like not concealed, just in case
   1676       var concealinfo = [0, '']
   1677 
   1678       # Loop over each character in the line
   1679       var col = 1
   1680 
   1681       # most of the time we won't use the diff_id, initialize to zero
   1682       var diff_id = 0
   1683 
   1684       while col <= len || (col == 1 && diffattr != 0)
   1685 	var id: number
   1686 	var startcol = col # The start column for processing text
   1687 	if !settings.ignore_conceal && has('conceal')
   1688 	  concealinfo = synconcealed(lnum, col)
   1689 	endif
   1690 	if !settings.ignore_conceal && concealinfo[0]
   1691 	  col = col + 1
   1692 	  # Speed loop (it's small - that's the trick)
   1693 	  # Go along till we find a change in the match sequence number (ending
   1694 	  # the specific concealed region) or until there are no more concealed
   1695 	  # characters.
   1696 	  while col <= len && concealinfo == synconcealed(lnum, col) | col = col + 1 | endwhile
   1697 	elseif diffattr != 0
   1698 	  diff_id = diff_hlID(lnum, col)
   1699 	  id = synID(lnum, col, 1)
   1700 	  col = col + 1
   1701 	  # Speed loop (it's small - that's the trick)
   1702 	  # Go along till we find a change in hlID
   1703 	  while col <= len && id == synID(lnum, col, 1) && diff_id == diff_hlID(lnum, col)
   1704 	    col = col + 1
   1705 	  endwhile
   1706 	  if len < &columns && !settings.no_pre
   1707 	    # Add spaces at the end of the raw text line to extend the changed
   1708 	    # line to the full width.
   1709 	    line = line .. repeat(' ', &columns - virtcol([lnum, len]) - margin)
   1710 	    len = &columns
   1711 	  endif
   1712 	else
   1713 	  id = synID(lnum, col, 1)
   1714 	  col = col + 1
   1715 	  # Speed loop (it's small - that's the trick)
   1716 	  # Go along till we find a change in synID
   1717 	  while col <= len && id == synID(lnum, col, 1) | col = col + 1 | endwhile
   1718 	endif
   1719 	var expandedtab: string
   1720 	if settings.ignore_conceal || !concealinfo[0]
   1721 	  # Expand tabs if needed
   1722 	  expandedtab = strpart(line, startcol - 1, col - startcol)
   1723 	  if settings.expand_tabs
   1724 	    var offset = 0
   1725 	    var idx = stridx(expandedtab, "\t")
   1726 	    var tablist = mapnew(split(&vts, ','), (_, v) => str2nr(v))
   1727 	    if empty(tablist)
   1728 	      tablist = [&ts]
   1729 	    endif
   1730 	    var tabidx = 0
   1731 	    var tabwidth = 0
   1732 	    var i: number
   1733 	    while idx >= 0
   1734 	      if startcol + idx == 1
   1735 		i = tablist[0]
   1736 	      else
   1737 		# Get the character, which could be multiple bytes, which falls
   1738 		# immediately before the found tab. Extract it by matching a
   1739 		# character just prior to the column where the tab matches.
   1740 		# We'll use this to get the byte index of the character
   1741 		# immediately preceding the tab, so we can then look up the
   1742 		# virtual column that character appears in, to determine how
   1743 		# much of the current tabstop has been used up.
   1744 		var prevc: string
   1745 		if idx == 0
   1746 		  # if the found tab is the first character in the text being
   1747 		  # processed, we need to get the character prior to the text,
   1748 		  # given by startcol.
   1749 		  prevc = matchstr(line, '.\%' .. (startcol + offset) .. 'c')
   1750 		else
   1751 		  # Otherwise, the byte index of the tab into expandedtab is
   1752 		  # given by idx.
   1753 		  prevc = matchstr(expandedtab, '.\%' .. (idx + 1) .. 'c')
   1754 		endif
   1755 		var vcol = virtcol([lnum, startcol + idx + offset - len(prevc)])
   1756 
   1757 		# find the tabstop interval to use for the tab we just found. Keep
   1758 		# adding tabstops (which could be variable) until we would exceed
   1759 		# the virtual screen position of the start of the found tab.
   1760 		while vcol >= tabwidth + tablist[tabidx]
   1761 		  tabwidth += tablist[tabidx]
   1762 		  if tabidx < len(tablist) - 1
   1763 		    tabidx = tabidx + 1
   1764 		  endif
   1765 		endwhile
   1766 		i = tablist[tabidx] - (vcol - tabwidth)
   1767 	      endif
   1768 	      # update offset to keep the index within the line corresponding to
   1769 	      # actual tab characters instead of replaced spaces; idx reflects
   1770 	      # replaced spaces in expandedtab, offset cancels out all but
   1771 	      # the tab character itself.
   1772 	      offset -= i - 1
   1773 	      expandedtab = substitute(expandedtab, '\t', repeat(' ', i), '')
   1774 	      idx = stridx(expandedtab, "\t")
   1775 	    endwhile
   1776 	  endif
   1777 
   1778 	  # get the highlight group name to use
   1779 	  id = synIDtrans(id)
   1780 	else
   1781 	  # use Conceal highlighting for concealed text
   1782 	  id = CONCEAL_ID
   1783 	  expandedtab = concealinfo[1]
   1784 	endif
   1785 
   1786 	# Output the text with the same synID, with class set to the highlight ID
   1787 	# name, unless it has been concealed completely.
   1788 	if strlen(expandedtab) > 0
   1789 	  new = new .. HtmlFormat(expandedtab, id, diff_id, "", false)
   1790 	endif
   1791       endwhile
   1792     endif
   1793 
   1794     extend(lines, split(new .. HtmlEndline, '\n', 1))
   1795     if !settings.no_progress && pgb.needs_redraw
   1796       redrawstatus
   1797       pgb.needs_redraw = 0
   1798     endif
   1799     lnum = lnum + 1
   1800 
   1801     if !settings.no_progress
   1802       pgb.Incr()
   1803     endif
   1804   endwhile
   1805 enddef
   1806 ProcessLines()
   1807 
   1808 # Diff filler is returned based on what needs inserting *before* the given line.
   1809 # So to get diff filler at the end of the buffer, we need to use last line + 1
   1810 Add_diff_fill(end + 1)
   1811 
   1812 if settings.dynamic_folds
   1813   # finish off any open folds
   1814   while !empty(foldstack)
   1815     lines[-1] ..= "</span></span>"
   1816     remove(foldstack, 0)
   1817   endwhile
   1818 
   1819   # add fold column to the style list if not already there
   1820   var id = FOLD_C_ID
   1821   if !has_key(stylelist, id)
   1822     stylelist[id] = '.FoldColumn { ' .. CSS1(id) .. '}'
   1823   endif
   1824 endif
   1825 
   1826 if settings.no_pre
   1827   if !settings.use_css
   1828     # Close off the font tag that encapsulates the whole <body>
   1829     extend(lines, ["</font>"])
   1830   else
   1831     extend(lines, ["</div>"])
   1832   endif
   1833 else
   1834   extend(lines, ["</pre>"])
   1835 endif
   1836 if !settings.no_doc
   1837   extend(lines, ["</body>", "</html>"])
   1838 endif
   1839 
   1840 execute $":{newwin}wincmd w"
   1841 setline(1, lines)
   1842 
   1843 # Mangle modelines so Vim doesn't try to use HTML text as a modeline if editing
   1844 # this file in the future; need to do this after generating all the text in case
   1845 # the modeline text has different highlight groups which all turn out to be
   1846 # stripped from the final output.
   1847 :%s!\v(%(^|\s+)%([Vv]i%(m%([<=>]?\d+)?)?|ex)):!\1\&#0058;!ge
   1848 
   1849 # The generated HTML is admittedly ugly and takes a LONG time to fold.
   1850 # Make sure the user doesn't do syntax folding when loading a generated file,
   1851 # using a modeline.
   1852 if !settings.no_modeline
   1853   append(line('$'), "<!-- vim: set foldmethod=manual : -->")
   1854 endif
   1855 
   1856 # Now, when we finally know which, we define the colors and styles
   1857 if settings.use_css && !settings.no_doc
   1858   :1;/<style\>/+1
   1859 
   1860   # Normal/global attributes
   1861   if settings.no_pre
   1862     append('.', "body { color: " .. fgc .. "; background-color: " .. bgc .. "; font-family: " .. htmlfont .. "; }")
   1863     :+
   1864   else
   1865     append('.', "pre { " .. whitespace .. "font-family: " .. htmlfont .. "; color: " .. fgc .. "; background-color: " .. bgc .. "; }")
   1866     :+
   1867     yank
   1868     put
   1869     execute "normal! ^cwbody\e"
   1870     # body should not have the wrap formatting, only the pre section
   1871     if whitespace != ''
   1872       execute 's#' .. whitespace
   1873     endif
   1874   endif
   1875   # fix browser inconsistencies (sometimes within the same browser) of different
   1876   # default font size for different elements
   1877   append('.', '* { font-size: 1em; }')
   1878   :+
   1879   # use color scheme styles for links
   1880   # browser-default blue/purple colors for links don't look like the existing theme and are unreadable on dark backgrounds
   1881   append('.', 'a { color: inherit; }')
   1882   :+
   1883   # if we use any input elements for unselectable content, make sure they look
   1884   # like normal text
   1885   if !empty(settings.prevent_copy)
   1886     if settings.use_input_for_pc !=# "none"
   1887       append('.', 'input { border: none; margin: 0; padding: 0; font-family: ' .. htmlfont .. '; }')
   1888       :+
   1889       # ch units for browsers which support them, em units for a somewhat
   1890       # reasonable fallback.
   1891       for w in range(1, 20, 1)
   1892 	append('.', [
   1893 	  "input[size='" .. w .. "'] { width: " .. w .. "em; width: " .. w .. "ch; }"
   1894 	])
   1895 	:+
   1896       endfor
   1897     endif
   1898 
   1899     if settings.use_input_for_pc !=# 'all'
   1900       var unselectable_styles: list<string> = []
   1901       if settings.prevent_copy =~# 'f'
   1902 	add(unselectable_styles, 'FoldColumn')
   1903       endif
   1904       if settings.prevent_copy =~# 'n'
   1905 	add(unselectable_styles, 'LineNr')
   1906       endif
   1907       if settings.prevent_copy =~# 't' && !settings.ignore_folding
   1908 	add(unselectable_styles, 'Folded')
   1909       endif
   1910       if settings.prevent_copy =~# 'd'
   1911 	add(unselectable_styles, 'DiffDelete')
   1912       endif
   1913       if settings.use_input_for_pc !=# 'none'
   1914 	append('.', [
   1915 	  '/* Note: IE does not support @supports conditionals, but also does not fully support',
   1916 	  '   "content:" with custom content, so we *want* the check to fail */',
   1917 	  '@supports ( content: attr(data-custom-content) ) {'
   1918 	])
   1919 	:+3
   1920       endif
   1921       # The line number column inside the foldtext is styled just like the fold
   1922       # text in Vim, but it should use the prevent_copy settings of line number
   1923       # rather than fold text. Apply the prevent_copy styles to foldtext
   1924       # specifically for line numbers, which always come after the fold column,
   1925       # or at the beginning of the line.
   1926       if settings.prevent_copy =~# 'n' && !settings.ignore_folding
   1927 	append('.', [
   1928 	  '  .FoldColumn + .Folded, .Folded:first-child { user-select: none; }',
   1929 	  '  .FoldColumn + [data-Folded-content]::before, [data-Folded-content]:first-child::before { content: attr(data-Folded-content); }',
   1930 	  '  .FoldColumn + [data-Folded-content]::before, [data-Folded-content]:first-child::before { padding-bottom: 1px; display: inline-block; /* match the 1-px padding of standard items with background */ }',
   1931 	  '  .FoldColumn + span[data-Folded-content]::before, [data-Folded-content]:first-child::before { cursor: default; }',
   1932 	])
   1933 	:+4
   1934       endif
   1935       for style_name in unselectable_styles
   1936 	append('.', [
   1937 	  '  .' .. style_name .. ' { user-select: none; }',
   1938 	  '  [data-' .. style_name .. '-content]::before { content: attr(data-' .. style_name .. '-content); }',
   1939 	  '  [data-' .. style_name .. '-content]::before { padding-bottom: 1px; display: inline-block; /* match the 1-px padding of standard items with background */ }',
   1940 	  '  span[data-' .. style_name .. '-content]::before { cursor: default; }',
   1941 	])
   1942 	:+4
   1943       endfor
   1944       if settings.use_input_for_pc !=# 'none'
   1945 	# Note, the extra '}' is to match the "@supports" above
   1946 	append('.', [
   1947 	  '  input { display: none; }',
   1948 	  '}'
   1949 	])
   1950 	:+2
   1951       endif
   1952     endif
   1953 
   1954     # Fix mouse cursor shape for the fallback <input> method of uncopyable text
   1955     if settings.use_input_for_pc !=# 'none'
   1956       if settings.prevent_copy =~# 'f'
   1957 	# Make the cursor show active fold columns as active areas, and empty fold
   1958 	# columns as not interactive.
   1959 	append('.', ['input.FoldColumn { cursor: pointer; }',
   1960 	  'input.FoldColumn[value="' .. repeat(' ', foldcolumn) .. '"] { cursor: default; }'
   1961 	])
   1962 	:+2
   1963 	if settings.use_input_for_pc !=# 'all'
   1964 	  append('.', [
   1965 	    'a[data-FoldColumn-content="' .. repeat(' ', foldcolumn) .. '"] { cursor: default; }'
   1966 	  ])
   1967 	  :+1
   1968 	endif
   1969       endif
   1970       # make line number column show as non-interactive if not selectable
   1971       if settings.prevent_copy =~# 'n'
   1972 	append('.', 'input.LineNr { cursor: default; }')
   1973 	:+
   1974       endif
   1975       # make fold text and line number column within fold text show as
   1976       # non-interactive if not selectable
   1977       if (settings.prevent_copy =~# 'n' || settings.prevent_copy =~# 't') && !settings.ignore_folding
   1978 	append('.', 'input.Folded { cursor: default; }')
   1979 	:+
   1980       endif
   1981       # make diff filler show as non-interactive if not selectable
   1982       if settings.prevent_copy =~# 'd'
   1983 	append('.', 'input.DiffDelete { cursor: default; }')
   1984 	:+
   1985       endif
   1986     endif
   1987   endif
   1988 endif
   1989 
   1990 if !settings.use_css && !settings.no_doc
   1991   # For Netscape 4, set <body> attributes too, though, strictly speaking, it's
   1992   # incorrect.
   1993   execute $':%s/<body\([^>]*\)/<body bgcolor="{bgc}" text="{fgc}"\1>\r<font face="{htmlfont}"'
   1994 endif
   1995 
   1996 # Gather attributes for all other classes. Do diff first so that normal
   1997 # highlight groups are inserted before it.
   1998 if settings.use_css && !settings.no_doc
   1999   if diff_mode
   2000     append('.', filter(map(keys(diffstylelist), (_, k) => diffstylelist[k]), (_, v) => v != ""))
   2001   endif
   2002   if !empty(stylelist)
   2003     append('.', filter(map(keys(stylelist), (_, k) => stylelist[k]), (_, v) => v != ""))
   2004   endif
   2005 endif
   2006 
   2007 # Add hyperlinks
   2008 if !settings.no_links
   2009   :%s+\(https\=://\S\{-}\)\(\([.,;:}]\=\(\s\|$\)\)\|[\\"'<>]\|&gt;\|&lt;\|&quot;\)+<a href="\1">\1</a>\2+ge
   2010 endif
   2011 
   2012 # The DTD
   2013 if !settings.no_doc
   2014   if settings.use_xhtml
   2015     execute "normal! gg$a\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
   2016   elseif html5
   2017     execute "normal! gg0i<!DOCTYPE html>\n"
   2018   else
   2019     execute "normal! gg0i<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
   2020   endif
   2021 endif
   2022 
   2023 if settings.use_xhtml && !settings.no_doc
   2024   execute "normal! gg/<html/e\na xmlns=\"http://www.w3.org/1999/xhtml\"\e"
   2025 endif
   2026 
   2027 # Cleanup
   2028 :%s/\s\+$//e
   2029 
   2030 # Restore old settings (new window first)
   2031 #
   2032 # Don't bother restoring foldmethod in case it was syntax because the markup is
   2033 # so weirdly formatted it can take a LONG time.
   2034 &l:foldenable = old_fen
   2035 &report = old_report
   2036 &title = old_title
   2037 &icon = old_icon
   2038 &paste = old_paste
   2039 &magic = old_magic
   2040 @/ = old_search
   2041 &more = old_more
   2042 
   2043 # switch to original window to restore those settings
   2044 execute $":{orgwin}wincmd w"
   2045 
   2046 if !settings.expand_tabs
   2047   &l:isprint = old_isprint
   2048 endif
   2049 &l:stl = origwin_stl
   2050 &l:et = old_et
   2051 &l:scrollbind = old_bind
   2052 
   2053 # and back to the new window again to end there
   2054 execute $":{newwin}wincmd w"
   2055 
   2056 &l:stl = newwin_stl
   2057 execute 'resize' old_winheight
   2058 &l:winfixheight = old_winfixheight
   2059 
   2060 &laststatus = ls_sav
   2061 &eventignore = ei_sav
   2062 
   2063 # Make sure any patches will probably use consistent indent
   2064 #   vim: ts=8 sw=2 sts=2 noet