robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
5.8 KiB178 linesraw
1-- use treesitter over syntax (for highlighted code blocks)
2vim.treesitter.start()
3
4--- Apply current colorscheme to lists of default highlight groups
5---
6--- Note: {patterns} is assumed to be sorted by occurrence in the file.
7--- @param patterns {start:string,stop:string,match:string}[]
8local function colorize_hl_groups(patterns)
9  local ns = vim.api.nvim_create_namespace('nvim.vimhelp')
10  vim.api.nvim_buf_clear_namespace(0, ns, 0, -1)
11
12  local save_cursor = vim.fn.getcurpos()
13
14  for _, pat in pairs(patterns) do
15    local start_lnum = vim.fn.search(pat.start, 'c')
16    local end_lnum = vim.fn.search(pat.stop)
17    if start_lnum == 0 or end_lnum == 0 then
18      break
19    end
20
21    for lnum = start_lnum, end_lnum do
22      local line = assert(vim.api.nvim_buf_get_lines(0, lnum - 1, lnum, true)[1])
23      local word = line:match(pat.match)
24      if vim.fn.hlexists(word) ~= 0 then
25        vim.api.nvim_buf_set_extmark(0, ns, lnum - 1, 0, { end_col = #word, hl_group = word })
26      end
27    end
28  end
29
30  vim.fn.setpos('.', save_cursor)
31end
32
33--- @param bufname string
34--- @param path string
35local function help_bufname_match(bufname, path)
36  return vim.endswith(bufname, path .. '.txt') or bufname:find(path .. '%.%a%ax$')
37end
38
39-- Add custom highlights for list in `:h highlight-groups`.
40local bufname = vim.fs.normalize(vim.api.nvim_buf_get_name(0))
41if help_bufname_match(bufname, '/doc/syntax') then
42  colorize_hl_groups({
43    { start = [[\*group-name\*]], stop = '^======', match = '^(%w+)\t' },
44    { start = [[\*highlight-groups\*]], stop = '^======', match = '^(%w+)\t' },
45  })
46elseif help_bufname_match(bufname, '/doc/treesitter') then
47  colorize_hl_groups({
48    {
49      start = [[\*treesitter-highlight-groups\*]],
50      stop = [[\*treesitter-highlight-spell\*]],
51      match = '^@[%w%p]+',
52    },
53  })
54elseif help_bufname_match(bufname, '/doc/diagnostic') then
55  colorize_hl_groups({
56    { start = [[\*diagnostic-highlights\*]], stop = '^======', match = '^(%w+)' },
57  })
58elseif help_bufname_match(bufname, '/doc/lsp') then
59  colorize_hl_groups({
60    { start = [[\*lsp-highlight\*]], stop = '^------', match = '^(%w+)' },
61    { start = [[\*lsp-semantic-highlight\*]], stop = '^======', match = '^@[%w%p]+' },
62  })
63end
64
65vim.keymap.set('n', 'gO', function()
66  require('vim.treesitter._headings').show_toc()
67end, { buf = 0, silent = true, desc = 'Show an Outline of the current buffer' })
68
69vim.keymap.set('n', ']]', function()
70  require('vim.treesitter._headings').jump({ count = 1 })
71end, { buf = 0, silent = false, desc = 'Jump to next section' })
72vim.keymap.set('n', '[[', function()
73  require('vim.treesitter._headings').jump({ count = -1 })
74end, { buf = 0, silent = false, desc = 'Jump to previous section' })
75
76local parser = assert(vim.treesitter.get_parser(0, 'vimdoc'))
77
78local function runnables()
79  ---@type table<integer, { lang: string, code: string }>
80  local code_blocks = {}
81  local query = vim.treesitter.query.parse(
82    'vimdoc',
83    [[
84    (codeblock
85      (language) @_lang
86      .
87      (code) @code
88      (#any-of? @_lang "lua\n" "vim\n")
89      (#set! @code lang @_lang))
90  ]]
91  )
92
93  local root = parser:parse()[1]:root()
94  for _, match, metadata in query:iter_matches(root, 0, 0, -1) do
95    for id, nodes in pairs(match) do
96      local name = query.captures[id]
97      local node = assert(nodes[1])
98
99      if name == 'code' then
100        local start, _, end_ = assert(node:parent()):range()
101        local code = vim.treesitter.get_node_text(node, 0)
102        local lang_id = assert(metadata[id]).lang --[[@as integer]]
103        local lang_node = assert(match[lang_id][1])
104        local lang = vim.treesitter.get_node_text(lang_node, 0)
105        for i = start + 1, end_ do
106          code_blocks[i] = { lang = lang, code = code }
107        end
108      end
109    end
110  end
111
112  vim.keymap.set('n', 'g==', function()
113    local pos = vim.api.nvim_win_get_cursor(0)[1]
114    local code_block = code_blocks[pos]
115    if not code_block then
116      vim.print('No code block found')
117    elseif code_block.lang == 'lua\n' then
118      vim.cmd.lua(code_block.code)
119    elseif code_block.lang == 'vim\n' then
120      vim.cmd(code_block.code)
121    end
122  end, { buf = 0 })
123end
124
125-- Retry once if the buffer has changed during the iteration of the code
126-- blocks. See #36574.
127if not pcall(runnables) then
128  runnables()
129end
130
131local url_ns = vim.api.nvim_create_namespace('nvim.help.urls')
132local function urls()
133  local filepath = vim.fs.normalize(vim.api.nvim_buf_get_name(0))
134
135  if vim.fs.relpath(assert(vim.env.VIMRUNTIME), filepath) ~= nil then
136    local base = 'https://neovim.io/doc/user/helptag/?tag='
137    local query = vim.treesitter.query.parse(
138      'vimdoc',
139      [[
140    ((optionlink) @helplink)
141    (taglink
142      text: (_) @helplink)
143    (tag
144      text: (_) @helplink)
145    ]]
146    )
147
148    vim.api.nvim_buf_clear_namespace(0, url_ns, 0, -1)
149    local root = parser:parse()[1]:root()
150    for _, match, _ in query:iter_matches(root, 0, 0, -1) do
151      for id, nodes in pairs(match) do
152        if query.captures[id] == 'helplink' then
153          for _, node in ipairs(nodes) do
154            local start_line, start_col, end_line, end_col = node:range()
155            local tag = vim.treesitter.get_node_text(node, 0)
156            vim.api.nvim_buf_set_extmark(0, url_ns, start_line, start_col, {
157              end_line = end_line,
158              end_col = end_col,
159              url = base .. vim.uri_encode(tag),
160            })
161          end
162        end
163      end
164    end
165  end
166end
167
168-- Retry once if the buffer has changed during the iteration of the code
169-- blocks. See #36574.
170if not pcall(urls) then
171  urls()
172end
173
174vim.b.undo_ftplugin = (vim.b.undo_ftplugin or '')
175  .. '\n sil! exe "nunmap <buffer> gO" | sil! exe "nunmap <buffer> g=="'
176  .. '\n sil! exe "nunmap <buffer> ]]" | sil! exe "nunmap <buffer> [["'
177  .. ('\n call v:lua.vim.api.nvim_buf_clear_namespace(0, %d, 0, -1)'):format(url_ns)
178vim.b.undo_ftplugin = vim.b.undo_ftplugin .. ' | call v:lua.vim.treesitter.stop()'