From 082111fa4eb86a307e489a2e9e3d14c1250b1127 Mon Sep 17 00:00:00 2001 From: jdhao Date: Tue, 13 May 2025 18:15:08 +0200 Subject: [PATCH] update LSP config (#410) --- lua/config/lsp.lua | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/lua/config/lsp.lua b/lua/config/lsp.lua index 2d6c187..41c48c9 100644 --- a/lua/config/lsp.lua +++ b/lua/config/lsp.lua @@ -20,7 +20,45 @@ vim.api.nvim_create_autocmd("LspAttach", { vim.keymap.set(mode, l, r, opts) end - map("n", "gd", vim.lsp.buf.definition, { desc = "go to definition" }) + map("n", "gd", function() + vim.lsp.buf.definition { + on_list = function(options) + -- custom logic to avoid showing multiple definition when you use this style of code: + -- `local M.my_fn_name = function() ... end`. + -- See also post here: https://www.reddit.com/r/neovim/comments/19cvgtp/any_way_to_remove_redundant_definition_in_lua_file/ + + -- vim.print(options.items) + local unique_defs = {} + local def_loc_hash = {} + + -- each item in options.items contain the location info for a definition provided by LSP server + for _, def_location in pairs(options.items) do + -- use filename and line number to uniquelly indentify a definition, + -- we do not expect/want multiple definition in single line! + local hash_key = def_location.filename .. def_location.lnum + + if not def_loc_hash[hash_key] then + def_loc_hash[hash_key] = true + table.insert(unique_defs, def_location) + end + end + + options.items = unique_defs + + -- set the location list + ---@diagnostic disable-next-line: param-type-mismatch + vim.fn.setloclist(0, {}, " ", options) + + -- open the location list when we have more than 1 definitions found, + -- otherwise, jump directly to the definition + if #options.items > 1 then + vim.cmd.lopen() + else + vim.cmd([[silent! lfirst]]) + end + end, + } + end, { desc = "go to definition" }) map("n", "", vim.lsp.buf.definition) map("n", "K", function() vim.lsp.buf.hover { border = "single", max_height = 25, max_width = 120 } @@ -88,6 +126,7 @@ local enabled_lsp_servers = { -- clangd = "clangd", vimls = "vim-language-server", bashls = "bash-language-server", + yamlls = "yaml-language-server", } for server_name, lsp_executable in pairs(enabled_lsp_servers) do