robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
27.1 KiB746 linesraw
1local log = require('vim.lsp.log')
2local protocol = require('vim.lsp.protocol')
3local util = require('vim.lsp.util')
4local api = vim.api
5local completion = require('vim.lsp.completion')
6
7--- @type table<string, lsp.Handler>
8local M = {}
9
10--- @deprecated
11--- Client to server response handlers.
12--- @type table<vim.lsp.protocol.Method.ClientToServer, lsp.Handler>
13local RCS = {}
14
15--- Server to client request handlers.
16--- @type table<vim.lsp.protocol.Method.ServerToClient, lsp.Handler>
17local RSC = {}
18
19--- Server to client notification handlers.
20--- @type table<vim.lsp.protocol.Method.ServerToClient, lsp.Handler>
21local NSC = {}
22
23--- Writes to error buffer.
24---@param ... string|number Will be concatenated before being written
25local function err_message(...)
26  vim.notify(table.concat(vim.iter({ ... }):flatten():totable()), vim.log.levels.ERROR)
27  api.nvim_command('redraw')
28end
29
30--- @param params lsp.ShowMessageParams|lsp.ShowMessageRequestParams
31--- @param ctx lsp.HandlerContext
32local function show_message_notification(params, ctx)
33  local message_type = params.type
34  local message = params.message
35  local client_id = ctx.client_id
36  local client = vim.lsp.get_client_by_id(client_id)
37  local client_name = client and client.name or string.format('id=%d', client_id)
38  if not client then
39    err_message('LSP[', client_name, '] client has shut down after sending ', message)
40  end
41  message = ('LSP[%s] %s'):format(client_name, message)
42  vim.notify(message, log._from_lsp_level(message_type))
43  return params
44end
45
46--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand
47---@diagnostic disable-next-line: deprecated
48RCS['workspace/executeCommand'] = function(_, _, _)
49  -- Error handling is done implicitly by wrapping all handlers; see end of this file
50end
51
52--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#progress
53---@param params lsp.ProgressParams
54---@param ctx lsp.HandlerContext
55---@diagnostic disable-next-line:no-unknown
56RSC['$/progress'] = function(_, params, ctx)
57  local client = vim.lsp.get_client_by_id(ctx.client_id)
58  if not client then
59    err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update')
60    return vim.NIL
61  end
62  local kind = nil
63  local value = params.value
64
65  if type(value) == 'table' then
66    kind = value.kind --- @type string
67    -- Carry over title of `begin` messages to `report` and `end` messages
68    -- So that consumers always have it available, even if they consume a
69    -- subset of the full sequence
70    if kind == 'begin' then
71      client.progress.pending[params.token] = value.title
72    else
73      value.title = client.progress.pending[params.token]
74      if kind == 'end' then
75        client.progress.pending[params.token] = nil
76      end
77    end
78  end
79
80  client.progress:push(params)
81
82  api.nvim_exec_autocmds('LspProgress', {
83    pattern = kind,
84    modeline = false,
85    data = { client_id = ctx.client_id, params = params },
86  })
87end
88
89--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_workDoneProgress_create
90---@param params lsp.WorkDoneProgressCreateParams
91---@param ctx lsp.HandlerContext
92RSC['window/workDoneProgress/create'] = function(_, params, ctx)
93  local client = vim.lsp.get_client_by_id(ctx.client_id)
94  if not client then
95    err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update')
96    return vim.NIL
97  end
98  client.progress:push(params)
99  return vim.NIL
100end
101
102--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessageRequest
103---@param params lsp.ShowMessageRequestParams
104RSC['window/showMessageRequest'] = function(_, params, ctx)
105  local actions = params.actions
106  if actions and next(actions) then
107    local co, is_main = coroutine.running()
108    if co and not is_main then
109      local opts = {
110        kind = 'lsp_message',
111        prompt = params.message .. ': ',
112        ---@param action lsp.MessageActionItem
113        ---@return string
114        format_item = function(action)
115          return (action.title:gsub('\r\n', '\\r\\n'):gsub('\n', '\\n'))
116        end,
117      }
118      vim.ui.select(actions, opts, function(choice)
119        -- schedule to ensure resume doesn't happen _before_ yield with
120        -- default synchronous vim.ui.select
121        vim.schedule(function()
122          coroutine.resume(co, choice or vim.NIL)
123        end)
124      end)
125      -- The coroutine.running() check above guards this yield.
126      ---@diagnostic disable-next-line: await-in-sync
127      return coroutine.yield()
128    else
129      local option_strings = { params.message, '\nRequest Actions:' }
130      for i, action in ipairs(actions) do
131        local title = action.title:gsub('\r\n', '\\r\\n')
132        title = title:gsub('\n', '\\n')
133        table.insert(option_strings, string.format('%d. %s', i, title))
134      end
135      local choice = vim.fn.inputlist(option_strings)
136      if choice < 1 or choice > #actions then
137        return vim.NIL
138      else
139        return actions[choice]
140      end
141    end
142  else
143    -- No actions, just show the message.
144    show_message_notification(params, ctx)
145    return vim.NIL
146  end
147end
148
149--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability
150--- @param params lsp.RegistrationParams
151RSC['client/registerCapability'] = function(_, params, ctx)
152  local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
153  client:_register(params.registrations)
154  for bufnr in pairs(client.attached_buffers) do
155    vim.lsp._set_defaults(client, bufnr)
156  end
157  for _, reg in ipairs(params.registrations) do
158    -- The capability framework's attach loop only runs during initial Client:on_attach.
159    -- When a client dynamically registers a new method, we need to manually trigger
160    -- on_attach for capabilities that are now supported.
161    for _, Cap in pairs(vim.lsp._capability.all) do
162      if reg.method == Cap.method then
163        for bufnr in pairs(client.attached_buffers) do
164          if
165            client:supports_method(Cap.method, bufnr)
166            and vim.lsp._capability.is_enabled(Cap.name, { bufnr = bufnr, client_id = client.id })
167          then
168            local capability = Cap.active[bufnr] or Cap:new(bufnr)
169            if not capability.client_state[client.id] then
170              capability:on_attach(client.id)
171            end
172          end
173        end
174      end
175    end
176  end
177  return vim.NIL
178end
179
180--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability
181--- @param params lsp.UnregistrationParams
182RSC['client/unregisterCapability'] = function(_, params, ctx)
183  local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
184  client:_unregister(params.unregisterations)
185  return vim.NIL
186end
187
188-- TODO(lewis6991): Do we need to notify other servers?
189--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit
190RSC['workspace/applyEdit'] = function(_, params, ctx)
191  assert(
192    params,
193    'workspace/applyEdit must be called with `ApplyWorkspaceEditParams`. Server is violating the specification'
194  )
195  -- TODO(ashkan) Do something more with label?
196  local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
197  if params.label then
198    print('Workspace edit', params.label)
199  end
200  local status, result = pcall(util.apply_workspace_edit, params.edit, client.offset_encoding)
201  return {
202    applied = status,
203    failureReason = result,
204  }
205end
206
207---@param table   table e.g., { foo = { bar = "z" } }
208---@param section string indicating the field of the table, e.g., "foo.bar"
209---@return any|nil setting value read from the table, or `nil` not found
210local function lookup_section(table, section)
211  local keys = vim.split(section, '.', { plain = true }) --- @type string[]
212  return vim.tbl_get(table, unpack(keys))
213end
214
215--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_configuration
216--- @param params lsp.ConfigurationParams
217RSC['workspace/configuration'] = function(_, params, ctx)
218  local client = vim.lsp.get_client_by_id(ctx.client_id)
219  if not client then
220    err_message(
221      'LSP[',
222      ctx.client_id,
223      '] client has shut down after sending a workspace/configuration request'
224    )
225    return
226  end
227  if not params.items then
228    return {}
229  end
230
231  local response = {}
232  for _, item in ipairs(params.items) do
233    if item.section then
234      local value = lookup_section(client.settings, item.section)
235      -- For empty sections with no explicit '' key, return settings as is
236      if value == nil and item.section == '' then
237        value = client.settings
238      end
239      if value == nil then
240        value = vim.NIL
241      end
242      table.insert(response, value)
243    else
244      -- If no section is provided, return settings as is
245      table.insert(response, client.settings)
246    end
247  end
248  return response
249end
250
251--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_workspaceFolders
252RSC['workspace/workspaceFolders'] = function(_, _, ctx)
253  local client = vim.lsp.get_client_by_id(ctx.client_id)
254  if not client then
255    err_message('LSP[id=', ctx.client_id, '] client has shut down after sending the message')
256    return
257  end
258  return client.workspace_folders or vim.NIL
259end
260
261NSC['textDocument/publishDiagnostics'] = function(...)
262  return vim.lsp.diagnostic.on_publish_diagnostics(...)
263end
264
265--- @private
266---@diagnostic disable-next-line: deprecated
267RCS['textDocument/diagnostic'] = function(...)
268  return vim.lsp.diagnostic.on_diagnostic(...)
269end
270
271--- @private
272---@diagnostic disable-next-line: deprecated
273RCS['textDocument/inlayHint'] = function(...)
274  return vim.lsp.inlay_hint.on_inlayhint(...)
275end
276
277--- Return a function that converts LSP responses to list items and opens the list
278---
279--- The returned function has an optional {config} parameter that accepts |vim.lsp.ListOpts|
280---
281---@param map_result fun(resp: any, bufnr: integer, position_encoding: 'utf-8'|'utf-16'|'utf-32'): table to convert the response
282---@param entity string name of the resource used in a `not found` error message
283---@param title_fn fun(ctx: lsp.HandlerContext): string Function to call to generate list title
284---@return lsp.Handler
285local function response_to_list(map_result, entity, title_fn)
286  --- @diagnostic disable-next-line:redundant-parameter
287  return function(_, result, ctx, config)
288    if not result or vim.tbl_isempty(result) then
289      vim.notify('No ' .. entity .. ' found')
290      return
291    end
292    config = config or {}
293    local title = title_fn(ctx)
294    local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
295    local items = map_result(result, ctx.bufnr, client.offset_encoding)
296
297    local list = { title = title, items = items, context = ctx }
298    if config.on_list then
299      assert(vim.is_callable(config.on_list), 'on_list is not a function')
300      config.on_list(list)
301    elseif config.loclist then
302      vim.fn.setloclist(0, {}, ' ', list)
303      vim.cmd.lopen()
304    else
305      vim.fn.setqflist({}, ' ', list)
306      vim.cmd('botright copen')
307    end
308  end
309end
310
311--- @deprecated remove in 0.13
312--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol
313---@diagnostic disable-next-line: deprecated
314RCS['textDocument/documentSymbol'] = response_to_list(
315  util.symbols_to_items,
316  'document symbols',
317  function(ctx)
318    local fname = vim.fn.fnamemodify(vim.uri_to_fname(ctx.params.textDocument.uri), ':.')
319    return string.format('Symbols in %s', fname)
320  end
321)
322
323--- @deprecated remove in 0.13
324--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_symbol
325---@diagnostic disable-next-line: deprecated
326RCS['workspace/symbol'] = response_to_list(util.symbols_to_items, 'symbols', function(ctx)
327  return string.format("Symbols matching '%s'", ctx.params.query)
328end)
329
330--- @deprecated remove in 0.13
331--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rename
332---@diagnostic disable-next-line: deprecated
333RCS['textDocument/rename'] = function(_, result, ctx)
334  if not result then
335    vim.notify("Language server couldn't provide rename result", vim.log.levels.INFO)
336    return
337  end
338  local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
339  util.apply_workspace_edit(result, client.offset_encoding)
340end
341
342--- @deprecated remove in 0.13
343--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rangeFormatting
344---@diagnostic disable-next-line: deprecated
345RCS['textDocument/rangeFormatting'] = function(_, result, ctx)
346  if not result then
347    return
348  end
349  local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
350  util.apply_text_edits(result, assert(ctx.bufnr), client.offset_encoding)
351end
352
353--- @deprecated remove in 0.13
354--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting
355---@diagnostic disable-next-line: deprecated
356RCS['textDocument/formatting'] = function(_, result, ctx)
357  if not result then
358    return
359  end
360  local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
361  util.apply_text_edits(result, assert(ctx.bufnr), client.offset_encoding)
362end
363
364--- @deprecated remove in 0.13
365--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
366---@diagnostic disable-next-line: deprecated
367RCS['textDocument/completion'] = function(_, result, _)
368  if vim.tbl_isempty(result or {}) then
369    return
370  end
371  local cursor = api.nvim_win_get_cursor(0)
372  local row, col = cursor[1], cursor[2]
373  local line = assert(api.nvim_buf_get_lines(0, row - 1, row, false)[1])
374  local line_to_cursor = line:sub(col + 1)
375  local textMatch = vim.fn.match(line_to_cursor, '\\k*$')
376  local prefix = line_to_cursor:sub(textMatch + 1)
377
378  local matches = completion._lsp_to_complete_items(result, prefix)
379  vim.fn.complete(textMatch + 1, matches)
380end
381
382--- @deprecated
383--- |lsp-handler| for the method "textDocument/hover"
384---
385--- ```lua
386--- vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(
387---   vim.lsp.handlers.hover, {
388---     -- Use a sharp border with `FloatBorder` highlights
389---     border = "single",
390---     -- add the title in hover float window
391---     title = "hover"
392---   }
393--- )
394--- ```
395---
396---@param _ lsp.ResponseError?
397---@param result lsp.Hover
398---@param ctx lsp.HandlerContext
399---@param config table Configuration table.
400---     - border:     (default=nil)
401---         - Add borders to the floating window
402---         - See |vim.lsp.util.open_floating_preview()| for more options.
403--- @diagnostic disable-next-line:redundant-parameter
404function M.hover(_, result, ctx, config)
405  config = config or {}
406  config.focus_id = ctx.method
407  if api.nvim_get_current_buf() ~= ctx.bufnr then
408    -- Ignore result since buffer changed. This happens for slow language servers.
409    return
410  end
411  if not (result and result.contents) then
412    if config.silent ~= true then
413      vim.notify('No information available')
414    end
415    return
416  end
417  local format = 'markdown'
418  local contents ---@type string[]
419  if type(result.contents) == 'table' and result.contents.kind == 'plaintext' then
420    format = 'plaintext'
421    contents = vim.split(result.contents.value or '', '\n', { trimempty = true })
422  else
423    contents = util.convert_input_to_markdown_lines(result.contents)
424  end
425  if vim.tbl_isempty(contents) then
426    if config.silent ~= true then
427      vim.notify('No information available')
428    end
429    return
430  end
431  return util.open_floating_preview(contents, format, config)
432end
433
434--- @deprecated remove in 0.13
435--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover
436--- @diagnostic disable-next-line: deprecated
437RCS['textDocument/hover'] = M.hover
438
439local sig_help_ns = api.nvim_create_namespace('nvim.lsp.signature_help')
440
441--- @deprecated remove in 0.13
442--- |lsp-handler| for the method "textDocument/signatureHelp".
443---
444--- The active parameter is highlighted with |hl-LspSignatureActiveParameter|.
445---
446--- ```lua
447--- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(
448---   vim.lsp.handlers.signature_help, {
449---     -- Use a sharp border with `FloatBorder` highlights
450---     border = "single"
451---   }
452--- )
453--- ```
454---
455---@param _ lsp.ResponseError?
456---@param result lsp.SignatureHelp? Response from the language server
457---@param ctx lsp.HandlerContext Client context
458---@param config table Configuration table.
459---     - border:     (default=nil)
460---         - Add borders to the floating window
461---         - See |vim.lsp.util.open_floating_preview()| for more options
462--- @diagnostic disable-next-line:redundant-parameter
463function M.signature_help(_, result, ctx, config)
464  config = config or {}
465  config.focus_id = ctx.method
466  if api.nvim_get_current_buf() ~= ctx.bufnr then
467    -- Ignore result since buffer changed. This happens for slow language servers.
468    return
469  end
470  -- When use `autocmd CompleteDone <silent><buffer> lua vim.lsp.buf.signature_help()` to call signatureHelp handler
471  -- If the completion item doesn't have signatures It will make noise. Change to use `print` that can use `<silent>` to ignore
472  if not (result and result.signatures and result.signatures[1]) then
473    if config.silent ~= true then
474      print('No signature help available')
475    end
476    return
477  end
478  local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
479  local triggers =
480    vim.tbl_get(client.server_capabilities, 'signatureHelpProvider', 'triggerCharacters')
481  local ft = vim.bo[ctx.bufnr].filetype
482  local lines, hl = util.convert_signature_help_to_markdown_lines(result, ft, triggers)
483  if not lines or vim.tbl_isempty(lines) then
484    if config.silent ~= true then
485      print('No signature help available')
486    end
487    return
488  end
489  local fbuf, fwin = util.open_floating_preview(lines, 'markdown', config)
490  -- Highlight the active parameter.
491  if hl then
492    vim.hl.range(
493      fbuf,
494      sig_help_ns,
495      'LspSignatureActiveParameter',
496      { hl[1], hl[2] },
497      { hl[3], hl[4] }
498    )
499  end
500  return fbuf, fwin
501end
502
503--- @deprecated remove in 0.13
504--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp
505--- @diagnostic disable-next-line:deprecated
506RCS['textDocument/signatureHelp'] = M.signature_help
507
508--- @deprecated remove in 0.13
509--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentHighlight
510---@diagnostic disable-next-line: deprecated
511RCS['textDocument/documentHighlight'] = function(_, result, ctx)
512  if not result then
513    return
514  end
515  local client_id = ctx.client_id
516  local client = vim.lsp.get_client_by_id(client_id)
517  if not client then
518    return
519  end
520  util.buf_highlight_references(assert(ctx.bufnr), result, client.offset_encoding)
521end
522
523--- Displays call hierarchy in the quickfix window.
524---
525--- @param direction 'from'|'to' `"from"` for incoming calls and `"to"` for outgoing calls
526--- @overload fun(direction:'from'): fun(_, result: lsp.CallHierarchyIncomingCall[]?)
527--- @overload fun(direction:'to'): fun(_, result: lsp.CallHierarchyOutgoingCall[]?)
528local function make_call_hierarchy_handler(direction)
529  --- @param result lsp.CallHierarchyIncomingCall[]|lsp.CallHierarchyOutgoingCall[]|nil
530  --- @param ctx lsp.HandlerContext
531  return function(_, result, ctx)
532    if not result then
533      return
534    end
535    local items = {}
536    for _, call_hierarchy_call in pairs(result) do
537      --- @type lsp.CallHierarchyItem
538      local call_hierarchy_item = call_hierarchy_call[direction]
539      local filename = nil
540      local bufnr = nil
541      if direction == 'from' then
542        filename = vim.uri_to_fname(call_hierarchy_item.uri)
543      else
544        bufnr = ctx.bufnr
545      end
546      for _, range in pairs(call_hierarchy_call.fromRanges) do
547        table.insert(items, {
548          filename = filename,
549          bufnr = bufnr,
550          text = call_hierarchy_item.name,
551          lnum = range.start.line + 1,
552          col = range.start.character + 1,
553        })
554      end
555    end
556    vim.fn.setqflist({}, ' ', { title = 'LSP call hierarchy', items = items })
557    vim.cmd('botright copen')
558  end
559end
560
561--- @deprecated remove in 0.13
562--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_incomingCalls
563---@diagnostic disable-next-line: deprecated
564RCS['callHierarchy/incomingCalls'] = make_call_hierarchy_handler('from')
565
566--- @deprecated remove in 0.13
567--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_outgoingCalls
568---@diagnostic disable-next-line: deprecated
569RCS['callHierarchy/outgoingCalls'] = make_call_hierarchy_handler('to')
570
571--- Displays type hierarchy in the quickfix window.
572local function make_type_hierarchy_handler()
573  --- @param result lsp.TypeHierarchyItem[]?
574  --- @param ctx lsp.HandlerContext
575  return function(_, result, ctx, _)
576    if not result then
577      return
578    end
579    --- @param item lsp.TypeHierarchyItem
580    local function format_item(item)
581      if not item.detail or #item.detail == 0 then
582        return item.name
583      end
584      return string.format('%s %s', item.name, item.detail)
585    end
586    local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
587    local items = {}
588    for _, type_hierarchy_item in pairs(result) do
589      local pos =
590        vim.pos.lsp(assert(ctx.bufnr), type_hierarchy_item.range.start, client.offset_encoding)
591      table.insert(items, {
592        filename = vim.uri_to_fname(type_hierarchy_item.uri),
593        text = format_item(type_hierarchy_item),
594        lnum = pos.row + 1,
595        col = pos.col + 1,
596      })
597    end
598    vim.fn.setqflist({}, ' ', { title = 'LSP type hierarchy', items = items })
599    vim.cmd('botright copen')
600  end
601end
602
603--- @deprecated remove in 0.13
604--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#typeHierarchy_incomingCalls
605---@diagnostic disable-next-line: deprecated
606RCS['typeHierarchy/subtypes'] = make_type_hierarchy_handler()
607
608--- @deprecated remove in 0.13
609--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#typeHierarchy_outgoingCalls
610---@diagnostic disable-next-line: deprecated
611RCS['typeHierarchy/supertypes'] = make_type_hierarchy_handler()
612
613--- @see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_logMessage
614--- @param params lsp.LogMessageParams
615NSC['window/logMessage'] = function(_, params, ctx)
616  local message_type = params.type
617  local message = params.message
618  local client_id = ctx.client_id
619  local client = vim.lsp.get_client_by_id(client_id)
620  local client_name = client and client.name or string.format('id=%d', client_id)
621  if not client then
622    err_message('LSP[', client_name, '] client has shut down after sending ', message)
623  end
624  if message_type == protocol.MessageType.Error then
625    log.error(message)
626  elseif message_type == protocol.MessageType.Warning then
627    log.warn(message)
628  elseif message_type == protocol.MessageType.Info or message_type == protocol.MessageType.Log then
629    log.info(message)
630  else
631    log.debug(message)
632  end
633  return params
634end
635
636--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessage
637--- @param params lsp.ShowMessageParams
638NSC['window/showMessage'] = function(_, params, ctx)
639  return show_message_notification(params, ctx)
640end
641
642--- @private
643--- @see # https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showDocument
644--- @param params lsp.ShowDocumentParams
645RSC['window/showDocument'] = function(_, params, ctx)
646  local uri = params.uri
647
648  if params.external then
649    -- TODO(lvimuser): ask the user for confirmation
650    local cmd, err = vim.ui.open(uri)
651    local ret = cmd and cmd:wait(2000) or nil
652
653    if ret == nil or ret.code ~= 0 then
654      return {
655        success = false,
656        error = {
657          code = protocol.ErrorCodes.UnknownErrorCode,
658          message = ret and ret.stderr or err,
659        },
660      }
661    end
662
663    return { success = true }
664  end
665
666  local client_id = ctx.client_id
667  local client = vim.lsp.get_client_by_id(client_id)
668  local client_name = client and client.name or string.format('id=%d', client_id)
669  if not client then
670    err_message('LSP[', client_name, '] client has shut down after sending ', ctx.method)
671    return vim.NIL
672  end
673
674  local success = util._show_document(uri, params.selection, client.offset_encoding, {
675    reuse_win = true,
676    focus = params.takeFocus,
677  })
678  return { success = success or false }
679end
680
681---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#codeLens_refresh
682RSC['workspace/codeLens/refresh'] = function(err, result, ctx)
683  return vim.lsp.codelens.on_refresh(err, result, ctx)
684end
685
686---@see https://microsoft.github.io/language-server-protocol/specification/#diagnostic_refresh
687RSC['workspace/diagnostic/refresh'] = function(err, result, ctx)
688  return vim.lsp.diagnostic.on_refresh(err, result, ctx)
689end
690
691---@see https://microsoft.github.io/language-server-protocol/specification/#workspace_foldingRange_refresh
692RSC['workspace/foldingRange/refresh'] = function(err, result, ctx)
693  return vim.lsp._folding_range.on_refresh(err, result, ctx)
694end
695
696---@see https://microsoft.github.io/language-server-protocol/specification/#workspace_inlayHint_refresh
697RSC['workspace/inlayHint/refresh'] = function(err, result, ctx)
698  return vim.lsp.inlay_hint.on_refresh(err, result, ctx)
699end
700
701---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#semanticTokens_refreshRequest
702RSC['workspace/semanticTokens/refresh'] = function(err, result, ctx)
703  return vim.lsp.semantic_tokens._refresh(err, result, ctx)
704end
705
706--- @nodoc
707--- @type table<string, lsp.Handler>
708---@diagnostic disable-next-line: deprecated
709M = vim.tbl_extend('force', M, RSC, NSC, RCS)
710
711-- Add boilerplate error validation and logging for all of these.
712for k, fn in pairs(M) do
713  --- @diagnostic disable-next-line:redundant-parameter
714  M[k] = function(err, result, ctx, config)
715    if log.trace() then
716      log.trace('default_handler', ctx.method, {
717        err = err,
718        result = result,
719        ctx = vim.inspect(ctx),
720      })
721    end
722
723    -- ServerCancelled errors should be propagated to the request handler
724    if err and err.code ~= protocol.ErrorCodes.ServerCancelled then
725      -- LSP spec:
726      -- interface ResponseError:
727      --  code: integer;
728      --  message: string;
729      --  data?: string | number | boolean | array | object | null;
730
731      -- Per LSP, don't show ContentModified error to the user.
732      if err.code ~= protocol.ErrorCodes.ContentModified then
733        local client = vim.lsp.get_client_by_id(ctx.client_id)
734        local client_name = client and client.name or string.format('client_id=%d', ctx.client_id)
735
736        err_message(client_name .. ': ' .. tostring(err.code) .. ': ' .. err.message)
737      end
738      return
739    end
740
741    --- @diagnostic disable-next-line:redundant-parameter
742    return fn(err, result, ctx, config)
743  end
744end
745
746return M