Skip to content

Commit c4e1914

Browse files
authored
fix(lsp): centralize LspOrganize command and add safety checks
Moves the `LspOrganize` command from a buffer-local definition within the `tsserver` on_attach function to a single, global user command. This refactoring prevents command duplication and potential errors. The new global command is now guarded by a check to ensure a `tsserver` client is attached to the current buffer before executing, making it safe to call from any context. The redundant local command definition has been removed.
1 parent 590e7f5 commit c4e1914

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

lua/plugins/nvim-lspconfig.lua

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -225,21 +225,31 @@ return {
225225
end
226226

227227
if vim.fn.executable("typescript-language-server") == 1 then
228+
-- Create the LspOrganize command once globally to avoid duplication warnings
229+
-- Use force = true to allow recreation on config reload
230+
vim.api.nvim_create_user_command("LspOrganize", function()
231+
-- Check if a TypeScript LSP client is attached to the current buffer
232+
local clients = vim.lsp.get_clients({ bufnr = 0, name = "ts_ls" })
233+
if #clients == 0 then
234+
vim.notify("No TypeScript LSP client attached to current buffer", vim.log.levels.WARN)
235+
return
236+
end
237+
238+
vim.lsp.buf.execute_command({
239+
command = "_typescript.organizeImports",
240+
arguments = { vim.api.nvim_buf_get_name(0) },
241+
title = "",
242+
})
243+
end, { desc = "Organize Imports", force = true })
244+
228245
lspconfig.ts_ls.setup({
229-
on_attach = function(client, bufnp)
230-
on_attach(client, bufnp)
246+
on_attach = function(client, bufnr)
247+
on_attach(client, bufnr)
231248

232249
client.server_capabilities.documentFormattingProvider = false
233250
client.server_capabilities.documentRangeFormattingProvider = false
234-
local keymap_opts = { buffer = bufnp, noremap = true, silent = true }
251+
local keymap_opts = { buffer = bufnr, noremap = true, silent = true }
235252
vim.keymap.set("n", "<leader>xo", "<cmd>LspOrganize<CR>", keymap_opts)
236-
vim.api.nvim_create_user_command("LspOrganize", function()
237-
vim.lsp.buf.execute_command({
238-
command = "_typescript.organizeImports",
239-
arguments = { vim.api.nvim_buf_get_name(0) },
240-
title = "",
241-
})
242-
end, { desc = "Organize Imports" })
243253
end,
244254
capabilities = caps,
245255
filetypes = {

0 commit comments

Comments
 (0)