robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
43.9 KiB1417 linesraw
1--- @brief
2---<pre>help
3---:[range]TOhtml {file}                                                *:TOhtml*
4---Converts the buffer shown in the current window to HTML, opens the generated
5---HTML in a new split window, and saves its contents to {file}. If {file} is not
6---given, a temporary file (created by |tempname()|) is used.
7---</pre>
8---
9--- The plugin is not loaded by default; use `:packadd` to activate it:
10--- ```
11--- :packadd nvim.tohtml
12--- ```
13
14-- This HTML conversion script is different from Vim's. If you want to use Vim's TOhtml converter,
15-- download the related files from the Vim repo:
16-- - https://github.com/vim/vim/blob/master/runtime/syntax/2html.vim
17-- - https://github.com/vim/vim/blob/master/runtime/autoload/tohtml.vim
18-- - https://github.com/vim/vim/blob/master/runtime/plugin/tohtml.vim
19--
20-- Main differences between this and the Vim version:
21-- - No "ignore some visual thing" settings (just set the right Vim option)
22-- - No support for legacy web engines
23-- - No support for legacy encoding (supports only UTF-8)
24-- - No interactive webpage
25-- - No specifying the internal HTML (no XHTML, no use_css=false)
26-- - No multiwindow diffs
27-- - No ranges
28--
29-- Remarks:
30-- - Not all visuals are supported, so it may differ.
31
32--- @class (private) vim.tohtml.state.global
33--- @field background string
34--- @field foreground string
35--- @field title string|false
36--- @field font string
37--- @field highlights_name table<integer,string>
38--- @field conf vim.tohtml.opt
39
40--- @class (private) vim.tohtml.state:vim.tohtml.state.global
41--- @field style vim.tohtml.styletable
42--- @field tabstop string|false
43--- @field opt vim.wo
44--- @field winid integer
45--- @field bufnr integer
46--- @field width integer
47--- @field start integer
48--- @field end_ integer
49
50--- @class (private) vim.tohtml.styletable
51--- @field [integer] vim.tohtml.line (integer: (1-index, exclusive))
52
53--- @class (private) vim.tohtml.line
54--- @field virt_lines {[integer]:[string,integer][]}
55--- @field pre_text [string, integer?][]
56--- @field hide? boolean
57--- @field [integer] vim.tohtml.cell? (integer: (1-index, exclusive))
58
59--- @class (private) vim.tohtml.cell
60--- @field [1] integer[] start
61--- @field [2] integer[] close
62--- @field [3] any[][] virt_text
63--- @field [4] any[][] overlay_text
64
65--- @type string[]
66local notifications = {}
67
68---@param msg string
69local function notify(msg)
70  if #notifications == 0 then
71    vim.schedule(function()
72      if #notifications > 1 then
73        vim.notify(('TOhtml: %s (+ %d more warnings)'):format(notifications[1], #notifications - 1))
74      elseif #notifications == 1 then
75        vim.notify('TOhtml: ' .. notifications[1])
76      end
77      notifications = {}
78    end)
79  end
80  table.insert(notifications, msg)
81end
82
83local HIDE_ID = -1
84-- stylua: ignore start
85local cterm_8_to_hex={
86  [0] = "#808080", "#ff6060", "#00ff00", "#ffff00",
87  "#8080ff", "#ff40ff", "#00ffff", "#ffffff",
88}
89local cterm_16_to_hex={
90  [0] = "#000000", "#c00000", "#008000", "#804000",
91  "#0000c0", "#c000c0", "#008080", "#c0c0c0",
92  "#808080", "#ff6060", "#00ff00", "#ffff00",
93  "#8080ff", "#ff40ff", "#00ffff", "#ffffff",
94}
95local cterm_88_to_hex={
96  [0] = "#000000", "#c00000", "#008000", "#804000",
97  "#0000c0", "#c000c0", "#008080", "#c0c0c0",
98  "#808080", "#ff6060", "#00ff00", "#ffff00",
99  "#8080ff", "#ff40ff", "#00ffff", "#ffffff",
100  "#000000", "#00008b", "#0000cd", "#0000ff",
101  "#008b00", "#008b8b", "#008bcd", "#008bff",
102  "#00cd00", "#00cd8b", "#00cdcd", "#00cdff",
103  "#00ff00", "#00ff8b", "#00ffcd", "#00ffff",
104  "#8b0000", "#8b008b", "#8b00cd", "#8b00ff",
105  "#8b8b00", "#8b8b8b", "#8b8bcd", "#8b8bff",
106  "#8bcd00", "#8bcd8b", "#8bcdcd", "#8bcdff",
107  "#8bff00", "#8bff8b", "#8bffcd", "#8bffff",
108  "#cd0000", "#cd008b", "#cd00cd", "#cd00ff",
109  "#cd8b00", "#cd8b8b", "#cd8bcd", "#cd8bff",
110  "#cdcd00", "#cdcd8b", "#cdcdcd", "#cdcdff",
111  "#cdff00", "#cdff8b", "#cdffcd", "#cdffff",
112  "#ff0000", "#ff008b", "#ff00cd", "#ff00ff",
113  "#ff8b00", "#ff8b8b", "#ff8bcd", "#ff8bff",
114  "#ffcd00", "#ffcd8b", "#ffcdcd", "#ffcdff",
115  "#ffff00", "#ffff8b", "#ffffcd", "#ffffff",
116  "#2e2e2e", "#5c5c5c", "#737373", "#8b8b8b",
117  "#a2a2a2", "#b9b9b9", "#d0d0d0", "#e7e7e7",
118}
119local cterm_256_to_hex={
120  [0] = "#000000", "#c00000", "#008000", "#804000",
121  "#0000c0", "#c000c0", "#008080", "#c0c0c0",
122  "#808080", "#ff6060", "#00ff00", "#ffff00",
123  "#8080ff", "#ff40ff", "#00ffff", "#ffffff",
124  "#000000", "#00005f", "#000087", "#0000af",
125  "#0000d7", "#0000ff", "#005f00", "#005f5f",
126  "#005f87", "#005faf", "#005fd7", "#005fff",
127  "#008700", "#00875f", "#008787", "#0087af",
128  "#0087d7", "#0087ff", "#00af00", "#00af5f",
129  "#00af87", "#00afaf", "#00afd7", "#00afff",
130  "#00d700", "#00d75f", "#00d787", "#00d7af",
131  "#00d7d7", "#00d7ff", "#00ff00", "#00ff5f",
132  "#00ff87", "#00ffaf", "#00ffd7", "#00ffff",
133  "#5f0000", "#5f005f", "#5f0087", "#5f00af",
134  "#5f00d7", "#5f00ff", "#5f5f00", "#5f5f5f",
135  "#5f5f87", "#5f5faf", "#5f5fd7", "#5f5fff",
136  "#5f8700", "#5f875f", "#5f8787", "#5f87af",
137  "#5f87d7", "#5f87ff", "#5faf00", "#5faf5f",
138  "#5faf87", "#5fafaf", "#5fafd7", "#5fafff",
139  "#5fd700", "#5fd75f", "#5fd787", "#5fd7af",
140  "#5fd7d7", "#5fd7ff", "#5fff00", "#5fff5f",
141  "#5fff87", "#5fffaf", "#5fffd7", "#5fffff",
142  "#870000", "#87005f", "#870087", "#8700af",
143  "#8700d7", "#8700ff", "#875f00", "#875f5f",
144  "#875f87", "#875faf", "#875fd7", "#875fff",
145  "#878700", "#87875f", "#878787", "#8787af",
146  "#8787d7", "#8787ff", "#87af00", "#87af5f",
147  "#87af87", "#87afaf", "#87afd7", "#87afff",
148  "#87d700", "#87d75f", "#87d787", "#87d7af",
149  "#87d7d7", "#87d7ff", "#87ff00", "#87ff5f",
150  "#87ff87", "#87ffaf", "#87ffd7", "#87ffff",
151  "#af0000", "#af005f", "#af0087", "#af00af",
152  "#af00d7", "#af00ff", "#af5f00", "#af5f5f",
153  "#af5f87", "#af5faf", "#af5fd7", "#af5fff",
154  "#af8700", "#af875f", "#af8787", "#af87af",
155  "#af87d7", "#af87ff", "#afaf00", "#afaf5f",
156  "#afaf87", "#afafaf", "#afafd7", "#afafff",
157  "#afd700", "#afd75f", "#afd787", "#afd7af",
158  "#afd7d7", "#afd7ff", "#afff00", "#afff5f",
159  "#afff87", "#afffaf", "#afffd7", "#afffff",
160  "#d70000", "#d7005f", "#d70087", "#d700af",
161  "#d700d7", "#d700ff", "#d75f00", "#d75f5f",
162  "#d75f87", "#d75faf", "#d75fd7", "#d75fff",
163  "#d78700", "#d7875f", "#d78787", "#d787af",
164  "#d787d7", "#d787ff", "#d7af00", "#d7af5f",
165  "#d7af87", "#d7afaf", "#d7afd7", "#d7afff",
166  "#d7d700", "#d7d75f", "#d7d787", "#d7d7af",
167  "#d7d7d7", "#d7d7ff", "#d7ff00", "#d7ff5f",
168  "#d7ff87", "#d7ffaf", "#d7ffd7", "#d7ffff",
169  "#ff0000", "#ff005f", "#ff0087", "#ff00af",
170  "#ff00d7", "#ff00ff", "#ff5f00", "#ff5f5f",
171  "#ff5f87", "#ff5faf", "#ff5fd7", "#ff5fff",
172  "#ff8700", "#ff875f", "#ff8787", "#ff87af",
173  "#ff87d7", "#ff87ff", "#ffaf00", "#ffaf5f",
174  "#ffaf87", "#ffafaf", "#ffafd7", "#ffafff",
175  "#ffd700", "#ffd75f", "#ffd787", "#ffd7af",
176  "#ffd7d7", "#ffd7ff", "#ffff00", "#ffff5f",
177  "#ffff87", "#ffffaf", "#ffffd7", "#ffffff",
178  "#080808", "#121212", "#1c1c1c", "#262626",
179  "#303030", "#3a3a3a", "#444444", "#4e4e4e",
180  "#585858", "#626262", "#6c6c6c", "#767676",
181  "#808080", "#8a8a8a", "#949494", "#9e9e9e",
182  "#a8a8a8", "#b2b2b2", "#bcbcbc", "#c6c6c6",
183  "#d0d0d0", "#dadada", "#e4e4e4", "#eeeeee",
184}
185-- stylua: ignore end
186
187--- @type table<integer,string>
188local cterm_color_cache = {}
189--- @type string?
190local background_color_cache = nil
191--- @type string?
192local foreground_color_cache = nil
193
194local len = vim.api.nvim_strwidth
195
196--- @see https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands
197--- @param color "background"|"foreground"|integer
198--- @return string?
199local function try_query_terminal_color(color)
200  local parameter = (color == 'foreground' and 10) or (color == 'background' and 11) or 4
201  local payload = type(color) == 'number' and ('\027]%s;%s;?\027\\'):format(parameter, color)
202    or ('\027]%s;?\027\\'):format(parameter)
203
204  --- @type string?
205  local hex = nil
206  vim.tty.request(payload, { timeout = 100 }, function(resp)
207    local r, g, b = resp:match('\027%]%d+;%d*;?rgb:(%w%w)%w%w/(%w%w)%w%w/(%w%w)%w%w') ---@type string?, string?, string?
208    if r and g and b then
209      hex = '#' .. r .. g .. b
210      return true
211    end
212  end)
213  vim.wait(100, function()
214    return hex ~= nil
215  end)
216  return hex
217end
218
219--- @param colorstr string
220--- @return string
221local function cterm_to_hex(colorstr)
222  if colorstr:sub(1, 1) == '#' then
223    return colorstr
224  end
225  local color = vim._assert_integer(colorstr)
226  assert(0 <= color and color <= 255)
227  if cterm_color_cache[color] then
228    return cterm_color_cache[color]
229  end
230  local hex = try_query_terminal_color(color)
231  if hex then
232    cterm_color_cache[color] = hex
233  else
234    notify("Couldn't get terminal colors, using fallback")
235    local t_Co = vim._assert_integer(vim.api.nvim_eval('&t_Co'))
236    if t_Co <= 8 then
237      cterm_color_cache = cterm_8_to_hex
238    elseif t_Co == 88 then
239      cterm_color_cache = cterm_88_to_hex
240    elseif t_Co == 256 then
241      cterm_color_cache = cterm_256_to_hex
242    else
243      cterm_color_cache = cterm_16_to_hex
244    end
245  end
246  -- EmmyLua retains the failed lookup narrowing after the cache is updated.
247  ---@diagnostic disable-next-line: return-type-mismatch
248  return cterm_color_cache[color]
249end
250
251--- @return string
252local function get_background_color()
253  local bg = vim.fn.synIDattr(vim.fn.hlID('Normal'), 'bg#')
254  if bg ~= '' then
255    return cterm_to_hex(bg)
256  end
257  if background_color_cache then
258    return background_color_cache
259  end
260  local hex = try_query_terminal_color('background')
261  if not hex or not hex:match('#%x%x%x%x%x%x') then
262    notify("Couldn't get terminal background colors, using fallback")
263    hex = vim.o.background == 'light' and '#ffffff' or '#000000'
264  end
265  background_color_cache = hex
266  return hex
267end
268
269--- @return string
270local function get_foreground_color()
271  local fg = vim.fn.synIDattr(vim.fn.hlID('Normal'), 'fg#')
272  if fg ~= '' then
273    return cterm_to_hex(fg)
274  end
275  if foreground_color_cache then
276    return foreground_color_cache
277  end
278  local hex = try_query_terminal_color('foreground')
279  if not hex or not hex:match('#%x%x%x%x%x%x') then
280    notify("Couldn't get terminal foreground colors, using fallback")
281    hex = vim.o.background == 'light' and '#000000' or '#ffffff'
282  end
283  foreground_color_cache = hex
284  return hex
285end
286
287--- @param style_line vim.tohtml.line
288--- @param col integer (1-index)
289--- @param field integer
290--- @param val any
291local function _style_line_insert(style_line, col, field, val)
292  if style_line[col] == nil then
293    style_line[col] = { {}, {}, {}, {} }
294  end
295  table.insert(assert(style_line[col][field]), val)
296end
297
298--- @param style_line vim.tohtml.line
299--- @param col integer (1-index)
300--- @param val any[]
301local function style_line_insert_overlay_char(style_line, col, val)
302  _style_line_insert(style_line, col, 4, val)
303end
304
305--- @param style_line vim.tohtml.line
306--- @param col integer (1-index)
307--- @param val any[]
308local function style_line_insert_virt_text(style_line, col, val)
309  _style_line_insert(style_line, col, 3, val)
310end
311
312--- @param state vim.tohtml.state
313--- @param hl string|integer|string[]|integer[]?
314--- @return nil|integer
315local function register_hl(state, hl)
316  if type(hl) == 'table' then
317    hl = hl[#hl] --- @type string|integer
318  end
319  if type(hl) == 'nil' then
320    return
321  elseif type(hl) == 'string' then
322    hl = vim.fn.hlID(hl)
323    assert(hl ~= 0)
324  end
325  hl = vim.fn.synIDtrans(hl)
326  if not state.highlights_name[hl] then
327    local name = vim.fn.synIDattr(hl, 'name')
328    assert(name ~= '')
329    state.highlights_name[hl] = name
330  end
331  return hl
332end
333
334--- @param state vim.tohtml.state
335--- @param start_row integer (1-index)
336--- @param start_col integer (1-index)
337--- @param end_row integer (1-index)
338--- @param end_col integer (1-index)
339--- @param conceal_text string
340--- @param hl_group string|integer?
341local function styletable_insert_conceal(
342  state,
343  start_row,
344  start_col,
345  end_row,
346  end_col,
347  conceal_text,
348  hl_group
349)
350  assert(state.opt.conceallevel > 0)
351  local styletable = state.style
352  if start_col == end_col and start_row == end_row then
353    return
354  end
355  if state.opt.conceallevel == 1 and conceal_text == '' then
356    local listchars = vim.opt_local.listchars:get() --[[@as table<string,string>]]
357    conceal_text = listchars.conceal or ' '
358  end
359  local hlid = register_hl(state, hl_group)
360  if vim.wo[state.winid].conceallevel ~= 3 then
361    _style_line_insert(styletable[start_row], start_col, 3, { conceal_text, hlid })
362  end
363  _style_line_insert(styletable[start_row], start_col, 1, HIDE_ID)
364  _style_line_insert(styletable[end_row], end_col, 2, HIDE_ID)
365end
366
367--- @param state vim.tohtml.state
368--- @param start_row integer (1-index)
369--- @param start_col integer (1-index)
370--- @param end_row integer (1-index)
371--- @param end_col integer (1-index)
372--- @param hl_group string|integer|nil
373local function styletable_insert_range(state, start_row, start_col, end_row, end_col, hl_group)
374  if start_col == end_col and start_row == end_row or not hl_group then
375    return
376  end
377  local styletable = state.style
378  _style_line_insert(styletable[start_row], start_col, 1, hl_group)
379  _style_line_insert(styletable[end_row], end_col, 2, hl_group)
380end
381
382--- @param bufnr integer
383--- @return vim.tohtml.styletable
384local function generate_styletable(bufnr)
385  --- @type vim.tohtml.styletable
386  local styletable = {}
387  for row = 1, vim.api.nvim_buf_line_count(bufnr) + 1 do
388    styletable[row] = { virt_lines = {}, pre_text = {} }
389  end
390  return styletable
391end
392
393--- @param state vim.tohtml.state
394local function styletable_syntax(state)
395  for row = state.start, state.end_ do
396    local prev_id = 0
397    local prev_col --- @type integer?
398    for col = 1, #vim.fn.getline(row) + 1 do
399      local hlid = vim.fn.synID(row, col, 1)
400      hlid = hlid == 0 and 0 or assert(register_hl(state, hlid))
401      if hlid ~= prev_id then
402        if prev_id ~= 0 then
403          styletable_insert_range(state, row, assert(prev_col), row, col, prev_id)
404        end
405        prev_col = col
406        prev_id = hlid
407      end
408    end
409  end
410end
411
412--- @param state vim.tohtml.state
413local function styletable_diff(state)
414  local styletable = state.style
415  for row = state.start, state.end_ do
416    local style_line = styletable[row]
417    local filler = vim.fn.diff_filler(row)
418    if filler ~= 0 then
419      local fillchars = vim.opt_local.fillchars:get() --[[@as table<string,string>]]
420      local fill = fillchars.diff or '-'
421      table.insert(
422        style_line.virt_lines,
423        { { fill:rep(state.width), register_hl(state, 'DiffDelete') } }
424      )
425    end
426    if row == state.end_ + 1 then
427      break
428    end
429    local prev_id = 0
430    local prev_col --- @type integer?
431    for col = 1, #vim.fn.getline(row) do
432      local hlid = vim.fn.diff_hlID(row, col)
433      hlid = hlid == 0 and 0 or assert(register_hl(state, hlid))
434      if hlid ~= prev_id then
435        if prev_id ~= 0 then
436          styletable_insert_range(state, row, assert(prev_col), row, col, prev_id)
437        end
438        prev_col = col
439        prev_id = hlid
440      end
441    end
442    if prev_id ~= 0 then
443      styletable_insert_range(state, row, assert(prev_col), row, #vim.fn.getline(row) + 1, prev_id)
444    end
445  end
446end
447
448--- @param state vim.tohtml.state
449local function styletable_treesitter(state)
450  local bufnr = state.bufnr
451  local buf_highlighter = vim.treesitter.highlighter.active[bufnr]
452  if not buf_highlighter then
453    return
454  end
455  buf_highlighter.tree:parse(true)
456  buf_highlighter.tree:for_each_tree(function(tstree, tree)
457    --- @cast tree vim.treesitter.LanguageTree
458    if not tstree then
459      return
460    end
461    local root = tstree:root()
462    local q = buf_highlighter:get_query(tree:lang())
463    --- @type vim.treesitter.Query?
464    local query = q:query()
465    if not query then
466      return
467    end
468    for capture, node, metadata in
469      query:iter_captures(root, buf_highlighter.bufnr, state.start - 1, state.end_)
470    do
471      local srow, scol, erow, ecol = node:range()
472      local c = query.captures[capture]
473      if c ~= nil then
474        local hlid = register_hl(state, '@' .. c .. '.' .. tree:lang())
475        if metadata.conceal and state.opt.conceallevel ~= 0 then
476          local conceal = metadata.conceal == true and '' or metadata.conceal --[[@as string]]
477          styletable_insert_conceal(state, srow + 1, scol + 1, erow + 1, ecol + 1, conceal)
478        end
479        styletable_insert_range(state, srow + 1, scol + 1, erow + 1, ecol + 1, hlid)
480      end
481    end
482  end)
483end
484
485--- @param state vim.tohtml.state
486--- @param extmark [integer, integer, integer, vim.api.keyset.extmark_details]
487--- @param namespaces table<integer,string>
488local function _styletable_extmarks_highlight(state, extmark, namespaces)
489  if not extmark[4].hl_group then
490    return
491  end
492  ---TODO(altermo) LSP semantic tokens (and some other extmarks) are only
493  ---generated in visible lines, and not in the whole buffer.
494  if (namespaces[extmark[4].ns_id] or ''):find('nvim.lsp.semantic_tokens') then
495    notify('lsp semantic tokens are not supported, HTML may be incorrect')
496    return
497  end
498  local srow, scol, erow, ecol =
499    extmark[2], extmark[3], extmark[4].end_row or extmark[2], extmark[4].end_col or extmark[3]
500  if scol == ecol and srow == erow then
501    return
502  end
503  local hlid = register_hl(state, extmark[4].hl_group)
504  styletable_insert_range(state, srow + 1, scol + 1, erow + 1, ecol + 1, hlid)
505end
506
507--- @param state vim.tohtml.state
508--- @param extmark [integer, integer, integer, vim.api.keyset.set_extmark|any]
509--- @param namespaces table<integer,string>
510local function _styletable_extmarks_virt_text(state, extmark, namespaces)
511  if not extmark[4].virt_text then
512    return
513  end
514  ---TODO(altermo) LSP semantic tokens (and some other extmarks) are only
515  ---generated in visible lines, and not in the whole buffer.
516  if (namespaces[extmark[4].ns_id] or ''):find('nvim.lsp.inlayhint') then
517    notify('lsp inlay hints are not supported, HTML may be incorrect')
518    return
519  end
520  local styletable = state.style
521  --- @type integer,integer
522  local row, col = extmark[2], extmark[3]
523  if
524    row < vim.api.nvim_buf_line_count(state.bufnr)
525    and (
526      extmark[4].virt_text_pos == 'inline'
527      or extmark[4].virt_text_pos == 'eol'
528      or extmark[4].virt_text_pos == 'overlay'
529    )
530  then
531    if extmark[4].virt_text_pos == 'eol' then
532      style_line_insert_virt_text(styletable[row + 1], #vim.fn.getline(row + 1) + 1, { ' ' })
533    end
534    local virt_text_len = 0
535    for _, i in
536      ipairs(extmark[4].virt_text --[[@as (string[][])]])
537    do
538      local hlid = register_hl(state, i[2])
539      if extmark[4].virt_text_pos == 'eol' then
540        style_line_insert_virt_text(
541          styletable[row + 1],
542          #vim.fn.getline(row + 1) + 1,
543          { i[1], hlid }
544        )
545      else
546        style_line_insert_virt_text(styletable[row + 1], col + 1, { i[1], hlid })
547      end
548      virt_text_len = virt_text_len + len(assert(i[1]))
549    end
550    if extmark[4].virt_text_pos == 'overlay' then
551      styletable_insert_range(state, row + 1, col + 1, row + 1, col + virt_text_len + 1, HIDE_ID)
552    end
553  end
554  local not_supported = {
555    virt_text_pos = 'right_align',
556    hl_mode = 'blend',
557    hl_group = 'combine',
558  }
559  for opt, val in pairs(not_supported) do
560    if extmark[4][opt] == val then
561      notify(('extmark.%s="%s" is not supported, HTML may be incorrect'):format(opt, val))
562    end
563  end
564end
565
566--- @param state vim.tohtml.state
567--- @param extmark [integer, integer, integer, vim.api.keyset.set_extmark|any]
568local function _styletable_extmarks_virt_lines(state, extmark)
569  ---TODO(altermo) if the fold start is equal to virt_line start then the fold hides the virt_line
570  if not extmark[4].virt_lines then
571    return
572  end
573  --- @type integer
574  local row = extmark[2] + (extmark[4].virt_lines_above and 1 or 2)
575  for _, line in
576    ipairs(extmark[4].virt_lines --[[@as (string[][][])]])
577  do
578    local virt_line = {}
579    for _, i in ipairs(line) do
580      local hlid = register_hl(state, i[2])
581      table.insert(virt_line, { i[1], hlid })
582    end
583    table.insert(state.style[row].virt_lines, virt_line)
584  end
585end
586
587--- @param state vim.tohtml.state
588--- @param extmark [integer, integer, integer, vim.api.keyset.extmark_details]
589local function _styletable_extmarks_conceal(state, extmark)
590  if not extmark[4].conceal or state.opt.conceallevel == 0 then
591    return
592  end
593  local srow, scol, erow, ecol =
594    extmark[2], extmark[3], extmark[4].end_row or extmark[2], extmark[4].end_col or extmark[3]
595  styletable_insert_conceal(
596    state,
597    srow + 1,
598    scol + 1,
599    erow + 1,
600    ecol + 1,
601    extmark[4].conceal,
602    extmark[4].hl_group or 'Conceal'
603  )
604end
605
606--- @param state vim.tohtml.state
607local function styletable_extmarks(state)
608  --TODO(altermo) extmarks may have col/row which is outside of the buffer, which could cause an error
609  local bufnr = state.bufnr
610  local extmarks = vim.api.nvim_buf_get_extmarks(bufnr, -1, 0, -1, { details = true })
611  --- @cast extmarks [integer,integer,integer,vim.api.keyset.extmark_details][]
612
613  local namespaces = {} --- @type table<integer, string>
614  for ns, ns_id in pairs(vim.api.nvim_get_namespaces()) do
615    namespaces[ns_id] = ns
616  end
617  for _, v in ipairs(extmarks) do
618    _styletable_extmarks_highlight(state, v, namespaces)
619  end
620  for _, v in ipairs(extmarks) do
621    _styletable_extmarks_conceal(state, v)
622  end
623  for _, v in ipairs(extmarks) do
624    _styletable_extmarks_virt_text(state, v, namespaces)
625  end
626  for _, v in ipairs(extmarks) do
627    _styletable_extmarks_virt_lines(state, v)
628  end
629end
630
631--- @param state vim.tohtml.state
632local function styletable_folds(state)
633  local styletable = state.style
634  local has_folded = false
635  for row = state.start, state.end_ do
636    if vim.fn.foldclosed(row) > 0 then
637      has_folded = true
638      styletable[row].hide = true
639    end
640    if vim.fn.foldclosed(row) == row then
641      local hlid = register_hl(state, 'Folded')
642      ---TODO(altermo): Is there a way to get highlighted foldtext?
643      local foldtext = vim.fn.foldtextresult(row)
644      local fillchars = vim.opt.fillchars:get() --[[@as table<string,string>]]
645      foldtext = foldtext .. (fillchars.fold or '·'):rep(state.width - #foldtext)
646      table.insert(styletable[row].virt_lines, { { foldtext, hlid } })
647    end
648  end
649  local foldtext = vim.o.foldtext
650  local foldtext_fn = type(foldtext) == 'function' and foldtext
651    or function()
652      return vim.api.nvim_eval(foldtext)
653    end
654  if has_folded and type(({ pcall(foldtext_fn) })[2]) == 'table' then
655    notify('foldtext returning a table with highlights is not supported, HTML may be incorrect')
656  end
657end
658
659--- @param state vim.tohtml.state
660local function styletable_conceal(state)
661  local bufnr = state.bufnr
662  vim._with({ buf = bufnr }, function()
663    for row = state.start, state.end_ do
664      --- @type table<integer,[integer,integer,string]>
665      local conceals = {}
666      local line_len_exclusive = #vim.fn.getline(row) + 1
667      for col = 1, line_len_exclusive do
668        --- @type integer,string,integer
669        local is_concealed, conceal, hlid = unpack(vim.fn.synconcealed(row, col) --[[@as table]])
670        if is_concealed ~= 0 then
671          if not conceals[hlid] then
672            conceals[hlid] = { col, math.min(col + 1, line_len_exclusive), conceal }
673          else
674            conceals[hlid][2] = math.min(col + 1, line_len_exclusive)
675          end
676        end
677      end
678      for _, v in pairs(conceals) do
679        styletable_insert_conceal(state, row, v[1], row, v[2], v[3], 'Conceal')
680      end
681    end
682  end)
683end
684
685--- @param state vim.tohtml.state
686local function styletable_match(state)
687  for _, match in ipairs(vim.fn.getmatches(state.winid)) do
688    local hlid = register_hl(state, match.group)
689    --- @param srow integer
690    --- @param scol integer
691    --- @param erow integer
692    --- @param ecol integer
693    local function range(srow, scol, erow, ecol)
694      if match.group == 'Conceal' and state.opt.conceallevel ~= 0 then
695        styletable_insert_conceal(state, srow, scol, erow, ecol, match.conceal or '', hlid)
696      else
697        styletable_insert_range(state, srow, scol, erow, ecol, hlid)
698      end
699    end
700    if match.pos1 then
701      for key, v in
702        pairs(match --[[@as table<string,[integer,integer,integer]>]])
703      do
704        if key:match('^pos(%d+)$') then
705          if #v == 1 then
706            range(v[1], 1, v[1], #vim.fn.getline(v[1]) + 1)
707          else
708            range(v[1], v[2], v[1], v[3] + v[2])
709          end
710        end
711      end
712    else
713      for _, v in
714        ipairs(vim.fn.matchbufline(state.bufnr, assert(match.pattern), 1, '$') --[[@as (table[])]])
715      do
716        range(v.lnum, v.byteidx + 1, v.lnum, v.byteidx + 1 + #v.text)
717      end
718    end
719  end
720end
721
722--- Requires state.conf.number_lines to be set to true
723--- @param state vim.tohtml.state
724local function styletable_statuscolumn(state)
725  if not state.conf.number_lines then
726    return
727  end
728  local statuscolumn = state.opt.statuscolumn
729
730  if statuscolumn == '' then
731    if state.opt.relativenumber then
732      if state.opt.number then
733        statuscolumn = '%C%s%{%v:lnum!=line(".")?"%=".v:relnum." ":v:lnum%}'
734      else
735        statuscolumn = '%C%s%{%"%=".v:relnum." "%}'
736      end
737    else
738      statuscolumn = '%C%s%{%"%=".v:lnum." "%}'
739    end
740  end
741  local minwidth = 0
742
743  local signcolumn = state.opt.signcolumn
744  if state.opt.number or state.opt.relativenumber then
745    minwidth = minwidth + state.opt.numberwidth
746    if signcolumn == 'number' then
747      signcolumn = 'no'
748    end
749  end
750  if signcolumn == 'number' then
751    signcolumn = 'auto'
752  end
753  if signcolumn ~= 'no' then
754    local max = vim._tointeger(signcolumn:match('^%w-:(%d)')) or 1
755    if signcolumn:match('^auto') then
756      --- @type table<integer,integer>
757      local signcount = {}
758      for _, extmark in
759        ipairs(vim.api.nvim_buf_get_extmarks(state.bufnr, -1, 0, -1, { details = true }))
760      do
761        --- @cast extmark [integer, integer, integer, vim.api.keyset.extmark_details]
762        if extmark[4].sign_text then
763          signcount[extmark[2]] = (signcount[extmark[2]] or 0) + 1
764        end
765      end
766      local maxsigns = 0
767      for _, v in pairs(signcount) do
768        if v > maxsigns then
769          maxsigns = v
770        end
771      end
772      minwidth = minwidth + math.min(maxsigns, max) * 2
773    else
774      minwidth = minwidth + max * 2
775    end
776  end
777
778  local foldcolumn = state.opt.foldcolumn
779  if foldcolumn ~= '0' then
780    if foldcolumn:match('^auto') then
781      local max = vim._tointeger(foldcolumn:match('^%w-:(%d)')) or 1
782      local maxfold = 0
783      vim._with({ buf = state.bufnr }, function()
784        for row = state.start, state.end_ do
785          local foldlevel = vim.fn.foldlevel(row)
786          if foldlevel > maxfold then
787            maxfold = foldlevel
788          end
789        end
790      end)
791      minwidth = minwidth + math.min(maxfold, max)
792    else
793      minwidth = minwidth + vim._assert_integer(foldcolumn)
794    end
795  end
796
797  --- @type table<integer,vim.api.keyset.eval_statusline_ret>
798  local statuses = {}
799  for row = state.start, state.end_ do
800    local status = vim.api.nvim_eval_statusline(
801      statuscolumn,
802      { winid = state.winid, use_statuscol_lnum = row, highlights = true }
803    )
804    local width = len(status.str)
805    if width > minwidth then
806      minwidth = width
807    end
808    table.insert(statuses, status)
809  end
810  for row, status in pairs(statuses) do
811    local str = status.str
812    local hls = status.highlights
813    for k, v in ipairs(hls) do
814      local hlsk1 = hls[k + 1]
815      local text = str:sub(v.start + 1, hlsk1 and hlsk1.start or nil)
816      if k == #hls then
817        text = text .. (' '):rep(minwidth - len(str))
818      end
819      if text ~= '' then
820        local hlid = register_hl(state, v.group)
821        local virt_text = { text, hlid }
822        table.insert(state.style[row].pre_text, virt_text)
823      end
824    end
825  end
826end
827
828--- @param state vim.tohtml.state
829local function styletable_listchars(state)
830  if not state.opt.list then
831    return
832  end
833  --- @param str string
834  --- @param i integer
835  --- @param j? integer
836  --- @return string
837  local function utf8_sub(str, i, j)
838    return vim.fn.strcharpart(str, i - 1, j and j - i + 1 or nil)
839  end
840  local listchars = vim.opt_local.listchars:get() --[[@as table<string,string>]]
841  local ids = setmetatable({}, {
842    __index = function(t, k)
843      rawset(t, k, register_hl(state, k))
844      return rawget(t, k)
845    end,
846  })
847
848  if listchars.eol then
849    for row = state.start, state.end_ do
850      local style_line = state.style[row]
851      style_line_insert_overlay_char(
852        style_line,
853        #vim.fn.getline(row) + 1,
854        { listchars.eol, ids.NonText }
855      )
856    end
857  end
858
859  if listchars.tab and state.tabstop then
860    for _, match in
861      ipairs(vim.fn.matchbufline(state.bufnr, '\t', 1, '$') --[[@as (table[])]])
862    do
863      local vcol = vim.fn.virtcol({ match.lnum, match.byteidx }, false, state.winid) --[[@as integer]]
864      local tablen = #state.tabstop - (vcol % #state.tabstop)
865      local text --- @type string
866      if len(listchars.tab) == 3 then
867        if tablen == 1 then
868          text = utf8_sub(listchars.tab, 3, 3)
869        else
870          text = utf8_sub(listchars.tab, 1, 1)
871            .. utf8_sub(listchars.tab, 2, 2):rep(tablen - 2)
872            .. utf8_sub(listchars.tab, 3, 3)
873        end
874      else
875        text = utf8_sub(listchars.tab, 1, 1) .. utf8_sub(listchars.tab, 2, 2):rep(tablen - 1)
876      end
877      style_line_insert_overlay_char(
878        state.style[match.lnum],
879        match.byteidx + 1,
880        { text, ids.Whitespace }
881      )
882    end
883  end
884
885  if listchars.space then
886    for _, match in
887      ipairs(vim.fn.matchbufline(state.bufnr, ' ', 1, '$') --[[@as (table[])]])
888    do
889      style_line_insert_overlay_char(
890        state.style[match.lnum],
891        match.byteidx + 1,
892        { listchars.space, ids.Whitespace }
893      )
894    end
895  end
896
897  if listchars.multispace then
898    for _, match in
899      ipairs(vim.fn.matchbufline(state.bufnr, [[  \+]], 1, '$') --[[@as (table[])]])
900    do
901      local text = utf8_sub(listchars.multispace:rep(len(match.text)), 1, len(match.text))
902      for i = 1, len(text) do
903        style_line_insert_overlay_char(
904          state.style[match.lnum],
905          match.byteidx + i,
906          { utf8_sub(text, i, i), ids.Whitespace }
907        )
908      end
909    end
910  end
911
912  if listchars.lead or listchars.leadmultispace then
913    for _, match in
914      ipairs(vim.fn.matchbufline(state.bufnr, [[^ \+]], 1, '$') --[[@as (table[])]])
915    do
916      local text = ''
917      if len(match.text) == 1 or not listchars.leadmultispace then
918        if listchars.lead then
919          text = listchars.lead:rep(len(match.text))
920        end
921      elseif listchars.leadmultispace then
922        text = utf8_sub(listchars.leadmultispace:rep(len(match.text)), 1, len(match.text))
923      end
924      for i = 1, len(text) do
925        style_line_insert_overlay_char(
926          state.style[match.lnum],
927          match.byteidx + i,
928          { utf8_sub(text, i, i), ids.Whitespace }
929        )
930      end
931    end
932  end
933
934  if listchars.trail then
935    for _, match in
936      ipairs(vim.fn.matchbufline(state.bufnr, [[ \+$]], 1, '$') --[[@as (table[])]])
937    do
938      local text = listchars.trail:rep(len(match.text))
939      for i = 1, len(text) do
940        style_line_insert_overlay_char(
941          state.style[match.lnum],
942          match.byteidx + i,
943          { utf8_sub(text, i, i), ids.Whitespace }
944        )
945      end
946    end
947  end
948
949  if listchars.nbsp then
950    for _, match in
951      ipairs(
952        vim.fn.matchbufline(state.bufnr, '\226\128\175\\|\194\160', 1, '$') --[[@as (table[])]]
953      )
954    do
955      style_line_insert_overlay_char(
956        state.style[match.lnum],
957        match.byteidx + 1,
958        { listchars.nbsp, ids.Whitespace }
959      )
960      for i = 2, #match.text do
961        style_line_insert_overlay_char(
962          state.style[match.lnum],
963          match.byteidx + i,
964          { '', ids.Whitespace }
965        )
966      end
967    end
968  end
969end
970
971--- @param name string
972--- @return string
973local function highlight_name_to_class_name(name)
974  return (name:gsub('%.', '-'):gsub('@', '-'))
975end
976
977--- @param name string
978--- @return string
979local function name_to_tag(name)
980  return '<span class="' .. highlight_name_to_class_name(name) .. '">'
981end
982
983--- @param _ string
984--- @return string
985local function name_to_closetag(_)
986  return '</span>'
987end
988
989--- @param str string
990--- @param tabstop string|false?
991--- @return string
992local function html_escape(str, tabstop)
993  str = str:gsub('&', '&amp;'):gsub('<', '&lt;'):gsub('>', '&gt;'):gsub('"', '&quot;')
994  if tabstop then
995    --- @type string
996    str = str:gsub('\t', tabstop)
997  end
998  return str
999end
1000
1001--- @param out string[]
1002--- @param state vim.tohtml.state.global
1003local function extend_style(out, state)
1004  table.insert(out, '<style>')
1005  table.insert(out, ('* {font-family: %s}'):format(state.font))
1006  table.insert(
1007    out,
1008    ('body {background-color: %s; color: %s}'):format(state.background, state.foreground)
1009  )
1010  for hlid, name in pairs(state.highlights_name) do
1011    --TODO(altermo) use local namespace (instead of global 0)
1012    local fg = vim.fn.synIDattr(hlid, 'fg#')
1013    local bg = vim.fn.synIDattr(hlid, 'bg#')
1014    local sp = vim.fn.synIDattr(hlid, 'sp#')
1015    local decor_line = {}
1016    if vim.fn.synIDattr(hlid, 'underline') ~= '' then
1017      table.insert(decor_line, 'underline')
1018    end
1019    if vim.fn.synIDattr(hlid, 'strikethrough') ~= '' then
1020      table.insert(decor_line, 'line-through')
1021    end
1022    if vim.fn.synIDattr(hlid, 'undercurl') ~= '' then
1023      table.insert(decor_line, 'underline')
1024    end
1025    local c = {
1026      color = fg ~= '' and cterm_to_hex(fg) or nil,
1027      ['background-color'] = bg ~= '' and cterm_to_hex(bg) or nil,
1028      ['font-style'] = vim.fn.synIDattr(hlid, 'italic') ~= '' and 'italic' or nil,
1029      ['font-weight'] = vim.fn.synIDattr(hlid, 'bold') ~= '' and 'bold' or nil,
1030      ['text-decoration-line'] = not vim.tbl_isempty(decor_line) and table.concat(decor_line, ' ')
1031        or nil,
1032      -- TODO(ribru17): fallback to displayed text color if sp not set
1033      ['text-decoration-color'] = sp ~= '' and cterm_to_hex(sp) or nil,
1034      --TODO(altermo) if strikethrough and undercurl then the strikethrough becomes wavy
1035      ['text-decoration-style'] = vim.fn.synIDattr(hlid, 'undercurl') ~= '' and 'wavy' or nil,
1036    }
1037    local attrs = {}
1038    for attr, val in pairs(c) do
1039      table.insert(attrs, attr .. ': ' .. val)
1040    end
1041    table.insert(
1042      out,
1043      '.' .. highlight_name_to_class_name(name) .. ' {' .. table.concat(attrs, '; ') .. '}'
1044    )
1045  end
1046  table.insert(out, '</style>')
1047end
1048
1049--- @param out string[]
1050--- @param state vim.tohtml.state.global
1051local function extend_head(out, state)
1052  table.insert(out, '<head>')
1053  table.insert(out, '<meta charset="UTF-8">')
1054  if state.title ~= false then
1055    table.insert(out, ('<title>%s</title>'):format(state.title))
1056  end
1057  local colorscheme = vim.api.nvim_exec2('colorscheme', { output = true }).output
1058  table.insert(
1059    out,
1060    ('<meta name="colorscheme" content="%s"></meta>'):format(html_escape(colorscheme))
1061  )
1062  extend_style(out, state)
1063  table.insert(out, '</head>')
1064end
1065
1066--- @param out string[]
1067--- @param state vim.tohtml.state
1068--- @param row integer
1069local function _extend_virt_lines(out, state, row)
1070  local style_line = state.style[row]
1071  for _, virt_line in ipairs(style_line.virt_lines) do
1072    local virt_s = ''
1073    for _, v in ipairs(virt_line) do
1074      if v[2] then
1075        virt_s = virt_s .. (name_to_tag(state.highlights_name[v[2]]))
1076      end
1077      virt_s = virt_s .. v[1]
1078      if v[2] then
1079        --- @type string
1080        virt_s = virt_s .. (name_to_closetag(state.highlights_name[v[2]]))
1081      end
1082    end
1083    table.insert(out, virt_s)
1084  end
1085end
1086
1087--- @param state vim.tohtml.state
1088--- @param row integer
1089--- @return string
1090local function _pre_text_to_html(state, row)
1091  local style_line = state.style[row]
1092  local s = ''
1093  for _, pre_text in ipairs(style_line.pre_text) do
1094    if pre_text[2] then
1095      s = s .. (name_to_tag(state.highlights_name[pre_text[2]]))
1096    end
1097    s = s .. (html_escape(pre_text[1], state.tabstop))
1098    if pre_text[2] then
1099      --- @type string
1100      s = s .. (name_to_closetag(state.highlights_name[pre_text[2]]))
1101    end
1102  end
1103  return s
1104end
1105
1106--- @param state vim.tohtml.state
1107--- @param char table
1108--- @return string
1109local function _char_to_html(state, char)
1110  local s = ''
1111  if char[2] then
1112    s = s .. name_to_tag(state.highlights_name[char[2]])
1113  end
1114  s = s .. html_escape(char[1], state.tabstop)
1115  if char[2] then
1116    s = s .. name_to_closetag(state.highlights_name[char[2]])
1117  end
1118  return s
1119end
1120
1121--- @param state vim.tohtml.state
1122--- @param cell vim.tohtml.cell
1123--- @return string
1124local function _virt_text_to_html(state, cell)
1125  local s = ''
1126  for _, v in ipairs(cell[3]) do
1127    if v[2] then
1128      s = s .. (name_to_tag(state.highlights_name[v[2]]))
1129    end
1130    --- @type string
1131    s = s .. html_escape(v[1], state.tabstop)
1132    if v[2] then
1133      s = s .. name_to_closetag(state.highlights_name[v[2]])
1134    end
1135  end
1136  return s
1137end
1138
1139--- @param out string[]
1140--- @param state vim.tohtml.state
1141local function extend_pre(out, state)
1142  local styletable = state.style
1143  table.insert(out, '<pre>')
1144  local out_start = #out
1145  local hide_count = 0
1146  --- @type integer[]
1147  local stack = {}
1148
1149  local before = ''
1150  local after = ''
1151  --- @param row integer
1152  local function loop(row)
1153    local inside = row <= state.end_ and row >= state.start
1154    local style_line = styletable[row]
1155    if style_line.hide and (styletable[row - 1] or {}).hide then
1156      return
1157    end
1158    if inside then
1159      _extend_virt_lines(out, state, row)
1160    end
1161    --Possible improvement (altermo):
1162    --Instead of looping over all the buffer characters per line,
1163    --why not loop over all the style_line cells,
1164    --and then calculating the amount of text.
1165    if style_line.hide then
1166      return
1167    end
1168    local line = vim.api.nvim_buf_get_lines(state.bufnr, row - 1, row, false)[1] or ''
1169    local s = ''
1170    if inside then
1171      s = s .. _pre_text_to_html(state, row)
1172    end
1173    local true_line_len = #line + 1
1174    for k in
1175      pairs(style_line --[[@as table<string,any>]])
1176    do
1177      if type(k) == 'number' and k > true_line_len then
1178        true_line_len = k --[[@as integer]]
1179      end
1180    end
1181    for col = 1, true_line_len do
1182      local cell = style_line[col]
1183      --- @type table?
1184      local char
1185      if cell then
1186        for i = #cell[2], 1, -1 do
1187          local hlid = cell[2][i]
1188          if hlid < 0 then
1189            if hlid == HIDE_ID then
1190              hide_count = hide_count - 1
1191            end
1192          else
1193            --- @type integer?
1194            local index
1195            for idx = #stack, 1, -1 do
1196              s = s .. (name_to_closetag(state.highlights_name[stack[idx]]))
1197              if stack[idx] == hlid then
1198                index = idx
1199                break
1200              end
1201            end
1202            assert(index, 'a coles tag which has no corresponding open tag')
1203            for idx = index + 1, #stack do
1204              s = s .. (name_to_tag(state.highlights_name[stack[idx]]))
1205            end
1206            table.remove(stack, index)
1207          end
1208        end
1209
1210        for _, hlid in ipairs(cell[1]) do
1211          if hlid < 0 then
1212            if hlid == HIDE_ID then
1213              hide_count = hide_count + 1
1214            end
1215          else
1216            table.insert(stack, hlid)
1217            s = s .. (name_to_tag(state.highlights_name[hlid]))
1218          end
1219        end
1220
1221        if cell[3] and inside then
1222          s = s .. _virt_text_to_html(state, cell)
1223        end
1224
1225        char = cell[4][#cell[4]]
1226      end
1227
1228      if col == true_line_len and not char then
1229        break
1230      end
1231
1232      if hide_count == 0 and inside then
1233        s = s
1234          .. _char_to_html(
1235            state,
1236            char
1237              or { vim.api.nvim_buf_get_text(state.bufnr, row - 1, col - 1, row - 1, col, {})[1] }
1238          )
1239      end
1240    end
1241    if row > state.end_ + 1 then
1242      after = after .. s
1243    elseif row < state.start then
1244      before = s .. before
1245    else
1246      table.insert(out, s)
1247    end
1248  end
1249
1250  for row = 1, vim.api.nvim_buf_line_count(state.bufnr) + 1 do
1251    loop(row)
1252  end
1253  out[out_start] = out[out_start] .. before
1254  out[#out] = out[#out] .. after
1255  assert(#stack == 0, 'an open HTML tag was never closed')
1256  table.insert(out, '</pre>')
1257end
1258
1259--- @param out string[]
1260--- @param fn fun()
1261local function extend_body(out, fn)
1262  table.insert(out, '<body style="display: flex">')
1263  fn()
1264  table.insert(out, '</body>')
1265end
1266
1267--- @param out string[]
1268--- @param fn fun()
1269local function extend_html(out, fn)
1270  table.insert(out, '<!DOCTYPE html>')
1271  table.insert(out, '<html>')
1272  fn()
1273  table.insert(out, '</html>')
1274end
1275
1276--- @param winid integer
1277--- @param global_state vim.tohtml.state.global
1278--- @return vim.tohtml.state
1279local function global_state_to_state(winid, global_state)
1280  local bufnr = vim.api.nvim_win_get_buf(winid)
1281  local opt = global_state.conf
1282  local width = opt.width or vim.bo[bufnr].textwidth
1283  if not width or width < 1 then
1284    width = vim.api.nvim_win_get_width(winid)
1285  end
1286  local range = opt.range or { 1, vim.api.nvim_buf_line_count(bufnr) }
1287  local state = setmetatable({
1288    winid = winid == 0 and vim.api.nvim_get_current_win() or winid,
1289    opt = vim.wo[winid],
1290    style = generate_styletable(bufnr),
1291    bufnr = bufnr,
1292    tabstop = (' '):rep(vim.bo[bufnr].tabstop),
1293    width = width,
1294    start = range[1],
1295    end_ = range[2],
1296  }, { __index = global_state })
1297  return state --[[@as vim.tohtml.state]]
1298end
1299
1300--- @param opt vim.tohtml.opt
1301--- @param title? string
1302--- @return vim.tohtml.state.global
1303local function opt_to_global_state(opt, title)
1304  local fonts = {} --- @type string[]
1305  if opt.font then
1306    fonts = (type(opt.font) == 'string' and { opt.font } or opt.font) --[[@as string[] ]]
1307    for i, v in pairs(fonts) do
1308      fonts[i] = ('"%s"'):format(v)
1309    end
1310  elseif vim.o.guifont:match('^[^:]+') then
1311    -- Example:
1312    -- Input: "Font,Escape\,comma, Ignore space after comma"
1313    -- Output: { "Font","Escape,comma","Ignore space after comma" }
1314    local prev = ''
1315    for name in vim.gsplit(assert(vim.o.guifont:match('^[^:]+')), ',', { trimempty = true }) do
1316      if vim.endswith(name, '\\') then
1317        prev = prev .. vim.trim(name:sub(1, -2) .. ',')
1318      elseif vim.trim(name) ~= '' then
1319        table.insert(fonts, ('"%s%s"'):format(prev, vim.trim(name)))
1320        prev = ''
1321      end
1322    end
1323  end
1324  -- Generic family names (monospace here) must not be quoted
1325  -- because the browser recognizes them as font families.
1326  table.insert(fonts, 'monospace')
1327  --- @type vim.tohtml.state.global
1328  local state = {
1329    background = get_background_color(),
1330    foreground = get_foreground_color(),
1331    title = opt.title or title or false,
1332    font = table.concat(fonts, ','),
1333    highlights_name = {},
1334    conf = opt,
1335  }
1336  return state
1337end
1338
1339--- @type fun(state: vim.tohtml.state)[]
1340local styletable_funcs = {
1341  styletable_syntax,
1342  styletable_diff,
1343  styletable_treesitter,
1344  styletable_match,
1345  styletable_extmarks,
1346  styletable_conceal,
1347  styletable_listchars,
1348  styletable_folds,
1349  styletable_statuscolumn,
1350}
1351
1352--- @param state vim.tohtml.state
1353local function state_generate_style(state)
1354  vim._with({ win = state.winid }, function()
1355    for _, fn in ipairs(styletable_funcs) do
1356      fn(state)
1357    end
1358  end)
1359end
1360
1361--- @param winid integer
1362--- @param opt? vim.tohtml.opt
1363--- @return string[]
1364local function win_to_html(winid, opt)
1365  opt = opt or {}
1366  local title = vim.api.nvim_buf_get_name(vim.api.nvim_win_get_buf(winid))
1367
1368  local global_state = opt_to_global_state(opt, title)
1369  local state = global_state_to_state(winid, global_state)
1370  state_generate_style(state)
1371
1372  local html = {}
1373  table.insert(html, '<!-- vim: set nomodeline: -->')
1374  extend_html(html, function()
1375    extend_head(html, global_state)
1376    extend_body(html, function()
1377      extend_pre(html, state)
1378    end)
1379  end)
1380  return html
1381end
1382
1383local M = {}
1384
1385--- @class vim.tohtml.opt
1386--- @inlinedoc
1387---
1388--- Title tag to set in the generated HTML code.
1389--- (default: buffer name)
1390--- @field title? string|false
1391---
1392--- Show line numbers.
1393--- (default: `false`)
1394--- @field number_lines? boolean
1395---
1396--- Fonts to use.
1397--- (default: `guifont`)
1398--- @field font? string[]|string
1399---
1400--- Width used for items which are either right aligned or repeat a character
1401--- infinitely.
1402--- (default: 'textwidth' if non-zero or window width otherwise)
1403--- @field width? integer
1404---
1405--- Range of rows to use.
1406--- (default: entire buffer)
1407--- @field range? integer[]
1408
1409--- Converts the buffer shown in the window {winid} to HTML and returns the output as a list of string.
1410--- @param winid? integer Window to convert (defaults to current window)
1411--- @param opt? vim.tohtml.opt Optional parameters.
1412--- @return string[]
1413function M.tohtml(winid, opt)
1414  return win_to_html(winid or 0, opt)
1415end
1416
1417return M