Lsp Plugin for working with Python virtual environments

Overview

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 for the nvim lsp.

Installation

Using vim-plug:

Plug 'HallerPatrick/py_lsp.nvim'

Using packer.nvim:

use {'HallerPatrick/py_lsp.nvim'}

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"
}

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

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
:PyLspCreateVenv venv name Creates a virtual env with given name (default: 'venv'). Requires host_python to be set and have virtualenv installed
:PyRun command Run files and modules from current virtuale env

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

Example Workflow

You open up your python project. Because there is no python virtual env confirgured, the LSP is not starting.

  1. You run :PyLspCreateVenv venv to create a new virtual env from host_python.
  2. You run :PyLspCurrentVenv to check if the LSP client is using your new venv.
  3. You run :PyRun -m pip install -r requirements.txt to install project dependencies.
  4. You run :PyLspReload so that the LSP client also find your new site-packages for autocompletion and correct linting.

You start programming!

Extras

The virtual environment path and name can be retrieved with client.config.settings.python.pythonPath and client.config.settings.python.venv_name. This can for example be used in your statuslines.

Example provider for feline:

local function lsp_provider(component)

    local clients = {}
    local icon = component.icon or ''

    for _, client in pairs(vim.lsp.buf_get_clients()) do
        if client.name == "pyright" then
          -- Check if lsp was initialized with py_lsp
          if client.config.settings.python["pythonPath"] ~= nil then
            local venv_name = client.config.settings.python.venv_name
            clients[#clients+1] = icon .. client.name .. '('.. venv_name .. ')'
          end
        else
          clients[#clients+1] = icon .. client.name
        end
    end

    return table.concat(clients, ' ')
end

This will give you a VSCode like status:

Statusline with LSP server and venv name

Configuration

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

Default:

Default Values:
    auto_source = true,
    language_server = "pyright",
    on_attach = nil,
    source_strategies = {"default", "poetry", "system"},
    capabilities = nil,
    host_python = nil

Todo

  • Support for different environment systems:
    • virtualenvwrapper
    • Conda
    • Pipenv

Limitations

  • All features are currently only available with pyright. pylsp is weird. It will still be started, but all features are run with a 'pyright' server or not at all.
  • py_lsp expects to find virtualenv in the cwd, please check for that

Note

This plugin is created due to following Issue.

This plugin currently includes a utility to automatically pass a virtualenv to the pyright lsp server before initialization also take from the Issue. (Thanks lithammer and others).

Comments
  • Telescope is a necessary dependency?

    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
    
    opened by Turbid 3
  • Add conda integration

    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.

    opened by cnrrobertson 3
  • Improve options: remove on_attach preset and add capabilities

    Improve options: remove on_attach preset and add capabilities

    Also removes the completion dependency.

    Resolves https://github.com/HallerPatrick/py_lsp.nvim/issues/7

    PS: I think I added some automatic styling in the first, older commit – sorry!

    opened by d-miketa 3
  • Issue with :PyFindVenvs

    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 ?

    opened by thomascrha 2
  • Conda integration

    Conda integration

    As discussed in #18, this adds support for finding and activating conda environments. Reloading and closing environment will work out of the box while PyRun and PyLspCreateVenv will need further work.

    opened by cnrrobertson 2
  • [Help]: more LSP support

    [Help]: more LSP support

    Currently the plugin supports pyright out of box. Is there any plannings of support other python LSP such as https://github.com/python-lsp/python-lsp-server and https://github.com/pappasam/jedi-language-server.

    opened by younger-1 2
  • Add completion.nvim plugin to Installation section in README

    Add completion.nvim plugin to Installation section in README

    Hey thanks for this plugin, it works great!

    When I installed this for the first time with Vim-Plug I did not know this plugin requires completion-nvim so the require("completion") part in options.lua caused an error when resourcing my init.vim file.

    Therefore, I added this to the Installation section :)

    opened by smjonas 1
  • Remove 'completion' from on_attach, add capabilities

    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.
    opened by d-miketa 0
  • Make :PyRun async with output printed to stdout

    Make :PyRun async with output printed to stdout

    Its annoying to wait for a pip install to finish. Also maybe do a auto reload of lsp server after so, the changes in site-packages are seen by Pyright

    enhancement 
    opened by HallerPatrick 0
  • Incompatible with LSP installed by LspInstall

    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

    opened by d-miketa 2
Releases(v0.0.1)
Owner
Patrick Haller
Computer Science Master, based in Berlin
Patrick Haller
A simple python implementation of a reverse shell

llehs A python implementation of a reverse shell. Note for contributors The project is open for contributions and is hacktoberfest registered! llehs u

Archisman Ghosh 2 Jul 05, 2022
CLI tool that helps manage shell libraries.

shmgr CLI tool that helps manage shell libraries. Badges 📛 project status badges: version badges: tools / frameworks used by test suite (i.e. used by

Bryan Bugyi 0 Dec 15, 2021
A CLI application for storing contacts as a csv file written in Python.

Contacter A CLI application for storing contacts as a csv file written in Python. You can use this to save your contacts with a special relations tag

nostalgicnerdpenguin 1 Oct 23, 2021
A simple CLI productivity tool to quickly display the syntax of a desired piece of code

Iforgor Iforgor is a customisable and easy to use command line tool to manage code samples. It's a good way to quickly get your hand on syntax you don

Solaris 21 Jan 03, 2023
A simple CLI tool for getting region-specific status of Logz.io components.

About A simple CLI tool for checking the current status of Logz.io components per region. Built With Python 3 The following packeges (see requirements

Yotam Bernaz 1 Dec 11, 2021
A terminal UI dashboard to monitor requests for code review across Github and Gitlab repositories.

A terminal UI dashboard to monitor requests for code review across Github and Gitlab repositories.

Kyle Harrison 150 Dec 14, 2022
Code for the Open Data Day 2022 publicbodies.org Nepal data scraping activities.

Open Data Day Publicbodies.org Nepal We've gathered on Saturday, 5th March 2022 with Open Knowledge Nepal in order to try and automate the collection

Augusto Herrmann 2 Mar 12, 2022
A simple python script to execute a command when a YubiKey is disconnected

YubiKeyExecute A python script to execute a command when a YubiKey / YubiKeys are disconnected. ‏‏‎ ‎ How to use: 1. Download the latest release and d

6 Mar 12, 2022
f90nml - A Fortran namelist parser, generator, and editor

f90nml - A Fortran namelist parser, generator, and editor A Python module and command line tool for parsing Fortran namelist files Documentation The c

Marshall Ward 110 Dec 14, 2022
A simple discord slash command handler for for discord.py.

A simple discord slash command handler for discord.py About ⦿ Installation ⦿ Disclaimer ⦿ Examples ⦿ Documentation ⦿ Discussions Note that master bran

641 Jan 03, 2023
A CLI tool for creating disposable environments.

dispenv - Disposable Python Environments ⚠️ WIP Need to make an environment to work on a GitHub issue? Want to try out a new package and not leave the

Peter Baumgartner 3 Mar 14, 2022
keep your machine's shell history synchronize

SyncShell Yet another tool for laziness Keep your machine's shell history synchronize Get SyncShell Currently, SyncShell is just available on PyPi and

Masoud Ghorbani 53 Dec 12, 2022
🌈 Lightweight Python package that makes it easy and fast to print terminal messages in colors. 🌈

🌈 Colorist for Python 🌈 Lightweight Python package that makes it easy and fast to print terminal messages in colors. Prerequisites Python 3.9 or hig

Jakob Bagterp 1 Feb 05, 2022
CLI/library to control FNIRSI DC Power Supply (DC-6006L, etc)

dc6006l - CLI/library to control FNIRSI DC Power Supply (DC-6006L, etc) What is this? FNIRSI DC6006L is a programmable DC power supply that is quite c

Taisuke Yamada 7 Sep 25, 2022
Run an FFmpeg command and see the percentage progress and ETA.

Run an FFmpeg command and see the percentage progress and ETA.

25 Dec 22, 2022
ServX | Bash Command as a Service

ServX | Bash Command as a Service Screenshots Instructions for running Run python3 servx.py. COMPATIBILITY TESTED ON ARCHLINUX(x64) & DEBIAN(x64) ONLY

ARPSyndicate 2 Mar 11, 2022
A communist shell written in Python

kash A communist shell written in Python It doesn't support escapes, quotes, comment lines, |, &&, , or similar yet. If you need help, get it from

Çınar Yılmaz 1 Dec 10, 2021
A ZSH plugin that enables you to use OpenAI's powerful Codex AI in the command line.

A ZSH plugin that enables you to use OpenAI's powerful Codex AI in the command line.

Tom Dörr 976 Jan 03, 2023
Wordle - Wordle solver with python

wordle what is wordle? https://www.powerlanguage.co.uk/wordle/ preparing $ pip i

shidocchi 0 Jan 24, 2022
A Python-based Wordle solver and CLI player

Wordle A Python-based Wordle solver and CLI player This was created using Python 3.9.7. SPOILER ALERT: the data directory contains spoilers for upcomi

Will Fitzgerald 1 Jul 24, 2022