tohtml.lua 43 KB

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