Open4

masonで入れたlsp (pyright)にPoetryを対応させる

pluckpluck

今の所はこんな感じでPoetry対応できている。

[[plugins]]
repo = "williamboman/mason.nvim"
hook_add = '''
lua <<EOF
  require("mason").setup()
EOF
'''
[[plugins]]
repo = "williamboman/mason-lspconfig.nvim"
depends = [
  "neovim/nvim-lspconfig",
  "williamboman/mason.nvim",
]
hook_add = '''
lua <<EOF
  local on_attach = function(client, bufnr)
    local set = vim.keymap.set
    set("n", "gD", "<cmd>lua vim.lsp.buf.declaration()<CR>")
    set("n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>")
    set("n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>")
    set("n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>")
    set("n", "<space>wa", "<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>")
    set("n", "<space>wr", "<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>")
    set("n", "<space>wl", "<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>")
    set("n", "<space>D", "<cmd>lua vim.lsp.buf.type_definition()<CR>")
    set("n", "<space>rn", "<cmd>lua vim.lsp.buf.rename()<CR>")
    set("n", "<space>ca", "<cmd>lua vim.lsp.buf.code_action()<CR>")
    set("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>")
    set("n", "<space>e", "<cmd>lua vim.diagnostic.get()<CR>")
    set("n", "[d", "<cmd>lua vim.diagnostic.goto_prev()<CR>")
    set("n", "]d", "<cmd>lua vim.diagnostic.goto_next()<CR>")
    set("n", "<space>q", "<cmd>lua vim.diagnostic.setqflist()<CR>")
    set("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>")
  end
  require("mason-lspconfig").setup()
  require("mason-lspconfig").setup_handlers {
    function (server_name) -- default handler (optional)
      require("lspconfig")[server_name].setup {
        on_attach = on_attach
      }
      require("lspconfig").pyright.setup{
        settings = {
          python = {
            venvPath = ".",
            pythonPath = "./.venv/bin/python",
            analysis = {
              extraPaths = {"."}
            }
          }
        }
      }
    end,
  }
EOF
'''
pluckpluck

pyrightにPoetry(virtualenv)の対応をさせるのは下の部分が重要で、pyrightの仕様にある通りにsettings.python.venvPathsettings.python.pythonPathあたり必要。

  require("mason-lspconfig").setup()
  require("mason-lspconfig").setup_handlers {
    function (server_name) -- default handler (optional)
      require("lspconfig")[server_name].setup {
        on_attach = on_attach
      }
      require("lspconfig").pyright.setup{
        settings = {
          python = {
            venvPath = ".",
            pythonPath = "./.venv/bin/python",
            analysis = {
              extraPaths = {"."}
            }
          }
        }
      }
    end,
  }

pyrightのsettingsの情報は下のURLに入っていた。
https://github.com/microsoft/pyright/blob/main/docs/settings.md

pluckpluck

この設定をすることで、Poetryでインストールしたライブラリ(実際に動かす環境)に対応してLSPの各種機能を使うことができる(補完やジャンプなど)。