Giter Club home page Giter Club logo

py_lsp.nvim's Introduction

py_lsp.nvim

What is py_lsp?

py_lsp.nvim is a neovim plugin that helps with using the lsp feature for python development.

It tackles the problem about the activation and usage of python virtual environments and conda environments for the nvim lsp.

Includes optional support for nvim-notify plugins (for custom popup information) and nvim-lsp-installer for LSP detection. Includes a detection inside the Virtual Environment for the LSP presence as last fallback (before check in the host machine).

Installation

Using vim-plug:

Plug 'HallerPatrick/py_lsp.nvim'

Using packer.nvim:

use {
    'HallerPatrick/py_lsp.nvim',
    -- Support for versioning
    -- tag = "v0.0.1" 
}

Usage

Instead of initializing the server on your own, like in nvim-lspconfig, py_lsp is doing that for you.

Put this in your init.lua (or wrap in lua call for your init.vim)

require'py_lsp'.setup {
  -- This is optional, but allows to create virtual envs from nvim
  host_python = "/path/to/python/bin",
  default_venv_name = ".venv" -- For local venv
}

This minimal setup will automatically pass a python virtual environment path to the LSP client for completion/linting.

WARNING: py_lsp is currently not agnostic against other python lsp servers that are starting or attaching. Please be aware of other plugins, autostarting lsp servers.

Features

py_lsp exposes several commands that help with a virtual env workflow.

Command Parameter Usage
:PyLspCurrentVenv No Prints the currently used python venv
:PyLspDeactiveVenv No Shuts down the current LSP client
:PyLspReload No Reload LSP client with current python venv
:PyLspActivateVenv venv name Activates a virtual env with given name (default: 'venv'). This venv should lie in project root
:PyLspActivateCondaEnv env name Activates a conda env with given name (default: 'base'). Requires conda to be installed on the system
:PyLspCreateVenv venv name Creates a virtual env with given name (default: 'venv'). Requires host_python to be set and have virtualenv installed
:PyRun Optional Run files and modules from current virtuale env. If no arguments specified, will run current buffer
:PyFindVenvs No List all found Virtualenvs found by different strategies. Select and reload LSP

Most of these commands can be also run over a popup menu with :PyLspPopup.

PyRun

The :PyRun command uses the currently activated virtuale environment to either execute the current buffer on or the arguments passed to pather. If toggleterm is an available plugin the command is executed through a toggleterm terminal.

Configuration

The configurations are not sensible yet, and are suiting my setup. This will change.

Default:

Default Values:
    auto_source = true,
    language_server = "pyright",
    source_strategies = {"default", "poetry", "conda", "system"},
    capabilities = nil,
    host_python = nil,
    on_attach = nil,
    on_server_ready = nil
    default_venv_name = nil,
    pylsp_plugins = {}, // the table with the various pylsp plugins with their parameters
    venvs = {}

One can also provide settings like default_venv_name or source_stragie in a pyproject.toml file, to have a per-project setting which venv to use.

[tool.py_lsp]
default_venv_name = "my_conda_venv"

# Beware, that the source_strategie is a string, not a table
source_strategie = "conda"

This requires a plugin for loading toml files, so include the following in your nvim config: Lazy:

{
    "HallerPatrick/py_lsp.nvim",
    dependencies = { "dharmx/toml.nvim" },
    ...
}

Other Language servers

I am using pyright and therefore works well with pyright. When using a not registered language server like jedi-language-server you can register it like following:

local nvim_lsp_configs = require "lspconfig.configs"

nvim_lsp_configs["jedi_language_server"] = {
    default_config = {
        cmd = {"jedi-language-server"},

        -- Depending on your environment
        root_dir = nvim_lsp.util.root_pattern(".git", "setup.py",
                                              "pyproject.toml"),
        filetypes = {"python"}
    }
}

local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp
                                                                     .protocol
                                                                     .make_client_capabilities())

require("py_lsp").setup({
    language_server = "jedi_language_server",
    capabilities = capabilities
})

Todo

  • Support for different environment systems:
    • virtualenvwrapper
    • Pipenv
  • Agnostic against other python lsp server

py_lsp.nvim's People

Contributors

cnrrobertson avatar d-miketa avatar hallerpatrick avatar jmanch avatar mte90 avatar smjonas avatar thomascrha avatar vlcinsky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

py_lsp.nvim's Issues

Telescope is a necessary dependency?

After installing the plugin:

E5113: Error while calling lua chunk: ...m/site/pack/packer/start/py_lsp.nvim/lua/py_lsp/init.lua:1: module 'telescope.pickers' not found:
        no field package.preload['telescope.pickers']
        no file './telescope/pickers.lua'
        no file '/__w/neovim/neovim/.deps/usr/share/luajit-2.1.0-beta3/telescope/pickers.lua'
        no file '/usr/local/share/lua/5.1/telescope/pickers.lua'
        no file '/usr/local/share/lua/5.1/telescope/pickers/init.lua'
        no file '/__w/neovim/neovim/.deps/usr/share/lua/5.1/telescope/pickers.lua'
        no file '/__w/neovim/neovim/.deps/usr/share/lua/5.1/telescope/pickers/init.lua'
        no file './telescope/pickers.so'
        no file '/usr/local/lib/lua/5.1/telescope/pickers.so'
        no file '/__w/neovim/neovim/.deps/usr/lib/lua/5.1/telescope/pickers.so'
        no file '/usr/local/lib/lua/5.1/loadall.so'
        no file './telescope.so'
        no file '/usr/local/lib/lua/5.1/telescope.so'
        no file '/__w/neovim/neovim/.deps/usr/lib/lua/5.1/telescope.so'
        no file '/usr/local/lib/lua/5.1/loadall.so'
stack traceback:
        [C]: in function 'require'
        ...m/site/pack/packer/start/py_lsp.nvim/lua/py_lsp/init.lua:1: in main chunk
        [C]: in function 'require'
        ...user/.config/nvim/lua/settings.lua:46: in main chunk
        [C]: in function 'require'
        /home/user/.config/nvim/init.lua:2: in main chunk

Telescope picker error

There is an undefined reference to M.stop_client() (a possible typo?) in the Telescope picker. I've submitted a PR #25 with the fix.

Detect python crash

So I had poetry that was crashing and the :checkhealth showed:

image

So my issue generated that error that I fixed #37 with a fallback but could be interesting a check with a popup in case the poetry (in this case) generate error.

Spawning language server with cmd: `pylsp` failed.

I am not sure how I can help debug this issue.

But I use lsp-zero and mason to install and configure lsp servers.

After adding py_lsp I see the following error when I open a python file with nvim.

Spawning language server with cmd: `pylsp` failed. The language server is either not installed, missing from PATH, or not executable.

The funny thing is that it does seem like the pyright lsp and the venv is activated.

Another curios thing is that the error message persists even after I remove py_lsp, which makes me wonder if py_lsp made a change somewhere that is not undone when you remove it.

Please let me know if I can run any debug steps on my side.

capabilities, on_attach and pylsp_plugins are empty

With this code you can see

require'py_lsp'.setup({
    language_server = "pylsp",
    source_strategies = {"poetry", "default", "system"},
    capabilities = capabilities,
    on_attach = on_attach,
    pylsp_plugins = {
        pyls_mypy = {
            enabled = true
        },
        rope_autoimport = {
            enabled = true
        },
        rope_completion = {
            enabled = true
        },
        pyls_isort = {
            enabled = true
        },
        pycodestyle = {
            enabled = false,
        },
        flake8 = {
            enabled = true,
            executable = venv_bin_detection("flake8"),
        }
    }
})

That on setup pylsp_plugins and the others are empty, excluded source_strategies.

Screenshot_20240305_182502

You can check the issue with:


  local ok, notify = pcall(require, "notify")
  for k, v in pairs(opts) do
  if type(v)=='table' then
      notify.notify(k .. table.concat(v, ','), "info", {
        title = " py_lsp.nvim",
        timeout = 300,
      })
  end

On setup function.
I saw this issue as the LSP is not applying the plugins, the data are there but they are not passed in the rest of the plugin.

Add conda integration

I noticed this is already on your todos, but it would be a really nice feature to see. It seems like you could integrate it pretty easily by searching the envs path at the conda installation location (usually something like ~/conda). I was able to follow the example here to create my own little change Python interpreter code:

function change_python_interpreter(path)
    vim.lsp.stop_client(vim.lsp.get_active_clients())
    configs.pyright.settings.python.pythonPath = path
    require'lspconfig'.pyright.setup(configs.pyright)
    vim.cmd('e%')
end

function get_python_interpreters(a, l, p)
    local paths = {}
    local is_home_dir = function()
        return vim.fn.getcwd(0) == vim.fn.expand("$HOME")
    end
    local commands = {'fd --glob -tl python $HOME/mambaforge', 'which -a python', is_home_dir() and '' or 'find . -name python'}
    for _, cmd in ipairs(commands) do
        local _paths = vim.fn.systemlist(cmd)
        if _paths then
            for _, path in ipairs(_paths) do
                table.insert(paths, path)
            end
        end
    end
    table.sort(paths)
    local res = {}
    for i, path in ipairs(paths) do
        if path ~= paths[i+1] then table.insert(res, path) end
    end
    return res
end

vim.api.nvim_exec([[
command! -nargs=1 -complete=customlist,PythonInterpreterComplete PythonInterpreter lua change_python_interpreter(<q-args>)

function! PythonInterpreterComplete(A,L,P) abort
  return v:lua.get_python_interpreters()
endfunction
]], false)

This provides a PythonInterpreter vim command which offers completion options of all conda environments and works well for me. However, I like what you are doing with this plugin much better.

Make FindLspFindVenvs showing a short env name at head?

image

For now, the FindLspFindVenvs show the usable env python path like this, but in fact it is hard to find the wanted one in absolute path. So perhaps it will be better to have the env name at the beginning? Some thing like【(Conda: py38) /home/xx/anaconda3/envs/py38/bin/python】. Thanks for the great work by the way.

Refactoring: Venv collection

Not happy with just using raw tables with strategies and paths. Maybe use metaclasses venvs and be more descriptive and less hacky

Incompatible with LSP installed by LspInstall

https://github.com/kabouzeid/nvim-lspinstall is a convenient plugin to install LSP servers. They end up in a separate directory outside of $PATH (~/.local/share/nvim/lspinstall/python/./node_modules/.bin/pyright-langserver in my case), but https://github.com/kabouzeid/nvim-lspinstall/blob/54b439241e83e0a9ce8f6bcdf3b2c560a2328792/lua/lspinstall.lua#L94 corrects the default cmd for lspconfig to point to that location. However py_lsp doesn't pick up on it for some reason, perhaps overriding cmd or cmd_cwd in default_config?

This is with py_lsp installed and used to set up Pyright:
image
image

And this is with py_lsp disabled: (note cmd)
image

Shouldn't PyLspActivateVenv be automatic?

Hi, thanks for you plugin. I just installed it and noticed that it's useful for me.
But I have a question about usage workflow.
When I open the project with venv folder inside, nvim not using this venv, until I run this command:
:PyLspActivateVenv

I thought that It will be simpler if nvim will look for some directories (venv, .venv, py) and if one of them exists (and contains venv), it will be activated automatically.

Isn't this the desired plugin behavior for everyone? Or did I miss something?

Issue with :PyFindVenvs

So when running this command I get this error
image

Doing some research (and editing my stratagies.lua the function table.unpack isn't available in older versions of lua info - any way I was able to fix it by removing the table.

Is this something you want to fix ? or should we recommend users update there Lua to 5.2 ?

Update docu

Make docu in general more clean.

  • Update for PyRun #28
  • Find venvs logic

Remove 'completion' from on_attach, add capabilities

Hi, thanks for the plugin! I'm currently deciding on my Python workflow and this'll probably make the cut. :) I have two improvements to suggest:

  1. It seems unnecessary to demand the completion plugin. It only appears in the default on_attach setting and can be safely removed.
  2. It'd be good to also expose a capabilities field when passing options to require'lspconfig'.setup as that's where you turn on snippet support.

Automatic source from PyLspFindVenvs results

There's an option to automatically source from PyLspFindVenvs results? I mean, I always have a .venv on my project root so there's any way to pass the PyLspFindVenvs results automatically activation?

Reload of LSP buggy

When reloading the lsp(s), the Pyright server is not getting started again

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.