robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
12.3 KiB384 linesraw
1local M = {}
2
3--- @param cmd string[]
4--- @param cwd string
5--- @param on_exit fun(out: vim.SystemCompleted)
6local function git_cmd(cmd, cwd, on_exit)
7  cmd = vim.list_extend({ 'git', '-c', 'gc.auto=0' }, cmd)
8  local env = vim.fn.environ() --- @type table<string,string>
9  env.GIT_DIR, env.GIT_WORK_TREE, env.GIT_INDEX_FILE = nil, nil, nil
10  local sys_opts = { cwd = cwd, text = true, env = env, clear_env = true }
11  vim.system(cmd, sys_opts, vim.schedule_wrap(on_exit))
12end
13
14local capabilities = {
15  codeActionProvider = true,
16  documentLinkProvider = { resolveProvider = false },
17  documentSymbolProvider = true,
18  executeCommandProvider = { commands = { 'delete_plugin', 'update_plugin', 'skip_update_plugin' } },
19  hoverProvider = true,
20}
21--- @type table<string,function>
22local methods = {}
23
24--- @param callback function
25function methods.initialize(_, callback)
26  return callback(nil, { capabilities = capabilities })
27end
28
29--- @param callback function
30function methods.shutdown(_, callback)
31  return callback(nil, nil)
32end
33
34--- @param uri string
35local function get_confirm_bufnr(uri)
36  return vim._tointeger(uri:match('^nvim%-pack://confirm#(%d+)$'))
37end
38
39local group_header_pattern = '^# (%S+)'
40local plugin_header_pattern = '^## (.+)$'
41
42--- @param bufnr integer
43--- @param lnum integer
44--- @return { group: string?, name: string?, from: integer?, to: integer?, active: boolean? }
45local function get_plug_data_at_lnum(bufnr, lnum)
46  local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
47  --- @type string, string, integer, integer
48  local group, name, from, to
49  for i = lnum, 1, -1 do
50    local line = lines[i]
51    if not line then
52      return {}
53    end
54    group = group or line:match(group_header_pattern) --[[@as string]]
55    -- If group is found earlier than name - `lnum` is for group header line
56    -- If later - proper group header line.
57    if group then
58      break
59    end
60    name = name or line:match(plugin_header_pattern) --[[@as string]]
61    from = (not from and name) and i or from --[[@as integer]]
62  end
63  if not (group and name and from) then
64    return {}
65  end
66  --- @cast group string
67  --- @cast from integer
68
69  for i = lnum + 1, #lines do
70    if lines[i]:match(group_header_pattern) or lines[i]:match(plugin_header_pattern) then
71      -- Do not include blank line before next section
72      to = i - 2
73      break
74    end
75  end
76  to = to or #lines
77
78  if not (from <= lnum and lnum <= to) then
79    return {}
80  end
81  return { group = group, name = name:gsub(' %(not active%)$', ''), from = from, to = to }
82end
83
84--- @alias vim.pack.lsp.Position { line: integer, character: integer }
85--- @alias vim.pack.lsp.Range { start: vim.pack.lsp.Position, end: vim.pack.lsp.Position }
86--- @alias vim.pack.lsp.DocumentLink { range: vim.pack.lsp.Range, target: string }
87
88--- Finds a line range to be linked and computes the LSP style link
89--- @param line string Buffer line to find a link in
90--- @param pattern string Pattern with three captures: `()`, the link text, and `()`,
91--- like `'^Path: +()(.+)()$'`. The empty captures return byte positions.
92--- @param link_type "commit"|"path"|"src"|"tag"
93--- @param lnum integer Line number in a buffer
94--- @param src string Plugin source
95--- @return vim.pack.lsp.DocumentLink? # A link structure according to the LSP specification
96local function match_link(line, pattern, link_type, lnum, src)
97  local from, match, to = line:match(pattern)
98  if type(from) ~= 'number' or type(match) ~= 'string' or type(to) ~= 'number' then
99    return nil
100  end
101
102  --- @cast from integer
103  --- @cast to integer
104  -- Convert to UTF index used in LSP positions
105  local start_col = vim.str_utfindex(line, 'utf-16', from - 1, false)
106  local end_col = vim.str_utfindex(line, 'utf-16', to - 2, false)
107
108  --- @type string?
109  local target = match
110  if link_type == 'commit' or link_type == 'tag' then
111    ---@diagnostic disable-next-line: param-type-mismatch
112    target = require('vim._core.util').get_forge_url(src, match, link_type)
113  elseif link_type == 'path' then
114    target = vim.uri_from_fname(match)
115  end
116
117  if target == nil then
118    return nil
119  end
120
121  return {
122    range = {
123      start = { line = lnum - 1, character = start_col },
124      ['end'] = { line = lnum - 1, character = end_col },
125    },
126    target = target,
127  }
128end
129
130--- @param params { textDocument: { uri: string } }
131--- @param callback function
132methods['textDocument/documentLink'] = function(params, callback)
133  local bufnr = get_confirm_bufnr(params.textDocument.uri)
134  if bufnr == nil then
135    return callback(nil, {})
136  end
137
138  --- @type vim.pack.lsp.DocumentLink[]
139  local links = {}
140  local cur_src = ''
141  local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
142  for i, l in ipairs(lines) do
143    cur_src = l:match('^Source: +(.+)$') or cur_src
144
145    links[#links + 1] = match_link(l, '^Path: +()(.+)()$', 'path', i, cur_src)
146    links[#links + 1] = match_link(l, '^Source: +()(.+)()$', 'src', i, cur_src)
147    links[#links + 1] = match_link(l, '^Revision[^:]*: +()(%S+)()', 'commit', i, cur_src)
148    -- NOTE: Assume that short revision works in the link
149    links[#links + 1] = match_link(l, '^[><] ()(%S+)()', 'commit', i, cur_src)
150    links[#links + 1] = match_link(l, '^• ()(.+)()$', 'tag', i, cur_src)
151  end
152
153  return callback(nil, links)
154end
155
156--- @param params { textDocument: { uri: string } }
157--- @param callback function
158methods['textDocument/documentSymbol'] = function(params, callback)
159  local bufnr = get_confirm_bufnr(params.textDocument.uri)
160  if bufnr == nil then
161    return callback(nil, {})
162  end
163
164  --- @alias vim.pack.lsp.Symbol {
165  ---   name: string,
166  ---   kind: number,
167  ---   range: vim.pack.lsp.Range,
168  ---   selectionRange: vim.pack.lsp.Range,
169  ---   children: vim.pack.lsp.Symbol[]?,
170  --- }
171
172  --- @param name string?
173  --- @param start_line integer?
174  --- @param end_line integer
175  --- @param kind integer
176  --- @return vim.pack.lsp.Symbol?
177  local function new_symbol(name, start_line, end_line, kind)
178    if name == nil then
179      return nil
180    end
181    local range = {
182      start = {
183        line = start_line --[[@as integer]],
184        character = 0,
185      },
186      ['end'] = { line = end_line, character = 0 },
187    }
188    return { name = name, kind = kind, range = range, selectionRange = range }
189  end
190
191  local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
192
193  --- @param pattern string
194  --- @param start_line integer
195  --- @param end_line integer
196  --- @param kind integer
197  --- @return vim.pack.lsp.Symbol[]
198  local function parse_headers(pattern, start_line, end_line, kind)
199    local res, cur_match, cur_start = {}, nil, nil
200    for i = start_line, end_line do
201      local m = assert(lines[i + 1]):match(pattern)
202      if m ~= nil and m ~= cur_match then
203        table.insert(res, new_symbol(cur_match, cur_start, i, kind))
204        cur_match, cur_start = m, i
205      end
206    end
207    table.insert(res, new_symbol(cur_match, cur_start, end_line, kind))
208    return res
209  end
210
211  local group_kind = vim.lsp.protocol.SymbolKind.Namespace
212  local symbols = parse_headers(group_header_pattern, 0, #lines - 1, group_kind)
213
214  local plug_kind = vim.lsp.protocol.SymbolKind.Module
215  for _, group in ipairs(symbols) do
216    local start_line, end_line = group.range.start.line, group.range['end'].line
217    group.children = parse_headers(plugin_header_pattern, start_line, end_line, plug_kind)
218  end
219
220  return callback(nil, symbols)
221end
222
223--- @alias vim.pack.lsp.CodeActionContext { diagnostics: table, only: table?, triggerKind: integer? }
224
225--- @param params { textDocument: { uri: string }, range: vim.pack.lsp.Range, context: vim.pack.lsp.CodeActionContext }
226--- @param callback function
227methods['textDocument/codeAction'] = function(params, callback)
228  local bufnr = get_confirm_bufnr(params.textDocument.uri)
229  local empty_kind = vim.lsp.protocol.CodeActionKind.Empty
230  local only = params.context.only or { empty_kind }
231  if not (bufnr and vim.tbl_contains(only, empty_kind)) then
232    return callback(nil, {})
233  end
234  local plug_data = get_plug_data_at_lnum(bufnr, params.range.start.line + 1)
235  if not plug_data.name then
236    return callback(nil, {})
237  end
238
239  --- @param title string
240  --- @param command string
241  local function new_action(title, command)
242    return {
243      title = ('%s `%s`'):format(title, plug_data.name),
244      command = { title = title, command = command, arguments = { bufnr, plug_data } },
245    }
246  end
247
248  local res = {}
249  if plug_data.group == 'Update' then
250    vim.list_extend(res, {
251      new_action('Update', 'update_plugin'),
252      new_action('Skip updating', 'skip_update_plugin'),
253    }, 0)
254  end
255  plug_data.active = assert(vim.pack.get({ plug_data.name })[1]).active
256  vim.list_extend(res, { new_action('Delete', 'delete_plugin') })
257  callback(nil, res)
258end
259
260local commands = {
261  update_plugin = function(plug_data)
262    vim.pack.update({ plug_data.name }, { force = true, offline = true })
263  end,
264  skip_update_plugin = function(_) end,
265  delete_plugin = function(plug_data)
266    if plug_data.active then
267      local confirm_msg = ('Plugin `%s` is active.'):format(plug_data.name)
268        .. ' Make sure its `vim.pack.add` call is removed from config.'
269      local choice = vim.fn.confirm(confirm_msg, 'Delete? &Yes\n&No', 1, 'Question')
270      if choice ~= 1 then
271        return 'skip_line_update'
272      end
273    end
274    vim.pack.del({ plug_data.name }, { force = true })
275  end,
276}
277
278-- NOTE: Use `vim.schedule_wrap` to avoid hit-enter after choosing code
279-- action via built-in `vim.fn.inputlist()`
280--- @param params { command: string, arguments: table }
281--- @param callback function
282methods['workspace/executeCommand'] = vim.schedule_wrap(function(params, callback)
283  --- @type integer, table
284  local bufnr, plug_data = unpack(params.arguments)
285  local ok, res = pcall(commands[params.command] --[[@as function]], plug_data)
286  if not ok then
287    return callback({ code = 1, message = res }, {})
288  end
289
290  -- Remove plugin lines (including blank line) to not later act on plugin
291  if res ~= 'skip_line_update' then
292    vim.bo[bufnr].modifiable = true
293    vim.api.nvim_buf_set_lines(bufnr, plug_data.from - 2, plug_data.to, false, {})
294    vim.bo[bufnr].modifiable, vim.bo[bufnr].modified = false, false
295  end
296
297  callback(nil, {})
298end)
299
300--- @param params { textDocument: { uri: string }, position: vim.pack.lsp.Position }
301--- @param callback function
302methods['textDocument/hover'] = function(params, callback)
303  local bufnr = get_confirm_bufnr(params.textDocument.uri)
304  if bufnr == nil then
305    return
306  end
307
308  local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
309  local lnum = params.position.line + 1
310  local line = lines[lnum]
311  if not line then
312    return
313  end
314  local commit = line:match('^[<>] (%x+) │') or line:match('^Revision.*:%s+(%x+)')
315  local tag = line:match('^• (.+)$')
316  if commit == nil and tag == nil then
317    return
318  end
319
320  local path --- @type string?
321  local path_lnum = lnum - 1
322  while path == nil and path_lnum >= 1 do
323    path = assert(lines[path_lnum]):match('^Path:%s+(.+)$')
324    path_lnum = path_lnum - 1
325  end
326  if path == nil then
327    return
328  end
329
330  --- @param sys_out vim.SystemCompleted
331  local on_exit = function(sys_out)
332    local markdown = '```diff\n' .. sys_out.stdout .. '\n```'
333    local res = { contents = { kind = vim.lsp.protocol.MarkupKind.Markdown, value = markdown } }
334    callback(nil, res)
335  end
336  git_cmd({ 'show', '--no-color', commit or tag }, path, on_exit)
337end
338
339local dispatchers = {}
340
341-- TODO: Simplify after `vim.lsp.server` is a thing
342-- https://github.com/neovim/neovim/pull/24338
343--- @param disp vim.lsp.rpc.Dispatchers
344local function cmd(disp)
345  -- Store dispatchers to use for showing progress notifications
346  dispatchers = disp
347  local res, closing, request_id = {}, false, 0
348
349  --- @param method vim.lsp.protocol.Method.ClientToServer.Request
350  --- @param params table?
351  --- @param callback fun(err: lsp.ResponseError?, result: any)
352  function res.request(method, params, callback)
353    local method_impl = methods[method]
354    if method_impl ~= nil then
355      method_impl(params, callback)
356    end
357    request_id = request_id + 1
358    return true, request_id
359  end
360
361  --- @param method vim.lsp.protocol.Method.ClientToServer.Notification
362  function res.notify(method, _)
363    if method == 'exit' then
364      dispatchers.on_exit(0, 15)
365    end
366    return false
367  end
368
369  function res.is_closing()
370    return closing
371  end
372
373  function res.terminate()
374    closing = true
375  end
376
377  return res
378end
379
380M.client_id = assert(
381  vim.lsp.start({ cmd = cmd, name = 'vim.pack', root_dir = vim.uv.cwd() }, { attach = false })
382)
383
384return M