Add auto format on save and auto virtenv py detection

This commit is contained in:
2026-06-29 19:00:42 +05:30
parent b9e8eeaec0
commit c2c98ec83c

View File

@@ -77,6 +77,18 @@ return {
client.server_capabilities.hoverProvider = false
end
-- Format on save if client supports it
if client and client:supports_method("textDocument/formatting") then
local format_grp = vim.api.nvim_create_augroup("LspFormat." .. bufnr, { clear = true })
vim.api.nvim_create_autocmd("BufWritePre", {
group = format_grp,
buffer = bufnr,
callback = function()
vim.lsp.buf.format({ bufnr = bufnr, id = client.id, async = false })
end,
})
end
-- LSP Keymaps
vim.keymap.set("n", "gd", function() vim.lsp.buf.definition() end, { buffer = bufnr, desc = "Go to definition" })
vim.keymap.set("n", "K", function() vim.lsp.buf.hover() end, { buffer = bufnr, desc = "LSP Hover info" })
@@ -94,6 +106,35 @@ return {
-- Configure Pyright (Python LSP) using native Neovim 0.11+ API
vim.lsp.config("pyright", {
capabilities = capabilities,
before_init = function(_, config)
-- 1. Try VIRTUAL_ENV environment variable (if venv is already active in shell)
if vim.env.VIRTUAL_ENV then
config.settings.python.pythonPath = vim.env.VIRTUAL_ENV .. "/bin/python"
return
end
-- 2. Check for .venv in workspace root
local root = vim.uv.cwd()
local local_venv = root .. "/.venv/bin/python"
if vim.fn.executable(local_venv) == 1 then
config.settings.python.pythonPath = local_venv
return
end
-- 3. Check for .venv in the directory of the current file or parent directories
local current_file = vim.api.nvim_buf_get_name(0)
if current_file ~= "" then
local dir = vim.fs.dirname(current_file)
local match = vim.fs.find(".venv", { path = dir, upward = true })[1]
if match then
local match_python = match .. "/bin/python"
if vim.fn.executable(match_python) == 1 then
config.settings.python.pythonPath = match_python
return
end
end
end
end,
settings = {
python = {
analysis = {
@@ -111,17 +152,6 @@ return {
capabilities = capabilities,
})
vim.lsp.enable("ruff")
-- Auto-format on save for Python using ruff
vim.api.nvim_create_autocmd("BufWritePre", {
pattern = "*.py",
callback = function(args)
local clients = vim.lsp.get_clients({ bufnr = args.buf, name = "ruff" })
if #clients > 0 then
vim.lsp.buf.format({ bufnr = args.buf, id = clients[1].id, async = false })
end
end,
})
end,
},
}