Coder Social home page Coder Social logo

jedi-language-server's Introduction

Jedi Language Server

image-version image-license image-python-versions image-pypi-downloads github-action-testing poetry

A Python Language Server powered by the latest version of Jedi.

Installation

Some frameworks, like coc-jedi and vscode-python, will install and manage jedi-language-server for you. If you're setting up manually, you can run the following from your command line (bash / zsh):

pip install -U jedi-language-server

Alternatively (and preferably), use pipx to keep jedi-language-server and its dependencies isolated from your other Python dependencies. Don't worry, jedi is smart enough to figure out which Virtual environment you're currently using!

Editor Setup

The following instructions show how to use jedi-language-server with your development tooling. The instructions assume you have already installed jedi-language-server.

Vim / Neovim

Users may choose 1 of the following options:

Note: this list is non-exhaustive. If you know of a great choice not included in this list, please submit a PR!

Emacs

Users may choose one of the following options:

Note: this list is non-exhaustive. If you know of a great choice not included in this list, please submit a PR!

Visual Studio Code (vscode)

Starting from the October 2021 release, set the python.languageServer setting to Jedi to use jedi-language-server.

See: #50 (comment)

Configuration

jedi-language-server supports the following initializationOptions:

{
  "initializationOptions": {
    "codeAction": {
      "nameExtractVariable": "jls_extract_var",
      "nameExtractFunction": "jls_extract_def"
    },
    "completion": {
      "disableSnippets": false,
      "resolveEagerly": false,
      "ignorePatterns": []
    },
    "diagnostics": {
      "enable": false,
      "didOpen": true,
      "didChange": true,
      "didSave": true
    },
    "hover": {
      "enable": true,
      "disable": {
        "class": { "all": false, "names": [], "fullNames": [] },
        "function": { "all": false, "names": [], "fullNames": [] },
        "instance": { "all": false, "names": [], "fullNames": [] },
        "keyword": { "all": false, "names": [], "fullNames": [] },
        "module": { "all": false, "names": [], "fullNames": [] },
        "param": { "all": false, "names": [], "fullNames": [] },
        "path": { "all": false, "names": [], "fullNames": [] },
        "property": { "all": false, "names": [], "fullNames": [] },
        "statement": { "all": false, "names": [], "fullNames": [] }
      }
    },
    "jediSettings": {
      "autoImportModules": [],
      "caseInsensitiveCompletion": true,
      "debug": false
    },
    "markupKindPreferred": "markdown",
    "workspace": {
      "extraPaths": [],
      "environmentPath": "/path/to/venv/bin/python",
      "symbols": {
        "ignoreFolders": [".nox", ".tox", ".venv", "__pycache__", "venv"],
        "maxSymbols": 20
      }
    }
  }
}

The different sections of the InitializationOptions are explained below, in detail. Section headers use a . to separate nested JSON-object keys.

markupKindPreferred

The preferred MarkupKind for all jedi-language-server messages that take MarkupContent.

  • type: string
  • accepted values: "markdown", "plaintext"

If omitted, jedi-language-server defaults to the client-preferred configuration. If there is no client-preferred configuration, jedi language server users "plaintext".

jediSettings.autoImportModules

Modules that jedi will directly import without analyzing. Improves autocompletion but loses goto definition.

  • type: string[]
  • default: []

If you're noticing that modules like numpy and pandas are taking a super long time to load, and you value completions / signatures over goto definition, I recommend using this option like this:

{
  "jediSettings": {
    "autoImportModules": ["numpy", "pandas"]
  }
}

jediSettings.caseInsensitiveCompletion

Completions are by default case-insensitive. Set to false to make completions case-sensitive.

  • type: boolean
  • default: true
{
  "jediSettings": {
    "caseInsensitiveCompletion": false
  }
}

jediSettings.debug

Print jedi debugging messages to stderr.

  • type: boolean
  • default: false
{
  "jediSettings": {
    "debug": false
  }
}

codeAction.nameExtractFunction

Function name generated by the 'extract_function' codeAction.

  • type: string
  • default: "jls_extract_def"

codeAction.nameExtractVariable

Variable name generated by the 'extract_variable' codeAction.

  • type: string
  • default: "jls_extract_var"

completion.disableSnippets

If your language client supports CompletionItem snippets but you don't like them, disable them by setting this option to true.

  • type: boolean
  • default: false

completion.resolveEagerly

Return all completion results in initial completion request. Set to true if your language client does not support completionItem/resolve.

  • type: boolean
  • default: false

completion.ignorePatterns

A list of regular expressions. If any regular expression in ignorePatterns matches a completion's name, that completion item is not returned to the client.

  • type: string[]
  • default: []

In general, you should prefer the default value for this option. Jedi is very good at filtering values for end users. That said, there are situations where IDE developers, or some programmers in some code bases, may want to filter some completions by name. This flexible interface is provided to accommodate these advanced use cases. If you have one of these advanced use cases, see below for some example patterns (and their corresponding regular expression).

All Private Names

Matches Non-Matches
_hello, __world __dunder__

Regular Expression:

^_{1,3}$|^_[^_].*$|^__.*(?<!__)$

Only private mangled names

Matches Non-Matches
__world _hello, __dunder__

Regular Expression:

^_{2,3}$|^__.*(?<!__)$

Only dunder names

Matches Non-Matches
__dunder__ _hello, __world

Regular Expression:

^__.*?__$

All names beginning with underscore

Matches Non-Matches
_hello, __world, __dunder__ regular

Regular Expression:

^_.*$

diagnostics.enable

Enables (or disables) diagnostics provided by Jedi.

  • type: boolean
  • default: true

diagnostics.didOpen

When diagnostics are enabled, run on document open

  • type: boolean
  • default: true

diagnostics.didChange

When diagnostics are enabled, run on in-memory document change (eg, while you're editing, without needing to save to disk)

  • type: boolean
  • default: true

diagnostics.didSave

When diagnostics are enabled, run on document save (to disk)

  • type: boolean
  • default: true

hover.enable

Enable (or disable) all hover text. If set to false, will cause the hover method not to be registered to the language server.

  • type: boolean
  • default: true

hover.disable.*

The following options are available under this prefix:

  • hover.disable.class.all
  • hover.disable.class.names
  • hover.disable.class.fullNames
  • hover.disable.function.all
  • hover.disable.function.names
  • hover.disable.function.fullNames
  • hover.disable.instance.all
  • hover.disable.instance.names
  • hover.disable.instance.fullNames
  • hover.disable.keyword.all
  • hover.disable.keyword.names
  • hover.disable.keyword.fullNames
  • hover.disable.module.all
  • hover.disable.module.names
  • hover.disable.module.fullNames
  • hover.disable.param.all
  • hover.disable.param.names
  • hover.disable.param.fullNames
  • hover.disable.path.all
  • hover.disable.path.names
  • hover.disable.path.fullNames
  • hover.disable.property.all
  • hover.disable.property.names
  • hover.disable.property.fullNames
  • hover.disable.statement.all
  • hover.disable.statement.names
  • hover.disable.statement.fullNames

hover.disable.[jedi-type].all

Disable all hover text of jedi-type specified.

  • type: bool
  • default: false

hover.disable.[jedi-type].names

Disable hover text identified by name in list of jedi-type specified.

  • type: string[]
  • default: []

hover.disable.[jedi-type].fullNames

Disable hover text identified by the fully qualified name in list of jedi-type specified. If no fully qualified name can be found, jedi-language-server will default to the name to prevent any unexpected behavior for users (relevant for jedi types like keywords that don't have full names).

  • type: string[]
  • default: []

workspace.extraPaths

Add additional paths for Jedi's analysis. Useful with vendor directories, packages in a non-standard location, etc. You probably won't need to use this, but you'll be happy it's here when you need it!

  • type: string[]
  • default: []

Non-absolute paths are relative to your project root. For example, let's say your Python project is structured like this:

├── funky
│   └── haha.py
├── poetry.lock
├── pyproject.toml
├── test.py

Assume that funky/haha.py contains 1 line, x = 12, and your build system does some wizardry that makes haha importable just like os or pathlib. In this example, if you want to have this same non-standard behavior with jedi-language-server, put the following in your coc-settings.json:

{
  "workspace": {
    "extraPaths": ["funky"]
  }
}

When editing test.py, you'll get completions, goto definition, and all other lsp features for the line from haha import ....

Again, you probably don't need this.

workspace.environmentPath

The Python executable path, typically the path of a virtual environment.

  • type: string

If omitted, defaults to the active Python environment.

workspace.symbols.maxSymbols

Maximum number of symbols returned by a call to workspace/symbols.

  • type: number
  • default: 20
{
  "workspace": {
    "symbols": {
      "maxSymbols": 20
    }
  }
}

A value less than or equal to zero removes the maximum and allows jedi-language-server to return all workplace symbols found by jedi.

workspace.symbols.ignoreFolders

Performance optimization that sets names of folders that are ignored for workspace/symbols.

  • type: string[]
  • default: [".nox", ".tox", ".venv", "__pycache__", "venv"]
{
  "workspace": {
    "symbols": {
      "ignoreFolders": ["hello", "world"]
    }
  }
}

If you manually set this option, it overrides the default. Setting it to an empty array will result in no ignored folders.

Diagnostics

Diagnostics are provided by Python's built-in compile function.

If you would like additional diagnostics, we recommend using other tools (like diagnostic-language-server) to complement jedi-language-server.

Code Formatting

Again, we recommend that you use diagnostic-language-server. It also supports code formatting.

Command line usage

jedi-language-server can be run directly from the command line.

$ jedi-language-server --help
usage: jedi-language-server [-h] [--version] [--tcp] [--ws] [--host HOST] [--port PORT] [--log-file LOG_FILE] [-v]

If testing sending requests over stdio manually from the command line, you must include Windows-style line endings: \r\n. For an example, from within this project, run the following:

$ jedi-language-server -v < ./example-initialization-request.txt
INFO:pygls.server:Starting IO server
...

If testing interactively, be sure to manually insert carriage returns. Although this may differ between shell environments, within most bash terminals, you can explicitly insert the required line endings by typing <C-v><C-m>, which will insert a ^M. See:

$ jedi-language-server 2>logs
Content-Length: 1062^M
^M
...

Technical capabilities

jedi-language-server aims to support Jedi's capabilities and expose them through the Language Server Protocol. It supports the following Language Server capabilities:

Language Features

Text Synchronization (for diagnostics)

Local Development

To build and run this project from source:

Dependencies

Install the following tools manually:

Recommended

Get source code

Fork this repository and clone the fork to your development machine:

git clone https://github.com/<YOUR-USERNAME>/jedi-language-server
cd jedi-language-server

Set up development environment

make setup

Automatically format files

make fix

Run tests

make lint
make typecheck
make tests

Inspiration

Palantir's python-language-server inspired this project. In fact, for consistency's sake, many of python-language-server's CLI options are used as-is in jedi-language-server.

Unlike python-language-server, jedi-language-server:

  • Uses pygls instead of creating its own low-level Language Server Protocol bindings
  • Supports one powerful 3rd party static analysis / completion / refactoring library: Jedi. By only supporting Jedi, we can focus on supporting all Jedi features without exposing ourselves to too many broken 3rd party dependencies (I'm looking at you, rope).
  • Is supremely simple because of its scope constraints. Leave complexity to the Jedi master. If the force is strong with you, please submit a PR!

Articles

Written by

Samuel Roeca

jedi-language-server's People

Contributors

anu-ka avatar asteppke avatar bollwyvl avatar daliusd avatar danielroseman avatar dimbleby avatar dmerejkowsky avatar dsblank avatar ericvw avatar fredcamps avatar gwerbin avatar hanspinckaers avatar jgarte avatar karthiknadig avatar kimadeline avatar krassowski avatar lunderberg avatar nekopsykose avatar nesstero avatar pappasam avatar peterjclaw avatar polyzen avatar pyscripter avatar rebornix avatar wyuenho avatar zhixuan-lin 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

jedi-language-server's Issues

Starting the server

Hi, I followed your instructions to install jedi-language-server: pip install jedi-language-server.
(This is a first installation. The Python version is 3.8.5.)

The package is installed but the command "jedi-language-server" is not installed, or is not
installed in a directory featuring in the PATH.

Am I missing something?

Docstring for some modules does not look right

Doc string for sys module with markdown style comes back with strange markup. This might be a general problem with docstrings. This is just part of it, that we get back from jedi-language-server:

\_enablelegacywindowsfsencoding -- [Windows only]
**stdin** -- the original stdin; don't touch!
**stdout** -- the original stdout; don't touch!
**stderr** -- the original stderr; don't touch!
**displayhook** -- the original displayhook; don't touch!
**excepthook** -- the original excepthook; don't touch!

Actual:
image

Expected:
image

Code Actions problems

I'm experimenting with LSP Code Actions in Ale and one person suggested that jedi-language-server is good candidate for testing code actions. However I usually get quite not perfect results with it. Let's say I have following python file:

def main():
    a = 1
    b = 2
    c = a + b

I give instructions to extract function for code starting with line a = 1 and ending with last line. The result is following (notice that return is in wrong line):


def func_dfouerpw():
    a = 1
    b = 2
    c = a + b    return c


def main():
    c = func_dfouerpw()

Here is JSON (vimscript format) that I get from jedi-language-server:

{'id': 7, 'jsonrpc': '2.0', 'result': [{'diagnostics': v:null, 'edit': {'changes': v:null, 'documentChanges': [{'edits': [{'range': {'end': {'character': 7, 'line': 1}, 'start': {'character': 4, 'line': 1}}, 'newText': 'fu'}, {'range': {'end': {'character': 8, 'line': 1}, 'start': {'character': 8, 'line': 1}}, 'newText': 'c_dfouerpw'}, {'range': {'end': {'character': 14, 'line': 4}, 'start': {'character': 14, 'line': 4}}, 'newText': '    return c^@^@^@def main():^@    c = func_dfouerpw()^@'}], 'textDocument': {'uri': 'file:///Users/daliusd/projects/photoscripts/test.py', 'version': v:null}}]}, 'kind': 'refactor.extract', 'title': 'Extract expression into function ''func_dfouerpw''', 'command': v:null}]}

I have not tested jedi-language-server with other LSP implementations but could it be that there is problem in jedi-language-server side.

How to use it with vscode?

README mentions only great editors like vim & emacs.

Is it possible to configure vscode to use this server?

Regards,
Artem.

Fix bad paths by removing "path" from Jedi as option

I get weird paths suggested by Jedi.

Suggested change: comment out the text_doc.path, see how this changes anything.

Also, should read about this Script parameter; why would I care about this?

def get_jedi_script(
    server: LanguageServer,
    params: Union[TextDocumentPositionParams, RenameParams],
) -> Script:
    """Simplifies getting jedi Script

    NOTE:
        * jedi is 1-indexed for lines and 0-indexed for columns
        * LSP is 0-indexed for lines and 0-indexed for columns
        * Therefore, add 1 to LSP's request for the line
    """
    workspace = server.workspace
    text_doc = workspace.get_document(params.textDocument.uri)
    return Script(
        source=text_doc.source,
        # path=text_doc.path,
        line=params.position.line + 1,
        column=params.position.character,
        environment=get_cached_default_environment(),
    )

Jupyter Integration?

Hello,

First apologies if this isn't the place to ask this question, but I couldn't find anywhere better to ask. I was just hoping to get a better understanding of how to implement this package into Jupyter. I have a Jupyterhub server that uses @krassowski/jupyterlab-lsp. It lists jedi-language-server as experimental but wanted to give it a try. I uninstalled pyls and installed jedi-language-server, but I'm pretty sure the settings I have are wrong, but I have absolutely no idea what they should be and there is no example anywhere that I can find. The jupyterlab-lsp always just says additional servers needed.

I grabbed the settings here: https://github.com/pappasam/coc-jedi and tried in a dozen different ways based off of how the pyls package's settings were done, but nothing really worked.

Does anyone know what settings I need to enter for jupyterlab-lsp to detect the jedi-language-server?

I was able to find this from here:

c.LanguageServerManager.language_servers = {
    "jedi-language-server": {
        "argv": ["jedi-language-server"],
        "languages": ["python"],
        "version": 2
    }
}
c.LanguageServerManager.autodetect = False

So assuming I need to add that to some file in jupyter --paths?

This documentation says it should be in /etc/jupyter/jupyter_server_config.d/jupyter_server_config.py but that doesn't exist.

Completions

I think this server has potential :) I'm posting a list of things that can be improved about the completions, and I hope we can reach some agreement on this.

some_function(arg1, arg2)
-------------
 filterText

-------------------------
         label


insertTextFormat: always put 2 (snippet) for function, 1 (plaintext) for anything else

if the editor can do signatureHelp:
	insertText: some_function($0)
else:
	insertText: some_function(${1:arg1}, ${2:arg2})

I'm noticing there are a lot of keys that point to falsy values. If the value is falsy, make sure the key isn't present at all. This makes the response payloads much smaller.

textDocument/definition not working

Hi nice work,

I have some problems using the goto definition feature.
My setup include nvim + LanguageClient (or even builtin LSP) and jedi-language-server.

The problem in my case is that when calling LanguageClient#textDocument_definition() the cursor do not move, nvim complains as:

[LC] data did not match any variant of untagged enum GotoDefinitionResponse

and the client log is as follows:

17:04:44 DEBUG reader-Some("python") src/rpcclient.rs:207 <= Some("python") {"id": 1, "jsonrpc": "2.0", "result": [{"uri": null, "range": {"start": {"line": 0, "character": 4}, "end": {"line": 0, "character": 7}}}]}
17:04:44 ERROR unnamed src/rpchandler.rs:27 Error handling message: data did not match any variant of untagged enum GotoDefinitionResponse
Message: {"jsonrpc":"2.0","method":"textDocument/definition","params":{"bufnr":1,"character":0,"filename":"/home/mauro/t.py","gotoCmd":null,"handle":true,"languageId":"python","line":4,"text":["def foo():","    print('FOO')","","","foo()",""]},"id":1}
Error: data did not match any variant of untagged enum GotoDefinitionResponse

In particular note that it seams that the server do not send back the URI to the file, instead there is a null entry, and that with the method textDocument/publishDiagnostics, the server send back the right URI to the file position.

I found the same problem with anakin muffinmad/anakin-language-server#17 but not with other servers such as python-language-server.

Request performance and feature telemetry

In VS Code we use telemetry from the LS for various requests do determine performance and feature usage. Is there a option to turn on telemetry events. If not then would it be ok to add telemetry?

The cases where we need this are:

  • rename, and codeAction request, we plan on replacing rope with jedi-language-server for refactor rename and refactor.
  • publish/diagnostics when LS finds problems. This is so we can decide to defer to linters.
  • workspace/symbol, definition, references request, we plan on replacing extracting symbols via ctags with this.

Performance telemetry, for document symbols, hover, rename, few other time consuming operations.

Having telemetry from jedi-language-server can help us make these decisions. If there is no telemetry option, and this is fine to add, I can create a PR for this.

/cc @luabud

Adding jedi-language-server to nixpkgs?

Is it possible to add this package to the nixpkgs repository? Other python language servers are present but I really like this one and it seems to be the only one missing.

Testing on the command line

The server supports communiction over STDIO. But I'm not able to get any answer out of if when running it on the command line.

I'm trying to run an intialize request here:

grafik

Pressing enter does not lead to a result. I must be missing something very basic here. Any help would be appreciated!

Testing from command line

According to the README I should be able to test from command line, so I grabbed a json (from strace again):

{
  "jsonrpc": "2.0",
  "method": "textDocument/documentHighlight",
  "params": {
    "textDocument": {
      "uri": "file:///home/mdk/clones/jedi-language-server/test.py"
    },
    "position": {
      "line": 1,
      "character": 4
    }
  },
  "id": 8
}

and trying to send it to jedi-language-server using jedi-language-server < request.json, but it does not return, it looks to fall in an infinite loop of stats, (like monitoring my Python files).

ValueError: `column` parameter (-1) is not in a valid range

Hi,

I'm using lsp-jedi in Emacs. I notice that when the cursor is placed at the end of a Python file (which is usually a blank line), the LSP server keeps printing errors like below

Failed to handle request 1761 textDocument/documentHighlight Object(textDocument=Object(uri='file:///Users/user/git/pastebin/test.py'), position=Object(line=3, character=0))
Traceback (most recent call last):
  File "/Users/user/.local/pipx/venvs/jedi-language-server/lib/python3.9/site-packages/pygls/protocol.py", line 324, in _handle_request
    self._execute_request(msg_id, handler, params)
  File "/Users/user/.local/pipx/venvs/jedi-language-server/lib/python3.9/site-packages/pygls/protocol.py", line 249, in _execute_request
    self._send_response(msg_id, handler(params))
  File "/Users/user/.local/pipx/venvs/jedi-language-server/lib/python3.9/site-packages/jedi_language_server/server.py", line 269, in highlight
    names = jedi_script.get_references(**jedi_lines, scope="file")
  File "/Users/user/.local/pipx/venvs/jedi-language-server/lib/python3.9/site-packages/jedi/api/helpers.py", line 485, in wrapper
    raise ValueError('`column` parameter (%d) is not in a valid range '
ValueError: `column` parameter (-1) is not in a valid range (0-0) for line 4 ('').

Screen Shot 2021-02-19 at 11 02 34 AM

Is this a server side issue? Thanks.

Outline does not show up in VS Code due to `"detail":null` in response to documentSymbol request

This is the response I get back from LS. The "detail":null causes Outline to not show up in VS Code. Removing it or replacing it with "detail": "" seems to address this issue.

[
    {
        "name": "SampleClass",
        "kind": 5,
        "range": {
            "start": {
                "line": 17,
                "character": 0
            },
            "end": {
                "line": 19,
                "character": 12
            }
        },
        "selectionRange": {
            "start": {
                "line": 17,
                "character": 6
            },
            "end": {
                "line": 17,
                "character": 17
            }
        },
        "detail": null,
        "children": [
            {
                "name": "__init__",
                "kind": 6,
                "range": {
                    "start": {
                        "line": 18,
                        "character": 4
                    },
                    "end": {
                        "line": 19,
                        "character": 12
                    }
                },
                "selectionRange": {
                    "start": {
                        "line": 18,
                        "character": 8
                    },
                    "end": {
                        "line": 18,
                        "character": 16
                    }
                },
                "detail": null,
                "children": [],
                "deprecated": false
            }
        ],
        "deprecated": false
    }
]

The fix for this should really go into pygls, but setting it to "" is a work around that can be done in jedi-language-server. This issue extends to other responses too like CodeAction for example.

Related:
openlawlibrary/pygls#145
https://github.com/microsoft/vscode/issues/115793

Extensibility / integration with other tools

Hi there! This projects looks very exciting. I've opened a PR in nvim-lsp to add it there: neovim/nvim-lspconfig#284

I know the name is explicit about this being a jedi language server, but would it make sense to integrate other tools to support operations that can't be provided by jedi (two examples that come to mind is diagnostics with mypy and code formatting with black) or maybe use something like pluggy to support adhoc extensions?

One can always run more than one language server, but it'd be good to be able to run just one 😁

Add support for setTrace Notification

This is used by LS client to set the tracing level on the server.

Failed to handle notification $/setTrace: Object(value='verbose')
Traceback (most recent call last):
  File "c:\Users\karth\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\lib\jedilsp\pygls\protocol.py", line 279, in _get_handler
    return self.fm.builtin_features[feature_name]
KeyError: '$/setTrace'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\karth\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\lib\jedilsp\pygls\protocol.py", line 282, in _get_handler
    return self.fm.features[feature_name]
KeyError: '$/setTrace'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\karth\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\lib\jedilsp\pygls\protocol.py", line 306, in _handle_notification
    handler = self._get_handler(method_name)
  File "c:\Users\karth\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\lib\jedilsp\pygls\protocol.py", line 284, in _get_handler
    raise JsonRpcMethodNotFound.of(feature_name)
pygls.exceptions.JsonRpcMethodNotFound

Does not work with Jedi 0.17.0

The latest version of Jedi introduces breaking changes to the public API. Starting the language server returns this result:

$ jedi-language-server
Traceback (most recent call last):
  File "/home/sroeca/src/flask-kipauth/.venv/bin/jedi-language-server", line 5, in <module>
    from jedi_language_server.cli import cli
  File "/home/sroeca/src/flask-kipauth/.venv/lib/python3.8/site-packages/jedi_language_server/cli.py", line 5, in <module>
    from .server import SERVER
  File "/home/sroeca/src/flask-kipauth/.venv/lib/python3.8/site-packages/jedi_language_server/server.py", line 37, in <module>
    from .server_utils import (
  File "/home/sroeca/src/flask-kipauth/.venv/lib/python3.8/site-packages/jedi_language_server/server_utils.py", line 10, in <module>
    from jedi.api.classes import Definition
ImportError: cannot import name 'Definition' from 'jedi.api.classes' (/home/sroeca/src/flask-kipauth/.venv/lib/python3.8/site-packages/jedi/api/classes.py)

Feature proposal: serve completion items from cache

Hi @pappasam,

I still use this language server every day and I really like it. Since I develop with quite large frameworks, autocompletion can be slow (even after an initial completion). I was thinking; it would be relatively* easy to implement a sort of caching layer. So we could serve autocompletions fast, and maybe update them after we get the actual autocompletion items from Jedi.

What do you think of such a feature? I could take a look how difficult it is to implement and start a pull request if you want.

Thanks,
Hans

  • famous last words

Can't get workspace symbols

I am using jedi-language-server version 0.19.3 with languageClient-neovim and I can't get workspace_symbols to work. When I invoke it, I get the error invalid type: null, expected sequence.

I'm not sure how to get more info about this error.
I have the same setup for rust with rust-analyzer and it works, so it has something to do with jedi-language-client.

No diagnostics with nvim-lsp

I checked in the debug logs and the payload for publishDiagnostics is empty. For cross-checking, I used pyls and I did get error messages.

I'm initialising the language server with pure defaults. But, AFAIK it should publish the diagnostics on open, change and save, which is not working.

ValueError: `column` parameter is not in a valid range

Hi!

Great work with this project, this has recently become my favourite LSP server to use while coding with Python in Neovim (latest HEAD). It's nice to have a lightweight alternative to pyls. 😀

However, I'm experiencing a fairly recurrent error that occurs when exiting insert mode. The error message returned from vim-lsc (my Neovim LSP client) is:

ValueError: column parameter (36) is not in a valid range (0-34) for line 7 ('from dataclasses import asdict, fi\n').

It doesn't happen all of the time, only when exiting insert mode after extending an already-existing line with more text, e.g. changing from dataclasses import asdict to from dataclasses import asdict, field.

This doesn't occur with pyls. I think they had the same issue, which was raise and fixed here: palantir/python-language-server#193

Any chance you could take a look at this?

Thanks.

nvim-lsp Expected a table for Hover.contents error

Hi,
for some entries, e.g.: len function signature or os.error completion, I get:

Error executing vim.schedule lua callback: /usr/share/nvim/runtime/lua/vim/lsp/util.lua:387 Expected a table for Hover.contents

nvim 0.5.0-625-g602e7505e
completion-nvim commit:b354c7fc
jedi-language-server 0.19.1

Add support for workspace/didChangeConfiguration notification

Add support for this notification: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_didChangeConfiguration

Currently I get this error when it is sent.

Failed to handle notification workspace/didChangeConfiguration
Traceback (most recent call last):
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\pygls\protocol.py", line 279, in _get_handler
    return self.fm.builtin_features[feature_name]
KeyError: 'workspace/didChangeConfiguration'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\pygls\protocol.py", line 282, in _get_handler
    return self.fm.features[feature_name]
KeyError: 'workspace/didChangeConfiguration'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\pygls\protocol.py", line 306, in _handle_notification
    handler = self._get_handler(method_name)
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\pygls\protocol.py", line 284, in _get_handler
    raise JsonRpcMethodNotFound.of(feature_name)
pygls.exceptions.JsonRpcMethodNotFound

reStructuredText in docstrings not converted to Markdown

Some Python docstrings use reStructuredText, one notable example being pandas. Here's an example from that link:

def add(num1, num2):
  """
  Add up two integer numbers.
  
  This function simply wraps the `+` operator, and does not
  do anything interesting, except for illustrating what is
  the docstring of a very simple function.
  
  Parameters
  ----------
  num1 : int
      First number to add
  num2 : int
      Second number to add
  
  Returns
  -------
  int
      The sum of `num1` and `num2`
  
  See Also
  --------
  subtract : Subtract one integer from another
  
  Examples
  --------
  >>> add(2, 2)
  4
  >>> add(25, 0)
  25
  >>> add(10, -10)
  0
  """
  return num1 + num2

This language server feeds these docstrings back directly to the client without any transformation into Markdown as expected by the LSP spec, so they don't always render well when you do things like hovers. For example, the code block sections beginning with >>> don't look good.

The Microsoft language server has special parsing code in it to handle this; see https://github.com/microsoft/python-language-server/blob/master/src/LanguageServer/Impl/Documentation/DocstringConverter.cs.

Note: I copied this with from a very similar issue I filed on palantir/python-language-server#760

LSP :: Error from the Language Server: KeyError: 28 (Invalid Parameters)

I'm trying jedi-language-server for the first time, sorry I'm I don't give all relevant infos...

Using emacs 27.1 on Debian, with lsp-jedi 20200812.1826, and jedi-language-server version 0.28.3.

In a file containing:

import random

random.gauss

If I point to the dot I get:

LSP :: Error from the Language Server: KeyError: 28 (Invalid Parameters)

in the minibuffer.

If you need more information, don't hesitate to ask (telling me how to gather them). I tried good old strace on jedi-language-server looking for tracebacks or KeyError but found nothing.

Sort param's first

Jedi's param completion for callable parameter names is super useful, but the sort order for them is places them too low in the hierarchy. They should be placed at the top

CodeAction fails in some cases

Repro code:

def func_efdbemfh(x):
    return x == 0


def factorial(x):
    if func_efdbemfh(x) or x == 1:
        return 1
    return x * factorial(x - 1)

This should probably go on jedi.

image

[Trace - 11:55:53 PM] Sending request 'textDocument/codeAction - (24)'.
Params: {
    "textDocument": {
        "uri": "file:///c%3A/GIT/repro/lsptest/tests/test_math2.py"
    },
    "range": {
        "start": {
            "line": 7,
            "character": 31
        },
        "end": {
            "line": 7,
            "character": 31
        }
    },
    "context": {
        "diagnostics": []
    }
}


Failed to handle request 24 textDocument/codeAction Object(textDocument=Object(uri='file:///c%3A/GIT/repro/lsptest/tests/test_math2.py'), range=Object(start=Object(line=7, character=31), end=Object(line=7, character=31)), context=Object(diagnostics=[]))
Traceback (most recent call last):
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\pygls\protocol.py", line 324, in _handle_request
    self._execute_request(msg_id, handler, params)
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\pygls\protocol.py", line 249, in _execute_request
    self._send_response(msg_id, handler(params))
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi_language_server\server.py", line 468, in code_action
    extract_function_refactoring = jedi_script.extract_function(
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi\api\helpers.py", line 488, in wrapper
    return func(self, line, column, *args, **kwargs)
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi\api\__init__.py", line 661, in extract_function
    return extract_function(
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi\api\refactoring\extract.py", line 244, in extract_function
    first, second = _split_prefix_at(after_leaf, until_pos[0])
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi\api\refactoring\extract.py", line 148, in _split_prefix_at
    second_line_count = leaf.start_pos[0] - until_line
AttributeError: 'NoneType' object has no attribute 'start_pos'
[Trace - 11:55:53 PM] Received response 'textDocument/codeAction - (24)' in 7ms. Request failed: AttributeError: 'NoneType' object has no attribute 'start_pos' (-32602).
Error data: "{'traceback': ['  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\pygls\\\\protocol.py\", line 324, in _handle_request\\n    self._execute_request(msg_id, handler, params)\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\pygls\\\\protocol.py\", line 249, in _execute_request\\n    self._send_response(msg_id, handler(params))\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi_language_server\\\\server.py\", line 468, in code_action\\n    extract_function_refactoring = jedi_script.extract_function(\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi\\\\api\\\\helpers.py\", line 488, in wrapper\\n    return func(self, line, column, *args, **kwargs)\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi\\\\api\\\\__init__.py\", line 661, in extract_function\\n    return extract_function(\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi\\\\api\\\\refactoring\\\\extract.py\", line 244, in extract_function\\n    first, second = _split_prefix_at(after_leaf, until_pos[0])\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi\\\\api\\\\refactoring\\\\extract.py\", line 148, in _split_prefix_at\\n    second_line_count = leaf.start_pos[0] - until_line\\n']}"


[Error - 11:55:53 PM] Request textDocument/codeAction failed.
  Message: AttributeError: 'NoneType' object has no attribute 'start_pos'
  Code: -32602 
{'traceback': ['  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\pygls\\protocol.py", line 324, in _handle_request\n    self._execute_request(msg_id, handler, params)\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\pygls\\protocol.py", line 249, in _execute_request\n    self._send_response(msg_id, handler(params))\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi_language_server\\server.py", line 468, in code_action\n    extract_function_refactoring = jedi_script.extract_function(\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi\\api\\helpers.py", line 488, in wrapper\n    return func(self, line, column, *args, **kwargs)\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi\\api\\__init__.py", line 661, in extract_function\n    return extract_function(\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi\\api\\refactoring\\extract.py", line 244, in extract_function\n    first, second = _split_prefix_at(after_leaf, until_pos[0])\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi\\api\\refactoring\\extract.py", line 148, in _split_prefix_at\n    second_line_count = leaf.start_pos[0] - until_line\n']}

image

[Trace - 11:59:46 PM] Sending request 'textDocument/codeAction - (5)'.
Params: {
    "textDocument": {
        "uri": "file:///c%3A/GIT/repro/lsptest/tests/test_math2.py"
    },
    "range": {
        "start": {
            "line": 5,
            "character": 23
        },
        "end": {
            "line": 5,
            "character": 23
        }
    },
    "context": {
        "diagnostics": []
    }
}


Failed to handle request 5 textDocument/codeAction Object(textDocument=Object(uri='file:///c%3A/GIT/repro/lsptest/tests/test_math2.py'), range=Object(start=Object(line=5, character=23), end=Object(line=5, character=23)), context=Object(diagnostics=[]))
Traceback (most recent call last):
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\pygls\protocol.py", line 324, in _handle_request
    self._execute_request(msg_id, handler, params)
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\pygls\protocol.py", line 249, in _execute_request
    self._send_response(msg_id, handler(params))
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi_language_server\server.py", line 446, in code_action
    extract_variable_refactoring = jedi_script.extract_variable(
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi\api\helpers.py", line 488, in wrapper
    return func(self, line, column, *args, **kwargs)
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi\api\__init__.py", line 614, in extract_variable
    return extract_variable(
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi\api\refactoring\extract.py", line 19, in extract_variable
    nodes = _find_nodes(module_node, pos, until_pos)
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi\api\refactoring\extract.py", line 87, in _find_nodes
    nodes = _remove_unwanted_expression_nodes(parent_node, pos, until_pos)
  File "c:\GIT\s p\vscode-python\pythonFiles\lib\python\jedi\api\refactoring\extract.py", line 198, in _remove_unwanted_expression_nodes
    nodes[0:1] = _remove_unwanted_expression_nodes(nodes[0], pos, until_pos)
IndexError: list index out of range
[Trace - 11:59:46 PM] Received response 'textDocument/codeAction - (5)' in 10ms. Request failed: IndexError: list index out of range (-32602).
Error data: "{'traceback': ['  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\pygls\\\\protocol.py\", line 324, in _handle_request\\n    self._execute_request(msg_id, handler, params)\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\pygls\\\\protocol.py\", line 249, in _execute_request\\n    self._send_response(msg_id, handler(params))\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi_language_server\\\\server.py\", line 446, in code_action\\n    extract_variable_refactoring = jedi_script.extract_variable(\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi\\\\api\\\\helpers.py\", line 488, in wrapper\\n    return func(self, line, column, *args, **kwargs)\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi\\\\api\\\\__init__.py\", line 614, in extract_variable\\n    return extract_variable(\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi\\\\api\\\\refactoring\\\\extract.py\", line 19, in extract_variable\\n    nodes = _find_nodes(module_node, pos, until_pos)\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi\\\\api\\\\refactoring\\\\extract.py\", line 87, in _find_nodes\\n    nodes = _remove_unwanted_expression_nodes(parent_node, pos, until_pos)\\n', '  File \"c:\\\\GIT\\\\s p\\\\vscode-python\\\\pythonFiles\\\\lib\\\\python\\\\jedi\\\\api\\\\refactoring\\\\extract.py\", line 198, in _remove_unwanted_expression_nodes\\n    nodes[0:1] = _remove_unwanted_expression_nodes(nodes[0], pos, until_pos)\\n']}"


[Error - 11:59:46 PM] Request textDocument/codeAction failed.
  Message: IndexError: list index out of range
  Code: -32602 
{'traceback': ['  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\pygls\\protocol.py", line 324, in _handle_request\n    self._execute_request(msg_id, handler, params)\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\pygls\\protocol.py", line 249, in _execute_request\n    self._send_response(msg_id, handler(params))\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi_language_server\\server.py", line 446, in code_action\n    extract_variable_refactoring = jedi_script.extract_variable(\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi\\api\\helpers.py", line 488, in wrapper\n    return func(self, line, column, *args, **kwargs)\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi\\api\\__init__.py", line 614, in extract_variable\n    return extract_variable(\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi\\api\\refactoring\\extract.py", line 19, in extract_variable\n    nodes = _find_nodes(module_node, pos, until_pos)\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi\\api\\refactoring\\extract.py", line 87, in _find_nodes\n    nodes = _remove_unwanted_expression_nodes(parent_node, pos, until_pos)\n', '  File "c:\\GIT\\s p\\vscode-python\\pythonFiles\\lib\\python\\jedi\\api\\refactoring\\extract.py", line 198, in _remove_unwanted_expression_nodes\n    nodes[0:1] = _remove_unwanted_expression_nodes(nodes[0], pos, until_pos)\n']}

Completions do not work for numpy

Hi there! Thanks for your work, jedi refactoring is so much better than rope. However, numpy completions is not working for me (does work with coc-python and vim-jedi), any idea how to debug?

Cheers,
Hans

What is jedi.trace.server?

I'm running into an issue with Emacs' lsp-jedi client. By default that client sends jedi.trace.server: 'verbose' param on the first workdspace/didChangeConfiguration after initialization. This parameter is clearly documented on coc-jedi, but I don't see where in the server code that is being processed. In fact, when sent, I get the following error:

fredcamps/lsp-jedi#3

I'm not sure if this is a documentation error or old code or what.

Problem with relative imports

I'm using JLS 0.23.1. I have the following structure in my project.

└── project
    └── module_a
        ├── __init__.py
        └── sub
            ├── a.py
            ├── b.py
            └── __init__.py

The code can be found here: https://github.com/oskarkv/jedi-problem

b.py looks like this:

from .a import a_func

def a_another():
    pass

def b_func(x):
    return a_func(x, 5)

And a.py looks like this:

def a_func(a, b):
    return a + b

In b.py I can't use, for example, find definition on a_func. But if I use the import statement from sub.a import a_func I can. Note that it seems I need the directory module_a above sub for it to not work; with just the sub directory it works fine with a relative import. It looks like jedi thinks a_func is a module in the first case, see the images below.

Thinks it's a module

Thinks it's a module

List index out of range

In jupyter lab, the following error occationally occurs:

Failed to handle request 648 textDocument/documentHighlight
Traceback (most recent call last):
  File "/Users/macbook/.pyenv/versions/3.8.7/lib/python3.8/site-packages/pygls/protocol.py", line 324, in _handle_request
    self._execute_request(msg_id, handler, params)
  File "/Users/macbook/.pyenv/versions/3.8.7/lib/python3.8/site-packages/pygls/protocol.py", line 249, in _execute_request
    self._send_response(msg_id, handler(params))
  File "/Users/macbook/.pyenv/versions/3.8.7/lib/python3.8/site-packages/jedi_language_server/server.py", line 268, in highlight
    jedi_lines = jedi_utils.line_column(jedi_script, params.position)
  File "/Users/macbook/.pyenv/versions/3.8.7/lib/python3.8/site-packages/jedi_language_server/jedi_utils.py", line 205, in line_column
    line_length = len(lines[position.line])
IndexError: list index out of range

jedi-langauge-server=0.23.1

regression: 0.28.3 fails to respond to `initialize` request, stalls and consumes high CPU

I'm working on an LSP client, and hoping to support jedi-language-server. When I started implementing, 0.27.2 was current, and this worked well. However, in testing, one of my testers reported that the client was hanging waiting for jedi-language-server.

Upon investigation, I found that the relevant difference was that the tester was running 0.28.3 rather than my 0.27.2, and upon updating my own installation of jedi-language-server to 0.28.3 I was able to reproduce the same symptom.

Platform: macOS 10.15.7
Python: 3.9.2
jedi-language-server: 0.28.3
Client: n/a

I don't have a clean test harness for reproducing this; I thought I could start jedi-language-server in a Terminal window and pipe or paste JSON into it, but that doesn't seem to work as expected. However, I have provided the JSON that is being sent to the server when it starts up, perhaps that is useful.

The regression is reproducible: use pip install -U jedi-language-server to install the current version (0.28.3 as I write this), and the server never responds to the initialize message. Sometimes it appears to continue running and consume high CPU, I have attached a macOS sample report, in case that is helpful.

Then, use pip uninstall jedi-language-server followed by pip install -Iv jedi-language-server==0.27.2 to install the older version, and the language server responds immediately and as expected to initialize and other protocol requests.

Thanks for reading; please let me know if there's any additional information I can provide.

initialize.json.zip
jedi-ls-sample.txt

No completion for matplotlib's subplot when using their new coding format

I was following the coding format from the 3.1.0 doc. I believe they call this the new object oriented approach.

I was not able to get completions, how ever if I use subplots in regular approach I get completions as expected.

Codes and Screenshots

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, (ax1, ax2) = plt.subplots(2)

fig.suptitle('Vertical stacked plots') # autocomplete here too
ax1.

python1

However after writing the complete functions, jedi language server doesn't show any error too, checked with both native jedi language server and pylint.

Information

Environment: I use coc-jedi with the coc.nvim plugin in vim/nvim.
OS: Linux
Editor: Vim/Neovim with coc.nvim as an lsp client

TypeError: tuple indices must be integers or slices, not str

First of all, thank you for your great work~
And the language server always crashes in recent versions.

Traceback

Traceback (most recent call last):
  File "/usr/local/bin/jedi-language-server", line 8, in <module>
    sys.exit(cli())
  File "/usr/local/lib/python3.7/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/lib/python3.7/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/jedi_language_server/cli.py", line 17, in cli
    SERVER.start_io()
  File "/usr/local/lib/python3.7/site-packages/pygls/server.py", line 179, in start_io
    self.lsp.data_received))
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 587, in run_until_complete
    return future.result()
  File "/usr/local/lib/python3.7/site-packages/pygls/server.py", line 69, in aio_readline
    proxy(b''.join(message))
  File "/usr/local/lib/python3.7/site-packages/pygls/protocol.py", line 445, in data_received
    object_hook=deserialize_message))
  File "/usr/local/lib/python3.7/site-packages/pygls/protocol.py", line 370, in _procedure_handler
    self._handle_response(message.id, message.result, message.error)
  File "/usr/local/lib/python3.7/site-packages/pygls/protocol.py", line 349, in _handle_response
    future.set_exception(JsonRpcException.from_dict(error))
  File "/usr/local/lib/python3.7/site-packages/pygls/exceptions.py", line 44, in from_dict
    if exc_class.supports_code(error['code']):
TypeError: tuple indices must be integers or slices, not str

Log

image

Version Info

jedi                 0.17.0
jedi-language-server 0.7.2
pygls                0.9.0

Extremely slow performance and high CPU usage for fastai library

I am using Neovim 0.5.0-dev+nightly with jedi-languange-server which works well and quickly for most packages like numpy for example. However when used with the fastai library the results take sometimes 10-30 minutes to show up when prompted.

To reproduce my issue you can install fastai via miniconda3:
conda install -c fastai -c pytorch fastai
and then install Jedi-language-server:
conda install jedi-language-server

Then open a file in neovim with the conda-env enabled and jedi enabled, here is a short example file:

from fastai.vision.all import *

path = untar_data(URLs.PETS)/'images'

def is_cat(x): return x[0].isupper()
dls = ImageDataLoaders.from_name_func(
        path, get_image_files(path), valid_pct=0.2, seed=42,
        label_func=is_cat, item_tfms=Resize(224))

learn = cnn_learner(dls, resnet34, metrics = error_rate)

then try to bring up hover help on one of the fastai functions like ImageDataLoaders. For me this takes several minutes and makes one of my CPUs stay at 100% for that entire time.

I'm wondering if this has something to do with the way that fastai is designed to be imported with from fastai import * which is not typical practice for python libraries.

If there is anymore information I can give you please let me know. Thanks

Static capabilities

I don't quite understand why this language server needs to register all of its capabilities dynamically:

:: --> jedi-language-server initialize(1): {'rootPath': '/home/raoul/.config/sublime-text-3/Packages/LSP', 'capabilities': {'experimental': {}, 'workspace': {'executeCommand': {}, 'didChangeConfiguration': {}, 'configuration': True, 'symbol': {'dynamicRegistration': True, 'symbolKind': {'valueSet': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]}}, 'applyEdit': True, 'workspaceFolders': True}, 'textDocument': {'typeDefinition': {'dynamicRegistration': True, 'linkSupport': True}, 'codeAction': {'dynamicRegistration': True, 'codeActionLiteralSupport': {'codeActionKind': {'valueSet': []}}}, 'implementation': {'dynamicRegistration': True, 'linkSupport': True}, 'rename': {'dynamicRegistration': True}, 'definition': {'dynamicRegistration': True, 'linkSupport': True}, 'completion': {'dynamicRegistration': True, 'completionItem': {'snippetSupport': True}, 'completionItemKind': {'valueSet': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]}}, 'hover': {'dynamicRegistration': True, 'contentFormat': ['markdown', 'plaintext']}, 'signatureHelp': {'dynamicRegistration': True, 'signatureInformation': {'parameterInformation': {'labelOffsetSupport': True}, 'documentationFormat': ['markdown', 'plaintext']}}, 'colorProvider': {'dynamicRegistration': True}, 'publishDiagnostics': {'relatedInformation': True}, 'formatting': {'dynamicRegistration': True}, 'rangeFormatting': {'dynamicRegistration': True}, 'references': {'dynamicRegistration': True}, 'declaration': {'dynamicRegistration': True, 'linkSupport': True}, 'documentSymbol': {'dynamicRegistration': True, 'symbolKind': {'valueSet': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]}}, 'documentHighlight': {'dynamicRegistration': True}, 'synchronization': {'willSaveWaitUntil': True, 'dynamicRegistration': True, 'willSave': True, 'didSave': True}}}, 'initializationOptions': {}, 'processId': 7057, 'workspaceFolders': [{'name': 'LSP', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP'}, {'name': 'LSP-eslint', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP-eslint'}, {'name': 'metals-sublime', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/metals-sublime'}, {'name': 'lsp_utils', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/lsp_utils'}, {'name': 'LSP-json', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP-json'}, {'name': 'UnitTesting', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/UnitTesting'}, {'name': 'LSP-vue', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP-vue'}, {'name': 'LSP-css', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP-css'}, {'name': 'LSP-html', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP-html'}, {'name': 'LSP-intelephense', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP-intelephense'}, {'name': 'LSP-typescript', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP-typescript'}, {'name': 'LSP-elm', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP-elm'}, {'name': 'User', 'uri': 'file:///home/raoul/.config/sublime-text-3/Packages/User'}, {'name': 'tonic', 'uri': 'file:///home/raoul/Documents/Programming/tonic'}], 'rootUri': 'file:///home/raoul/.config/sublime-text-3/Packages/LSP', 'clientInfo': {'name': 'Sublime Text LSP'}}
:: <<< jedi-language-server 1: {'capabilities': {'referencesProvider': False, 'hoverProvider': False, 'renameProvider': False, 'definitionProvider': False, 'executeCommandProvider': {'commands': []}, 'documentSymbolProvider': False, 'documentHighlightProvider': False, 'documentRangeFormattingProvider': False, 'workspaceSymbolProvider': False, 'workspace': {'workspaceFolders': {'changeNotifications': True, 'supported': True}}, 'documentFormattingProvider': False, 'textDocumentSync': 2, 'codeActionProvider': False}}
::  -> jedi-language-server initialized: {}
::  -> jedi-language-server textDocument/didOpen
:: <-- jedi-language-server workspace/configuration(03b5234d-8f0c-4316-9965-9f3911e0cef5): {'items': [{'section': 'jedi', 'scopeUri': None}]}
:: >>> jedi-language-server 03b5234d-8f0c-4316-9965-9f3911e0cef5: [None]
:: <-- jedi-language-server client/registerCapability(8f4015fb-a9b9-4c52-8d6a-cb46c4220d3d): {'registrations': [{'id': 'de8a2314-4162-4c6d-8d6a-f620854f465f', 'method': 'textDocument/completion', 'registerOptions': {'triggerCharacters': ['.', "'", '"']}}]}
:: >>> jedi-language-server 8f4015fb-a9b9-4c52-8d6a-cb46c4220d3d: None
:: <-- jedi-language-server client/registerCapability(88ac0d23-4fa3-4a94-98cb-e75688ffb04a): {'registrations': [{'id': '8b2739bf-9fc0-4809-a48d-0bd551987b87', 'method': 'textDocument/definition', 'registerOptions': {}}]}
:: >>> jedi-language-server 88ac0d23-4fa3-4a94-98cb-e75688ffb04a: None
:: <-- jedi-language-server client/registerCapability(3a30f99e-f728-47db-956a-bd9beb364c6b): {'registrations': [{'id': '780e31e2-9b02-4585-b3c2-a21e027cf2a8', 'method': 'textDocument/documentHighlight', 'registerOptions': {}}]}
:: >>> jedi-language-server 3a30f99e-f728-47db-956a-bd9beb364c6b: None
:: <-- jedi-language-server client/registerCapability(1f5b653f-6ca0-45a4-ae42-00071d96d874): {'registrations': [{'id': '2133486f-74c0-4022-b783-98f4febb33a5', 'method': 'textDocument/documentSymbol', 'registerOptions': {}}]}
:: >>> jedi-language-server 1f5b653f-6ca0-45a4-ae42-00071d96d874: None
:: <-- jedi-language-server client/registerCapability(d67ef90d-a7e5-4728-b088-57695a3140cb): {'registrations': [{'id': '595a229e-94b1-4fea-8d47-6e41dd026ff5', 'method': 'textDocument/hover', 'registerOptions': {}}]}
:: >>> jedi-language-server d67ef90d-a7e5-4728-b088-57695a3140cb: None
:: <-- jedi-language-server client/registerCapability(7c7d37b8-cace-47dc-8ea9-a5adb97928d7): {'registrations': [{'id': '90ba73d4-b6b1-41ca-a93f-61ee324cb138', 'method': 'textDocument/references', 'registerOptions': {}}]}
:: >>> jedi-language-server 7c7d37b8-cace-47dc-8ea9-a5adb97928d7: None
:: <-- jedi-language-server client/registerCapability(04bab9f0-ef3a-4169-9266-b86d066e7095): {'registrations': [{'id': '8c0863db-96c7-4c9e-8c69-9cef51acb92b', 'method': 'textDocument/rename', 'registerOptions': {}}]}
:: >>> jedi-language-server 04bab9f0-ef3a-4169-9266-b86d066e7095: None
:: <-- jedi-language-server client/registerCapability(cfe3dfd6-c3a1-407d-a5ac-bfc403097b7f): {'registrations': [{'id': '1e058f76-d10c-432a-8c45-f64e639c5fbb', 'method': 'textDocument/signatureHelp', 'registerOptions': {'triggerCharacters': ['(', ',', ')']}}]}
:: >>> jedi-language-server cfe3dfd6-c3a1-407d-a5ac-bfc403097b7f: None
:: <-- jedi-language-server client/registerCapability(66429cb1-ed0f-4efd-8a44-740d2481338e): {'registrations': [{'id': '91701d2c-5e7c-4334-965e-84d88254de85', 'method': 'workspace/symbol', 'registerOptions': {}}]}
:: >>> jedi-language-server 66429cb1-ed0f-4efd-8a44-740d2481338e: None
:: <-- jedi-language-server client/registerCapability(82c9352c-06f4-4a39-9169-5a4c7a0d1f7a): {'registrations': [{'id': '58635467-db25-41c9-b78d-8c31d68c856e', 'method': 'textDocument/didOpen', 'registerOptions': {}}]}
:: >>> jedi-language-server 82c9352c-06f4-4a39-9169-5a4c7a0d1f7a: None
:: <-- jedi-language-server client/registerCapability(5f60e62b-e254-4e14-9bc1-84ca459b4095): {'registrations': [{'id': '086b4cc1-8511-43db-bf9a-c3e66410db49', 'method': 'textDocument/didChange', 'registerOptions': {}}]}
:: >>> jedi-language-server 5f60e62b-e254-4e14-9bc1-84ca459b4095: None
:: <-- jedi-language-server client/registerCapability(35874c00-9974-4aa3-a032-76f08914f4ca): {'registrations': [{'id': '1e6b6b84-4f18-4521-8625-f663e1a32187', 'method': 'textDocument/didSave', 'registerOptions': {}}]}
:: >>> jedi-language-server 35874c00-9974-4aa3-a032-76f08914f4ca: None
:: <-  jedi-language-server window/showMessage: {'type': 3, 'message': 'jedi-language-server initialized'}

Wouldn't it be easier to put all this stuff in the initialize response?

Renaming merges two lines

Info

NVIM v0.5.0-dev+1073-gb894fbcbe
jedi-language-server, version 0.21.0
Python 3.9.1

Problem

Renaming a variable merges the line where the variable is defined with the line above.

Minimal init.vim

set runtimepath^=~/.local/share/nvim/plugins/nvim-lspconfig
lua require 'lspconfig'.jedi_language_server.setup{}
nnoremap gr :lua vim.lsp.buf.rename()<cr>

Minimal bug.py

# bug incoming
x = 1

Reproduce

  1. Install neovim-nightly
  2. Install nvim-lspconfig and put it on nvims runtimepath. In my case its ~/.local/share/nvim/plugins/nvim-lspconfig
  3. Create minimal vimrc and bug.py
  4. Open bug.py with neovim
  5. Move cursor on the variable x
  6. Type gr and rename variable to y

The comment and the variable are now merged into a single line:

# bug incomingx = 1

I tried the same setup with the python-language-server and it worked without the bug.

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.