robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
8.6 KiB298 linesraw
1--- @diagnostic disable:no-unknown
2
3--- @class (private) vim._inspector.Extmark
4--- @field id integer
5--- @field row integer
6--- @field col integer
7--- @field end_row integer
8--- @field end_col integer
9--- @field opts vim.api.keyset.extmark_details & { hl_group_link?: string }
10--- @field ns_id integer
11--- @field ns string
12
13--- @class vim._inspector.Filter
14--- @inlinedoc
15---
16--- Include syntax based highlight groups.
17--- (default: `true`)
18--- @field syntax boolean
19---
20--- Include treesitter based highlight groups.
21--- (default: `true`)
22--- @field treesitter boolean
23---
24--- Include extmarks. When `all`, then extmarks without a `hl_group` will also be included.
25--- (default: true)
26--- @field extmarks boolean|"all"
27---
28--- Include semantic token highlights.
29--- (default: true)
30--- @field semantic_tokens boolean
31local defaults = {
32  syntax = true,
33  treesitter = true,
34  extmarks = true,
35  semantic_tokens = true,
36}
37
38---Get all the items at a given buffer position.
39---
40---Can also be pretty-printed with `:Inspect!`. [:Inspect!]()
41---
42---@since 11
43---@param buf? integer defaults to the current buffer
44---@param row? integer row to inspect, 0-based. Defaults to the row of the current cursor
45---@param col? integer col to inspect, 0-based. Defaults to the col of the current cursor
46---@param filter? vim._inspector.Filter Table with key-value pairs to filter the items
47---@return {treesitter:table,syntax:table,extmarks:table,semantic_tokens:table,buffer:integer,col:integer,row:integer} (table) a table with the following key-value pairs. Items are in "traversal order":
48---               - treesitter: a list of treesitter captures
49---               - syntax: a list of syntax groups
50---               - semantic_tokens: a list of semantic tokens
51---               - extmarks: a list of extmarks
52---               - buffer: the buffer used to get the items
53---               - row: the row used to get the items
54---               - col: the col used to get the items
55function vim.inspect_pos(buf, row, col, filter)
56  filter = vim.tbl_deep_extend('force', defaults, filter or {})
57
58  buf = buf or 0
59  if row == nil or col == nil then
60    -- get the row/col from the first window displaying the buffer
61    local win = buf == 0 and vim.api.nvim_get_current_win() or vim.fn.bufwinid(buf)
62    if win == -1 then
63      error('row/col is required for buffers not visible in a window')
64    end
65    local cursor = vim.api.nvim_win_get_cursor(win)
66    row, col = cursor[1] - 1, cursor[2]
67  end
68  buf = vim._resolve_bufnr(buf)
69  ---@cast row integer
70  ---@cast col integer
71
72  local results = {
73    treesitter = {}, --- @type table[]
74    syntax = {}, --- @type table[]
75    extmarks = {},
76    semantic_tokens = {},
77    buffer = buf,
78    row = row,
79    col = col,
80  }
81
82  -- resolve hl links
83  --- @generic T: { hl_group?: string, hl_group_link?: string }
84  --- @param data T
85  local function resolve_hl(data)
86    if data.hl_group then
87      local hlid = vim.api.nvim_get_hl_id_by_name(data.hl_group)
88      local name = vim.fn.synIDattr(vim.fn.synIDtrans(hlid), 'name')
89      data.hl_group_link = name
90    end
91    return data
92  end
93
94  -- treesitter
95  if filter.treesitter then
96    for _, capture in pairs(vim.treesitter.get_captures(buf, { row, col })) do
97      --- @diagnostic disable-next-line: inject-field
98      capture.hl_group = '@' .. capture.capture .. '.' .. capture.lang
99      results.treesitter[#results.treesitter + 1] = resolve_hl(capture)
100    end
101  end
102
103  -- syntax
104  if filter.syntax and vim.api.nvim_buf_is_valid(buf) then
105    vim._with({ buf = buf }, function()
106      for _, i1 in ipairs(vim.fn.synstack(row + 1, col + 1)) do
107        results.syntax[#results.syntax + 1] =
108          resolve_hl({ hl_group = vim.fn.synIDattr(i1, 'name') })
109      end
110    end)
111  end
112
113  -- namespace id -> name map
114  local nsmap = {} --- @type table<integer,string>
115  for name, id in pairs(vim.api.nvim_get_namespaces()) do
116    nsmap[id] = name
117  end
118
119  --- Convert an extmark tuple into a table
120  --- @param extmark vim.api.keyset.get_extmark_item
121  local function to_map(extmark)
122    local opts = resolve_hl(assert(extmark[4]))
123    return {
124      id = extmark[1],
125      row = extmark[2],
126      col = extmark[3],
127      end_row = opts.end_row or extmark[2],
128      end_col = opts.end_col or extmark[3],
129      opts = opts,
130      ns_id = opts.ns_id,
131      ns = nsmap[opts.ns_id] or '',
132    }
133  end
134
135  --- Exclude end_col and unpaired marks from the overlapping marks, unless
136  --- filter.extmarks == 'all' (a highlight is drawn until end_col - 1).
137  --- @param extmark vim._inspector.Extmark
138  local function exclude_end_col(extmark)
139    return filter.extmarks == 'all' or row < extmark.end_row or col < extmark.end_col
140  end
141
142  -- All overlapping extmarks at this position:
143  local marks = vim.api.nvim_buf_get_extmarks(buf, -1, { row, col }, { row, col }, {
144    details = true,
145    overlap = true,
146  })
147  local extmarks = vim.tbl_map(to_map, marks)
148  extmarks = vim.tbl_filter(exclude_end_col, extmarks)
149
150  if filter.semantic_tokens then
151    results.semantic_tokens = vim.tbl_filter(function(extmark)
152      return extmark.ns:find('nvim.lsp.semantic_tokens') == 1
153    end, extmarks)
154  end
155
156  if filter.extmarks then
157    results.extmarks = vim.tbl_filter(function(extmark)
158      return extmark.ns:find('nvim.lsp.semantic_tokens') ~= 1
159        and (filter.extmarks == 'all' or extmark.opts.hl_group ~= nil)
160    end, extmarks)
161  end
162
163  return results
164end
165
166---Show all the items at a given buffer position.
167---
168---Can also be shown with `:Inspect`. [:Inspect]()
169---
170---See also |:marks| to list all extmarks.
171---
172---Example: To bind this function to the vim-scriptease
173---inspired `zS` in Normal mode:
174---
175---```lua
176---vim.keymap.set('n', 'zS', vim.show_pos)
177---```
178---
179---@since 11
180---@param buf? integer defaults to the current buffer
181---@param row? integer row to inspect, 0-based. Defaults to the row of the current cursor
182---@param col? integer col to inspect, 0-based. Defaults to the col of the current cursor
183---@param filter? vim._inspector.Filter
184function vim.show_pos(buf, row, col, filter)
185  local items = vim.inspect_pos(buf, row, col, filter)
186
187  local lines = { {} }
188
189  ---@param str string
190  ---@param hl? string
191  local function append(str, hl)
192    table.insert(lines[#lines], { str, hl })
193  end
194
195  local function nl()
196    table.insert(lines, {})
197  end
198
199  --- @param data { hl_group: string, hl_group_link: string }
200  --- @param comment? string
201  local function item(data, comment)
202    append('  - ')
203    append(data.hl_group, data.hl_group)
204    append(' ')
205    if data.hl_group ~= data.hl_group_link then
206      append('links to ', 'MoreMsg')
207      append(data.hl_group_link, data.hl_group_link)
208      append('   ')
209    end
210    if comment then
211      append(comment, 'Dimmed')
212    end
213    nl()
214  end
215
216  -- treesitter
217  if #items.treesitter > 0 then
218    append('Treesitter', 'Title')
219    nl()
220    for _, capture in ipairs(items.treesitter) do
221      item(
222        capture,
223        string.format(
224          'priority: %d   language: %s',
225          capture.metadata.priority
226            or (capture.metadata[capture.id] and capture.metadata[capture.id].priority)
227            or vim.hl.priorities.treesitter,
228          capture.lang
229        )
230      )
231    end
232    nl()
233  end
234
235  -- semantic tokens
236  if #items.semantic_tokens > 0 then
237    append('Semantic Tokens', 'Title')
238    nl()
239    local sorted_marks = vim.fn.sort(items.semantic_tokens, function(left, right)
240      local left_first = left.opts.priority < right.opts.priority
241        or left.opts.priority == right.opts.priority and left.opts.hl_group < right.opts.hl_group
242      return left_first and -1 or 1
243    end)
244    for _, extmark in ipairs(sorted_marks) do
245      item(extmark.opts, 'priority: ' .. extmark.opts.priority)
246    end
247    nl()
248  end
249
250  -- syntax
251  if #items.syntax > 0 then
252    append('Syntax', 'Title')
253    nl()
254    for _, syn in ipairs(items.syntax) do
255      item(syn)
256    end
257    nl()
258  end
259
260  -- extmarks
261  if #items.extmarks > 0 then
262    append('Extmarks', 'Title')
263    nl()
264    for _, extmark in ipairs(items.extmarks) do
265      if extmark.opts.hl_group then
266        item(extmark.opts, extmark.ns)
267      else
268        append('  - ')
269        append(extmark.ns, 'Dimmed')
270        nl()
271      end
272    end
273    nl()
274  end
275
276  if #lines[#lines] == 0 then
277    table.remove(lines)
278  end
279
280  local chunks = {}
281  for _, line in ipairs(lines) do
282    vim.list_extend(chunks, line)
283    table.insert(chunks, { '\n' })
284  end
285  if #chunks == 0 then
286    chunks = {
287      {
288        'No items found at position '
289          .. items.row
290          .. ','
291          .. items.col
292          .. ' in buffer '
293          .. items.buffer,
294      },
295    }
296  end
297  vim.api.nvim_echo(chunks, false, { kind = 'list_cmd' })
298end