diff options
Diffstat (limited to 'runtime/lua/vim/diagnostic.lua')
| -rw-r--r-- | runtime/lua/vim/diagnostic.lua | 1010 |
1 files changed, 692 insertions, 318 deletions
diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua index 99448982b4..d5075d7d3d 100644 --- a/runtime/lua/vim/diagnostic.lua +++ b/runtime/lua/vim/diagnostic.lua @@ -2,15 +2,260 @@ local api, if_nil = vim.api, vim.F.if_nil local M = {} ----@enum DiagnosticSeverity +--- [diagnostic-structure]() +--- +--- Diagnostics use the same indexing as the rest of the Nvim API (i.e. 0-based +--- rows and columns). |api-indexing| +--- @class vim.Diagnostic +--- +--- Buffer number +--- @field bufnr? integer +--- +--- The starting line of the diagnostic (0-indexed) +--- @field lnum integer +--- +--- The final line of the diagnostic (0-indexed) +--- @field end_lnum? integer +--- +--- The starting column of the diagnostic (0-indexed) +--- @field col integer +--- +--- The final column of the diagnostic (0-indexed) +--- @field end_col? integer +--- +--- The severity of the diagnostic |vim.diagnostic.severity| +--- @field severity? vim.diagnostic.Severity +--- +--- The diagnostic text +--- @field message string +--- +--- The source of the diagnostic +--- @field source? string +--- +--- The diagnostic code +--- @field code? string|integer +--- +--- @field _tags? { deprecated: boolean, unnecessary: boolean} +--- +--- Arbitrary data plugins or users can add +--- @field user_data? any arbitrary data plugins can add +--- +--- @field namespace? integer + +--- Each of the configuration options below accepts one of the following: +--- - `false`: Disable this feature +--- - `true`: Enable this feature, use default settings. +--- - `table`: Enable this feature with overrides. Use an empty table to use default values. +--- - `function`: Function with signature (namespace, bufnr) that returns any of the above. +--- @class vim.diagnostic.Opts +--- +--- Use underline for diagnostics. +--- (default: `true`) +--- @field underline? boolean|vim.diagnostic.Opts.Underline|fun(namespace: integer, bufnr:integer): vim.diagnostic.Opts.Underline +--- +--- Use virtual text for diagnostics. If multiple diagnostics are set for a +--- namespace, one prefix per diagnostic + the last diagnostic message are +--- shown. +--- (default: `true`) +--- @field virtual_text? boolean|vim.diagnostic.Opts.VirtualText|fun(namespace: integer, bufnr:integer): vim.diagnostic.Opts.VirtualText +--- +--- Use signs for diagnostics |diagnostic-signs|. +--- (default: `true`) +--- @field signs? boolean|vim.diagnostic.Opts.Signs|fun(namespace: integer, bufnr:integer): vim.diagnostic.Opts.Signs +--- +--- Options for floating windows. See |vim.diagnostic.Opts.Float|. +--- @field float? boolean|vim.diagnostic.Opts.Float|fun(namespace: integer, bufnr:integer): vim.diagnostic.Opts.Float +--- +--- Update diagnostics in Insert mode +--- (if `false`, diagnostics are updated on |InsertLeave|) +--- (default: `false`) +--- @field update_in_insert? boolean +--- +--- Sort diagnostics by severity. This affects the order in which signs and +--- virtual text are displayed. When true, higher severities are displayed +--- before lower severities (e.g. ERROR is displayed before WARN). +--- Options: +--- - {reverse}? (boolean) Reverse sort order +--- (default: `false) +--- @field severity_sort? boolean|{reverse?:boolean} + +--- @class (private) vim.diagnostic.OptsResolved +--- @field float vim.diagnostic.Opts.Float +--- @field update_in_insert boolean +--- @field underline vim.diagnostic.Opts.Underline +--- @field virtual_text vim.diagnostic.Opts.VirtualText +--- @field signs vim.diagnostic.Opts.Signs +--- @field severity_sort {reverse?:boolean} + +--- @class vim.diagnostic.Opts.Float +--- +--- Buffer number to show diagnostics from. +--- (default: current buffer) +--- @field bufnr? integer +--- +--- Limit diagnostics to the given namespace +--- @field namespace? integer +--- +--- Show diagnostics from the whole buffer (`buffer"`, the current cursor line +--- (`line`), or the current cursor position (`cursor`). Shorthand versions +--- are also accepted (`c` for `cursor`, `l` for `line`, `b` for `buffer`). +--- (default: `line`) +--- @field scope? 'line'|'buffer'|'cursor'|'c'|'l'|'b' +--- +--- If {scope} is "line" or "cursor", use this position rather than the cursor +--- position. If a number, interpreted as a line number; otherwise, a +--- (row, col) tuple. +--- @field pos? integer|{[1]:integer,[2]:integer} +--- +--- Sort diagnostics by severity. +--- Overrides the setting from |vim.diagnostic.config()|. +--- (default: `false`) +--- @field severity_sort? boolean|{reverse?:boolean} +--- +--- See |diagnostic-severity|. +--- Overrides the setting from |vim.diagnostic.config()|. +--- @field severity? vim.diagnostic.SeverityFilter +--- +--- String to use as the header for the floating window. If a table, it is +--- interpreted as a `[text, hl_group]` tuple. +--- Overrides the setting from |vim.diagnostic.config()|. +--- @field header? string|{[1]:string,[2]:any} +--- +--- Include the diagnostic source in the message. +--- Use "if_many" to only show sources if there is more than one source of +--- diagnostics in the buffer. Otherwise, any truthy value means to always show +--- the diagnostic source. +--- Overrides the setting from |vim.diagnostic.config()|. +--- @field source? boolean|'if_many' +--- +--- A function that takes a diagnostic as input and returns a string. +--- The return value is the text used to display the diagnostic. +--- Overrides the setting from |vim.diagnostic.config()|. +--- @field format? fun(diagnostic:vim.Diagnostic): string +--- +--- Prefix each diagnostic in the floating window: +--- - If a `function`, {i} is the index of the diagnostic being evaluated and +--- {total} is the total number of diagnostics displayed in the window. The +--- function should return a `string` which is prepended to each diagnostic +--- in the window as well as an (optional) highlight group which will be +--- used to highlight the prefix. +--- - If a `table`, it is interpreted as a `[text, hl_group]` tuple as +--- in |nvim_echo()| +--- - If a `string`, it is prepended to each diagnostic in the window with no +--- highlight. +--- Overrides the setting from |vim.diagnostic.config()|. +--- @field prefix? string|table|(fun(diagnostic:vim.Diagnostic,i:integer,total:integer): string, string) +--- +--- Same as {prefix}, but appends the text to the diagnostic instead of +--- prepending it. +--- Overrides the setting from |vim.diagnostic.config()|. +--- @field suffix? string|table|(fun(diagnostic:vim.Diagnostic,i:integer,total:integer): string, string) +--- +--- @field focus_id? string + +--- @class vim.diagnostic.Opts.Underline +--- +--- Only underline diagnostics matching the given +--- severity |diagnostic-severity|. +--- @field severity? vim.diagnostic.SeverityFilter + +--- @class vim.diagnostic.Opts.VirtualText +--- +--- Only show virtual text for diagnostics matching the given +--- severity |diagnostic-severity| +--- @field severity? vim.diagnostic.SeverityFilter +--- +--- Include the diagnostic source in virtual text. Use `'if_many'` to only +--- show sources if there is more than one diagnostic source in the buffer. +--- Otherwise, any truthy value means to always show the diagnostic source. +--- @field source? boolean|"if_many" +--- +--- Amount of empty spaces inserted at the beginning of the virtual text. +--- @field spacing? integer +--- +--- Prepend diagnostic message with prefix. If a `function`, {i} is the index +--- of the diagnostic being evaluated, and {total} is the total number of +--- diagnostics for the line. This can be used to render diagnostic symbols +--- or error codes. +--- @field prefix? string|(fun(diagnostic:vim.Diagnostic,i:integer,total:integer): string) +--- +--- Append diagnostic message with suffix. +--- This can be used to render an LSP diagnostic error code. +--- @field suffix? string|(fun(diagnostic:vim.Diagnostic): string) +--- +--- The return value is the text used to display the diagnostic. Example: +--- ```lua +--- function(diagnostic) +--- if diagnostic.severity == vim.diagnostic.severity.ERROR then +--- return string.format("E: %s", diagnostic.message) +--- end +--- return diagnostic.message +--- end +--- ``` +--- @field format? fun(diagnostic:vim.Diagnostic): string +--- +--- See |nvim_buf_set_extmark()|. +--- @field hl_mode? 'replace'|'combine'|'blend' +--- +--- See |nvim_buf_set_extmark()|. +--- @field virt_text? {[1]:string,[2]:any}[] +--- +--- See |nvim_buf_set_extmark()|. +--- @field virt_text_pos? 'eol'|'overlay'|'right_align'|'inline' +--- +--- See |nvim_buf_set_extmark()|. +--- @field virt_text_win_col? integer +--- +--- See |nvim_buf_set_extmark()|. +--- @field virt_text_hide? boolean + +--- @class vim.diagnostic.Opts.Signs +--- +--- Only show virtual text for diagnostics matching the given +--- severity |diagnostic-severity| +--- @field severity? vim.diagnostic.SeverityFilter +--- +--- Base priority to use for signs. When {severity_sort} is used, the priority +--- of a sign is adjusted based on its severity. +--- Otherwise, all signs use the same priority. +--- (default: `10`) +--- @field priority? integer +--- +--- A table mapping |diagnostic-severity| to the sign text to display in the +--- sign column. The default is to use `"E"`, `"W"`, `"I"`, and `"H"` for errors, +--- warnings, information, and hints, respectively. Example: +--- ```lua +--- vim.diagnostic.config({ +--- signs = { text = { [vim.diagnostic.severity.ERROR] = 'E', ... } } +--- }) +--- ``` +--- @field text? table<vim.diagnostic.Severity,string> +--- +--- A table mapping |diagnostic-severity| to the highlight group used for the +--- line number where the sign is placed. +--- @field numhl? table<vim.diagnostic.Severity,string> +--- +--- A table mapping |diagnostic-severity| to the highlight group used for the +--- whole line the sign is placed in. +--- @field linehl? table<vim.diagnostic.Severity,string> + +--- @nodoc +--- @enum vim.diagnostic.Severity M.severity = { ERROR = 1, WARN = 2, INFO = 3, HINT = 4, + [1] = 'ERROR', + [2] = 'WARN', + [3] = 'INFO', + [4] = 'HINT', } -vim.tbl_add_reverse_lookup(M.severity) +--- @alias vim.diagnostic.SeverityInt 1|2|3|4 + +--- See |diagnostic-severity| and |vim.diagnostic.get()| +--- @alias vim.diagnostic.SeverityFilter vim.diagnostic.Severity|vim.diagnostic.Severity[]|{min:vim.diagnostic.Severity,max:vim.diagnostic.Severity} -- Mappings from qflist/loclist error types to severities M.severity.E = M.severity.ERROR @@ -18,6 +263,7 @@ M.severity.W = M.severity.WARN M.severity.I = M.severity.INFO M.severity.N = M.severity.HINT +--- @type vim.diagnostic.Opts local global_diagnostic_options = { signs = true, underline = true, @@ -27,6 +273,12 @@ local global_diagnostic_options = { severity_sort = false, } +--- @class (private) vim.diagnostic.Handler +--- @field show? fun(namespace: integer, bufnr: integer, diagnostics: vim.Diagnostic[], opts?: vim.diagnostic.OptsResolved) +--- @field hide? fun(namespace:integer, bufnr:integer) + +--- @nodoc +--- @type table<string,vim.diagnostic.Handler> M.handlers = setmetatable({}, { __newindex = function(t, name, handler) vim.validate({ handler = { handler, 't' } }) @@ -39,6 +291,9 @@ M.handlers = setmetatable({}, { -- Metatable that automatically creates an empty table when assigning to a missing key local bufnr_and_namespace_cacher_mt = { + --- @param t table<integer,table> + --- @param bufnr integer + --- @return table __index = function(t, bufnr) assert(bufnr > 0, 'Invalid buffer number') t[bufnr] = {} @@ -46,10 +301,13 @@ local bufnr_and_namespace_cacher_mt = { end, } -local diagnostic_cache +-- bufnr -> ns -> Diagnostic[] +local diagnostic_cache = {} --- @type table<integer,table<integer,vim.Diagnostic[]>> do local group = api.nvim_create_augroup('DiagnosticBufWipeout', {}) - diagnostic_cache = setmetatable({}, { + setmetatable(diagnostic_cache, { + --- @param t table<integer,vim.Diagnostic[]> + --- @param bufnr integer __index = function(t, bufnr) assert(bufnr > 0, 'Invalid buffer number') api.nvim_create_autocmd('BufWipeout', { @@ -65,61 +323,93 @@ do }) end +--- @class (private) vim.diagnostic._extmark +--- @field [1] integer id +--- @field [2] integer start +--- @field [3] integer end +--- @field [4] table details + +--- @type table<integer,table<integer,vim.diagnostic._extmark[]>> local diagnostic_cache_extmarks = setmetatable({}, bufnr_and_namespace_cacher_mt) + +--- @type table<integer,true> local diagnostic_attached_buffers = {} + +--- @type table<integer,true|table<integer,true>> local diagnostic_disabled = {} + +--- @type table<integer,table<integer,table>> local bufs_waiting_to_update = setmetatable({}, bufnr_and_namespace_cacher_mt) +--- @class vim.diagnostic.NS +--- @field name string +--- @field opts vim.diagnostic.Opts +--- @field user_data table +--- @field disabled? boolean + +--- @type table<integer,vim.diagnostic.NS> local all_namespaces = {} +---@param severity string|vim.diagnostic.Severity +---@return vim.diagnostic.Severity? local function to_severity(severity) if type(severity) == 'string' then - return assert( - M.severity[string.upper(severity)], - string.format('Invalid severity: %s', severity) - ) + assert(M.severity[string.upper(severity)], string.format('Invalid severity: %s', severity)) + return M.severity[string.upper(severity)] end return severity end +--- @param severity vim.diagnostic.SeverityFilter +--- @param diagnostics vim.Diagnostic[] +--- @return vim.Diagnostic[] local function filter_by_severity(severity, diagnostics) if not severity then return diagnostics end if type(severity) ~= 'table' then - severity = to_severity(severity) + severity = assert(to_severity(severity)) + --- @param t vim.Diagnostic return vim.tbl_filter(function(t) return t.severity == severity end, diagnostics) end if severity.min or severity.max then + --- @cast severity {min:vim.diagnostic.Severity,max:vim.diagnostic.Severity} local min_severity = to_severity(severity.min) or M.severity.HINT local max_severity = to_severity(severity.max) or M.severity.ERROR + --- @param t vim.Diagnostic return vim.tbl_filter(function(t) return t.severity <= min_severity and t.severity >= max_severity end, diagnostics) end - local severities = {} + --- @cast severity vim.diagnostic.Severity[] + + local severities = {} --- @type table<vim.diagnostic.Severity,true> for _, s in ipairs(severity) do - severities[to_severity(s)] = true + severities[assert(to_severity(s))] = true end + --- @param t vim.Diagnostic return vim.tbl_filter(function(t) return severities[t.severity] end, diagnostics) end +--- @param bufnr integer +--- @return integer local function count_sources(bufnr) - local seen = {} + local seen = {} --- @type table<string,true> local count = 0 for _, namespace_diagnostics in pairs(diagnostic_cache[bufnr]) do for _, diagnostic in ipairs(namespace_diagnostics) do - if diagnostic.source and not seen[diagnostic.source] then - seen[diagnostic.source] = true + local source = diagnostic.source + if source and not seen[source] then + seen[source] = true count = count + 1 end end @@ -127,51 +417,65 @@ local function count_sources(bufnr) return count end +--- @param diagnostics vim.Diagnostic[] +--- @return vim.Diagnostic[] local function prefix_source(diagnostics) + --- @param d vim.Diagnostic return vim.tbl_map(function(d) if not d.source then return d end - local t = vim.deepcopy(d) + local t = vim.deepcopy(d, true) t.message = string.format('%s: %s', d.source, d.message) return t end, diagnostics) end +--- @param diagnostics vim.Diagnostic[] +--- @return vim.Diagnostic[] local function reformat_diagnostics(format, diagnostics) vim.validate({ format = { format, 'f' }, diagnostics = { diagnostics, 't' }, }) - local formatted = vim.deepcopy(diagnostics) + local formatted = vim.deepcopy(diagnostics, true) for _, diagnostic in ipairs(formatted) do diagnostic.message = format(diagnostic) end return formatted end +--- @param option string +--- @param namespace integer? +--- @return table local function enabled_value(option, namespace) local ns = namespace and M.get_namespace(namespace) or {} if ns.opts and type(ns.opts[option]) == 'table' then return ns.opts[option] end - if type(global_diagnostic_options[option]) == 'table' then - return global_diagnostic_options[option] + local global_opt = global_diagnostic_options[option] + if type(global_opt) == 'table' then + return global_opt end return {} end +--- @param option string +--- @param value any? +--- @param namespace integer? +--- @param bufnr integer +--- @return any local function resolve_optional_value(option, value, namespace, bufnr) if not value then return false elseif value == true then return enabled_value(option, namespace) elseif type(value) == 'function' then - local val = value(namespace, bufnr) + local val = value(namespace, bufnr) --- @type any if val == true then return enabled_value(option, namespace) else @@ -179,15 +483,18 @@ local function resolve_optional_value(option, value, namespace, bufnr) end elseif type(value) == 'table' then return value - else - error('Unexpected option type: ' .. vim.inspect(value)) end + error('Unexpected option type: ' .. vim.inspect(value)) end +--- @param opts vim.diagnostic.Opts? +--- @param namespace integer? +--- @param bufnr integer +--- @return vim.diagnostic.OptsResolved local function get_resolved_options(opts, namespace, bufnr) local ns = namespace and M.get_namespace(namespace) or {} -- Do not use tbl_deep_extend so that an empty table can be used to reset to default values - local resolved = vim.tbl_extend('keep', opts or {}, ns.opts or {}, global_diagnostic_options) + local resolved = vim.tbl_extend('keep', opts or {}, ns.opts or {}, global_diagnostic_options) --- @type table<string,any> for k in pairs(global_diagnostic_options) do if resolved[k] ~= nil then resolved[k] = resolve_optional_value(k, resolved[k], namespace, bufnr) @@ -204,9 +511,11 @@ local diagnostic_severities = { [M.severity.HINT] = { ctermfg = 7, guifg = 'LightGrey' }, } --- Make a map from DiagnosticSeverity -> Highlight Name +--- Make a map from vim.diagnostic.Severity -> Highlight Name +--- @param base_name string +--- @return table<vim.diagnostic.SeverityInt,string> local function make_highlight_map(base_name) - local result = {} + local result = {} --- @type table<vim.diagnostic.SeverityInt,string> for k in pairs(diagnostic_severities) do local name = M.severity[k] name = name:sub(1, 1) .. name:sub(2):lower() @@ -216,35 +525,13 @@ local function make_highlight_map(base_name) return result end +-- TODO(lewis6991): these highlight maps can only be indexed with an integer, however there usage +-- implies they can be indexed with any vim.diagnostic.Severity local virtual_text_highlight_map = make_highlight_map('VirtualText') local underline_highlight_map = make_highlight_map('Underline') local floating_highlight_map = make_highlight_map('Floating') local sign_highlight_map = make_highlight_map('Sign') ----@private -local define_default_signs = (function() - local signs_defined = false - return function() - if signs_defined then - return - end - - for severity, sign_hl_name in pairs(sign_highlight_map) do - if vim.tbl_isempty(vim.fn.sign_getdefined(sign_hl_name)) then - local severity_name = M.severity[severity] - vim.fn.sign_define(sign_hl_name, { - text = (severity_name or 'U'):sub(1, 1), - texthl = sign_hl_name, - linehl = '', - numhl = '', - }) - end - end - - signs_defined = true - end -end)() - local function get_bufnr(bufnr) if not bufnr or bufnr == 0 then return api.nvim_get_current_buf() @@ -252,12 +539,14 @@ local function get_bufnr(bufnr) return bufnr end +--- @param diagnostics vim.Diagnostic[] +--- @return table<integer,vim.Diagnostic[]> local function diagnostic_lines(diagnostics) if not diagnostics then return {} end - local diagnostics_by_line = {} + local diagnostics_by_line = {} --- @type table<integer,vim.Diagnostic[]> for _, diagnostic in ipairs(diagnostics) do local line_diagnostics = diagnostics_by_line[diagnostic.lnum] if not line_diagnostics then @@ -269,6 +558,9 @@ local function diagnostic_lines(diagnostics) return diagnostics_by_line end +--- @param namespace integer +--- @param bufnr integer +--- @param diagnostics vim.Diagnostic[] local function set_diagnostic_cache(namespace, bufnr, diagnostics) for _, diagnostic in ipairs(diagnostics) do assert(diagnostic.lnum, 'Diagnostic line number is required') @@ -283,10 +575,12 @@ local function set_diagnostic_cache(namespace, bufnr, diagnostics) diagnostic_cache[bufnr][namespace] = diagnostics end +--- @param bufnr integer +--- @param last integer local function restore_extmarks(bufnr, last) for ns, extmarks in pairs(diagnostic_cache_extmarks[bufnr]) do local extmarks_current = api.nvim_buf_get_extmarks(bufnr, ns, 0, -1, { details = true }) - local found = {} + local found = {} --- @type table<integer,true> for _, extmark in ipairs(extmarks_current) do -- nvim_buf_set_lines will move any extmark to the line after the last -- nvim_buf_set_text will move any extmark to the last line @@ -304,6 +598,8 @@ local function restore_extmarks(bufnr, last) end end +--- @param namespace integer +--- @param bufnr? integer local function save_extmarks(namespace, bufnr) bufnr = get_bufnr(bufnr) if not diagnostic_attached_buffers[bufnr] then @@ -321,6 +617,7 @@ local function save_extmarks(namespace, bufnr) api.nvim_buf_get_extmarks(bufnr, namespace, 0, -1, { details = true }) end +--- @type table<string,true> local registered_autocmds = {} local function make_augroup_key(namespace, bufnr) @@ -328,6 +625,8 @@ local function make_augroup_key(namespace, bufnr) return string.format('DiagnosticInsertLeave:%s:%s', bufnr, ns.name) end +--- @param namespace integer +--- @param bufnr integer local function execute_scheduled_display(namespace, bufnr) local args = bufs_waiting_to_update[bufnr][namespace] if not args then @@ -343,6 +642,9 @@ end --- Table of autocmd events to fire the update for displaying new diagnostic information local insert_leave_auto_cmds = { 'InsertLeave', 'CursorHoldI' } +--- @param namespace integer +--- @param bufnr integer +--- @param args any[] local function schedule_display(namespace, bufnr, args) bufs_waiting_to_update[bufnr][namespace] = args @@ -361,6 +663,8 @@ local function schedule_display(namespace, bufnr, args) end end +--- @param namespace integer +--- @param bufnr integer local function clear_scheduled_display(namespace, bufnr) local key = make_augroup_key(namespace, bufnr) @@ -370,6 +674,10 @@ local function clear_scheduled_display(namespace, bufnr) end end +--- @param bufnr integer? +--- @param opts vim.diagnostic.GetOpts? +--- @param clamp boolean +--- @return vim.Diagnostic[] local function get_diagnostics(bufnr, opts, clamp) opts = opts or {} @@ -377,16 +685,21 @@ local function get_diagnostics(bufnr, opts, clamp) local diagnostics = {} -- Memoized results of buf_line_count per bufnr + --- @type table<integer,integer> local buf_line_count = setmetatable({}, { + --- @param t table<integer,integer> + --- @param k integer + --- @return integer __index = function(t, k) t[k] = api.nvim_buf_line_count(k) return rawget(t, k) end, }) + ---@param b integer + ---@param d vim.Diagnostic local function add(b, d) if not opts.lnum or d.lnum == opts.lnum then - d = vim.deepcopy(d) if clamp and api.nvim_buf_is_loaded(b) then local line_count = buf_line_count[b] - 1 if @@ -397,8 +710,9 @@ local function get_diagnostics(bufnr, opts, clamp) or d.col < 0 or d.end_col < 0 then + d = vim.deepcopy(d, true) d.lnum = math.max(math.min(d.lnum, line_count), 0) - d.end_lnum = math.max(math.min(d.end_lnum, line_count), 0) + d.end_lnum = math.max(math.min(assert(d.end_lnum), line_count), 0) d.col = math.max(d.col, 0) d.end_col = math.max(d.end_col, 0) end @@ -407,6 +721,8 @@ local function get_diagnostics(bufnr, opts, clamp) end end + --- @param buf integer + --- @param diags vim.Diagnostic[] local function add_all_diags(buf, diags) for _, diagnostic in pairs(diags) do add(buf, diagnostic) @@ -440,18 +756,20 @@ local function get_diagnostics(bufnr, opts, clamp) return diagnostics end +--- @param loclist boolean +--- @param opts vim.diagnostic.setqflist.Opts|vim.diagnostic.setloclist.Opts? local function set_list(loclist, opts) opts = opts or {} - local open = vim.F.if_nil(opts.open, true) + local open = if_nil(opts.open, true) local title = opts.title or 'Diagnostics' local winnr = opts.winnr or 0 - local bufnr + local bufnr --- @type integer? if loclist then bufnr = api.nvim_win_get_buf(winnr) end -- Don't clamp line numbers since the quickfix list can already handle line -- numbers beyond the end of the buffer - local diagnostics = get_diagnostics(bufnr, opts, false) + local diagnostics = get_diagnostics(bufnr, opts --[[@as vim.diagnostic.GetOpts]], false) local items = M.toqflist(diagnostics) if loclist then vim.fn.setloclist(winnr, {}, ' ', { title = title, items = items }) @@ -463,10 +781,16 @@ local function set_list(loclist, opts) end end +--- @param position {[1]: integer, [2]: integer} +--- @param search_forward boolean +--- @param bufnr integer +--- @param opts vim.diagnostic.GotoOpts +--- @param namespace integer +--- @return vim.Diagnostic? local function next_diagnostic(position, search_forward, bufnr, opts, namespace) position[1] = position[1] - 1 bufnr = get_bufnr(bufnr) - local wrap = vim.F.if_nil(opts.wrap, true) + local wrap = if_nil(opts.wrap, true) local line_count = api.nvim_buf_line_count(bufnr) local diagnostics = get_diagnostics(bufnr, vim.tbl_extend('keep', opts, { namespace = namespace }), true) @@ -483,6 +807,7 @@ local function next_diagnostic(position, search_forward, bufnr, opts, namespace) end if line_diagnostics[lnum] and not vim.tbl_isempty(line_diagnostics[lnum]) then local line_length = #api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1] + --- @type function, function local sort_diagnostics, is_next if search_forward then sort_diagnostics = function(a, b) @@ -501,7 +826,9 @@ local function next_diagnostic(position, search_forward, bufnr, opts, namespace) end table.sort(line_diagnostics[lnum], sort_diagnostics) if i == 0 then - for _, v in pairs(line_diagnostics[lnum]) do + for _, v in + pairs(line_diagnostics[lnum] --[[@as table<string,any>]]) + do if is_next(v) then return v end @@ -513,10 +840,12 @@ local function next_diagnostic(position, search_forward, bufnr, opts, namespace) end end +--- @param opts vim.diagnostic.GotoOpts? +--- @param pos {[1]:integer,[2]:integer}|false local function diagnostic_move_pos(opts, pos) opts = opts or {} - local float = vim.F.if_nil(opts.float, true) + local float = if_nil(opts.float, true) local win_id = opts.win_id or api.nvim_get_current_win() if not pos then @@ -566,76 +895,18 @@ end --- --- then virtual text will not be enabled for those diagnostics. --- ----@note Each of the configuration options below accepts one of the following: ---- - `false`: Disable this feature ---- - `true`: Enable this feature, use default settings. ---- - `table`: Enable this feature with overrides. Use an empty table to use default values. ---- - `function`: Function with signature (namespace, bufnr) that returns any of the above. ---- ----@param opts table|nil When omitted or "nil", retrieve the current configuration. Otherwise, a ---- configuration table with the following keys: ---- - underline: (default true) Use underline for diagnostics. Options: ---- * severity: Only underline diagnostics matching the given ---- severity |diagnostic-severity| ---- - virtual_text: (default true) Use virtual text for diagnostics. If multiple diagnostics ---- are set for a namespace, one prefix per diagnostic + the last diagnostic ---- message are shown. In addition to the options listed below, the ---- "virt_text" options of |nvim_buf_set_extmark()| may also be used here ---- (e.g. "virt_text_pos" and "hl_mode"). ---- Options: ---- * severity: Only show virtual text for diagnostics matching the given ---- severity |diagnostic-severity| ---- * source: (boolean or string) Include the diagnostic source in virtual ---- text. Use "if_many" to only show sources if there is more than ---- one diagnostic source in the buffer. Otherwise, any truthy value ---- means to always show the diagnostic source. ---- * spacing: (number) Amount of empty spaces inserted at the beginning ---- of the virtual text. ---- * prefix: (string or function) prepend diagnostic message with prefix. ---- If a function, it must have the signature (diagnostic, i, total) ---- -> string, where {diagnostic} is of type |diagnostic-structure|, ---- {i} is the index of the diagnostic being evaluated, and {total} ---- is the total number of diagnostics for the line. This can be ---- used to render diagnostic symbols or error codes. ---- * suffix: (string or function) Append diagnostic message with suffix. ---- If a function, it must have the signature (diagnostic) -> ---- string, where {diagnostic} is of type |diagnostic-structure|. ---- This can be used to render an LSP diagnostic error code. ---- * format: (function) A function that takes a diagnostic as input and ---- returns a string. The return value is the text used to display ---- the diagnostic. Example: ---- <pre>lua ---- function(diagnostic) ---- if diagnostic.severity == vim.diagnostic.severity.ERROR then ---- return string.format("E: %s", diagnostic.message) ---- end ---- return diagnostic.message ---- end ---- </pre> ---- - signs: (default true) Use signs for diagnostics. Options: ---- * severity: Only show signs for diagnostics matching the given ---- severity |diagnostic-severity| ---- * priority: (number, default 10) Base priority to use for signs. When ---- {severity_sort} is used, the priority of a sign is adjusted based on ---- its severity. Otherwise, all signs use the same priority. ---- - float: Options for floating windows. See |vim.diagnostic.open_float()|. ---- - update_in_insert: (default false) Update diagnostics in Insert mode (if false, ---- diagnostics are updated on InsertLeave) ---- - severity_sort: (default false) Sort diagnostics by severity. This affects the order in ---- which signs and virtual text are displayed. When true, higher severities ---- are displayed before lower severities (e.g. ERROR is displayed before WARN). ---- Options: ---- * reverse: (boolean) Reverse sort order ---- ----@param namespace integer|nil Update the options for the given namespace. When omitted, update the ---- global diagnostic options. +---@param opts vim.diagnostic.Opts? When omitted or `nil`, retrieve the current +--- configuration. Otherwise, a configuration table (see |vim.diagnostic.Opts|). +---@param namespace integer? Update the options for the given namespace. +--- When omitted, update the global diagnostic options. +---@return vim.diagnostic.Opts? : Current diagnostic config if {opts} is omitted. function M.config(opts, namespace) vim.validate({ opts = { opts, 't', true }, namespace = { namespace, 'n', true }, }) - local t + local t --- @type vim.diagnostic.Opts if namespace then local ns = M.get_namespace(namespace) t = ns.opts @@ -645,10 +916,12 @@ function M.config(opts, namespace) if not opts then -- Return current config - return vim.deepcopy(t) + return vim.deepcopy(t, true) end - for k, v in pairs(opts) do + for k, v in + pairs(opts --[[@as table<any,any>]]) + do t[k] = v end @@ -671,8 +944,8 @@ end --- ---@param namespace integer The diagnostic namespace ---@param bufnr integer Buffer number ----@param diagnostics table A list of diagnostic items |diagnostic-structure| ----@param opts table|nil Display options to pass to |vim.diagnostic.show()| +---@param diagnostics vim.Diagnostic[] +---@param opts? vim.diagnostic.Opts Display options to pass to |vim.diagnostic.show()| function M.set(namespace, bufnr, diagnostics, opts) vim.validate({ namespace = { namespace, 'n' }, @@ -698,6 +971,7 @@ function M.set(namespace, bufnr, diagnostics, opts) api.nvim_exec_autocmds('DiagnosticChanged', { modeline = false, buffer = bufnr, + -- TODO(lewis6991): should this be deepcopy()'d like they are in vim.diagnostic.get() data = { diagnostics = diagnostics }, }) end @@ -705,11 +979,11 @@ end --- Get namespace metadata. --- ---@param namespace integer Diagnostic namespace ----@return table Namespace metadata +---@return vim.diagnostic.NS : Namespace metadata function M.get_namespace(namespace) vim.validate({ namespace = { namespace, 'n' } }) if not all_namespaces[namespace] then - local name + local name --- @type string? for k, v in pairs(api.nvim_get_namespaces()) do if namespace == v then name = k @@ -730,48 +1004,56 @@ end --- Get current diagnostic namespaces. --- ----@return table A list of active diagnostic namespaces |vim.diagnostic|. +---@return table<integer,vim.diagnostic.NS> : List of active diagnostic namespaces |vim.diagnostic|. function M.get_namespaces() - return vim.deepcopy(all_namespaces) + return vim.deepcopy(all_namespaces, true) end ----@class Diagnostic ----@field bufnr? integer ----@field lnum integer 0-indexed ----@field end_lnum? integer 0-indexed ----@field col integer 0-indexed ----@field end_col? integer 0-indexed ----@field severity? DiagnosticSeverity ----@field message string ----@field source? string ----@field code? string ----@field _tags? { deprecated: boolean, unnecessary: boolean} ----@field user_data? any arbitrary data plugins can add - --- Get current diagnostics. --- ---- Modifying diagnostics in the returned table has no effect. To set diagnostics in a buffer, use |vim.diagnostic.set()|. +--- Modifying diagnostics in the returned table has no effect. +--- To set diagnostics in a buffer, use |vim.diagnostic.set()|. --- ----@param bufnr integer|nil Buffer number to get diagnostics from. Use 0 for ---- current buffer or nil for all buffers. ----@param opts table|nil A table with the following keys: ---- - namespace: (number) Limit diagnostics to the given namespace. ---- - lnum: (number) Limit diagnostics to the given line number. ---- - severity: See |diagnostic-severity|. ----@return Diagnostic[] table A list of diagnostic items |diagnostic-structure|. Keys `bufnr`, `end_lnum`, `end_col`, and `severity` are guaranteed to be present. +---@param bufnr integer? Buffer number to get diagnostics from. Use 0 for +--- current buffer or nil for all buffers. +---@param opts? vim.diagnostic.GetOpts +---@return vim.Diagnostic[] : Fields `bufnr`, `end_lnum`, `end_col`, and `severity` +--- are guaranteed to be present. function M.get(bufnr, opts) vim.validate({ bufnr = { bufnr, 'n', true }, opts = { opts, 't', true }, }) - return get_diagnostics(bufnr, opts, false) + return vim.deepcopy(get_diagnostics(bufnr, opts, false), true) +end + +--- Get current diagnostics count. +--- +---@param bufnr? integer Buffer number to get diagnostics from. Use 0 for +--- current buffer or nil for all buffers.< |