feat: Move 'LspAttach' autocmd boilerplate to dedicated library function

This commit is contained in:
punkfairie 2025-01-02 21:04:51 -08:00
parent 45b1cb99ee
commit 432f7e0595
Signed by: punkfairie
GPG key ID: A509E8F77FB9D696
4 changed files with 121 additions and 120 deletions

View file

@ -1,6 +1,8 @@
---@class lib
local M = {}
M.lsp = require('lib.lsp')
---Find the root of a project based on `vim.g.root_spec`. Defaults to
---`{ '.git' }` if unset.
---@return string?

20
nvim/lua/lib/lsp.lua Normal file
View file

@ -0,0 +1,20 @@
---@class lib.lsp
local M = {}
---Boilerplate to create an autocommand to do something on LspAttach.
---@param callback fun(client:vim.lsp.Client, buffer:number)
---@param name? string
function M.on_attach(callback, name)
return vim.api.nvim_create_autocmd('LspAttach', {
callback = function(args)
local buffer = args.buf ---@type number
local client = vim.lsp.get_client_by_id(args.data.client_id)
if client and (not name or client.name == name) then
return callback(client, buffer)
end
end,
})
end
return M

View file

@ -82,25 +82,13 @@ vim.lsp.config('*', {
vim.lsp.enable({ 'lua-language-server' })
-- Keymaps -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
vim.api.nvim_create_autocmd('LspAttach', {
callback = function(args)
local client = vim.lsp.get_client_by_id(args.data.client_id)
if not client then
return
end
MarleyVim.lsp.on_attach(function(client)
local set = vim.keymap.set
set('n', 'gD', vim.lsp.buf.declaration, { desc = 'declaration' })
set('n', 'gI', vim.lsp.buf.implementation, { desc = 'implementation' })
set(
'n',
'gr',
vim.lsp.buf.references,
{ desc = 'references', nowait = true }
)
set('n', 'gr', vim.lsp.buf.references, { desc = 'references', nowait = true })
set('n', 'gy', vim.lsp.buf.type_definition, { desc = 'type definition' })
@ -179,5 +167,4 @@ vim.api.nvim_create_autocmd('LspAttach', {
Snacks.rename.rename_file()
end, { desc = 'rename file' })
end
end,
})
end)

View file

@ -248,14 +248,7 @@ return {
require('fzf-lua').setup(opts)
-- LSP keybinds.
vim.api.nvim_create_autocmd('LspAttach', {
callback = function(args)
local client = vim.lsp.get_client_by_id(args.data.client_id)
if not client then
return
end
MarleyVim.lsp.on_attach(function(client)
local set = vim.keymap.set
local pickOpts =
@ -288,7 +281,6 @@ return {
{ desc = 'definition' }
)
end
end,
})
end)
end,
}