robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
39.0 KiB1149 linesraw
1local api = vim.api
2local nvim_on = require('vim._core.util').nvim_on
3
4-- TODO(lewis6991): deprecate some top level functions in favour of the submodule version
5-- e.g. vim.diagnostic.get_namespace() -> vim.diagnostic.namespace.get()
6local M = vim._defer_require('vim.diagnostic', {
7  _config = ..., --- @module 'vim.diagnostic._config'
8  _display = ..., --- @module 'vim.diagnostic._display'
9  _float = ..., --- @module 'vim.diagnostic._float'
10  _jump = ..., --- @module 'vim.diagnostic._jump'
11  _severity = ..., --- @module 'vim.diagnostic._severity'
12  _store = ..., --- @module 'vim.diagnostic._store'
13  _handlers = ..., --- @module 'vim.diagnostic._handlers'
14})
15
16--- Diagnostics use the same indexing as the rest of the Nvim API (i.e. 0-based
17--- rows, and columns given as 0-based byte indices). |api-indexing|
18--- @class vim.Diagnostic.Set
19---
20--- The starting line of the diagnostic (0-indexed)
21--- @field lnum integer
22---
23--- The starting column of the diagnostic (0-indexed)
24--- (default: `0`)
25--- @field col? integer
26---
27--- The final line of the diagnostic (0-indexed)
28--- (default: `lnum`)
29--- @field end_lnum? integer
30---
31--- The final column of the diagnostic (0-indexed)
32--- (default: `col`)
33--- @field end_col? integer
34---
35--- The severity of the diagnostic |vim.diagnostic.severity|
36--- (default: `vim.diagnostic.severity.ERROR`)
37--- @field severity? vim.diagnostic.Severity
38---
39--- The diagnostic text
40--- @field message string
41---
42--- The source of the diagnostic
43--- @field source? string
44---
45--- The diagnostic code
46--- @field code? string|integer
47---
48--- @field _tags? { deprecated: boolean, unnecessary: boolean}
49---
50--- Arbitrary data plugins or users can add
51--- @field user_data? any arbitrary data plugins can add
52
53--- [diagnostic-structure]()
54---
55--- Diagnostics use |api-indexing| (i.e. 0-based rows, and columns given as 0-based byte
56--- indices). See also |vim.pos| and |vim.range| to convert positions from other systems.
57---
58--- @class vim.Diagnostic : vim.Diagnostic.Set
59--- @field bufnr integer Buffer number
60--- @field end_lnum integer The final line of the diagnostic (0-indexed)
61--- @field col integer The starting column of the diagnostic (0-indexed)
62--- @field end_col integer The final column of the diagnostic (0-indexed)
63--- @field severity vim.diagnostic.Severity The severity of the diagnostic |vim.diagnostic.severity|
64--- @field namespace? integer
65--- @field _extmark_id? integer
66
67--- Many of the configuration options below accept one of the following:
68--- - `false`: Disable this feature
69--- - `true`: Enable this feature, use default settings.
70--- - `table`: Enable this feature with overrides. Use an empty table to use default values.
71--- - `function`: Function with signature (namespace, bufnr) that returns any of the above.
72--- @class vim.diagnostic.Opts
73---
74--- Used to call attention to a diagnostic ("underline" is a misnomer).
75--- Controls the |hl-DiagnosticUnnecessary| and |hl-DiagnosticDeprecated| highlights.
76--- (default: `true`)
77--- @field underline? boolean|vim.diagnostic.Opts.Underline|fun(namespace: integer, bufnr:integer): vim.diagnostic.Opts.Underline
78---
79--- Use virtual text for diagnostics. If multiple diagnostics are set for a
80--- namespace, one prefix per diagnostic + the last diagnostic message are
81--- shown.
82--- (default: `false`)
83--- @field virtual_text? boolean|vim.diagnostic.Opts.VirtualText|fun(namespace: integer, bufnr:integer): vim.diagnostic.Opts.VirtualText
84---
85--- Use virtual lines for diagnostics.
86--- (default: `false`)
87--- @field virtual_lines? boolean|vim.diagnostic.Opts.VirtualLines|fun(namespace: integer, bufnr:integer): vim.diagnostic.Opts.VirtualLines
88---
89--- Use signs for diagnostics |diagnostic-signs|.
90--- (default: `true`)
91--- @field signs? boolean|vim.diagnostic.Opts.Signs|fun(namespace: integer, bufnr:integer): vim.diagnostic.Opts.Signs
92---
93--- Options for floating windows. See |vim.diagnostic.Opts.Float|.
94--- @field float? boolean|vim.diagnostic.Opts.Float|fun(namespace?: integer|integer[], bufnr:integer): vim.diagnostic.Opts.Float
95---
96--- Options for the statusline component.
97--- @field status? vim.diagnostic.Opts.Status
98---
99--- Update diagnostics in Insert mode
100--- (if `false`, diagnostics are updated on |InsertLeave|)
101--- (default: `false`)
102--- @field update_in_insert? boolean
103---
104--- Sort diagnostics by severity. This affects the order in which signs,
105--- virtual text, and highlights are displayed. When true, higher severities are
106--- displayed before lower severities (e.g. ERROR is displayed before WARN).
107--- Options:
108---   - {reverse}? (boolean) Reverse sort order
109--- (default: `false`)
110--- @field severity_sort? boolean|{reverse?:boolean}
111---
112--- Default values for |vim.diagnostic.jump()|. See |vim.diagnostic.Opts.Jump|.
113--- @field jump? vim.diagnostic.Opts.Jump
114
115--- @class vim.diagnostic.Opts.Float : vim.lsp.util.open_floating_preview.Opts
116---
117--- Buffer number to show diagnostics from.
118--- (default: current buffer)
119--- @field bufnr? integer
120---
121--- Limit diagnostics to the given namespace(s).
122--- @field namespace? integer|integer[]
123---
124--- Show diagnostics from the whole buffer (`buffer`), the current cursor line
125--- (`line`), or the current cursor position (`cursor`). Shorthand versions
126--- are also accepted (`c` for `cursor`, `l` for `line`, `b` for `buffer`).
127--- (default: `line`)
128--- @field scope? 'line'|'buffer'|'cursor'|'c'|'l'|'b'
129---
130--- If {scope} is "line" or "cursor", use this position rather than the cursor
131--- position. If a number, interpreted as a line number; otherwise, a
132--- (row, col) tuple.
133--- @field pos? integer|[integer,integer]
134---
135--- Sort diagnostics by severity.
136--- Overrides the setting from |vim.diagnostic.config()|.
137--- (default: `false`)
138--- @field severity_sort? boolean|{reverse?:boolean}
139---
140--- See |diagnostic-severity|.
141--- Overrides the setting from |vim.diagnostic.config()|.
142--- @field severity? vim.diagnostic.SeverityFilter
143---
144--- String to use as the header for the floating window. If a table, it is
145--- interpreted as a `[text, hl_group]` tuple.
146--- Overrides the setting from |vim.diagnostic.config()|.
147--- @field header? string|[string,any]
148---
149--- Include the diagnostic source in the message.
150--- Use "if_many" to only show sources if there is more than one source of
151--- diagnostics in the buffer. Otherwise, any truthy value means to always show
152--- the diagnostic source.
153--- Overrides the setting from |vim.diagnostic.config()|.
154--- @field source? boolean|'if_many'
155---
156--- A function that takes a diagnostic as input and returns a string or nil.
157--- If the return value is nil, the diagnostic is not displayed by the handler.
158--- Else the output text is used to display the diagnostic.
159--- Overrides the setting from |vim.diagnostic.config()|.
160--- @field format? fun(diagnostic:vim.Diagnostic): string?
161---
162--- Prefix each diagnostic in the floating window:
163--- - If a `function`, {i} is the index of the diagnostic being evaluated and
164---   {total} is the total number of diagnostics displayed in the window. The
165---   function should return a `string` which is prepended to each diagnostic
166---   in the window as well as an (optional) highlight group which will be
167---   used to highlight the prefix.
168--- - If a `table`, it is interpreted as a `[text, hl_group]` tuple as
169---   in |nvim_echo()|
170--- - If a `string`, it is prepended to each diagnostic in the window with no
171---   highlight.
172--- Overrides the setting from |vim.diagnostic.config()|.
173--- @field prefix? string|table|(fun(diagnostic:vim.Diagnostic,i:integer,total:integer): string, string)
174---
175--- Same as {prefix}, but appends the text to the diagnostic instead of
176--- prepending it.
177--- Overrides the setting from |vim.diagnostic.config()|.
178--- @field suffix? string|table|(fun(diagnostic:vim.Diagnostic,i:integer,total:integer): string, string)
179
180--- @class vim.diagnostic.Opts.Status
181---
182--- Function that accepts a mapping of |diagnostic-severity| to the number of diagnostics of the
183--- corresponding severity (only those having at least 1 diagnostic) and returns a 'statusline'
184--- component. Highlights must be applied by the `format` function.
185--- Example:
186--- ```lua
187--- local signs = {
188---   [vim.diagnostic.severity.ERROR] = "A",
189---   -- ...
190--- }
191--- local hl_map = {
192---   [vim.diagnostic.severity.ERROR] = 'DiagnosticSignError',
193---   -- ...
194--- }
195--- vim.diagnostic.config({
196---   status = {
197---     format = function(severity_counts)
198---       local items = {}
199---       for severity in ipairs(vim.diagnostic.severity) do
200---         local count = severity_counts[severity] or 0
201---         table.insert(items, ("%%#%s#%s %s"):format(hl_map[severity], signs[severity], count))
202---       end
203---       return table.concat(items, " ")
204---     end
205---   }
206--- })
207--- ```
208--- @field format? (fun(counts:table<vim.diagnostic.Severity,integer>): string)
209
210--- @class vim.diagnostic.Opts.Underline
211---
212--- Only underline diagnostics matching the given
213--- severity |diagnostic-severity|.
214--- @field severity? vim.diagnostic.SeverityFilter
215
216--- @class vim.diagnostic.Opts.VirtualText
217---
218--- Only show virtual text for diagnostics matching the given
219--- severity |diagnostic-severity|
220--- @field severity? vim.diagnostic.SeverityFilter
221---
222--- Show or hide diagnostics based on the current cursor line.  If `true`, only diagnostics on the
223--- current cursor line are shown.  If `false`, all diagnostics are shown except on the current
224--- cursor line.  If `nil`, all diagnostics are shown. Updated on |CursorHold|, see 'updatetime'.
225--- (default: `nil`)
226--- @field current_line? boolean
227---
228--- Include the diagnostic source in virtual text. Use `'if_many'` to only
229--- show sources if there is more than one diagnostic source in the buffer.
230--- Otherwise, any truthy value means to always show the diagnostic source.
231--- @field source? boolean|"if_many"
232---
233--- Amount of empty spaces inserted at the beginning of the virtual text.
234--- @field spacing? integer
235---
236--- Prepend diagnostic message with prefix. If a `function`, {i} is the index
237--- of the diagnostic being evaluated, and {total} is the total number of
238--- diagnostics for the line. This can be used to render diagnostic symbols
239--- or error codes.
240--- @field prefix? string|(fun(diagnostic:vim.Diagnostic,i:integer,total:integer): string)
241---
242--- Append diagnostic message with suffix.
243--- This can be used to render an LSP diagnostic error code.
244--- @field suffix? string|(fun(diagnostic:vim.Diagnostic): string)
245---
246--- If not nil, the return value is the text used to display the diagnostic. Example:
247--- ```lua
248--- function(diagnostic)
249---   if diagnostic.severity == vim.diagnostic.severity.ERROR then
250---     return string.format("E: %s", diagnostic.message)
251---   end
252---   return diagnostic.message
253--- end
254--- ```
255--- If the return value is nil, the diagnostic is not displayed by the handler.
256--- @field format? fun(diagnostic:vim.Diagnostic): string?
257---
258--- See |nvim_buf_set_extmark()|.
259--- @field hl_mode? 'replace'|'combine'|'blend'
260---
261--- See |nvim_buf_set_extmark()|.
262--- @field virt_text? [string,any][]
263---
264--- See |nvim_buf_set_extmark()|.
265--- @field virt_text_pos? 'eol'|'eol_right_align'|'inline'|'overlay'|'right_align'
266---
267--- See |nvim_buf_set_extmark()|.
268--- @field virt_text_win_col? integer
269---
270--- See |nvim_buf_set_extmark()|.
271--- @field virt_text_hide? boolean
272
273--- @class vim.diagnostic.Opts.VirtualLines
274---
275--- Only show virtual lines for diagnostics matching the given
276--- severity |diagnostic-severity|
277--- @field severity? vim.diagnostic.SeverityFilter
278---
279--- Only show diagnostics for the current line. Updated on |CursorHold|, see 'updatetime'.
280--- (default: `false`)
281--- @field current_line? boolean
282---
283--- A function that takes a diagnostic as input and returns a string or nil.
284--- If the return value is nil, the diagnostic is not displayed by the handler.
285--- Else the output text is used to display the diagnostic.
286--- @field format? fun(diagnostic:vim.Diagnostic): string?
287---
288--- See `virt_lines_overflow` in |nvim_buf_set_extmark()|.
289--- (default: `auto`)
290--- @field overflow? 'trunc'|'scroll'|'wrap'|'auto'
291
292--- @class vim.diagnostic.Opts.Signs
293---
294--- Only show signs for diagnostics matching the given
295--- severity |diagnostic-severity|
296--- @field severity? vim.diagnostic.SeverityFilter
297---
298--- Base priority to use for signs. When {severity_sort} is used, the priority
299--- of a sign is adjusted based on its severity.
300--- Otherwise, all signs use the same priority.
301--- (default: `10`)
302--- @field priority? integer
303---
304--- A table mapping |diagnostic-severity| to the sign text to display in the
305--- sign column and statusline. The default is to use `"E"`, `"W"`, `"I"`, and `"H"`
306--- for errors, warnings, information, and hints, respectively. Example:
307--- ```lua
308--- vim.diagnostic.config({
309---   signs = { text = { [vim.diagnostic.severity.ERROR] = 'E', ... } }
310--- })
311--- ```
312--- @field text? table<vim.diagnostic.Severity|vim.diagnostic.SeverityName,string>
313---
314--- A table mapping |diagnostic-severity| to the highlight group used for the
315--- line number where the sign is placed.
316--- @field numhl? table<vim.diagnostic.Severity,string>
317---
318--- A table mapping |diagnostic-severity| to the highlight group used for the
319--- whole line the sign is placed in.
320--- @field linehl? table<vim.diagnostic.Severity,string>
321
322--- @class vim.diagnostic.Opts.Jump
323---
324--- Default value of the {on_jump} parameter of |vim.diagnostic.jump()|.
325--- @field on_jump? fun(diagnostic:vim.Diagnostic?, bufnr:integer)
326---
327--- Default value of the {wrap} parameter of |vim.diagnostic.jump()|.
328--- (default: true)
329--- @field wrap? boolean
330---
331--- Default value of the {severity} parameter of |vim.diagnostic.jump()|.
332--- @field severity? vim.diagnostic.SeverityFilter
333---
334--- Default value of the {_highest} parameter of |vim.diagnostic.jump()|.
335--- @field package _highest? boolean
336
337-- TODO: inherit from `vim.diagnostic.Opts`, implement its fields.
338--- Optional filters |kwargs|, or `nil` for all.
339--- @class vim.diagnostic.Filter
340--- @inlinedoc
341---
342--- Diagnostic namespace, or `nil` for all.
343--- @field ns_id? integer
344---
345--- Buffer number, or 0 for current buffer, or `nil` for all buffers.
346--- @field bufnr? integer
347
348--- See |diagnostic-severity| and |vim.diagnostic.get()|
349--- @alias vim.diagnostic.SeverityFilter
350--- | vim.diagnostic.Severity
351--- | vim.diagnostic.Severity[]
352--- | {min:vim.diagnostic.Severity,max:vim.diagnostic.Severity}
353
354--- @nodoc
355--- @enum vim.diagnostic.Severity
356M.severity = {
357  ERROR = 1,
358  WARN = 2,
359  INFO = 3,
360  HINT = 4,
361}
362
363--- @enum vim.diagnostic.SeverityName
364local severity_invert = {
365  [1] = 'ERROR',
366  [2] = 'WARN',
367  [3] = 'INFO',
368  [4] = 'HINT',
369}
370
371do
372  --- Set extra fields through table alias to hide from analysis tools
373  local s = M.severity --- @type table<any,any>
374
375  for i, name in ipairs(severity_invert) do
376    s[i] = name
377  end
378
379  --- Mappings from qflist/loclist error types to severities
380  s.E = 1
381  s.W = 2
382  s.I = 3
383  s.N = 4
384end
385
386local builtin_handler_names = {
387  signs = true,
388  underline = true,
389  virtual_text = true,
390  virtual_lines = true,
391}
392
393--- @nodoc
394--- @type table<string,vim.diagnostic.Handler>
395M.handlers = setmetatable({}, {
396  __newindex = function(t, name, handler)
397    vim.validate('handler', handler, 'table')
398    rawset(t, name, handler)
399    if not builtin_handler_names[name] then
400      M._config.enable_handler(name)
401    end
402  end,
403})
404
405--- @type table<integer,true|table<integer,true>>
406local diagnostic_disabled = {}
407
408--- @class vim.diagnostic.NS
409--- @field name string
410--- @field opts vim.diagnostic.Opts
411--- @field user_data table
412--- @field disabled? boolean
413
414--- @type table<integer, vim.diagnostic.NS>
415local all_namespaces = {}
416
417--- Configure diagnostic options globally or for a specific diagnostic
418--- namespace.
419---
420--- Configuration can be specified globally, per-namespace, or ephemerally
421--- (i.e. only for a single call to |vim.diagnostic.set()| or
422--- |vim.diagnostic.show()|). Ephemeral configuration has highest priority,
423--- followed by namespace configuration, and finally global configuration.
424---
425--- For example, if a user enables virtual text globally with
426---
427--- ```lua
428--- vim.diagnostic.config({ virtual_text = true })
429--- ```
430---
431--- and a diagnostic producer sets diagnostics with
432---
433--- ```lua
434--- vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false })
435--- ```
436---
437--- then virtual text will not be enabled for those diagnostics.
438---
439---@param opts vim.diagnostic.Opts? When omitted or `nil`, retrieve the current
440---       configuration. Otherwise, a configuration table (see |vim.diagnostic.Opts|).
441---@param namespace integer? Update the options for the given namespace.
442---                          When omitted, update the global diagnostic options.
443---@return vim.diagnostic.Opts? : Current diagnostic config if {opts} is omitted.
444---@overload fun(opts?: nil, namespace?: integer): vim.diagnostic.Opts
445function M.config(opts, namespace)
446  return M._config.config(opts, namespace)
447end
448
449--- Set diagnostics for the given namespace and buffer.
450---
451---@param namespace integer The diagnostic namespace
452---@param buf integer Buffer number
453---@param diagnostics vim.Diagnostic.Set[]
454---@param opts? vim.diagnostic.Opts Display options to pass to |vim.diagnostic.show()|
455function M.set(namespace, buf, diagnostics, opts)
456  vim.validate('opts', opts, 'table', true)
457  M._store.set(namespace, buf, diagnostics)
458  M.show(namespace, buf, nil, opts)
459
460  api.nvim_exec_autocmds('DiagnosticChanged', {
461    modeline = false,
462    buf = vim._resolve_bufnr(buf),
463    -- TODO(lewis6991): should this be deepcopy()'d like they are in vim.diagnostic.get()
464    data = { diagnostics = diagnostics },
465  })
466end
467
468--- Get namespace metadata.
469---
470---@param namespace integer Diagnostic namespace
471---@return vim.diagnostic.NS : Namespace metadata
472function M.get_namespace(namespace)
473  vim.validate('namespace', namespace, 'number')
474
475  if not all_namespaces[namespace] then
476    local name --- @type string?
477    for k, v in pairs(api.nvim_get_namespaces()) do
478      if namespace == v then
479        name = k
480        break
481      end
482    end
483
484    assert(name, 'namespace does not exist or is anonymous')
485
486    all_namespaces[namespace] = {
487      name = name,
488      opts = {},
489      user_data = {},
490    }
491  end
492
493  return all_namespaces[namespace]
494end
495
496--- Get current diagnostic namespaces.
497---
498---@return table<integer,vim.diagnostic.NS> : List of active diagnostic namespaces |vim.diagnostic|.
499function M.get_namespaces()
500  return vim.deepcopy(all_namespaces, true)
501end
502
503--- Get current diagnostics.
504---
505--- Modifying diagnostics in the returned table has no effect.
506--- To set diagnostics in a buffer, use |vim.diagnostic.set()|.
507---
508---@param buf integer? Buffer number to get diagnostics from. Use 0 for
509---                      current buffer or nil for all buffers.
510---@param opts? vim.diagnostic.GetOpts
511---@return vim.Diagnostic[]
512function M.get(buf, opts)
513  return M._store.get(buf, opts)
514end
515
516--- Get current diagnostics count.
517---
518---@param buf? integer Buffer number to get diagnostics from. Use 0 for
519---                      current buffer or nil for all buffers.
520---@param opts? vim.diagnostic.GetOpts
521---@return table<integer, integer> : Table with actually present severity values as keys
522---                (see |diagnostic-severity|) and integer counts as values.
523function M.count(buf, opts)
524  return M._store.count(buf, opts)
525end
526
527--- Get the previous diagnostic closest to the cursor position.
528---
529---@param opts? vim.diagnostic.JumpOpts
530---@return vim.Diagnostic? : Previous diagnostic
531function M.get_prev(opts)
532  return M._jump.get_prev(opts)
533end
534
535--- Return the position of the previous diagnostic in the current buffer.
536---
537---@param opts? vim.diagnostic.JumpOpts
538---@return table|false: Previous diagnostic position as a `(row, col)` tuple
539---                     or `false` if there is no prior diagnostic.
540---@deprecated
541function M.get_prev_pos(opts)
542  return M._jump.get_prev_pos(opts)
543end
544
545--- Move to the previous diagnostic in the current buffer.
546---@param opts? vim.diagnostic.JumpOpts
547---@deprecated
548function M.goto_prev(opts)
549  return M._jump.goto_prev(opts)
550end
551
552--- Get the next diagnostic closest to the cursor position.
553---
554---@param opts? vim.diagnostic.JumpOpts
555---@return vim.Diagnostic? : Next diagnostic
556function M.get_next(opts)
557  return M._jump.get_next(opts)
558end
559
560--- Return the position of the next diagnostic in the current buffer.
561---
562---@param opts? vim.diagnostic.JumpOpts
563---@return table|false : Next diagnostic position as a `(row, col)` tuple or false if no next
564---                      diagnostic.
565---@deprecated
566function M.get_next_pos(opts)
567  return M._jump.get_next_pos(opts)
568end
569
570--- A table with the following keys:
571--- @class vim.diagnostic.GetOpts
572---
573--- Limit diagnostics to one or more namespaces.
574--- @field namespace? integer[]|integer
575---
576--- Limit diagnostics to those spanning the specified line number (0-indexed, see |diagnostic-structure|).
577--- @field lnum? integer
578---
579--- See |diagnostic-severity|.
580--- @field severity? vim.diagnostic.SeverityFilter
581---
582--- Limit diagnostics to only enabled or disabled. If nil, enablement is ignored.
583--- See |vim.diagnostic.enable()|
584--- (default: `nil`)
585--- @field enabled? boolean
586
587--- Configuration table with the keys listed below. Some parameters can have their default values
588--- changed with |vim.diagnostic.config()|.
589--- @class vim.diagnostic.JumpOpts : vim.diagnostic.GetOpts
590---
591--- The diagnostic to jump to. Mutually exclusive with {count}, {namespace},
592--- and {severity}.
593--- @field diagnostic? vim.Diagnostic
594---
595--- The number of diagnostics to move by, starting from {pos}. A positive
596--- integer moves forward by {count} diagnostics, while a negative integer moves
597--- backward by {count} diagnostics. Mutually exclusive with {diagnostic}.
598--- @field count? integer
599---
600--- Cursor position as a `(row, col)` tuple. See |nvim_win_get_cursor()|. Used
601--- to find the nearest diagnostic when {count} is used. Only used when {count}
602--- is non-nil. Default is the current cursor position.
603--- @field pos? [integer,integer]
604---
605--- Whether to loop around file or not. Similar to 'wrapscan'.
606--- (default: `true`)
607--- @field wrap? boolean
608---
609--- See |diagnostic-severity|.
610--- @field severity? vim.diagnostic.SeverityFilter
611---
612--- Go to the diagnostic with the highest severity.
613--- (default: `false`)
614--- @field package _highest? boolean
615---
616--- Optional callback invoked with the diagnostic that was jumped to.
617--- @field on_jump? fun(diagnostic:vim.Diagnostic?, bufnr:integer)
618---
619--- Window ID
620--- (default: `0`)
621--- @field winid? integer
622
623--- @nodoc
624--- @class vim.diagnostic.JumpOpts1 : vim.diagnostic.JumpOpts
625--- @field win_id? integer (deprecated) use winid
626--- @field cursor_position? [integer, integer] (deprecated) use pos
627--- @field float? table|boolean (deprecated) use on_jump
628
629--- Move to a diagnostic.
630---
631--- @param opts vim.diagnostic.JumpOpts
632--- @return vim.Diagnostic? # The diagnostic that was moved to.
633function M.jump(opts)
634  return M._jump.jump(opts)
635end
636
637--- Move to the next diagnostic.
638---
639---@param opts? vim.diagnostic.JumpOpts
640---@deprecated
641function M.goto_next(opts)
642  return M._jump.goto_next(opts)
643end
644
645M.handlers.signs = {
646  show = function(...)
647    return M._handlers.signs.show(...)
648  end,
649  hide = function(namespace, bufnr)
650    return M._handlers.signs.hide(namespace, bufnr)
651  end,
652}
653
654M.handlers.underline = {
655  show = function(...)
656    return M._handlers.underline.show(...)
657  end,
658  hide = function(namespace, bufnr)
659    return M._handlers.underline.hide(namespace, bufnr)
660  end,
661}
662
663M.handlers.virtual_text = {
664  show = function(...)
665    return M._handlers.virtual_text.show(...)
666  end,
667  hide = function(namespace, bufnr)
668    return M._handlers.virtual_text.hide(namespace, bufnr)
669  end,
670}
671
672M.handlers.virtual_lines = {
673  show = function(...)
674    return M._handlers.virtual_lines.show(...)
675  end,
676  hide = function(namespace, bufnr)
677    return M._handlers.virtual_lines.hide(namespace, bufnr)
678  end,
679}
680
681--- Hide currently displayed diagnostics.
682---
683--- This only clears the decorations displayed in the buffer. Diagnostics can
684--- be redisplayed with |vim.diagnostic.show()|. To completely remove
685--- diagnostics, use |vim.diagnostic.reset()|.
686---
687--- To hide diagnostics and prevent them from re-displaying, use
688--- |vim.diagnostic.enable()|.
689---
690---@param namespace integer? Diagnostic namespace. When omitted, hide
691---                          diagnostics from all namespaces.
692---@param buf integer? Buffer number, or 0 for current buffer. When
693---                      omitted, hide diagnostics in all buffers.
694function M.hide(namespace, buf)
695  return M._display.hide(namespace, buf)
696end
697
698--- Check whether diagnostics are enabled.
699---
700--- @param filter vim.diagnostic.Filter?
701--- @return boolean
702--- @since 12
703function M.is_enabled(filter)
704  filter = filter or {}
705  if filter.ns_id and M.get_namespace(filter.ns_id).disabled then
706    return false
707  elseif filter.bufnr == nil then
708    -- See enable() logic.
709    return vim.tbl_isempty(diagnostic_disabled) and not diagnostic_disabled[1]
710  end
711
712  local bufnr = vim._resolve_bufnr(filter.bufnr)
713  if type(diagnostic_disabled[bufnr]) == 'table' then
714    return not diagnostic_disabled[bufnr][filter.ns_id]
715  end
716
717  return diagnostic_disabled[bufnr] == nil
718end
719
720--- Display diagnostics for the given namespace and buffer.
721---
722---@param namespace integer? Diagnostic namespace. When omitted, show
723---                          diagnostics from all namespaces.
724---@param buf integer? Buffer number, or 0 for current buffer. When omitted, show
725---                      diagnostics in all buffers.
726---@param diagnostics vim.Diagnostic[]? The diagnostics to display. When omitted, use the
727---                             saved diagnostics for the given namespace and
728---                             buffer. This can be used to display a list of diagnostics
729---                             without saving them or to display only a subset of
730---                             diagnostics. May not be used when {namespace}
731---                             or {buf} is nil.
732---@param opts? vim.diagnostic.Opts Display options.
733function M.show(namespace, buf, diagnostics, opts)
734  return M._display.show(namespace, buf, diagnostics, opts)
735end
736
737--- Show diagnostics in a floating window.
738---
739---@param opts vim.diagnostic.Opts.Float?
740---@return integer? float_bufnr
741---@return integer? winid
742function M.open_float(opts, ...)
743  return M._float.open(opts, ...)
744end
745
746--- Remove all diagnostics from the given namespace.
747---
748--- Unlike |vim.diagnostic.hide()|, this function removes all saved
749--- diagnostics. They cannot be redisplayed using |vim.diagnostic.show()|. To
750--- simply remove diagnostic decorations in a way that they can be
751--- re-displayed, use |vim.diagnostic.hide()|.
752---
753---@param namespace integer? Diagnostic namespace. When omitted, remove
754---                          diagnostics from all namespaces.
755---@param buf integer? Remove diagnostics for the given buffer. When omitted,
756---                     diagnostics are removed for all buffers.
757function M.reset(namespace, buf)
758  vim.validate('namespace', namespace, 'number', true)
759  vim.validate('buf', buf, 'number', true)
760
761  local buffers = buf and { vim._resolve_bufnr(buf) } or M._store.get_bufnrs()
762  for _, iter_bufnr in ipairs(buffers) do
763    local namespaces = namespace and { namespace } or M._store.get_buf_namespaces(iter_bufnr)
764    for _, iter_namespace in ipairs(namespaces) do
765      M._store.clear(iter_namespace, iter_bufnr)
766      M.hide(iter_namespace, iter_bufnr)
767    end
768
769    if api.nvim_buf_is_valid(iter_bufnr) then
770      api.nvim_exec_autocmds('DiagnosticChanged', {
771        modeline = false,
772        buf = iter_bufnr,
773        data = { diagnostics = {} },
774      })
775    else
776      M._store.drop_buf(iter_bufnr)
777    end
778  end
779end
780
781--- @type table<vim.diagnostic.Severity, string>
782local errlist_type_map = {
783  [M.severity.ERROR] = 'E',
784  [M.severity.WARN] = 'W',
785  [M.severity.INFO] = 'I',
786  [M.severity.HINT] = 'N',
787}
788
789--- @param title string
790--- @return integer?
791local function get_qf_id_for_title(title)
792  local lastqflist = vim.fn.getqflist({ nr = '$' })
793  for i = 1, assert(lastqflist.nr) do
794    local qflist = vim.fn.getqflist({ nr = i, id = 0, title = 0 })
795    if qflist.title == title then
796      return qflist.id
797    end
798  end
799
800  return nil
801end
802
803--- @param loclist boolean
804--- @param opts? vim.diagnostic.setqflist.Opts|vim.diagnostic.setloclist.Opts
805local function set_list(loclist, opts)
806  opts = opts or {}
807  local open = vim.nonnil(opts.open, true)
808  local title = opts.title or 'Diagnostics'
809  local winnr = opts.winnr or 0
810  local bufnr --- @type integer?
811  if loclist then
812    bufnr = api.nvim_win_get_buf(winnr)
813  end
814
815  -- Don't clamp line numbers since the quickfix list can already handle line
816  -- numbers beyond the end of the buffer
817  local diagnostics = M._store.get_diagnostics(bufnr, opts --[[@as vim.diagnostic.GetOpts]], false)
818  if opts.format then
819    diagnostics = require('vim.diagnostic._shared').reformat_diagnostics(opts.format, diagnostics)
820  end
821  local items = M.toqflist(diagnostics)
822  local qf_id = nil
823  if loclist then
824    vim.fn.setloclist(winnr, {}, 'u', { title = title, items = items })
825  else
826    qf_id = get_qf_id_for_title(title)
827    -- If we already have a diagnostics quickfix, update it rather than creating a new one.
828    -- This avoids polluting the finite set of quickfix lists, and preserves the currently selected
829    -- entry.
830    vim.fn.setqflist({}, qf_id and 'u' or ' ', {
831      title = title,
832      items = items,
833      id = qf_id,
834    })
835  end
836
837  if open then
838    if not loclist then
839      -- First navigate to the diagnostics quickfix list.
840      local qflist = vim.fn.getqflist({ id = qf_id, nr = 0 })
841      local nr = assert(qflist.nr)
842      api.nvim_command(('silent %dchistory'):format(nr))
843      -- Now open the quickfix list.
844      api.nvim_command('botright cwindow')
845    else
846      api.nvim_command('lwindow')
847    end
848  end
849end
850
851--- Configuration table with the following keys:
852--- @class vim.diagnostic.setqflist.Opts
853--- @inlinedoc
854---
855--- Only add diagnostics from the given namespace(s).
856--- @field namespace? integer[]|integer
857---
858--- Open quickfix list after setting.
859--- (default: `true`)
860--- @field open? boolean
861---
862--- Title of quickfix list. Defaults to "Diagnostics". If there's already a quickfix list with this
863--- title, it's updated. If not, a new quickfix list is created.
864--- @field title? string
865---
866--- See |diagnostic-severity|.
867--- @field severity? vim.diagnostic.SeverityFilter
868---
869--- A function that takes a diagnostic as input and returns a string or nil.
870--- If the return value is nil, the diagnostic is not displayed in the quickfix list.
871--- Else the output text is used to display the diagnostic.
872--- @field format? fun(diagnostic:vim.Diagnostic): string?
873
874--- Add all diagnostics to the quickfix list.
875---
876---@param opts? vim.diagnostic.setqflist.Opts
877function M.setqflist(opts)
878  return set_list(false, opts)
879end
880
881---Configuration table with the following keys:
882--- @class vim.diagnostic.setloclist.Opts
883--- @inlinedoc
884---
885--- Only add diagnostics from the given namespace(s).
886--- @field namespace? integer[]|integer
887---
888--- Window number to set location list for.
889--- (default: `0`)
890--- @field winnr? integer
891---
892--- Open the location list after setting.
893--- (default: `true`)
894--- @field open? boolean
895---
896--- Title of the location list. Defaults to "Diagnostics".
897--- @field title? string
898---
899--- See |diagnostic-severity|.
900--- @field severity? vim.diagnostic.SeverityFilter
901---
902--- A function that takes a diagnostic as input and returns a string or nil.
903--- If the return value is nil, the diagnostic is not displayed in the location list.
904--- Else the output text is used to display the diagnostic.
905--- @field format? fun(diagnostic:vim.Diagnostic): string?
906
907--- Add buffer diagnostics to the location list.
908---
909---@param opts? vim.diagnostic.setloclist.Opts
910function M.setloclist(opts)
911  return set_list(true, opts)
912end
913
914--- Enables or disables diagnostics.
915---
916--- To "toggle", pass the inverse of `is_enabled()`:
917---
918--- ```lua
919--- vim.diagnostic.enable(not vim.diagnostic.is_enabled())
920--- ```
921---
922--- @param enable (boolean|nil) true/nil to enable, false to disable
923--- @param filter vim.diagnostic.Filter?
924function M.enable(enable, filter)
925  filter = filter or {}
926  vim.validate('enable', enable, 'boolean', true)
927  vim.validate('filter', filter, 'table', true)
928
929  enable = enable == nil and true or enable
930  local bufnr = filter.bufnr
931  local ns_id = filter.ns_id
932
933  if not bufnr then
934    if not ns_id then
935      --- @type table<integer,true|table<integer,true>>
936      diagnostic_disabled = (
937        enable
938          -- Enable everything by setting diagnostic_disabled to an empty table.
939          and {}
940        -- Disable everything (including as yet non-existing buffers and namespaces) by setting
941        -- diagnostic_disabled to an empty table and set its metatable to always return true.
942        or setmetatable({}, {
943          __index = function()
944            return true
945          end,
946        })
947      )
948    else
949      local ns = M.get_namespace(ns_id)
950      ns.disabled = not enable
951    end
952  else
953    bufnr = vim._resolve_bufnr(bufnr)
954    if not ns_id then
955      diagnostic_disabled[bufnr] = (not enable) and true or nil
956    else
957      if type(diagnostic_disabled[bufnr]) ~= 'table' then
958        if enable then
959          return
960        end
961        diagnostic_disabled[bufnr] = {}
962      end
963      diagnostic_disabled[bufnr][ns_id] = (not enable) and true or nil
964    end
965  end
966
967  if enable then
968    M.show(ns_id, bufnr)
969  else
970    M.hide(ns_id, bufnr)
971  end
972end
973
974--- Parse a diagnostic from a string.
975---
976--- For example, consider a line of output from a linter:
977---
978--- ```
979--- WARNING filename:27:3: Variable 'foo' does not exist
980--- ```
981---
982--- This can be parsed into a |vim.Diagnostic.Set| structure with:
983---
984--- ```lua
985--- local s = "WARNING filename:27:3: Variable 'foo' does not exist"
986--- local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$"
987--- local groups = { "severity", "lnum", "col", "message" }
988--- vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN })
989--- ```
990---
991---@param str string String to parse diagnostics from.
992---@param pat string Lua pattern with capture groups.
993---@param groups string[] List of fields in a |vim.Diagnostic.Set| structure to
994---                    associate with captures from {pat}.
995---@param severity_map table A table mapping the severity field from {groups}
996---                          with an item from |vim.diagnostic.severity|.
997---@param defaults table? Table of default values for any fields not listed in {groups}.
998---                       When omitted, numeric values default to 0 and "severity" defaults to
999---                       ERROR.
1000---@return vim.Diagnostic.Set?: |vim.Diagnostic.Set| structure or `nil` if {pat} fails to match {str}.
1001function M.match(str, pat, groups, severity_map, defaults)
1002  return M._severity.match(str, pat, groups, severity_map, defaults)
1003end
1004
1005--- Convert a list of diagnostics to a list of quickfix items that can be
1006--- passed to |setqflist()| or |setloclist()|.
1007---
1008---@param diagnostics vim.Diagnostic[]
1009---@return table[] : Quickfix list items |setqflist-what|
1010function M.toqflist(diagnostics)
1011  vim.validate('diagnostics', diagnostics, vim.islist, 'a list of diagnostics')
1012
1013  local list = {} --- @type table[]
1014  for _, diagnostic in ipairs(diagnostics) do
1015    list[#list + 1] = {
1016      bufnr = diagnostic.bufnr,
1017      lnum = diagnostic.lnum + 1,
1018      col = diagnostic.col and (diagnostic.col + 1) or nil,
1019      end_lnum = diagnostic.end_lnum and (diagnostic.end_lnum + 1) or nil,
1020      end_col = diagnostic.end_col and (diagnostic.end_col + 1) or nil,
1021      text = diagnostic.message,
1022      nr = tonumber(diagnostic.code),
1023      type = errlist_type_map[diagnostic.severity] or 'E',
1024      valid = 1,
1025    }
1026  end
1027
1028  table.sort(list, function(a, b)
1029    if a.bufnr == b.bufnr then
1030      if a.lnum == b.lnum then
1031        return a.col < b.col
1032      end
1033
1034      return a.lnum < b.lnum
1035    end
1036
1037    return a.bufnr < b.bufnr
1038  end)
1039
1040  return list
1041end
1042
1043--- Configuration table with the following keys:
1044--- @class vim.diagnostic.fromqflist.Opts
1045--- @inlinedoc
1046---
1047--- When true, items with valid=0 are appended to the previous valid item's
1048--- message with a newline. (default: false)
1049--- @field merge_lines? boolean
1050
1051--- Convert a list of quickfix items to a list of diagnostics.
1052---
1053---@param list vim.fn.getqflist.ret.item[] List of quickfix items from |getqflist()| or |getloclist()|.
1054---@param opts? vim.diagnostic.fromqflist.Opts
1055---@return vim.Diagnostic[]
1056function M.fromqflist(list, opts)
1057  vim.validate('list', list, 'table')
1058
1059  opts = opts or {}
1060  local merge = opts.merge_lines
1061
1062  local diagnostics = {} --- @type vim.Diagnostic[]
1063  local last_diag --- @type vim.Diagnostic?
1064  for _, item in ipairs(list) do
1065    if item.valid == 1 then
1066      local lnum = math.max(0, (item.lnum or 0) - 1)
1067      local col = math.max(0, (item.col or 0) - 1)
1068      local end_lnum = item.end_lnum and item.end_lnum > 0 and (item.end_lnum - 1) or lnum
1069      local end_col = item.end_col and item.end_col > 0 and (item.end_col - 1) or col
1070      local code = item.nr > 0 and item.nr or nil
1071      local item_type = item.type or ''
1072      --- @type vim.Diagnostic
1073      local diag = {
1074        bufnr = item.bufnr,
1075        lnum = lnum,
1076        col = col,
1077        end_lnum = end_lnum,
1078        end_col = end_col,
1079        severity = item_type ~= '' and M.severity[item_type:upper()] or M.severity.ERROR,
1080        message = item.text,
1081        code = code,
1082      }
1083      diagnostics[#diagnostics + 1] = diag
1084      last_diag = diag
1085    elseif merge and last_diag then
1086      last_diag.message = last_diag.message .. '\n' .. item.text
1087    end
1088  end
1089
1090  return diagnostics
1091end
1092
1093--- @type table<vim.diagnostic.Severity, string>
1094local status_hl_map = {
1095  [M.severity.ERROR] = 'DiagnosticSignError',
1096  [M.severity.WARN] = 'DiagnosticSignWarn',
1097  [M.severity.INFO] = 'DiagnosticSignInfo',
1098  [M.severity.HINT] = 'DiagnosticSignHint',
1099}
1100
1101--- @type table<vim.diagnostic.Severity, string>
1102local default_status_signs = {
1103  [M.severity.ERROR] = 'E',
1104  [M.severity.WARN] = 'W',
1105  [M.severity.INFO] = 'I',
1106  [M.severity.HINT] = 'H',
1107}
1108
1109--- Returns formatted string with diagnostics for the current buffer.
1110--- The severities with 0 diagnostics are left out.
1111--- Example `E:2 W:3 I:4 H:5`
1112---
1113--- To customise appearance, see |vim.diagnostic.Opts.Status|.
1114---
1115---@param buf? integer Buffer number to get diagnostics from.
1116---                      Defaults to 0 for the current buffer
1117---
1118---@return string
1119function M.status(buf)
1120  vim.validate('buf', buf, 'number', true)
1121  buf = buf or 0
1122  local config = vim.diagnostic.config().status or {} --- @type vim.diagnostic.Opts.Status
1123  vim.validate('config.format', config.format, 'function', true)
1124
1125  local counts = M.count(buf)
1126  local format = config.format
1127  if type(format) == 'function' then
1128    local result_str = format(counts)
1129    return result_str:len() > 0 and '%#(' .. result_str .. '%#)' or ''
1130  end
1131  local resolved_signs = M._config.get_resolved_options(vim.diagnostic.config(), nil, buf).signs
1132  local signs = (type(resolved_signs) == 'table' and resolved_signs.text) or default_status_signs
1133  return vim
1134    .iter(pairs(counts))
1135    :map(function(level, value)
1136      return ('%%#(%%$%s$%s:%s%%#)'):format(status_hl_map[level], signs[level], value)
1137    end)
1138    :join(' ')
1139end
1140
1141nvim_on('DiagnosticChanged', api.nvim_create_augroup('nvim.diagnostic.status'), {
1142  desc = 'diagnostics component for the statusline',
1143}, function(ev)
1144  if vim.fn.win_gettype(vim.fn.bufwinid(ev.buf)) == '' then
1145    api.nvim__redraw({ buf = ev.buf, statusline = true })
1146  end
1147end)
1148
1149return M