owenrusk.dev

dotfiles

shell, editor, ssh.

git clone https://owenrusk.dev/dotfiles.git

commit 004472059a2716a3f4f42414c3e118b9b956fca7
parent 5beecf9b4b1c038bac47ffebc579717fc7aa1a16
author Owen Rusk <owen@papermothgames.com>
date   2024-07-02 14:30:22 -0500
nvim: ruff server next to pyright, format on save
nvim/lua/owen/lsp.lua+31-11
diff --git a/nvim/lua/owen/lsp.lua b/nvim/lua/owen/lsp.lua
index 3309698..b71a481 100644
--- a/nvim/lua/owen/lsp.lua
+++ b/nvim/lua/owen/lsp.lua
@@ -1,24 +1,37 @@
 -- servers come from the system, not from neovim.
-local function root(buf, markers)
-  local name = vim.api.nvim_buf_get_name(buf)
-  local found = vim.fs.find(markers, { upward = true, path = vim.fs.dirname(name) })[1]
-  return found and vim.fs.dirname(found) or nil
-end
+local servers = {
+  pyright = {
+    cmd = { "pyright-langserver", "--stdio" },
+    markers = { "pyproject.toml", "setup.py", ".git" },
+    settings = { python = { analysis = { typeCheckingMode = "standard" } } },
+  },
+  ruff = {
+    cmd = { "ruff", "server" },
+    markers = { "pyproject.toml", "ruff.toml", ".git" },
+  },
+}
 
 vim.api.nvim_create_autocmd("FileType", {
   pattern = "python",
   callback = function(args)
-    vim.lsp.start({
-      name = "pyright",
-      cmd = { "pyright-langserver", "--stdio" },
-      root_dir = root(args.buf, { "pyproject.toml", "setup.py", ".git" }),
-      settings = { python = { analysis = { typeCheckingMode = "standard" } } },
-    })
+    for name, s in pairs(servers) do
+      vim.lsp.start({
+        name = name,
+        cmd = s.cmd,
+        root_dir = vim.fs.root(args.buf, s.markers),
+        settings = s.settings,
+      })
+    end
   end,
 })
 
 vim.api.nvim_create_autocmd("LspAttach", {
   callback = function(args)
+    local client = vim.lsp.get_client_by_id(args.data.client_id)
+    -- pyright answers hover better
+    if client and client.name == "ruff" then
+      client.server_capabilities.hoverProvider = false
+    end
     local opts = { buffer = args.buf }
     vim.keymap.set("n", "gd", vim.lsp.buf.definition, opts)
     vim.keymap.set("n", "gr", vim.lsp.buf.references, opts)
@@ -28,4 +41,11 @@ vim.api.nvim_create_autocmd("LspAttach", {
   end,
 })
 
+vim.api.nvim_create_autocmd("BufWritePre", {
+  pattern = "*.py",
+  callback = function(args)
+    vim.lsp.buf.format({ bufnr = args.buf, name = "ruff", timeout_ms = 1000 })
+  end,
+})
+
 vim.keymap.set("n", "<leader>d", vim.diagnostic.open_float)