From c75b7636e0156bc6fffc211b7817c6c75a9cccd5 Mon Sep 17 00:00:00 2001 From: Marty Oehme Date: Wed, 1 Mar 2023 15:57:28 +0100 Subject: [PATCH] nvim: Determine python venv on lsp start --- nvim/.config/nvim/lua/plug/_lsp.lua | 9 ++++++ nvim/.config/nvim/lua/util/pyenv.lua | 45 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 nvim/.config/nvim/lua/util/pyenv.lua diff --git a/nvim/.config/nvim/lua/plug/_lsp.lua b/nvim/.config/nvim/lua/plug/_lsp.lua index 8acd3cc..29cdf34 100644 --- a/nvim/.config/nvim/lua/plug/_lsp.lua +++ b/nvim/.config/nvim/lua/plug/_lsp.lua @@ -52,6 +52,15 @@ lsp.on_attach(function(client, bufnr) { buffer = bufnr, desc = 'Type definition' }) end) lsp.nvim_workspace() +-- ensure python virtualenv is determined automatically on lsp start +lsp.configure("pyright", { + on_attach = function(client, _) + local python_path, msg = require('util.pyenv').get_path(client.config + .root_dir) + vim.notify(string.format('%s\n%s', msg, python_path)) + client.config.settings.python.pythonPath = python_path + end +}) lsp.setup_nvim_cmp({ sources = { { name = 'path' }, { name = 'nvim_lsp', keyword_length = 2 }, diff --git a/nvim/.config/nvim/lua/util/pyenv.lua b/nvim/.config/nvim/lua/util/pyenv.lua new file mode 100644 index 0000000..0beb2d2 --- /dev/null +++ b/nvim/.config/nvim/lua/util/pyenv.lua @@ -0,0 +1,45 @@ +local util = require('lspconfig/util') +local path = util.path +local T = {} +local exepath = vim.fn.exepath + +local path_sep = function() + local is_win = vim.loop.os_uname().sysname:find('Windows') + if is_win then + return '\\' + else + return '/' + end +end + +-- from https://github.com/ray-x/navigator.lua/issues/247#issue-1465308677 +T.get_path = function(workspace) + -- Use activated virtualenv. + if vim.env.VIRTUAL_ENV then + return path.join(vim.env.VIRTUAL_ENV, 'bin', 'python'), 'virtual env' + end + + -- Find and use virtualenv in workspace directory. + for _, pattern in ipairs({ '*', '.*' }) do + local match = vim.fn.glob(path.join(workspace, pattern, 'pyvenv.cfg')) + local sep = path_sep() + local py = 'bin' .. sep .. 'python' + if match ~= '' then + match = string.gsub(match, 'pyvenv.cfg', py) + return match, string.format('venv base folder: %s', match) + end + match = vim.fn.glob(path.join(workspace, pattern, 'poetry.lock')) + if match ~= '' then + local venv_base_folder = vim.fn.trim(vim.fn.system( + 'poetry env info -p')) + return path.join(venv_base_folder, 'bin', 'python'), + string.format('venv base folder: %s', venv_base_folder) + end + end + + -- Fallback to system Python. + return exepath('python3') or exepath('python') or 'python', + 'fallback to system python path' +end + +return T