robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
69.8 KiB2063 linesraw
1local protocol = require('vim.lsp.protocol')
2local validate = vim.validate
3local api = vim.api
4local nvim_on = require('vim._core.util').nvim_on
5local list_extend = vim.list_extend
6local uv = vim.uv
7
8local M = {}
9
10--- @param border string|(string|[string,string])[]
11--- @return never
12local function border_error(border)
13  error(
14    string.format(
15      'invalid floating preview border: %s. :help vim.api.nvim_open_win()',
16      vim.inspect(border)
17    ),
18    2
19  )
20end
21
22local border_size = {
23  none = { 0, 0 },
24  single = { 2, 2 },
25  double = { 2, 2 },
26  rounded = { 2, 2 },
27  solid = { 2, 2 },
28  shadow = { 1, 1 },
29  bold = { 2, 2 },
30}
31
32--- Check the border given by opts or the default border for the additional
33--- size it adds to a float.
34--- @param opts? vim.lsp.util.open_floating_preview.Opts
35--- @return integer height
36--- @return integer width
37local function get_border_size(opts)
38  local border = opts and opts.border or vim.o.winborder
39
40  if border == '' then
41    border = 'none'
42  end
43
44  -- Convert winborder string option with custom characters into a table
45  if type(border) == 'string' and border:find(',') then
46    border = vim.split(border, ',')
47  end
48
49  if type(border) == 'string' then
50    if not border_size[border] then
51      border_error(border)
52    end
53    local r = border_size[border]
54    return r[1], r[2]
55  end
56
57  if 8 % #border ~= 0 then
58    border_error(border)
59  end
60
61  --- @param id integer
62  --- @return string
63  local function elem(id)
64    id = (id - 1) % #border + 1
65    local e = border[id]
66    if type(e) == 'table' then
67      -- border specified as a table of <character, highlight group>
68      return e[1]
69    elseif type(e) == 'string' then
70      -- border specified as a list of border characters
71      return e
72    end
73    -- EmmyLua rejects `never` as a subtype of the declared string result.
74    ---@diagnostic disable-next-line: return-type-mismatch
75    return border_error(border)
76  end
77
78  --- @param e string
79  --- @return integer
80  local function border_height(e)
81    return #e > 0 and 1 or 0
82  end
83
84  local top, bottom = elem(2), elem(6)
85  local height = border_height(top) + border_height(bottom)
86
87  local right, left = elem(4), elem(8)
88  local width = vim.fn.strdisplaywidth(right) + vim.fn.strdisplaywidth(left)
89
90  return height, width
91end
92
93--- Splits string at newlines, optionally removing unwanted blank lines.
94---
95--- @param s string Multiline string
96--- @param no_blank boolean? Drop blank lines for each @param/@return (except one empty line
97--- separating each, and before a codeblock).
98--- Workaround for https://github.com/LuaLS/lua-language-server/issues/2333
99local function split_lines(s, no_blank)
100  s = string.gsub(s, '\r\n?', '\n')
101  local raw = vim.split(s, '\n', { plain = true, trimempty = true })
102
103  --- @param l string
104  --- @return boolean # true if line begins a (4-space-indented) codeblock. #40860
105  local function codeblock(l)
106    return l:find('^    ') ~= nil or l:find('^\t') ~= nil
107  end
108
109  local lines = {}
110  local in_desc = true -- Main description block, before seeing any @foo.
111  for i, line in ipairs(raw) do
112    local start_annotation = not not line:find('^ ?%@.?[pr]')
113    in_desc = (not start_annotation) and in_desc or false
114    if start_annotation and no_blank and not (lines[#lines] or ''):find('^%s*$') then
115      table.insert(lines, '') -- Separate each @foo with a blank line.
116    end
117
118    local blank = line:find('^%s*$')
119    local keep_blank = blank and codeblock(raw[i + 1] or '') -- Keep if it precedes a codeblock. #40860
120    if in_desc or not no_blank or not blank or keep_blank then
121      table.insert(lines, line)
122    end
123  end
124  return lines
125end
126
127local function create_window_without_focus()
128  local prev = api.nvim_get_current_win()
129  vim.cmd.new()
130  local new = api.nvim_get_current_win()
131  api.nvim_set_current_win(prev)
132  return new
133end
134
135--- @param fn fun(x:any):any[]
136--- @return function
137local function sort_by_key(fn)
138  return function(a, b)
139    local ka, kb = fn(a), fn(b)
140    assert(#ka == #kb)
141    for i = 1, #ka do
142      if ka[i] ~= kb[i] then
143        return ka[i] < kb[i]
144      end
145    end
146    -- every value must have been equal here, which means it's not less than.
147    return false
148  end
149end
150
151-- TODO(ofseed): remove these exported functions by replacing their usages with `vim.pos`.
152local get_lines = require('vim.pos._util').get_lines
153local get_line = require('vim.pos._util').get_line
154
155local cursor_ns = api.nvim_create_namespace('nvim.lsp.util.cursor')
156
157--- Anchors the cursor to the text under it, so edits before it don't drag it along.
158---
159--- @param bufnr integer
160--- @return fun()? # Restores the cursor and deletes the mark.
161local function anchor_cursor(bufnr)
162  local win = api.nvim_get_current_win()
163  if api.nvim_win_get_buf(win) ~= bufnr then
164    return function() end
165  end
166  local cursor = api.nvim_win_get_cursor(win)
167  local mark = api.nvim_buf_set_extmark(bufnr, cursor_ns, cursor[1] - 1, cursor[2], {})
168  return function()
169    local pos = api.nvim_buf_get_extmark_by_id(bufnr, cursor_ns, mark, {})
170    api.nvim_buf_del_extmark(bufnr, cursor_ns, mark)
171    if pos[1] and api.nvim_win_is_valid(win) and api.nvim_win_get_buf(win) == bufnr then
172      api.nvim_win_set_cursor(win, { pos[1] + 1, pos[2] })
173    end
174  end
175end
176
177--- @class vim.lsp.util.apply_text_edits.Opts
178--- @inlinedoc
179---
180--- Keep the cursor on the text it is on, instead of letting the edits move it.
181--- (default: `false`)
182--- @field keep_cursor? boolean
183
184--- Applies a list of text edits to a buffer. Note: this mutates `text_edits` (sorts in-place and
185--- adds `_index` fields).
186---
187---@param text_edits (lsp.TextEdit|lsp.AnnotatedTextEdit)[]
188---@param bufnr integer Buffer id
189---@param position_encoding 'utf-8'|'utf-16'|'utf-32'
190---@param change_annotations? table<string, lsp.ChangeAnnotation>
191---@param opts? vim.lsp.util.apply_text_edits.Opts
192---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit
193function M.apply_text_edits(text_edits, bufnr, position_encoding, change_annotations, opts)
194  validate('text_edits', text_edits, 'table', false)
195  validate('bufnr', bufnr, 'number', false)
196  validate('position_encoding', position_encoding, 'string', false)
197  validate('change_annotations', change_annotations, 'table', true)
198  validate('opts', opts, 'table', true)
199  opts = opts or {}
200
201  if not next(text_edits) then
202    return
203  end
204
205  assert(bufnr ~= 0, 'Explicit buffer number is required')
206
207  if not api.nvim_buf_is_loaded(bufnr) then
208    vim.fn.bufload(bufnr)
209  end
210
211  local marks = {} --- @type table<string,[integer,integer]>
212  local has_eol_text_edit = false
213
214  local function apply_text_edits()
215    -- Fix reversed range and indexing each text_edits
216    for index, text_edit in ipairs(text_edits) do
217      --- @cast text_edit lsp.TextEdit & { _index?: integer }
218      -- XXX: Preserve existing _index to avoid surprises if the same edit is reapplied. #39344
219      if text_edit._index == nil then
220        text_edit._index = index
221      end
222
223      if
224        text_edit.range.start.line > text_edit.range['end'].line
225        or text_edit.range.start.line == text_edit.range['end'].line
226          and text_edit.range.start.character > text_edit.range['end'].character
227      then
228        local start = text_edit.range.start
229        text_edit.range.start = text_edit.range['end']
230        text_edit.range['end'] = start
231      end
232    end
233
234    --- @cast text_edits ((lsp.TextEdit|lsp.AnnotatedTextEdit)&{_index: integer})[]
235
236    -- The checker rejects this array against its own inferred intersection type.
237    --- @diagnostic disable-next-line: param-type-mismatch
238    table.sort(text_edits, function(a, b)
239      if a.range.start.line ~= b.range.start.line then
240        return a.range.start.line > b.range.start.line
241      end
242      if a.range.start.character ~= b.range.start.character then
243        return a.range.start.character > b.range.start.character
244      end
245      return a._index > b._index
246    end)
247
248    -- save and restore local marks since they get deleted by nvim_buf_set_lines
249    for _, m in pairs(vim.fn.getmarklist(bufnr)) do
250      if m.mark:match("^'[a-z]$") then
251        marks[m.mark:sub(2, 2)] = { m.pos[2], m.pos[3] - 1 } -- api-indexed
252      end
253    end
254
255    for _, text_edit in ipairs(text_edits) do
256      -- Normalize line ending
257      text_edit.newText, _ = string.gsub(text_edit.newText, '\r\n?', '\n')
258
259      -- Convert from LSP style ranges to Neovim style ranges.
260      local range = vim.range.lsp(bufnr, text_edit.range, position_encoding)
261      local start_row, start_col, end_row, end_col =
262        range.start_row, range.start_col, range.end_row, range.end_col
263      local text = vim.split(text_edit.newText, '\n', { plain = true })
264
265      local max = api.nvim_buf_line_count(bufnr)
266      -- If the whole edit is after the lines in the buffer we can simply add the new text to the end
267      -- of the buffer.
268      if max <= start_row then
269        api.nvim_buf_set_lines(bufnr, max, max, false, text)
270        has_eol_text_edit = true
271      else
272        local last_line_len = #get_line(bufnr, math.min(end_row, max - 1))
273        -- Some LSP servers may return +1 range of the buffer content but nvim_buf_set_text can't
274        -- accept it so we should fix it here.
275        if max <= end_row then
276          end_row = max - 1
277          end_col = last_line_len
278          has_eol_text_edit = true
279        else
280          -- If the replacement is over the end of a line (i.e. end_col is equal to the line length and the
281          -- replacement text ends with a newline We can likely assume that the replacement is assumed
282          -- to be meant to replace the newline with another newline and we need to make sure this
283          -- doesn't add an extra empty line. E.g. when the last line to be replaced contains a '\r'
284          -- in the file some servers (clangd on windows) will include that character in the line
285          -- while nvim_buf_set_text doesn't count it as part of the line.
286          if
287            end_col >= last_line_len
288            and text_edit.range['end'].character > end_col
289            and #text_edit.newText > 0
290            and string.sub(text_edit.newText, -1) == '\n'
291          then
292            table.remove(text, #text)
293          end
294        end
295        -- Make sure we don't go out of bounds for end_col
296        end_col = math.min(last_line_len, end_col)
297
298        api.nvim_buf_set_text(bufnr, start_row, start_col, end_row, end_col, text)
299      end
300    end
301  end
302
303  --- Track how many times each change annotation is applied to build up the final description.
304  ---@type table<string, integer>
305  local change_count = {}
306
307  -- If there are any annotated text edits, we need to confirm them before applying the edits.
308  local confirmations = {} ---@type table<string, integer>
309  for _, text_edit in ipairs(text_edits) do
310    if text_edit.annotationId then
311      assert(
312        change_annotations ~= nil,
313        'change_annotations must be provided for annotated text edits'
314      )
315
316      local annotation = change_annotations[text_edit.annotationId]
317      if not annotation then
318        error(string.format('No change annotation found for ID: %s', text_edit.annotationId))
319      end
320
321      if annotation.needsConfirmation then
322        confirmations[text_edit.annotationId] = (confirmations[text_edit.annotationId] or 0) + 1
323      end
324
325      change_count[text_edit.annotationId] = (change_count[text_edit.annotationId] or 0) + 1
326    end
327  end
328
329  if next(confirmations) then
330    local message = { 'Apply all changes?' }
331    for id, count in pairs(confirmations) do
332      local annotation = assert(change_annotations)[id]
333      message[#message + 1] = annotation.label
334        .. (annotation.description and (string.format(': %s', annotation.description)) or '')
335        .. (count > 1 and string.format(' (%d)', count) or '')
336    end
337
338    local response = vim.fn.confirm(table.concat(message, '\n'), '&Yes\n&No', 1, 'Question')
339    if response ~= 1 then
340      return
341    end
342  end
343
344  -- Anchor after the prompt, so the mark only exists while the buffer is actually being edited.
345  local restore_cursor = opts.keep_cursor and anchor_cursor(bufnr) or nil
346  apply_text_edits()
347
348  if change_annotations ~= nil and next(change_count) then
349    local change_message = { 'Applied changes:' }
350    for id, count in pairs(change_count) do
351      local annotation = change_annotations[id]
352      change_message[#change_message + 1] = annotation.label
353        .. (annotation.description and (': ' .. annotation.description) or '')
354        .. (count > 1 and string.format(' (%d)', count) or '')
355    end
356    vim.notify(table.concat(change_message, '\n'), vim.log.levels.INFO)
357  end
358
359  local max = api.nvim_buf_line_count(bufnr)
360
361  -- no need to restore marks that still exist
362  for _, m in pairs(vim.fn.getmarklist(bufnr)) do
363    marks[m.mark:sub(2, 2)] = nil
364  end
365  -- restore marks
366  for mark, pos in pairs(marks) do
367    if pos then
368      -- make sure we don't go out of bounds
369      pos[1] = math.min(pos[1], max)
370      pos[2] = math.min(pos[2], #get_line(bufnr, pos[1] - 1))
371      api.nvim_buf_set_mark(bufnr or 0, mark, pos[1], pos[2])
372    end
373  end
374
375  -- Remove final line if needed
376  local fix_eol = has_eol_text_edit
377  fix_eol = fix_eol and (vim.bo[bufnr].eol or (vim.bo[bufnr].fixeol and not vim.bo[bufnr].binary))
378  fix_eol = fix_eol and get_line(bufnr, max - 1) == ''
379  if fix_eol then
380    api.nvim_buf_set_lines(bufnr, -2, -1, false, {})
381  end
382
383  if restore_cursor then
384    restore_cursor()
385  end
386end
387
388--- Applies a `TextDocumentEdit`, which is a list of changes to a single
389--- document.
390---
391---@param text_document_edit lsp.TextDocumentEdit
392---@param index? integer: Optional index of the edit, if from a list of edits (or nil, if not from a list)
393---@param position_encoding 'utf-8'|'utf-16'|'utf-32'
394---@param change_annotations? table<string, lsp.ChangeAnnotation>
395---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentEdit
396function M.apply_text_document_edit(
397  text_document_edit,
398  index,
399  position_encoding,
400  change_annotations
401)
402  validate('position_encoding', position_encoding, 'string')
403
404  local text_document = text_document_edit.textDocument
405  local bufnr = vim.uri_to_bufnr(text_document.uri)
406
407  -- `VersionedTextDocumentIdentifier`s version may be null
408  --  https://microsoft.github.io/language-server-protocol/specification#versionedTextDocumentIdentifier
409  if
410    -- For lists of text document edits,
411    -- do not check the version after the first edit.
412    not (index and index > 1)
413    and (
414      text_document.version ~= vim.NIL
415      and text_document.version > 0
416      and M.buf_versions[bufnr] > text_document.version
417    )
418  then
419    print('Buffer ', text_document.uri, ' newer than edits.')
420    return
421  end
422
423  -- Snippet edits are not supported or advertised in our client capabilities.
424  local edits = text_document_edit.edits --[[@as (lsp.TextEdit|lsp.AnnotatedTextEdit)[] ]]
425  M.apply_text_edits(edits, bufnr, position_encoding, change_annotations)
426end
427
428--- @param path string
429local function path_components(path)
430  return vim.split(path, '/', { plain = true })
431end
432
433--- @param path string[]
434--- @param prefix string[]
435--- @return boolean
436local function path_under_prefix(path, prefix)
437  for i, c in ipairs(prefix) do
438    if c ~= path[i] then
439      return false
440    end
441  end
442  return true
443end
444
445--- Get list of loaded writable buffers whose filename matches the given path
446--- prefix (normalized full path).
447---@param prefix string
448---@return integer[]
449local function get_writable_bufs(prefix)
450  local prefix_parts = path_components(prefix)
451  local buffers = {} --- @type integer[]
452  for _, buf in ipairs(api.nvim_list_bufs()) do
453    -- No need to care about unloaded or nofile buffers. Also :saveas won't work for them.
454    if
455      api.nvim_buf_is_loaded(buf)
456      and not vim.list_contains({ 'nofile', 'nowrite' }, vim.bo[buf].buftype)
457    then
458      local bname = api.nvim_buf_get_name(buf)
459      local path = path_components(vim.fs.normalize(bname, { plain = true }))
460      if path_under_prefix(path, prefix_parts) then
461        buffers[#buffers + 1] = buf
462      end
463    end
464  end
465  return buffers
466end
467
468--- @param s string
469local function escape_gsub_repl(s)
470  return (s:gsub('%%', '%%%%'))
471end
472
473--- @class vim.lsp.util.rename.Opts
474--- @inlinedoc
475--- @field overwrite? boolean
476--- @field ignoreIfExists? boolean
477
478--- Rename old_fname to new_fname
479---
480--- Existing buffers are renamed as well, while maintaining their bufnr.
481---
482--- It deletes existing buffers that conflict with the renamed file name only when
483--- * `opts` requests overwriting; or
484--- * the conflicting buffers are not loaded, so that deleting them does not result in data loss.
485---
486--- @param old_fname string
487--- @param new_fname string
488--- @param opts? vim.lsp.util.rename.Opts Options:
489function M.rename(old_fname, new_fname, opts)
490  opts = opts or {}
491  local skip = not opts.overwrite or opts.ignoreIfExists
492
493  local old_fname_full = uv.fs_realpath(vim.fs.normalize(old_fname, { plain = true }))
494  if not old_fname_full then
495    vim.notify('Invalid path: ' .. old_fname, vim.log.levels.ERROR)
496    return
497  end
498
499  local target_exists = uv.fs_stat(new_fname) ~= nil
500  if target_exists and skip then
501    vim.notify(new_fname .. ' already exists. Skipping rename.', vim.log.levels.ERROR)
502    return
503  end
504
505  local buf_rename = {} ---@type table<integer, {from: string, to: string}>
506  local old_fname_pat = '^' .. vim.pesc(old_fname_full)
507  for _, b in ipairs(get_writable_bufs(old_fname_full)) do
508    -- Renaming a buffer may conflict with another buffer that happens to have the same name. In
509    -- most cases, this would have been already detected by the file conflict check above, but the
510    -- conflicting buffer may not be associated with a file. For example, 'buftype' can be "nofile"
511    -- or "nowrite", or the buffer can be a normal buffer but has not been written to the file yet.
512    -- Renaming should fail in such cases to avoid losing the contents of the conflicting buffer.
513    local old_bname = api.nvim_buf_get_name(b)
514    local new_bname = old_bname:gsub(old_fname_pat, escape_gsub_repl(new_fname))
515    if vim.fn.bufexists(new_bname) == 1 then
516      local existing_buf = vim.fn.bufnr(new_bname)
517      if api.nvim_buf_is_loaded(existing_buf) and skip then
518        vim.notify(
519          new_bname .. ' already exists in the buffer list. Skipping rename.',
520          vim.log.levels.ERROR
521        )
522        return
523      end
524      -- no need to preserve if such a buffer is empty
525      api.nvim_buf_delete(existing_buf)
526    end
527
528    buf_rename[b] = { from = old_bname, to = new_bname }
529  end
530
531  local newdir = vim.fs.dirname(new_fname)
532  vim.fn.mkdir(newdir, 'p')
533
534  assert(os.rename(old_fname_full, new_fname))
535
536  local old_undofile = vim.fn.undofile(old_fname_full)
537  if uv.fs_stat(old_undofile) ~= nil then
538    local new_undofile = vim.fn.undofile(new_fname)
539    vim.fn.mkdir(vim.fs.dirname(new_undofile), 'p')
540    os.rename(old_undofile, new_undofile)
541  end
542
543  for b, rename in pairs(buf_rename) do
544    -- Rename with :saveas. This does two things:
545    -- * Unset BF_WRITE_MASK, so that users don't get E13 when they do :write.
546    -- * Send didClose and didOpen via textDocument/didSave handler.
547    vim._with({ buf = b }, function()
548      vim.cmd('keepalt saveas! ' .. vim.fn.fnameescape(rename.to))
549    end)
550    -- Delete the new buffer with the old name created by :saveas. nvim_buf_delete and
551    -- :bwipeout are futile because the buffer will be added again somewhere else.
552    vim.cmd('bdelete! ' .. vim.fn.bufnr(rename.from))
553  end
554end
555
556--- @param change lsp.CreateFile
557local function create_file(change)
558  local opts = change.options or {}
559  -- from spec: Overwrite wins over `ignoreIfExists`
560  local fname = vim.uri_to_fname(change.uri)
561  if not opts.ignoreIfExists or opts.overwrite then
562    vim.fn.mkdir(vim.fs.dirname(fname), 'p')
563    local file = io.open(fname, 'w')
564    if file then
565      file:close()
566    end
567  end
568  vim.fn.bufadd(fname)
569end
570
571--- @param change lsp.DeleteFile
572local function delete_file(change)
573  local opts = change.options or {}
574  local fname = vim.uri_to_fname(change.uri)
575  local bufnr = vim.fn.bufadd(fname)
576  vim.fs.rm(fname, {
577    force = opts.ignoreIfNotExists,
578    recursive = opts.recursive,
579  })
580  api.nvim_buf_delete(bufnr, { force = true })
581end
582
583--- Applies a `WorkspaceEdit`.
584---
585---@param workspace_edit lsp.WorkspaceEdit
586---@param position_encoding 'utf-8'|'utf-16'|'utf-32' (required)
587---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit
588function M.apply_workspace_edit(workspace_edit, position_encoding)
589  validate('workspace_edit', workspace_edit, 'table')
590  validate('position_encoding', position_encoding, 'string')
591
592  if workspace_edit.documentChanges then
593    for idx, change in ipairs(workspace_edit.documentChanges) do
594      if change.kind == 'rename' then
595        local options = change.options --[[@as vim.lsp.util.rename.Opts]]
596        M.rename(vim.uri_to_fname(change.oldUri), vim.uri_to_fname(change.newUri), options)
597      elseif change.kind == 'create' then
598        create_file(change)
599      elseif change.kind == 'delete' then
600        delete_file(change)
601      elseif change.kind then --- @diagnostic disable-line:undefined-field
602        error(string.format('Unsupported change: %q', vim.inspect(change)))
603      else
604        local bufnr = vim.uri_to_bufnr(change.textDocument.uri)
605        M.apply_text_document_edit(change, idx, position_encoding, workspace_edit.changeAnnotations)
606        -- avoid triggering OptionSet
607        if not vim.bo[bufnr].buflisted then
608          vim.bo[bufnr].buflisted = true
609        end
610      end
611    end
612    return
613  end
614
615  local all_changes = workspace_edit.changes
616  if not (all_changes and not vim.tbl_isempty(all_changes)) then
617    return
618  end
619
620  for uri, changes in pairs(all_changes) do
621    local bufnr = vim.uri_to_bufnr(uri)
622    M.apply_text_edits(changes, bufnr, position_encoding, workspace_edit.changeAnnotations)
623    -- avoid triggering OptionSet
624    if not vim.bo[bufnr].buflisted then
625      vim.bo[bufnr].buflisted = true
626    end
627  end
628end
629
630--- Converts any of `MarkedString` | `MarkedString[]` | `MarkupContent` into
631--- a list of lines containing valid markdown. Useful to populate the hover
632--- window for `textDocument/hover`, for parsing the result of
633--- `textDocument/signatureHelp`, and potentially others.
634---
635--- Note that if the input is of type `MarkupContent` and its kind is `plaintext`,
636--- then the corresponding value is returned without further modifications.
637---
638---@diagnostic disable-next-line: deprecated
639---@param input lsp.MarkedString|lsp.MarkedString[]|lsp.MarkupContent
640---@param contents string[]? List of strings to extend with converted lines. Defaults to {}.
641---@return string[] extended with lines of converted markdown.
642---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover
643function M.convert_input_to_markdown_lines(input, contents)
644  contents = contents or {}
645  -- MarkedString variation 1
646  if type(input) == 'string' then
647    list_extend(contents, split_lines(input, true))
648  else
649    assert(type(input) == 'table', 'Expected a table for LSP input')
650    -- MarkupContent
651    if input.kind then
652      local value = input.value or ''
653      list_extend(contents, split_lines(value, true))
654      -- MarkupString variation 2
655    elseif input.language then
656      table.insert(contents, '```' .. input.language)
657      list_extend(contents, split_lines(input.value or ''))
658      table.insert(contents, '```')
659      -- By deduction, this must be MarkedString[]
660    else
661      -- Use our existing logic to handle MarkedString
662      for _, marked_string in ipairs(input) do
663        M.convert_input_to_markdown_lines(marked_string, contents)
664      end
665    end
666  end
667  if (contents[1] == '' or contents[1] == nil) and #contents == 1 then
668    return {}
669  end
670  return contents
671end
672
673--- Returns the line/column-based position in `contents` at the given offset.
674---
675---@param offset integer
676---@param contents string[]
677---@return { [1]: integer, [2]: integer }?
678local function get_pos_from_offset(offset, contents)
679  local i = 0
680  for l, line in ipairs(contents) do
681    if offset >= i and offset < i + #line then
682      return { l - 1, offset - i + 1 }
683    else
684      i = i + #line + 1
685    end
686  end
687end
688
689--- Converts `textDocument/signatureHelp` response to markdown lines.
690---
691---@param signature_help lsp.SignatureHelp Response of `textDocument/SignatureHelp`
692---@param ft string? filetype that will be use as the `lang` for the label markdown code block
693---@param triggers string[]? list of trigger characters from the lsp server. used to better determine parameter offsets
694---@return string[]? # lines of converted markdown.
695---@return Range4? # highlight range for the active parameter
696---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp
697function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers)
698  --The active signature. If omitted or the value lies outside the range of
699  --`signatures` the value defaults to zero or is ignored if `signatures.length == 0`.
700  --Whenever possible implementors should make an active decision about
701  --the active signature and shouldn't rely on a default value.
702  local contents = {} --- @type string[]
703  local active_offset ---@type [integer, integer]?
704  local active_signature = signature_help.activeSignature or 0
705  -- If the activeSignature is not inside the valid range, then clip it.
706  -- In 3.15 of the protocol, activeSignature was allowed to be negative
707  if active_signature >= #signature_help.signatures or active_signature < 0 then
708    active_signature = 0
709  end
710  local signature = signature_help.signatures[active_signature + 1]
711  if not signature then
712    return
713  end
714  signature = vim.deepcopy(signature)
715  local label = signature.label
716  if ft then
717    -- wrap inside a code block for proper rendering
718    label = ('```%s\n%s\n```'):format(ft, label)
719  end
720  list_extend(contents, vim.split(label, '\n', { plain = true, trimempty = true }))
721  local doc = signature.documentation
722  if doc then
723    -- if LSP returns plain string, we treat it as plaintext. This avoids
724    -- special characters like underscore or similar from being interpreted
725    -- as markdown font modifiers
726    if type(doc) == 'string' then
727      doc = { kind = 'plaintext', value = doc }
728    end
729    -- Add delimiter if there is documentation to display
730    if doc.value ~= '' then
731      contents[#contents + 1] = '---'
732    end
733    M.convert_input_to_markdown_lines(doc, contents)
734  end
735  if signature.parameters and #signature.parameters > 0 then
736    local active_parameter = signature.activeParameter or signature_help.activeParameter
737
738    -- NOTE: We intentionally violate the LSP spec, which states that if `activeParameter`
739    -- is not provided or is out-of-bounds, it should default to 0.
740    -- Instead, we default to `nil`, as most clients do. In practice, 'no active parameter'
741    -- is better default than 'first parameter' and aligns better with user expectations.
742    -- Related discussion: https://github.com/microsoft/language-server-protocol/issues/1271
743    if
744      not active_parameter
745      or active_parameter == vim.NIL
746      or active_parameter < 0
747      or active_parameter >= #signature.parameters
748    then
749      return contents, nil
750    end
751
752    -- The active parameter was checked against the bounds of this array above.
753    local parameter = assert(signature.parameters[active_parameter + 1])
754    local parameter_label = parameter.label
755    if type(parameter_label) == 'table' then
756      active_offset = parameter_label
757    else
758      local offset = 1 ---@type integer?
759      -- try to set the initial offset to the first found trigger character
760      for _, t in ipairs(triggers or {}) do
761        local trigger_offset = signature.label:find(t, 1, true)
762        if trigger_offset and (offset == 1 or trigger_offset < offset) then
763          offset = trigger_offset
764        end
765      end
766      for p, param in pairs(signature.parameters) do
767        local plabel = param.label
768        assert(type(plabel) == 'string', 'Expected label to be a string')
769        offset = signature.label:find(plabel, offset, true)
770        if not offset then
771          break
772        end
773        if p == active_parameter + 1 then
774          active_offset = { offset - 1, offset + #parameter_label - 1 }
775          break
776        end
777        offset = offset + #plabel + 1
778      end
779    end
780    if parameter.documentation then
781      M.convert_input_to_markdown_lines(parameter.documentation, contents)
782    end
783  end
784
785  local active_hl = nil
786  if active_offset then
787    -- Treat LSP's uinteger offsets as integers for arithmetic.
788    --- @cast active_offset [integer, integer]
789    -- Account for the start of the markdown block.
790    if ft then
791      active_offset[1] = active_offset[1] + #contents[1]
792      active_offset[2] = active_offset[2] + #contents[1]
793    end
794
795    local a_start = get_pos_from_offset(active_offset[1], contents)
796    local a_end = get_pos_from_offset(active_offset[2], contents)
797    if a_start and a_end then
798      active_hl = { a_start[1], a_start[2], a_end[1], a_end[2] }
799    end
800  end
801
802  return contents, active_hl
803end
804
805--- Creates a table with sensible default options for a floating window. The
806--- table can be passed to |nvim_open_win()|.
807---
808---@param width integer window width (in character cells)
809---@param height integer window height (in character cells)
810---@param opts? vim.lsp.util.open_floating_preview.Opts
811---@return vim.api.keyset.win_config
812function M.make_floating_popup_options(width, height, opts)
813  validate('opts', opts, 'table', true)
814  opts = opts or {}
815  validate('opts.offset_x', opts.offset_x, 'number', true)
816  validate('opts.offset_y', opts.offset_y, 'number', true)
817
818  local lines_above = vim.fn.winline() - 1
819  local lines_below = vim.fn.winheight(0) - lines_above
820  if opts.relative == 'mouse' then
821    lines_above = vim.fn.getmousepos().line - 1
822    lines_below = vim.fn.winheight(0) - lines_above
823  elseif opts.relative == 'editor' then
824    -- No cursor to anchor against; treat the whole editor as space below.
825    lines_above = 0
826    lines_below = vim.o.lines
827  end
828
829  local anchor_bias = opts.anchor_bias or 'auto'
830
831  local anchor_below --- @type boolean?
832
833  if anchor_bias == 'below' then
834    anchor_below = (lines_below > lines_above) or (height <= lines_below)
835  elseif anchor_bias == 'above' then
836    local anchor_above = (lines_above > lines_below) or (height <= lines_above)
837    anchor_below = not anchor_above
838  else
839    anchor_below = lines_below > lines_above
840  end
841
842  local border_height = get_border_size(opts)
843  local row, col --- @type integer?, integer?
844  if anchor_below then
845    height = math.max(math.min(lines_below - border_height, height), 0)
846    row = 1
847  else
848    height = math.max(math.min(lines_above - border_height, height), 0)
849    row = 0
850  end
851
852  local wincol = vim.fn.wincol()
853  if opts.relative == 'mouse' then
854    wincol = vim.fn.getmousepos().column
855  elseif opts.relative == 'editor' then
856    wincol = 0
857  end
858
859  local anchor --- @type 'NW'|'NE'|'SW'|'SE'
860  if wincol + width + (opts.offset_x or 0) <= vim.o.columns then
861    anchor = anchor_below and 'NW' or 'SW'
862    col = 0
863  else
864    anchor = anchor_below and 'NE' or 'SE'
865    col = 1
866  end
867
868  local title = ((opts.border or vim.o.winborder ~= '') and opts.title) and opts.title or nil
869  local title_pos --- @type 'left'|'center'|'right'?
870
871  if title then
872    title_pos = opts.title_pos or 'center'
873  end
874
875  return {
876    anchor = anchor,
877    row = row + (opts.offset_y or 0),
878    col = col + (opts.offset_x or 0),
879    height = height,
880    focusable = opts.focusable,
881    relative = (opts.relative == 'mouse' or opts.relative == 'editor') and opts.relative
882      or 'cursor',
883    style = 'minimal',
884    width = width,
885    border = opts.border,
886    zindex = opts.zindex or (api.nvim_win_get_config(0).zindex or 49) + 1,
887    title = title,
888    title_pos = title_pos,
889  }
890end
891
892--- @class vim.lsp.util.show_document.Opts
893--- @inlinedoc
894---
895--- Jump to existing window if buffer is already open.
896--- @field reuse_win? boolean
897---
898--- Whether to focus/jump to location if possible.
899--- (defaults: true)
900--- @field focus? boolean
901
902--- Shows document and optionally jumps to the location.
903---
904---@param location lsp.Location|lsp.LocationLink
905---@param position_encoding 'utf-8'|'utf-16'|'utf-32'
906---@param opts? vim.lsp.util.show_document.Opts
907---@return boolean `true` if succeeded
908function M.show_document(location, position_encoding, opts)
909  validate('position_encoding', position_encoding, 'string')
910
911  -- location may be Location or LocationLink
912  local uri = location.uri or location.targetUri
913  if uri == nil then
914    return false
915  end
916  local range = location.range or location.targetSelectionRange
917  return M._show_document(uri, range, position_encoding, opts)
918end
919
920--- Shows a document, preserving its cursor position when no range is given.
921--- @private
922--- @param uri string
923--- @param range lsp.Range?
924--- @param position_encoding 'utf-8'|'utf-16'|'utf-32'
925--- @param opts? vim.lsp.util.show_document.Opts
926--- @return boolean
927function M._show_document(uri, range, position_encoding, opts)
928  local bufnr = vim.uri_to_bufnr(uri)
929
930  -- Return early if the buffer fails to load, to avoid partial setup.
931  local loaded, err = pcall(vim.fn.bufload, bufnr)
932  if not loaded then
933    vim.notify(tostring(err), vim.log.levels.ERROR)
934    return false
935  end
936
937  opts = opts or {}
938  local focus = vim.nonnil(opts.focus, true)
939  if focus then
940    -- Save position in jumplist
941    vim.cmd("normal! m'")
942
943    -- Push a new item into tagstack
944    local from = { vim.fn.bufnr('%'), vim.fn.line('.'), vim.fn.col('.'), 0 }
945    local items = { { tagname = vim.fn.expand('<cword>'), from = from } }
946    vim.fn.settagstack(vim.fn.win_getid(), { items = items }, 't')
947  end
948
949  local win = opts.reuse_win and vim.fn.win_findbuf(bufnr)[1]
950    or focus and api.nvim_get_current_win()
951    or create_window_without_focus()
952
953  vim.bo[bufnr].buflisted = true
954  api.nvim_win_set_buf(win, bufnr)
955  if focus then
956    api.nvim_set_current_win(win)
957  end
958
959  if range then
960    -- Jump to new location (adjusting for encoding of characters)
961    local pos = vim.pos.lsp(bufnr, range.start, position_encoding)
962    local row, col = pos.row, pos.col
963    api.nvim_win_set_cursor(win, { row + 1, col })
964    vim._with({ win = win }, function()
965      -- Open folds under the cursor
966      vim.cmd('normal! zv')
967    end)
968
969    -- nvim_win_set_cursor clamps to last char at EOL. In insert mode the cursor
970    -- should be past the last char (append position).
971    if api.nvim_get_mode().mode == 'i' then
972      local line = api.nvim_buf_get_lines(bufnr, row, row + 1, false)[1] or ''
973      if col >= #line then
974        api.nvim_feedkeys(vim.keycode('<End>'), 'n', false)
975      end
976    end
977  end
978
979  return true
980end
981
982--- Previews a location in a floating window
983---
984--- behavior depends on type of location:
985---   - for Location, range is shown (e.g., function definition)
986---   - for LocationLink, targetRange is shown (e.g., body of function definition)
987---
988---@param location lsp.Location|lsp.LocationLink
989---@param opts? vim.lsp.util.open_floating_preview.Opts
990---@return integer? buffer id of float window
991---@return integer? window id of float window
992function M.preview_location(location, opts)
993  -- location may be LocationLink or Location (more useful for the former)
994  local uri = location.targetUri or location.uri
995  if uri == nil then
996    return
997  end
998  local bufnr = vim.uri_to_bufnr(uri)
999  if not api.nvim_buf_is_loaded(bufnr) then
1000    vim.fn.bufload(bufnr)
1001  end
1002  local range = location.targetRange or location.range
1003  local contents = api.nvim_buf_get_lines(bufnr, range.start.line, range['end'].line + 1, false)
1004  local syntax = vim.bo[bufnr].syntax
1005  if syntax == '' then
1006    -- When no syntax is set, we use filetype as fallback. This might not result
1007    -- in a valid syntax definition.
1008    -- An empty syntax is more common now with TreeSitter, since TS disables syntax.
1009    syntax = vim.bo[bufnr].filetype
1010  end
1011  opts = opts or {}
1012  opts.focus_id = 'location'
1013  return M.open_floating_preview(contents, syntax, opts)
1014end
1015
1016--- @param name string
1017--- @param value any
1018local function find_window_by_var(name, value)
1019  for _, win in ipairs(api.nvim_list_wins()) do
1020    if vim.w[win][name] == value then
1021      return win
1022    end
1023  end
1024end
1025
1026---@param winnr integer
1027---@return boolean `true` if `winnr` is a valid floating window
1028local function is_float(winnr)
1029  return api.nvim_win_is_valid(winnr) and vim.fn.win_gettype(winnr) == 'popup'
1030end
1031
1032---Returns true if the line is empty or only contains whitespace.
1033---@param line string?
1034---@return boolean
1035local function is_blank_line(line)
1036  return line ~= nil and line:match('^%s*$') ~= nil
1037end
1038
1039---Returns true if the line corresponds to a Markdown thematic break.
1040---@see https://github.github.com/gfm/#thematic-break
1041---@param line string
1042---@return boolean
1043local function is_separator_line(line)
1044  local i = 1
1045  -- 1. Skip up to 3 leading spaces
1046  local leading_spaces = 3
1047  while i <= #line and line:byte(i) == string.byte(' ') and leading_spaces > 0 do
1048    i = i + 1
1049    leading_spaces = leading_spaces - 1
1050  end
1051  -- 2. Determine the delimiter character
1052  local delimiter = line:byte(i) -- nil if i > #line
1053  if
1054    delimiter ~= string.byte('-')
1055    and delimiter ~= string.byte('_')
1056    and delimiter ~= string.byte('*')
1057  then
1058    return false
1059  end
1060  local ndelimiters = 1
1061  i = i + 1
1062  -- 3. Iterate until found non-whitespace or other than expected delimiter
1063  while i <= #line do
1064    local char = line:byte(i)
1065    if char == delimiter then
1066      ndelimiters = ndelimiters + 1
1067    elseif not (char == string.byte(' ') or char == string.byte('\t')) then
1068      return false
1069    end
1070    i = i + 1
1071  end
1072  return ndelimiters >= 3
1073end
1074
1075---Replaces separator lines by the given divider and removing surrounding blank lines.
1076---@param contents string[]
1077---@param divider string
1078---@return string[]
1079local function replace_separators(contents, divider)
1080  local trimmed = {}
1081  local l = 1
1082  while l <= #contents do
1083    local line = assert(contents[l])
1084    if is_separator_line(line) then
1085      if l > 1 and is_blank_line(contents[l - 1]) then
1086        table.remove(trimmed)
1087      end
1088      table.insert(trimmed, divider)
1089      if is_blank_line(contents[l + 1]) then
1090        l = l + 1
1091      end
1092    else
1093      table.insert(trimmed, line)
1094    end
1095    l = l + 1
1096  end
1097
1098  return trimmed
1099end
1100
1101---Collapses successive blank lines in the input table into a single one.
1102---@param contents string[]
1103---@return string[]
1104local function collapse_blank_lines(contents)
1105  local collapsed = {}
1106  local l = 1
1107  while l <= #contents do
1108    local line = contents[l]
1109    if is_blank_line(line) then
1110      while is_blank_line(contents[l + 1]) do
1111        l = l + 1
1112      end
1113    end
1114    table.insert(collapsed, line)
1115    l = l + 1
1116  end
1117  return collapsed
1118end
1119
1120local function get_markdown_fences()
1121  local fences = {} --- @type table<string,string>
1122  for _, fence in
1123    pairs(vim.g.markdown_fenced_languages or {} --[[@as string[] ]])
1124  do
1125    local lang, syntax = fence:match('^(.*)=(.*)$')
1126    if lang then
1127      fences[lang] = syntax
1128    end
1129  end
1130  return fences
1131end
1132
1133--- @deprecated
1134--- Converts markdown into syntax highlighted regions by stripping the code
1135--- blocks and converting them into highlighted code.
1136--- This will by default insert a blank line separator after those code block
1137--- regions to improve readability.
1138---
1139--- This method configures the given buffer and returns the lines to set.
1140---
1141--- If you want to open a popup with fancy markdown, use `open_floating_preview` instead
1142---
1143---@param bufnr integer
1144---@param contents string[] of lines to show in window
1145---@param opts? table with optional fields
1146---  - height    of floating window
1147---  - max_height maximal height of floating window
1148---  - max_width  maximal width of floating window
1149---  - separator insert separator after code block
1150---  - width     of floating window
1151---  - wrap_at   character to wrap at for computing height
1152---@return table stripped content
1153function M.stylize_markdown(bufnr, contents, opts)
1154  vim.deprecate('vim.lsp.util.stylize_markdown', nil, '0.14')
1155  validate('contents', contents, 'table')
1156  validate('opts', opts, 'table', true)
1157  opts = opts or {}
1158
1159  -- table of fence types to {ft, begin, end}
1160  -- when ft is nil, we get the ft from the regex match
1161  local matchers = {
1162    block = { nil, '```+%s*([a-zA-Z0-9_]*)', '```+' },
1163    pre = { nil, '<pre>([a-z0-9]*)', '</pre>' },
1164    code = { '', '<code>', '</code>' },
1165    text = { 'text', '<text>', '</text>' },
1166  }
1167
1168  --- @param line string
1169  --- @return {pattern:string,ft:string}?
1170  local function match_begin(line)
1171    for _, pattern in pairs(matchers) do
1172      --- @type string?
1173      local ret = line:match(string.format('^%%s*%s%%s*$', pattern[2]))
1174      if ret then
1175        return {
1176          pattern = pattern[3],
1177          ft = pattern[1] or ret,
1178        }
1179      end
1180    end
1181  end
1182
1183  --- @param line string
1184  --- @param match {pattern:string,ft:string}
1185  --- @return string?
1186  local function match_end(line, match)
1187    return line:match(string.format('^%%s*%s%%s*$', match.pattern))
1188  end
1189
1190  -- Clean up
1191  contents = vim.split(table.concat(contents, '\n'), '\n', { trimempty = true })
1192
1193  local stripped = {} --- @type string[]
1194  local highlights = {} --- @type {ft:string,start:integer,finish:integer}[]
1195
1196  local i = 1
1197  while i <= #contents do
1198    local line = assert(contents[i])
1199    local match = match_begin(line)
1200    if match then
1201      local start = #stripped
1202      i = i + 1
1203      while i <= #contents do
1204        line = assert(contents[i])
1205        if match_end(line, match) then
1206          i = i + 1
1207          break
1208        end
1209        stripped[#stripped + 1] = line
1210        i = i + 1
1211      end
1212      table.insert(highlights, {
1213        ft = match.ft,
1214        start = start + 1,
1215        finish = #stripped,
1216      })
1217      -- add a separator, but not on the last line
1218      if opts.separator and i < #contents then
1219        stripped[#stripped + 1] = '---'
1220      end
1221    else
1222      -- strip any empty lines or separators prior to this separator in actual markdown
1223      if line:match('^---+$') then
1224        while
1225          stripped[#stripped]
1226          and (stripped[#stripped]:match('^%s*$') or stripped[#stripped]:match('^---+$'))
1227        do
1228          stripped[#stripped] = nil
1229        end
1230      end
1231      -- add the line if its not an empty line following a separator
1232      if
1233        not (line:match('^%s*$') and stripped[#stripped] and stripped[#stripped]:match('^---+$'))
1234      then
1235        stripped[#stripped + 1] = line
1236      end
1237      i = i + 1
1238    end
1239  end
1240
1241  -- Handle some common html escape sequences
1242  --- @type string[]
1243  stripped = vim.tbl_map(
1244    --- @param line string
1245    function(line)
1246      local escapes = {
1247        ['&gt;'] = '>',
1248        ['&lt;'] = '<',
1249        ['&quot;'] = '"',
1250        ['&apos;'] = "'",
1251        ['&ensp;'] = ' ',
1252        ['&emsp;'] = ' ',
1253        ['&amp;'] = '&',
1254      }
1255      return (line:gsub('&[^ ;]+;', escapes))
1256    end,
1257    stripped
1258  )
1259
1260  -- Compute size of float needed to show (wrapped) lines
1261  opts.wrap_at = opts.wrap_at or (vim.wo['wrap'] and api.nvim_win_get_width(0))
1262  local width = M._make_floating_popup_size(stripped, opts)
1263
1264  local sep_line = string.rep('─', math.min(width, opts.wrap_at or width))
1265
1266  for l, line in ipairs(stripped) do
1267    if line:match('^---+$') then
1268      stripped[l] = sep_line
1269    end
1270  end
1271
1272  api.nvim_buf_set_lines(bufnr, 0, -1, false, stripped)
1273
1274  local idx = 1
1275  -- keep track of syntaxes we already included.
1276  -- no need to include the same syntax more than once
1277  local langs = {} --- @type table<string,boolean>
1278  local fences = get_markdown_fences()
1279  --- @param ft string
1280  --- @param start integer
1281  --- @param finish integer
1282  local function apply_syntax_to_region(ft, start, finish)
1283    if ft == '' then
1284      vim.cmd(
1285        string.format(
1286          'syntax region markdownCode start=+\\%%%dl+ end=+\\%%%dl+ keepend extend',
1287          start,
1288          finish + 1
1289        )
1290      )
1291      return
1292    end
1293    ft = fences[ft] or ft
1294    local name = ft .. idx
1295    idx = idx + 1
1296    local lang = '@' .. ft:upper()
1297    if not langs[lang] then
1298      -- HACK: reset current_syntax, since some syntax files like markdown won't load if it is already set
1299      pcall(api.nvim_buf_del_var, bufnr, 'current_syntax')
1300      if #api.nvim_get_runtime_file(('syntax/%s.vim'):format(ft), true) == 0 then
1301        return
1302      end
1303      --- @diagnostic disable-next-line:param-type-mismatch
1304      pcall(vim.cmd, string.format('syntax include %s syntax/%s.vim', lang, ft))
1305      langs[lang] = true
1306    end
1307    vim.cmd(
1308      string.format(
1309        'syntax region %s start=+\\%%%dl+ end=+\\%%%dl+ contains=%s keepend',
1310        name,
1311        start,
1312        finish + 1,
1313        lang
1314      )
1315    )
1316  end
1317
1318  -- needs to run in the buffer for the regions to work
1319  vim._with({ buf = bufnr }, function()
1320    -- we need to apply lsp_markdown regions speperately, since otherwise
1321    -- markdown regions can "bleed" through the other syntax regions
1322    -- and mess up the formatting
1323    local last = 1
1324    for _, h in ipairs(highlights) do
1325      if last < h.start then
1326        apply_syntax_to_region('lsp_markdown', last, h.start - 1)
1327      end
1328      apply_syntax_to_region(h.ft, h.start, h.finish)
1329      last = h.finish + 1
1330    end
1331    if last <= #stripped then
1332      apply_syntax_to_region('lsp_markdown', last, #stripped)
1333    end
1334  end)
1335
1336  return stripped
1337end
1338
1339--- @class (private) vim.lsp.util._normalize_markdown.Opts
1340--- @field width? integer Thematic breaks are expanded to this size. Defaults to 80.
1341
1342--- Normalizes Markdown input to a canonical form.
1343---
1344--- The returned Markdown adheres to the GitHub Flavored Markdown (GFM)
1345--- specification, as required by the LSP.
1346---
1347--- The following transformations are made:
1348---
1349---   1. Carriage returns ('\r') and empty lines at the beginning and end are removed
1350---   2. Successive empty lines are collapsed into a single empty line
1351---   3. Thematic breaks are expanded to the given width
1352---
1353---@param contents string[]
1354---@param opts? vim.lsp.util._normalize_markdown.Opts
1355---@return string[] table of lines containing normalized Markdown
1356---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#markupContent
1357---@see https://github.github.com/gfm
1358function M._normalize_markdown(contents, opts)
1359  validate('contents', contents, 'table')
1360  validate('opts', opts, 'table', true)
1361  opts = opts or {}
1362
1363  -- 1. Carriage returns are removed
1364  contents = vim.split(table.concat(contents, '\n'):gsub('\r', ''), '\n', { trimempty = true })
1365
1366  -- 2. Successive empty lines are collapsed into a single empty line
1367  contents = collapse_blank_lines(contents)
1368
1369  -- 3. Thematic breaks are expanded to the given width
1370  local divider = string.rep('─', opts.width or 80)
1371  contents = replace_separators(contents, divider)
1372
1373  return contents
1374end
1375
1376--- Closes the preview window
1377---
1378---@param winnr integer window id of preview window
1379---@param bufnrs table? optional list of ignored buffers
1380local function close_preview_window(winnr, bufnrs)
1381  vim.schedule(function()
1382    -- exit if we are in one of ignored buffers
1383    if bufnrs and vim.list_contains(bufnrs, api.nvim_get_current_buf()) then
1384      return
1385    end
1386
1387    local augroup = 'nvim.preview_window_' .. winnr
1388    pcall(api.nvim_del_augroup_by_name, augroup)
1389
1390    -- Preview window was converted to a normal window (e.g. |CTRL-W_H|):
1391    -- keep it open and stop managing it.
1392    if api.nvim_win_is_valid(winnr) and not is_float(winnr) then
1393      local srcbuf = vim.w[winnr].lsp_floating_bufnr
1394      if
1395        srcbuf
1396        and api.nvim_buf_is_valid(srcbuf)
1397        and vim.b[srcbuf].lsp_floating_preview == winnr
1398      then
1399        vim.b[srcbuf].lsp_floating_preview = nil
1400      end
1401      return
1402    end
1403
1404    pcall(api.nvim_win_close, winnr, true)
1405  end)
1406end
1407
1408--- Creates autocommands to close a preview window when events happen.
1409---
1410---@param events table list of events
1411---@param winnr integer window id of preview window
1412---@param floating_bufnr integer floating preview buffer
1413---@param bufnr integer buffer that opened the floating preview buffer
1414---@see autocmd-events
1415local function close_preview_autocmd(events, winnr, floating_bufnr, bufnr)
1416  local augroup = api.nvim_create_augroup('nvim.preview_window_' .. winnr, {
1417    clear = true,
1418  })
1419
1420  -- close the preview window when entered a buffer that is not
1421  -- the floating window buffer or the buffer that spawned it
1422  nvim_on('BufLeave', augroup, { buf = bufnr }, function()
1423    vim.schedule(function()
1424      -- When jumping to the quickfix window from the preview window,
1425      -- do not close the preview window.
1426      if api.nvim_get_option_value('filetype', { buf = 0 }) ~= 'qf' then
1427        close_preview_window(winnr, { floating_bufnr, bufnr })
1428      end
1429    end)
1430  end)
1431
1432  if #events > 0 then
1433    nvim_on(events, augroup, { buf = bufnr }, function()
1434      close_preview_window(winnr)
1435    end)
1436  end
1437end
1438
1439--- Computes size of float needed to show contents (with optional wrapping)
1440---
1441---@param contents string[] of lines to show in window
1442---@param opts? vim.lsp.util.open_floating_preview.Opts
1443---@return integer width size of float
1444---@return integer height size of float
1445function M._make_floating_popup_size(contents, opts)
1446  validate('contents', contents, 'table')
1447  validate('opts', opts, 'table', true)
1448  opts = opts or {}
1449
1450  local width = opts.width
1451  local height = opts.height
1452  local wrap_at = opts.wrap_at
1453  local max_width = opts.max_width
1454  local max_height = opts.max_height
1455  local line_widths = {} --- @type table<integer,integer>
1456
1457  if not width then
1458    width = 0
1459    for i, line in ipairs(contents) do
1460      -- TODO(ashkan) use nvim_strdisplaywidth if/when that is introduced.
1461      line_widths[i] = vim.fn.strdisplaywidth(line:gsub('%z', '\n'))
1462      width = math.max(line_widths[i], width)
1463    end
1464  end
1465
1466  local _, border_width = get_border_size(opts)
1467  local screen_width = opts.relative == 'editor' and vim.o.columns or api.nvim_win_get_width(0)
1468  width = math.min(width, screen_width)
1469
1470  -- make sure borders are always inside the screen
1471  width = math.min(width, screen_width - border_width)
1472
1473  -- Make sure that the width is large enough to fit the title.
1474  local title_length = 0
1475  local chunks = type(opts.title) == 'string' and { { opts.title } } or opts.title or {}
1476  for _, chunk in
1477    ipairs(chunks --[=[@as [string, string][] ]=])
1478  do
1479    title_length = title_length + vim.fn.strdisplaywidth(chunk[1])
1480  end
1481
1482  width = math.max(width, title_length)
1483
1484  if wrap_at then
1485    wrap_at = math.min(wrap_at, width)
1486  end
1487
1488  if max_width then
1489    width = math.min(width, max_width)
1490    wrap_at = math.min(wrap_at or max_width, max_width)
1491  end
1492
1493  if not height then
1494    height = #contents
1495    if wrap_at and width >= wrap_at then
1496      height = 0
1497      if vim.tbl_isempty(line_widths) then
1498        for _, line in ipairs(contents) do
1499          local line_width = vim.fn.strdisplaywidth(line:gsub('%z', '\n'))
1500          height = height + math.max(1, math.ceil(line_width / wrap_at))
1501        end
1502      else
1503        for i = 1, #contents do
1504          height = height + math.max(1, math.ceil(line_widths[i] / wrap_at))
1505        end
1506      end
1507    end
1508  end
1509  if max_height then
1510    height = math.min(height, max_height)
1511  end
1512
1513  return width, height
1514end
1515
1516--- @class vim.lsp.util.open_floating_preview.Opts
1517---
1518--- Height of floating window
1519--- @field height? integer
1520---
1521--- Width of floating window
1522--- @field width? integer
1523---
1524--- Wrap long lines
1525--- (default: `true`)
1526--- @field wrap? boolean
1527---
1528--- Character to wrap at for computing height when wrap is enabled
1529--- @field wrap_at? integer
1530---
1531--- Maximal width of floating window
1532--- @field max_width? integer
1533---
1534--- Maximal height of floating window
1535--- @field max_height? integer
1536---
1537--- If a popup with this id is opened, then focus it
1538--- @field focus_id? string
1539---
1540--- List of events that closes the floating window
1541--- @field close_events? table
1542---
1543--- Make float focusable.
1544--- (default: `true`)
1545--- @field focusable? boolean
1546---
1547--- If `true`, and if {focusable} is also `true`, focus an existing floating
1548--- window with the same {focus_id}
1549--- (default: `true`)
1550--- @field focus? boolean
1551---
1552--- offset to add to `col`
1553--- @field offset_x? integer
1554---
1555--- offset to add to `row`
1556--- @field offset_y? integer
1557--- @field border? ''|'none'|'single'|'double'|'rounded'|'solid'|'shadow'|'bold'|(string|[string,string])[] override `border`
1558--- @field zindex? integer override `zindex`, defaults to 50
1559--- @field title? string|[string,string][]
1560--- @field title_pos? 'left'|'center'|'right'
1561---
1562--- (default: `'cursor'`)
1563--- @field relative? 'mouse'|'cursor'|'editor'
1564---
1565--- Adjusts placement relative to cursor.
1566--- - "auto": place window based on which side of the cursor has more lines
1567--- - "above": place the window above the cursor unless there are not enough lines
1568---   to display the full window height.
1569--- - "below": place the window below the cursor unless there are not enough lines
1570---   to display the full window height.
1571--- (default: `'auto'`)
1572--- @field anchor_bias? 'auto'|'above'|'below'
1573---
1574--- @field _update_win? integer
1575
1576--- Shows contents in a floating window.
1577---
1578---@param contents table of lines to show in window
1579---@param syntax string of syntax to set for opened buffer
1580---@param opts? vim.lsp.util.open_floating_preview.Opts with optional fields
1581--- (additional keys are filtered with |vim.lsp.util.make_floating_popup_options()|
1582--- before they are passed on to |nvim_open_win()|)
1583---@return integer bufnr of newly created float window
1584---@return integer winid of newly created float window preview window
1585function M.open_floating_preview(contents, syntax, opts)
1586  validate('contents', contents, 'table')
1587  validate('syntax', syntax, 'string', true)
1588  validate('opts', opts, 'table', true)
1589  opts = opts or {}
1590  opts.wrap = opts.wrap ~= false -- wrapping by default
1591  opts.focus = opts.focus ~= false
1592  opts.close_events = opts.close_events or { 'CursorMoved', 'CursorMovedI', 'InsertCharPre' }
1593
1594  local bufnr = api.nvim_get_current_buf()
1595
1596  local floating_winnr = opts._update_win
1597
1598  -- Create/get the buffer
1599  local floating_bufnr --- @type integer
1600  if floating_winnr then
1601    floating_bufnr = api.nvim_win_get_buf(floating_winnr)
1602  else
1603    -- check if this popup is focusable and we need to focus
1604    if opts.focus_id and opts.focusable ~= false and opts.focus then
1605      -- Go back to previous window if we are in a focusable one
1606      local current_winnr = api.nvim_get_current_win()
1607      if vim.w[current_winnr][opts.focus_id] and is_float(current_winnr) then
1608        api.nvim_command('wincmd p')
1609        return bufnr, current_winnr
1610      end
1611      do
1612        local win = find_window_by_var(opts.focus_id, bufnr)
1613        if win and is_float(win) and vim.fn.pumvisible() == 0 then
1614          -- focus and return the existing buf, win
1615          api.nvim_set_current_win(win)
1616          api.nvim_command('stopinsert')
1617          return api.nvim_win_get_buf(win), win
1618        end
1619      end
1620    end
1621
1622    -- check if another floating preview already exists for this buffer
1623    -- and close it if needed
1624    local existing_float = vim.b[bufnr].lsp_floating_preview
1625    if existing_float and is_float(existing_float) then
1626      api.nvim_win_close(existing_float, true)
1627    end
1628    floating_bufnr = api.nvim_create_buf(false, true)
1629  end
1630
1631  -- Set up the contents, using treesitter for markdown
1632  local do_stylize = syntax == 'markdown' and vim.g.syntax_on ~= nil
1633
1634  if do_stylize then
1635    local width = M._make_floating_popup_size(contents, opts)
1636    contents = M._normalize_markdown(contents, { width = width })
1637  else
1638    -- Clean up input: trim empty lines
1639    contents = vim.split(table.concat(contents, '\n'), '\n', { trimempty = true })
1640
1641    if syntax then
1642      vim.bo[floating_bufnr].syntax = syntax
1643    end
1644  end
1645
1646  vim.bo[floating_bufnr].modifiable = true
1647  api.nvim_buf_set_lines(floating_bufnr, 0, -1, false, contents)
1648
1649  if floating_winnr then
1650    api.nvim_win_set_config(floating_winnr, {
1651      border = opts.border,
1652      title = opts.title,
1653    })
1654  else
1655    -- Compute size of float needed to show (wrapped) lines
1656    if opts.wrap then
1657      opts.wrap_at = opts.wrap_at or api.nvim_win_get_width(0)
1658    else
1659      opts.wrap_at = nil
1660    end
1661
1662    -- TODO(lewis6991): These function assume the current window to determine options,
1663    -- therefore it won't work for opts._update_win and the current window if the floating
1664    -- window
1665    local width, height = M._make_floating_popup_size(contents, opts)
1666    local float_option = M.make_floating_popup_options(width, height, opts)
1667
1668    floating_winnr = api.nvim_open_win(floating_bufnr, false, float_option)
1669
1670    api.nvim_buf_set_keymap(
1671      floating_bufnr,
1672      'n',
1673      'q',
1674      '<cmd>bdelete<cr>',
1675      { silent = true, noremap = true, nowait = true }
1676    )
1677    close_preview_autocmd(opts.close_events, floating_winnr, floating_bufnr, bufnr)
1678
1679    -- save focus_id
1680    if opts.focus_id then
1681      api.nvim_win_set_var(floating_winnr, opts.focus_id, bufnr)
1682    end
1683    api.nvim_buf_set_var(bufnr, 'lsp_floating_preview', floating_winnr)
1684    api.nvim_win_set_var(floating_winnr, 'lsp_floating_bufnr', bufnr)
1685  end
1686
1687  nvim_on(
1688    'WinClosed',
1689    api.nvim_create_augroup('nvim.closing_floating_preview', { clear = true }),
1690    function(args)
1691      local winid = vim._assert_integer(args.match)
1692      local preview_bufnr = vim.w[winid].lsp_floating_bufnr --- @type integer?
1693      if
1694        preview_bufnr
1695        and api.nvim_buf_is_valid(preview_bufnr)
1696        and winid == vim.b[preview_bufnr].lsp_floating_preview
1697      then
1698        vim.b[bufnr].lsp_floating_preview = nil
1699        return true
1700      end
1701    end
1702  )
1703
1704  vim.wo[floating_winnr].foldenable = false -- Disable folding.
1705  vim.wo[floating_winnr].wrap = opts.wrap -- Soft wrapping.
1706  vim.wo[floating_winnr].linebreak = true -- Break lines a bit nicer
1707  vim.wo[floating_winnr].breakindent = true -- Slightly better list presentation.
1708  vim.wo[floating_winnr].smoothscroll = true -- Scroll by screen-line instead of buffer-line.
1709  vim.wo[floating_winnr].winfixbuf = true -- Disable buffer switching.
1710
1711  vim.bo[floating_bufnr].modifiable = false
1712  vim.bo[floating_bufnr].bufhidden = 'wipe'
1713
1714  if do_stylize then
1715    vim.wo[floating_winnr].conceallevel = 2
1716    vim.wo[floating_winnr].concealcursor = ''
1717    vim.bo[floating_bufnr].filetype = 'markdown'
1718    vim.treesitter.start(floating_bufnr)
1719    if not opts.height then
1720      -- Reduce window height if TS highlighter conceals code block backticks.
1721      local win_height = api.nvim_win_get_height(floating_winnr)
1722      local text_height = api.nvim_win_text_height(floating_winnr, { max_height = win_height }).all
1723      if text_height < win_height then
1724        api.nvim_win_resize(floating_winnr, -1, text_height)
1725      end
1726    end
1727  end
1728
1729  return floating_bufnr, floating_winnr
1730end
1731
1732do --[[ References ]]
1733  local reference_ns = api.nvim_create_namespace('nvim.lsp.references')
1734
1735  --- Removes document highlights from a buffer.
1736  ---
1737  ---@param bufnr integer? Buffer id
1738  function M.buf_clear_references(bufnr)
1739    api.nvim_buf_clear_namespace(bufnr or 0, reference_ns, 0, -1)
1740  end
1741
1742  --- Shows a list of document highlights for a certain buffer.
1743  ---
1744  ---@param bufnr integer Buffer id
1745  ---@param references lsp.DocumentHighlight[] objects to highlight
1746  ---@param position_encoding 'utf-8'|'utf-16'|'utf-32'
1747  ---@see https://microsoft.github.io/language-server-protocol/specification/#textDocumentContentChangeEvent
1748  function M.buf_highlight_references(bufnr, references, position_encoding)
1749    validate('bufnr', bufnr, 'number', true)
1750    validate('position_encoding', position_encoding, 'string', false)
1751    for _, reference in ipairs(references) do
1752      local range = vim.range.lsp(bufnr, reference.range, position_encoding)
1753
1754      local document_highlight_kind = {
1755        [protocol.DocumentHighlightKind.Text] = 'LspReferenceText',
1756        [protocol.DocumentHighlightKind.Read] = 'LspReferenceRead',
1757        [protocol.DocumentHighlightKind.Write] = 'LspReferenceWrite',
1758      }
1759      local kind = reference['kind'] or protocol.DocumentHighlightKind.Text
1760      vim.hl.range(
1761        bufnr,
1762        reference_ns,
1763        document_highlight_kind[kind],
1764        { range.start_row, range.start_col },
1765        { range.end_row, range.end_col },
1766        { priority = vim.hl.priorities.user }
1767      )
1768    end
1769  end
1770end
1771
1772local position_sort = sort_by_key(function(v)
1773  return { v.start.line, v.start.character }
1774end)
1775
1776--- Returns the items with the byte position calculated correctly and in sorted
1777--- order, for display in quickfix and location lists.
1778---
1779--- The `user_data` field of each resulting item will contain the original
1780--- `Location` or `LocationLink` it was computed from.
1781---
1782--- The result can be passed to the {list} argument of |setqflist()| or
1783--- |setloclist()|.
1784---
1785---@param locations lsp.Location[]|lsp.LocationLink[]
1786---@param position_encoding 'utf-8'|'utf-16'|'utf-32'
1787---@return vim.quickfix.entry[] # See |setqflist()| for the format
1788function M.locations_to_items(locations, position_encoding)
1789  validate('position_encoding', position_encoding, 'string')
1790
1791  local items = {} --- @type vim.quickfix.entry[]
1792
1793  ---@type table<string, {start: lsp.Position, end: lsp.Position, location: lsp.Location|lsp.LocationLink}[]>
1794  local grouped = {}
1795  for _, d in ipairs(locations) do
1796    -- locations may be Location or LocationLink
1797    local uri = d.uri or d.targetUri
1798    local range = d.range or d.targetSelectionRange
1799    grouped[uri] = grouped[uri] or {}
1800    table.insert(grouped[uri], { start = range.start, ['end'] = range['end'], location = d })
1801  end
1802
1803  for uri, rows in vim.spairs(grouped) do
1804    table.sort(rows, position_sort)
1805    local filename = vim.uri_to_fname(uri)
1806
1807    local line_numbers = {}
1808    for _, temp in ipairs(rows) do
1809      table.insert(line_numbers, temp.start.line)
1810      if temp.start.line ~= temp['end'].line then
1811        table.insert(line_numbers, temp['end'].line)
1812      end
1813    end
1814
1815    -- get all the lines for this uri
1816    local lines = get_lines(vim.uri_to_bufnr(uri), line_numbers)
1817
1818    for _, temp in ipairs(rows) do
1819      local pos = temp.start
1820      local end_pos = temp['end']
1821      local row = pos.line
1822      local end_row = end_pos.line
1823      local line = lines[row]
1824      local end_line = lines[end_row]
1825      local col = vim.str_byteindex(line, position_encoding, pos.character, false)
1826      local end_col = vim.str_byteindex(end_line, position_encoding, end_pos.character, false)
1827
1828      items[#items + 1] = {
1829        filename = filename,
1830        lnum = row + 1,
1831        end_lnum = end_row + 1,
1832        col = col + 1,
1833        end_col = end_col + 1,
1834        text = line,
1835        user_data = temp.location,
1836      }
1837    end
1838  end
1839  return items
1840end
1841
1842--- Converts symbols to quickfix list items.
1843---
1844---@param symbols lsp.DocumentSymbol[]|lsp.SymbolInformation[]|lsp.WorkspaceSymbol[] list of symbols
1845---@param bufnr? integer buffer handle or 0 for current, defaults to current
1846---@param position_encoding 'utf-8'|'utf-16'|'utf-32'
1847---@return vim.quickfix.entry[] # See |setqflist()| for the format
1848function M.symbols_to_items(symbols, bufnr, position_encoding)
1849  validate('position_encoding', position_encoding, 'string')
1850
1851  bufnr = vim._resolve_bufnr(bufnr)
1852
1853  local items = {} --- @type vim.quickfix.entry[]
1854  for _, symbol in ipairs(symbols) do
1855    --- @type string?, vim.Range?
1856    local filename, range
1857
1858    if symbol.location then
1859      --- @cast symbol lsp.SymbolInformation
1860      filename = vim.uri_to_fname(symbol.location.uri)
1861      range = vim.range.lsp(bufnr, symbol.location.range, position_encoding)
1862    elseif symbol.selectionRange then
1863      --- @cast symbol lsp.DocumentSymbol
1864      filename = api.nvim_buf_get_name(bufnr)
1865      range = vim.range.lsp(bufnr, symbol.selectionRange, position_encoding)
1866    end
1867
1868    if filename and range then
1869      local kind = protocol.SymbolKind[symbol.kind] or 'Unknown'
1870      ---@diagnostic disable-next-line: deprecated
1871      local is_deprecated = not vim.isnil(symbol.deprecated or nil)
1872        or (
1873          not vim.isnil(symbol.tags)
1874          and vim.tbl_contains(symbol.tags, protocol.SymbolTag.Deprecated)
1875        )
1876      local text = string.format(
1877        '[%s] %s%s%s',
1878        kind,
1879        symbol.name,
1880        not vim.isnil(symbol.containerName) and ' in ' .. symbol.containerName or '',
1881        is_deprecated and ' (deprecated)' or ''
1882      )
1883
1884      items[#items + 1] = {
1885        filename = filename,
1886        lnum = range.start_row + 1,
1887        col = range.start_col + 1,
1888        end_lnum = range.end_row + 1,
1889        end_col = range.end_col + 1,
1890        kind = kind,
1891        text = text,
1892      }
1893    end
1894
1895    if symbol.children then
1896      list_extend(items, M.symbols_to_items(symbol.children, bufnr, position_encoding))
1897    end
1898  end
1899
1900  return items
1901end
1902
1903--- Creates a `TextDocumentPositionParams` object for the current buffer and cursor position.
1904---
1905---@param win integer?: |window-ID| or 0 for current, defaults to current
1906---@param position_encoding 'utf-8'|'utf-16'|'utf-32'
1907---@return lsp.TextDocumentPositionParams
1908---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams
1909function M.make_position_params(win, position_encoding)
1910  win = win or 0
1911  return {
1912    textDocument = M.make_text_document_params(api.nvim_win_get_buf(win)),
1913    position = vim.pos.cursor(win):to_lsp(position_encoding),
1914  }
1915end
1916
1917--- Using the current position in the current buffer, creates an object that
1918--- can be used as a building block for several LSP requests, such as
1919--- `textDocument/codeAction`, `textDocument/colorPresentation`,
1920--- `textDocument/rangeFormatting`.
1921---
1922---@param win integer?: |window-ID| or 0 for current, defaults to current
1923---@param position_encoding "utf-8"|"utf-16"|"utf-32"
1924---@return { textDocument: { uri: lsp.DocumentUri }, range: lsp.Range }
1925function M.make_range_params(win, position_encoding)
1926  win = win or 0
1927  local buf = api.nvim_win_get_buf(win)
1928  local position = vim.pos.cursor(buf, api.nvim_win_get_cursor(win)):to_lsp(position_encoding)
1929  return {
1930    textDocument = M.make_text_document_params(buf),
1931    range = { start = position, ['end'] = position },
1932  }
1933end
1934
1935--- Using the given range in the current buffer, creates an object that
1936--- is similar to |vim.lsp.util.make_range_params()|.
1937---
1938---@param start_pos [integer,integer]? {row,col} mark-indexed position.
1939--- Defaults to the start of the last visual selection.
1940---@param end_pos [integer,integer]? {row,col} mark-indexed position.
1941--- Defaults to the end of the last visual selection.
1942---@param bufnr integer? buffer handle or 0 for current, defaults to current
1943---@param position_encoding 'utf-8'|'utf-16'|'utf-32'
1944---@return { textDocument: { uri: lsp.DocumentUri }, range: lsp.Range }
1945function M.make_given_range_params(start_pos, end_pos, bufnr, position_encoding)
1946  validate('start_pos', start_pos, 'table', true)
1947  validate('end_pos', end_pos, 'table', true)
1948  validate('position_encoding', position_encoding, 'string')
1949
1950  bufnr = vim._resolve_bufnr(bufnr)
1951  local start_row, start_col = unpack(start_pos or api.nvim_buf_get_mark(bufnr, '<'))
1952  local end_row, end_col = unpack(end_pos or api.nvim_buf_get_mark(bufnr, '>'))
1953  return {
1954    textDocument = M.make_text_document_params(bufnr),
1955    range = vim.range.mark(bufnr, start_row, start_col, end_row, end_col):to_lsp(position_encoding),
1956  }
1957end
1958
1959--- Creates a `TextDocumentIdentifier` object for the current buffer.
1960---
1961---@param bufnr integer?: Buffer handle, defaults to current
1962---@return lsp.TextDocumentIdentifier
1963---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier
1964function M.make_text_document_params(bufnr)
1965  return { uri = vim.uri_from_bufnr(bufnr or 0) }
1966end
1967
1968--- Create the workspace params
1969---@param added lsp.WorkspaceFolder[]
1970---@param removed lsp.WorkspaceFolder[]
1971---@return lsp.DidChangeWorkspaceFoldersParams
1972function M.make_workspace_params(added, removed)
1973  return { event = { added = added, removed = removed } }
1974end
1975
1976--- Returns indentation size.
1977---
1978---@see 'shiftwidth'
1979---@param bufnr integer?: Buffer handle, defaults to current
1980---@return integer indentation size
1981function M.get_effective_tabstop(bufnr)
1982  validate('bufnr', bufnr, 'number', true)
1983  local bo = bufnr and vim.bo[bufnr] or vim.bo
1984  local sw = bo.shiftwidth
1985  return (sw == 0 and bo.tabstop) or sw
1986end
1987
1988--- Creates a `DocumentFormattingParams` object for the current buffer and cursor position.
1989---
1990---@param options lsp.FormattingOptions? with valid `FormattingOptions` entries
1991---@return lsp.DocumentFormattingParams object
1992---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting
1993function M.make_formatting_params(options)
1994  validate('options', options, 'table', true)
1995  options = vim.tbl_extend('keep', options or {}, {
1996    tabSize = M.get_effective_tabstop(),
1997    insertSpaces = vim.bo.expandtab,
1998  }) --[[@as lsp.FormattingOptions]]
1999  return {
2000    textDocument = { uri = vim.uri_from_bufnr(0) },
2001    options = options,
2002  }
2003end
2004
2005--- Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer.
2006---
2007---@deprecated
2008---@param buf integer buffer number (0 for current)
2009---@param row integer 0-indexed line
2010---@param col integer 0-indexed byte offset in line
2011---@param position_encoding 'utf-8'|'utf-16'|'utf-32'
2012---@return integer `position_encoding` index of the character in line {row} column {col} in buffer {buf}
2013function M.character_offset(buf, row, col, position_encoding)
2014  vim.deprecate('vim.lsp.util.character_offset', 'vim.str_utfindex', '0.14')
2015  validate('position_encoding', position_encoding, 'string')
2016
2017  local line = get_line(buf, row)
2018  return vim.str_utfindex(line, position_encoding, col, false)
2019end
2020
2021---@class (private) vim.lsp.util._cancel_requests.Filter
2022---@field bufnr? integer
2023---@field clients? vim.lsp.Client[]
2024---@field method? vim.lsp.protocol.Method.ClientToServer.Request
2025---@field type? string
2026
2027--- Cancel all {filter}ed requests.
2028---
2029---@param filter? vim.lsp.util._cancel_requests.Filter
2030function M._cancel_requests(filter)
2031  filter = filter or {}
2032  local bufnr = filter.bufnr and vim._resolve_bufnr(filter.bufnr) or nil
2033  local clients = filter.clients
2034  local method = filter.method
2035  local type = filter.type
2036
2037  for _, client in
2038    ipairs(clients or vim.lsp.get_clients({
2039      bufnr = bufnr,
2040      method = method,
2041    }))
2042  do
2043    for id, request in pairs(client.requests) do
2044      if
2045        (bufnr == nil or bufnr == request.bufnr)
2046        and (method == nil or method == request.method)
2047        and (type == nil or type == request.type)
2048      then
2049        client:cancel_request(id)
2050      end
2051    end
2052  end
2053end
2054
2055---@nodoc
2056---@type table<integer,integer>
2057M.buf_versions = setmetatable({}, {
2058  __index = function(t, bufnr)
2059    return rawget(t, bufnr) or 0
2060  end,
2061})
2062
2063return M