robin/laufey

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

robinmerge: 8c77b5be50c50ab119

master
11.1 KiB418 linesraw
1-- TODO(justinmk): move most of this to `vim.text`.
2
3local fmt = string.format
4
5--- @class nvim.util.MDNode
6--- @field [integer] nvim.util.MDNode
7--- @field type string
8--- @field text? string
9
10local INDENTATION = 4
11
12local NBSP = string.char(160)
13
14local M = {}
15
16local function contains(t, xs)
17  return vim.tbl_contains(xs, t)
18end
19
20-- Map of api_level:version, by inspection of:
21--    :lua= vim.mpack.decode(vim.fn.readfile('test/functional/fixtures/api_level_9.mpack','B')).version
22M.version_level = {
23  [15] = '0.13.0',
24  [14] = '0.12.0',
25  [13] = '0.11.0',
26  [12] = '0.10.0',
27  [11] = '0.9.0',
28  [10] = '0.8.0',
29  [9] = '0.7.0',
30  [8] = '0.6.0',
31  [7] = '0.5.0',
32  [6] = '0.4.0',
33  [5] = '0.3.2',
34  [4] = '0.3.0',
35  [3] = '0.2.1',
36  [2] = '0.2.0',
37  [1] = '0.1.0',
38}
39
40--- @param txt string
41--- @param srow integer
42--- @param scol integer
43--- @param erow? integer
44--- @param ecol? integer
45--- @return string
46local function slice_text(txt, srow, scol, erow, ecol)
47  local lines = vim.split(txt, '\n')
48
49  if srow == erow then
50    return lines[srow + 1]:sub(scol + 1, ecol)
51  end
52
53  if erow then
54    -- Trim the end
55    for _ = erow + 2, #lines do
56      table.remove(lines, #lines)
57    end
58  end
59
60  -- Trim the start
61  for _ = 1, srow do
62    table.remove(lines, 1)
63  end
64
65  lines[1] = lines[1]:sub(scol + 1)
66  lines[#lines] = lines[#lines]:sub(1, ecol)
67
68  return table.concat(lines, '\n')
69end
70
71--- @param text string
72--- @return nvim.util.MDNode
73local function parse_md_inline(text)
74  local parser = vim.treesitter.languagetree.new(text, 'markdown_inline')
75  local root = parser:parse(true)[1]:root()
76
77  --- @param node TSNode
78  --- @return nvim.util.MDNode?
79  local function extract(node)
80    local ntype = node:type()
81
82    if ntype:match('^%p$') then
83      return
84    end
85
86    --- @type table<any,any>
87    local ret = { type = ntype }
88    ret.text = vim.treesitter.get_node_text(node, text)
89
90    local row, col = 0, 0
91
92    for child, child_field in node:iter_children() do
93      local e = extract(child)
94      if e and ntype == 'inline' then
95        local srow, scol = child:start()
96        if (srow == row and scol > col) or srow > row then
97          local t = slice_text(ret.text, row, col, srow, scol)
98          if t and t ~= '' then
99            table.insert(ret, { type = 'text', j = true, text = t })
100          end
101        end
102        row, col = child:end_()
103      end
104
105      if child_field then
106        ret[child_field] = e
107      else
108        table.insert(ret, e)
109      end
110    end
111
112    if ntype == 'inline' and (row > 0 or col > 0) then
113      local t = slice_text(ret.text, row, col)
114      if t and t ~= '' then
115        table.insert(ret, { type = 'text', text = t })
116      end
117    end
118
119    return ret
120  end
121
122  return extract(root) or {}
123end
124
125--- @param text string
126--- @return nvim.util.MDNode
127local function parse_md(text)
128  local parser = vim.treesitter.languagetree.new(text, 'markdown', {
129    injections = { markdown = '' },
130  })
131
132  local root = parser:parse(true)[1]:root()
133
134  local EXCLUDE_TEXT_TYPE = {
135    list = true,
136    list_item = true,
137    section = true,
138    document = true,
139    fenced_code_block = true,
140    fenced_code_block_delimiter = true,
141  }
142
143  --- @param node TSNode
144  --- @return nvim.util.MDNode?
145  local function extract(node)
146    local ntype = node:type()
147
148    if ntype:match('^%p$') or contains(ntype, { 'block_continuation' }) then
149      return
150    end
151
152    --- @type table<any,any>
153    local ret = { type = ntype }
154
155    if not EXCLUDE_TEXT_TYPE[ntype] then
156      ret.text = vim.treesitter.get_node_text(node, text)
157    end
158
159    if ntype == 'inline' then
160      ret = parse_md_inline(ret.text)
161    end
162
163    for child, child_field in node:iter_children() do
164      local e = extract(child)
165      if child_field then
166        ret[child_field] = e
167      else
168        table.insert(ret, e)
169      end
170    end
171
172    return ret
173  end
174
175  return extract(root) or {}
176end
177
178--- Prefixes each line in `text`.
179---
180--- Does not wrap, not important for "meta" files? (You probably want md_to_vimdoc instead.)
181---
182--- @param text string
183--- @param prefix_ string
184function M.prefix_lines(prefix_, text)
185  local r = ''
186  for _, l in ipairs(vim.split(text, '\n', { plain = true })) do
187    r = r .. vim.trim(prefix_ .. l) .. '\n'
188  end
189  return r
190end
191
192--- @param x string
193--- @param start_indent integer
194--- @param indent integer
195--- @param text_width integer
196--- @return string
197function M.wrap(x, start_indent, indent, text_width)
198  local words = vim.split(vim.trim(x), '%s+')
199  local parts = { string.rep(' ', start_indent) } --- @type string[]
200  local count = indent
201
202  for i, w in ipairs(words) do
203    if count > indent and count + #w > text_width - 1 then
204      parts[#parts + 1] = '\n'
205      parts[#parts + 1] = string.rep(' ', indent)
206      count = indent
207    elseif i ~= 1 then
208      parts[#parts + 1] = ' '
209      count = count + 1
210    end
211    count = count + #w
212    parts[#parts + 1] = w
213  end
214
215  return (table.concat(parts):gsub('%s+\n', '\n'):gsub('\n+$', ''))
216end
217
218--- @param node nvim.util.MDNode
219--- @param start_indent integer
220--- @param indent integer
221--- @param text_width integer
222--- @param level integer
223--- @return string[]
224local function render_md(node, start_indent, indent, text_width, level, is_list)
225  local parts = {} --- @type string[]
226
227  -- For debugging
228  local add_tag = false
229  -- local add_tag = true
230
231  local ntype = node.type
232
233  if add_tag then
234    parts[#parts + 1] = '<' .. ntype .. '>'
235  end
236
237  if ntype == 'text' then
238    parts[#parts + 1] = node.text
239  elseif ntype == 'atx_heading' then
240    parts[#parts + 1] = ('*%s*'):format(node.heading_content.text)
241  elseif ntype == 'html_tag' then
242    error('html_tag: ' .. node.text)
243  elseif ntype == 'inline_link' then
244    -- Markdown links with empty URLs, e.g. [lsp-buftypes](), are converted
245    -- to vim help tags, e.g. *lsp-buftypes*.
246    vim.list_extend(parts, { '*', node[1].text, '*' })
247  elseif ntype == 'shortcut_link' then
248    if node[1].text:find('^<.*>$') then
249      parts[#parts + 1] = node[1].text
250    elseif node[1].text:find('^%d+$') then
251      vim.list_extend(parts, { '[', node[1].text, ']' })
252    else
253      vim.list_extend(parts, { '|', node[1].text, '|' })
254    end
255  elseif ntype == 'backslash_escape' then
256    parts[#parts + 1] = node.text
257  elseif ntype == 'emphasis' then
258    parts[#parts + 1] = node.text:sub(2, -2)
259  elseif ntype == 'code_span' then
260    vim.list_extend(parts, { '`', node.text:sub(2, -2):gsub(' ', NBSP), '`' })
261  elseif ntype == 'inline' then
262    if #node == 0 then
263      local text = assert(node.text)
264      parts[#parts + 1] = M.wrap(text, start_indent, indent, text_width)
265    else
266      for _, child in ipairs(node) do
267        vim.list_extend(parts, render_md(child, start_indent, indent, text_width, level + 1))
268      end
269    end
270  elseif ntype == 'paragraph' then
271    local pparts = {}
272    for _, child in ipairs(node) do
273      vim.list_extend(pparts, render_md(child, start_indent, indent, text_width, level + 1))
274    end
275    parts[#parts + 1] = M.wrap(table.concat(pparts), start_indent, indent, text_width)
276    parts[#parts + 1] = '\n'
277  elseif ntype == 'code_fence_content' then
278    local lines = vim.split(node.text:gsub('\n%s*$', ''), '\n')
279
280    local cindent = indent + INDENTATION
281    if level > 3 then
282      -- The tree-sitter markdown parser doesn't parse the code blocks indents
283      -- correctly in lists. Fudge it!
284      lines[1] = '    ' .. lines[1] -- ¯\_(ツ)_/¯
285      cindent = indent - level
286      local _, initial_indent = lines[1]:find('^%s*')
287      initial_indent = initial_indent + cindent
288      if initial_indent < indent then
289        cindent = indent - INDENTATION
290      end
291    end
292
293    for _, l in ipairs(lines) do
294      if #l > 0 then
295        parts[#parts + 1] = string.rep(' ', cindent)
296        parts[#parts + 1] = l
297      end
298      parts[#parts + 1] = '\n'
299    end
300  elseif ntype == 'fenced_code_block' then
301    parts[#parts + 1] = '>'
302    for _, child in ipairs(node) do
303      if child.type == 'info_string' then
304        parts[#parts + 1] = child.text
305        break
306      end
307    end
308    parts[#parts + 1] = '\n'
309    for _, child in ipairs(node) do
310      if child.type ~= 'info_string' then
311        vim.list_extend(parts, render_md(child, start_indent, indent, text_width, level + 1))
312      end
313    end
314    parts[#parts + 1] = '<\n'
315  elseif ntype == 'html_block' then
316    local text = node.text:gsub('^<pre>help%s*', '')
317    text = text:gsub('</pre>%s*$', '')
318    parts[#parts + 1] = text
319  elseif ntype == 'list_marker_dot' then
320    parts[#parts + 1] = node.text
321  elseif contains(ntype, { 'list_marker_minus', 'list_marker_star' }) then
322    parts[#parts + 1] = '• '
323  elseif ntype == 'list_item' then
324    parts[#parts + 1] = string.rep(' ', indent)
325    local offset = node[1].type == 'list_marker_dot' and 3 or 2
326    for i, child in ipairs(node) do
327      local sindent = i <= 2 and 0 or (indent + offset)
328      vim.list_extend(
329        parts,
330        render_md(child, sindent, indent + offset, text_width, level + 1, true)
331      )
332    end
333  else
334    if node.text then
335      error(fmt('cannot render:\n%s', vim.inspect(node)))
336    end
337    for i, child in ipairs(node) do
338      local start_indent0 = i == 1 and start_indent or indent
339      vim.list_extend(
340        parts,
341        render_md(child, start_indent0, indent, text_width, level + 1, is_list)
342      )
343      if ntype ~= 'list' and i ~= #node then
344        if (node[i + 1] or {}).type ~= 'list' then
345          parts[#parts + 1] = '\n'
346        end
347      end
348    end
349  end
350
351  if add_tag then
352    parts[#parts + 1] = '</' .. ntype .. '>'
353  end
354
355  return parts
356end
357
358--- @param text_width integer
359function M.align_tags(text_width)
360  --- @param line string
361  --- @return string
362  return function(line)
363    local tag_pat = '%s*(%*.+%*)%s*$'
364    local tags = {}
365    for m in line:gmatch(tag_pat) do
366      table.insert(tags, m)
367    end
368
369    if #tags > 0 then
370      line = line:gsub(tag_pat, '')
371      local tags_str = ' ' .. table.concat(tags, ' ')
372      --- @type integer
373      local conceal_offset = select(2, tags_str:gsub('%*', '')) - 2
374      local pad = string.rep(' ', text_width - #line - #tags_str + conceal_offset)
375      return line .. pad .. tags_str
376    end
377
378    return line
379  end
380end
381
382--- @param text string
383--- @param start_indent integer
384--- @param indent integer
385--- @param is_list? boolean
386--- @return string
387function M.md_to_vimdoc(text, start_indent, indent, text_width, is_list)
388  -- Add an extra newline so the parser can properly capture ending ```
389  local parsed = parse_md(text .. '\n')
390  local ret = render_md(parsed, start_indent, indent, text_width, 0, is_list)
391
392  local lines = vim.split(table.concat(ret):gsub(NBSP, ' '), '\n')
393
394  lines = vim.tbl_map(M.align_tags(text_width), lines)
395
396  local s = table.concat(lines, '\n')
397
398  -- Reduce whitespace in code-blocks
399  s = s:gsub('\n+%s*>([a-z]+)\n', ' >%1\n')
400  s = s:gsub('\n+%s*>\n?\n', ' >\n')
401
402  return s
403end
404
405--- Sorts a list in-place, with underscore-prefixed names last (e.g. "_cmdline_offset").
406--- If `key` is given, sorts by `item[key]`; otherwise sorts by value.
407---
408--- @param t any[]
409--- @param key? string
410function M.sort_by_key(t, key)
411  table.sort(t, function(a, b)
412    local a_val = key and a[key] or a
413    local b_val = key and b[key] or b
414    return a_val:gsub('^_', '~') < b_val:gsub('^_', '~')
415  end)
416end
417
418return M