Giter Site home page Giter Site logo

jupyter-lsp / jupyterlab-lsp Goto Github PK

View Code? Open in Web Editor NEW
1.7K 20.0 141.0 9.16 MB

Coding assistance for JupyterLab (code navigation + hover suggestions + linters + autocompletion + rename) using Language Server Protocol

Home Page: https://jupyterlab-lsp.readthedocs.io

License: BSD 3-Clause "New" or "Revised" License

JavaScript 0.97% Shell 0.06% TypeScript 64.81% CSS 1.96% Python 20.87% R 0.07% RobotFramework 9.21% Dockerfile 0.01% Jupyter Notebook 2.00% TeX 0.01% Less 0.01% SCSS 0.02% Julia 0.01%
jupyterlab jupyterlab-extension language-server-protocol jupyter-lab lsp linter jupyter jupyter-notebook notebook notebook-jupyter ipython autocompletion julia-language r

jupyterlab-lsp's Introduction

Language Server Protocol integration for Jupyter(Lab)

CI Documentation Status Python Demo R Demo Julia Demo Binder

Installation | Configuring | Changelog | Roadmap | Contributing | Extending

Features

Examples show Python code, but most features also work in R, bash, typescript, and many other languages.

Hover

Hover over any piece of code; if an underline appears, you can press Ctrl to get a tooltip with function/class signature, module documentation or any other piece of information that the language server provides

hover

Diagnostics

Critical errors have red underline, warnings are orange, etc. Hover over the underlined code to see a more detailed message

inspections

Jump to Definition and References

Use the context menu entry, or Alt + 🖱️ to jump to definitions/references (you can change it to Ctrl/ in settings); use Alt + o to jump back.

jump

Highlight References

Place your cursor on a variable, function, etc and all the usages will be highlighted

Automatic Completion and Continuous Hinting

  • Certain characters, for example '.' (dot) in Python, will automatically trigger completion.
  • You can choose to receive the completion suggestions as you type by enabling continuousHinting setting.

invoke

Automatic Signature Suggestions

Function signatures will automatically be displayed

signature

Kernel-less Autocompletion

Advanced static-analysis autocompletion without a running kernel

autocompletion

The runtime kernel suggestions are still there

When a kernel is available the suggestions from the kernel (such as keys of a dict and columns of a DataFrame) are merged with the suggestions from the Language Server (in notebook).

If the kernel is too slow to respond promptly only the Language Server suggestions will be shown (default threshold: 0.6s). You can configure the completer to not attempt to fetch the kernel completions if the kernel is busy (skipping the 0.6s timeout).

You can deactivate the kernel suggestions by adding "Kernel" to the disableCompletionsFrom in the completion section of Advanced Settings. Alternatively if you only want kernel completions you can add "LSP" to the same setting; Or add both if you like to code in hardcore mode and get no completions, or if another provider has been added.

Rename

Rename variables, functions and more, in both: notebooks and the file editor. Use the context menu option or the F2 shortcut to invoke.

rename

Diagnostics panel

Sort and jump between the diagnostics using the diagnostics panel. Open it searching for "Show diagnostics panel" in JupyterLab commands palette or from the context menu. Use context menu on rows in the panel to filter out diagnostics or copy their message.

panel

Prerequisites

You will need to have both of the following installed:

  • JupyterLab >=4.1.0,<5.0.0a0
  • Python 3.8+

In addition, if you wish to use javascript, html, markdown or any other NodeJS-based language server you will need to have appropriate NodeJS version installed.

Note: Installation for JupyterLab 2.x requires a different procedure, please consult the documentation for the extension version 2.x.

Installation

For more extensive installation instructions, see the documentation.

For the current stable version, the following steps are recommended. Use of a python virtualenv or a conda env is also recommended.

  1. install python 3

    conda install -c conda-forge python=3
  2. install JupyterLab and the extensions

    conda install -c conda-forge 'jupyterlab>=4.1.0,<5.0.0a0' jupyterlab-lsp
    # or
    pip install 'jupyterlab>=4.1.0,<5.0.0a0' jupyterlab-lsp

    Note: jupyterlab-lsp provides both the server extension and the lab extension.

    Note: With conda, you could take advantage of the bundles: jupyter-lsp-python or jupyter-lsp-r to install both the server extension and the language server.

  3. install LSP servers for languages of your choice; for example, for Python (pylsp) and R (languageserver) servers:

    pip install 'python-lsp-server[all]'
    R -e 'install.packages("languageserver")'

    or from conda-forge

    conda install -c conda-forge python-lsp-server r-languageserver

    Please see our full list of supported language servers which includes installation hints for the common package managers (npm/pip/conda). In general, any LSP server from the Microsoft list should work after some additional configuration.

    Note: it is worth visiting the repository of each server you install as many provide additional configuration options.

  4. Restart JupyterLab

    If JupyterLab is running when you installed the extension, a restart is required for the server extension and any language servers to be recognized by JupyterLab.

  5. (Optional, IPython users only) to improve the performance of autocompletion, disable Jedi in IPython (the LSP servers for Python use Jedi too). You can do that temporarily with:

    %config Completer.use_jedi = False
    

    or permanently by setting c.Completer.use_jedi = False in your ipython_config.py file.

  6. (Optional, Linux/OSX-only) As a security measure by default Jupyter server only allows access to files under the Jupyter root directory (the place where you launch the Jupyter server). Thus, in order to allow jupyterlab-lsp to navigate to external files such as packages installed system-wide or to libraries inside a virtual environment (conda, pip, ...) this access control mechanism needs to be circumvented: inside your Jupyter root directory create a symlink named .lsp_symlink pointing to your system root /.

    ln -s / .lsp_symlink
    

    As this symlink is a hidden file the Jupyter server must be instructed to serve hidden files. Either use the appropriate command line flag:

    jupyter lab --ContentsManager.allow_hidden=True
    

    or, alternatively, set the corresponding setting inside your jupyter_server_config.py.

    Help in implementing a custom ContentsManager which will enable navigating to external files without the symlink is welcome.

Configuring the servers

Server configurations can be edited using the Advanced Settings editor in JupyterLab (Settings > Advanced Settings Editor). For settings specific to each server, please see the table of language servers. Example settings might include:

{
  "language_servers": {
    "pylsp": {
      "serverSettings": {
        "pylsp.plugins.pydocstyle.enabled": true,
        "pylsp.plugins.pyflakes.enabled": false,
        "pylsp.plugins.flake8.enabled": true
      }
    },
    "r-languageserver": {
      "serverSettings": {
        "r.lsp.debug": false,
        "r.lsp.diagnostics": false
      }
    }
  }
}

The serverSettings key specifies the configurations sent to the language servers. These can be written using stringified dot accessors like above (in the VSCode style), or as nested JSON objects, e.g.:

{
  "language_servers": {
    "pylsp": {
      "serverSettings": {
        "pylsp": {
          "plugins": {
            "pydocstyle": {
              "enabled": true
            },
            "pyflakes": {
              "enabled": false
            },
            "flake8": {
              "enabled": true
            }
          }
        }
      }
    }
  }
}

Other configuration methods

Some language servers, such as pylsp, provide other configuration methods in addition to language-server configuration messages (accessed using the Advanced Settings Editor). For example, pylsp allows users to configure the server using a local configuration file. You can change the inspection/diagnostics for server plugins like pycodestyle there.

The exact configuration details will vary between operating systems (please see the configuration section of pycodestyle documentation), but as an example, on Linux you would simply need to create a file called ~/.config/pycodestyle, which may look like that:

[pycodestyle]
ignore = E402, E703
max-line-length = 120

In the example above:

  • ignoring E402 allows imports which are not on the very top of the file,
  • ignoring E703 allows terminating semicolon (useful for matplotlib plots),
  • the maximal allowed line length is increased to 120.

After changing the configuration you may need to restart the JupyterLab, and please be advised that the errors in configuration may prevent the servers from functioning properly.

Again, please do check the pycodestyle documentation for specific error codes, and check the configuration of other feature providers and language servers as needed.

Acknowledgements

This would not be possible without the fantastic initial work at wylieconlon/lsp-editor-adapter.

jupyterlab-lsp's People

Contributors

andaag avatar bollwyvl avatar bsyouness avatar carreau avatar cccs-jc avatar dependabot[bot] avatar dpriedel avatar edzkite avatar fcollonval avatar frenzymadness avatar i-aki-y avatar icankeep avatar jessicabarh avatar jtpio avatar julioyildo avatar justin-f-perez avatar karlaspuldaro avatar krassowski avatar marimeireles avatar martinrenou avatar michaelaye avatar mnowacki-b avatar nickfong avatar quantum-booty avatar slavistan avatar trajamsmith avatar yamaton avatar yunair avatar yuntan avatar zhanba 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  avatar  avatar  avatar  avatar  avatar  avatar

jupyterlab-lsp's Issues

Investigate possible issues with jupyterlab 1.2

JupyterLab 1.2.0rc0 is up on pip and conda, with the planned release date of 2019-10-29 (doh #65) we should at least take a look at it... i'll give it a minimal look through, and if it seems ok, will look at popping up the dependency strings. It would be great if we could support it transparently. Who knows, might find something useful for upstream!

CamelCase naming convention?

I see codes like:

  connect_completion() {
    // see https://github.com/jupyterlab/jupyterlab/blob/c0e9eb94668832d1208ad3b00a9791ef181eca4c/packages/completer-extension/src/index.ts#L198-L213
    const cell = this.widget.content.activeCell;
    this.set_completion_connector(cell);
    const handler = this.completion_manager.register({
      connector: this.current_completion_connector,
      editor: cell.editor,
      parent: this.widget
    });
    this.widget.content.activeCellChanged.connect((notebook, cell) => {
      this.set_completion_connector(cell);

      handler.editor = cell.editor;
      handler.connector = this.current_completion_connector;
    });
  }

The JupyterLab project's naming convention is CamelCase, eg.this.widget.content.activeCellChanged, it looks better if the extension code use the same naming convention.

Implement "Highlight all" action in notebooks

The action is offered in the context menu, but it does not work yet.

Note: this is different from what the default JupyterLab 1.0 search provider does, as LSP implemention - as for now - does not cover the markdown cells. Those could be included in the future, as to allow rename action to cover references in markdown cells.

Initialization problem?

Both binder and my local version work now perfectly (after refactoring all the features and removing the dependency on third-party CodeMirrorAdapter), but they appear to only work after refreshing the window. It seems that there is a problem with initialization after connection/registration of features.

Split the CodeMirrorAdapterExtension into smaller modules

So far I have tried to follow the patterns from the upstream CodeMirrorAdapter of wylieconlon/lsp-editor-adapter. Their design is alright for the number of LSP features implemented; however, the added complexity of the virtual document model introduced to support notebooks and nested foreign code makes it no longer sustainable to keep everything in one large class. As I plan to implement more LSP functions, it does not seem to be reasonable to keep inheriting from the upstream class as there are too many divergent needs when it comes to JupyterLab integration.

I think that having one file per LSP function and using a manager pattern (as used for the extensions in JupyterLab) would be a good idea. A similar idea for the reduction of complexity of the index was suggested in #22.

The initial interface idea:

interface ILSPFunction {
  /** Connect event handlers to the editor, virtual document and connection(s) **/
  register(
    virtualEditor: IVritualEditor,
    virtualDocument: IVritualDocument,
    connection: ILSPConnection
  );
  /** Will allow the user to disable specific functions **/
  isEnabled: boolean;
  /** Return JupyterLab commands to be registered;
  * intended for single-use in index.ts (during extension registration)
  **/
  get commands(): IJupyterLabCommand;
  /** Return the context menu commands to be added during extension registration.
  * The comands would be grouped by target context menu (like Cell or FileEditor).
  **/
  get contextMenuCommands();
  /** Remove event handlers on descruction **/
  remove();
}

Using such a pattern would also make it easier to unit test specific functions.

There is a small performance penalty, as some things which share logic in a single handler will need to be repeated for the individual functions and multiple event handlers will be needed; I do not think that this will be significant.

How to make jupyterlab-lsp work with Jupyter Lab - Launching Example Server failed: Error: spawn pyls ENOENT

It might be a lame question, but I went through all the installation steps and still can't get jupyterlab-lsp to work:

  • extension was installed in jupyter lab
  • I installed the python-language-server
  • servers.yml file - is in the folder from where my virtual env starts and I launch jupyter lab
  • before starting jupyter lab I run the following line but it results in this error:
node /Users/konrad/.local/share/virtualenvs/SharedEnv-r6sHwbPo/share/jupyter/lab/staging/node_modules/jsonrpc-ws-proxy/dist/server.js --port 3000 --languageServers servers.yml

image

What am I missing here?

Unit test connection and connection restoration after failure

Follow up on #4. Two major scenarios to test:

  • LSP server not available when notebook starting, but available afterwards
  • connection to the LSP server temporarily lost

Also:

  • the LSP server encounters a serious error and the pipe gets broken; it should be restarted; we should require that no more that 3 failures occur or that they occur not more often than once every 15 minutes.

Support %run magic for IPython

This is a conceptually similar task to the task of the code extractor, but instead of extracting some code from the file it adds code at each virtual document refresh operation.

We would need to open the file, process the included notebook into a virtual document and embed it in the current virtual document. This definitely goes to the future jupyterlab-lsp-python (or ipython) extension.

FileNotFoundError in web and server console

Hello,

Thank you for this extension! Started to working on it and have an issue:
Constantly getting an errors for accessing folders in my working directory.

Can you please help?

Traceback (most recent call last):
  File "/opt/conda/lib/python3.7/site-packages/pyls_jsonrpc/endpoint.py", line 113, in consume
    self._handle_request(message['id'], message['method'], message.get('params'))
  File "/opt/conda/lib/python3.7/site-packages/pyls_jsonrpc/endpoint.py", line 182, in _handle_request
    handler_result = handler(params)
  File "/opt/conda/lib/python3.7/site-packages/pyls_jsonrpc/dispatchers.py", line 23, in handler
    return method(**(params or {}))
  File "/opt/conda/lib/python3.7/site-packages/pyls/python_ls.py", line 311, in m_text_document__document_highlight
    return self.highlight(textDocument['uri'], position)
  File "/opt/conda/lib/python3.7/site-packages/pyls/python_ls.py", line 248, in highlight
    return flatten(self._hook('pyls_document_highlight', doc_uri, position=position)) or None
  File "/opt/conda/lib/python3.7/site-packages/pyls/python_ls.py", line 143, in _hook
    return hook_handlers(config=self.config, workspace=workspace, document=doc, **kwargs)
  File "/opt/conda/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__
    return self._hookexec(self, self.get_hookimpls(), kwargs)
  File "/opt/conda/lib/python3.7/site-packages/pluggy/manager.py", line 92, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "/opt/conda/lib/python3.7/site-packages/pluggy/manager.py", line 335, in traced_hookexec
    return outcome.get_result()
  File "/opt/conda/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/opt/conda/lib/python3.7/site-packages/pluggy/callers.py", line 52, in from_call
    result = func()
  File "/opt/conda/lib/python3.7/site-packages/pluggy/manager.py", line 333, in <lambda>
    outcome = _Result.from_call(lambda: oldcall(hook, hook_impls, kwargs))
  File "/opt/conda/lib/python3.7/site-packages/pluggy/manager.py", line 86, in <lambda>
    firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
  File "/opt/conda/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
    return outcome.get_result()
  File "/opt/conda/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/opt/conda/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
    res = hook_impl.function(*args)
  File "/opt/conda/lib/python3.7/site-packages/pyls/plugins/highlight.py", line 10, in pyls_document_highlight
    usages = document.jedi_script(position).usages()
  File "/opt/conda/lib/python3.7/site-packages/jedi/api/__init__.py", line 349, in usages
    return _usages(**kwargs)
  File "/opt/conda/lib/python3.7/site-packages/jedi/api/__init__.py", line 343, in _usages
    names = usages.usages(self._get_module(), tree_name)
  File "/opt/conda/lib/python3.7/site-packages/jedi/evaluate/usages.py", line 44, in usages
    for m in imports.get_modules_containing_name(module_context.evaluator, modules, search_name):
  File "/opt/conda/lib/python3.7/site-packages/jedi/evaluate/imports.py", line 565, in get_modules_containing_name
    for file_io, base_names in get_file_ios_to_check():
  File "/opt/conda/lib/python3.7/site-packages/jedi/evaluate/imports.py", line 557, in get_file_ios_to_check
    for file_io in check_directory(folder_io):
  File "/opt/conda/lib/python3.7/site-packages/jedi/evaluate/imports.py", line 520, in check_directory
    for file_name in folder_io.list():
  File "/opt/conda/lib/python3.7/site-packages/jedi/file_io.py", line 19, in list
    return os.listdir(self.path)
FileNotFoundError: [Errno 2] No such file or directory: '/education/yandex_praktikum/data_analyst'

image

Scala Metals fails

Scala Metals is a language server that communicates over JSON-RPC. It can be installed with

curl -Lo coursier https://git.io/coursier-cli && chmod +x coursier
./coursier bootstrap org.scalameta:metals_2.12:0.7.0 -o metals -f`

The contents of my servers.yml:

langservers:
  scala:
    - /Users/marduk/metals

I launched Jupyter Lab as follows:

node miniconda3/share/jupyter/lab/staging/node_modules/jsonrpc-ws-proxy/dist/server.js --port 3000 --languageServers servers.yml 

jupyter lab

I created a Scala notebook (using the Almond kernel) and in ~/Library/Caches/org.scalameta.metals/global.log I got the following error:

INFO  tracing is disabled for protocol LSP, to enable tracing of incoming and outgoing JSON messages create an empty file at /Users/marduk/Library/Caches/org.scalameta.metals/lsp.trace.json
INFO  Starting Metals server with configuration: MetalsServerConfig(
  bloop-protocol=BloopProtocol(auto),
  glob-syntax=GlobSyntaxConfig(uri),
  status-bar=StatusBarConfig(off),
  slow-task=SlowTaskConfig(off),
  execute-client-command=ExecuteClientCommandConfig(off),
  show-message=ShowMessageConfig(on),
  show-message-request=ShowMessageRequestConfig(on),
  no-initialized=false,
  compilers=PresentationCompilerConfigImpl(false,None,None,Map(scala/collection/mutable/ -> mutable., java/util/ -> ju.),Ascii,true,true,true,true,true,20,SECONDS),
  http=false,
  input-box=false,
  icons=none,
  statistics=StatisticsConfig(default)
)
INFO  logging to file /.metals/metals.log
Sep 01, 2019 9:45:07 PM org.eclipse.lsp4j.jsonrpc.RemoteEndpoint fallbackResponseError
SEVERE: Internal error: java.nio.file.AccessDeniedException: /.metals

So it seems that Metals cannot create the directory .metals in the current workspace. I did some research and it appears that the workspace for the language server is set by jsonrpc-ws-proxy/dist/server.js.

Metals works in all the major editors, but it would be awesome to have it available in JupyterLab. See Integrating a new editor for details.

Settings system

An issue to write down ideas or requests for what options should be included.

As a starting point I imagine that the JSON structure will hold 'general' settings in one key and language-specific overrides (empty by default) in all the following keys.

The settings will be further subdivided by the LSP function. Possibly like that:

{
  "general": {
    "inspections": {},
    "autocompletion": {
        "auto-invoke": true,
        "invoke-after-any": false 
    },
    "highlight-on-cursor": {}
  },
  "python": {
     "inspections": {
        "ignore": ["E222"]
     },
    // specific functions can be disabled by the user by setting false
    // (or maybe 'disable'?)
    "highlight-on-cursor": false
  }
}

Edit - other settings worth to include:

  • whether to display the documentation in the signature suggestion
  • magic overrides
  • foreign code extractors (regular expressions)
  • modifier key for the hover action
  • the default inspections severity (when server does not provide one)

KeyError when opening new notebook

I followed the steps outlined in readme, but it seems that pyls can't find source files I get this error:

Example Server: 2019-09-12 10:35:37,818 UTC - ERROR - pyls_jsonrpc.endpoint - Failed to handle notification textDocument/didChange: {'textDocument': {'uri': 'file:///test.ipynb.python', 'version': 1}, 'contentChanges': [{'text': 'import pandas as pd\n\n\npd.\n'}]}
Traceback (most recent call last):                                                                                                                                                                                    File "/usr/local/miniconda3/envs/notebook/lib/python3.7/site-packages/pyls_jsonrpc/endpoint.py", line 142, in _handle_notification
    handler_result = handler(params)
  File "/usr/local/miniconda3/envs/notebook/lib/python3.7/site-packages/pyls_jsonrpc/dispatchers.py", line 23, in handler                                                                                               return method(**(params or {}))
  File "/usr/local/miniconda3/envs/notebook/lib/python3.7/site-packages/pyls/python_ls.py", line 281, in m_text_document__did_change
    version=textDocument.get('version')                                                                                                                                                                               File "/usr/local/miniconda3/envs/notebook/lib/python3.7/site-packages/pyls/workspace.py", line 77, in update_document
    self._docs[doc_uri].apply_change(change)
KeyError: 'file:///test.ipynb.python'

jupyterlab-lsp and jupyterhub

First: thanks a lot for this awesome work @krassowski and thanks too for your PR @bollwyvl.

I installed jupyterlab-lsp on jupyterhub (with dockerspawner) and jupyter-server-proxy.

For that, I use two things from @bollwyvl 's PR:

  • Add the schema file (require for install)
  • And replace (in src/adapters/jupyterlab.ts):
    let socket = new WebSocket('ws://localhost:3000/' + language);
    by
    const wsBase = PageConfig.getBaseUrl().replace(/^http/, '');
    const wsUrl = `ws${wsBase}lsp/${language}`;
    let socket = new WebSocket(wsUrl);

And it works !!! So thanks a lot again !!

Some improvement ideas:

Regards

Create separate repositories for R, Julia, Scala, etc binder demos?

Runtimes which are not installed by default (i.e. Python, typescript and friends) slow down the binder setup.

We could create additional repositories with custom binder configuration to allow for more demos, e.g. one per language. The central repo could either stay with Python and typescript only, or it could incorporate all the supported runtimes (so that if any one of them fails we do not miss this).

Autocompletion should work in excluded cells

Currently the %% IPython cells are assumed to contain foreign code and excluded; however, at a minimum, the LSP completer - which does not work for such cells as the cell is not in the virtual document map - should pass the completion request to the kernel completer to avoid regressions.

The warnings underline may have too low contrast

It is perfect in the night mode, but I have difficulty seeing it with the light theme (sometimes, when my eyes are tired), thus I imagine that this could be a big issue for people with vision problems.

Using a programmatic underline would allow adjusting width of the underline (boldness of the line), as well as using the "wavy" underline which is more commonly associated with linters/spellcheck suggestions; see this comment.

Selectively enable/disable LSP features

Extracting discussion from #55, quote by @bollwyvl :

Not in this pr, but: I'd also like to see a toolbar item that let you
enable/disable different language server ui features for the current file.
It could be right aligned, but left of the kernel name/status icon, and
also have an indicator of whether there is pending stuff... This would be
particularly useful in the typescript case which takes upwards of a
minute
to fully resolve all the references in, say, index.ts.

I think that a statusbar would be a good place for it (so that we have it for both files and notebooks).

Sketch:

{
    "disableForKernels": {
      "title": "Disable for specific kernels",
      "type": "array",
      "items": {
        "type": "string"
      },
      "default": []
    }
}

Code completion sometimes overwrites existing text

Happens only when completing a code symbol which is in the middle of a line (not at the end). Needs unit tests to prevent this in the future.

Example:
DataFrame(da<tab>) leads to DataFrame(dta=), should DataFrame(data=)

R examples:
data.frame(row.nam<tab>data.frame(row.nrow.names
data.f<tab>data.fdata.frame

An error occurred when installing

A UnicodeDecodeError occurred when installing with the following command:

$ jupyter labextension install "@krassowski/jupyterlab-lsp"
Building jupyterlab assets
/Exception in thread Thread-2:

Traceback (most recent call last):
  File "c:\users\****\anaconda3\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "c:\users\****\anaconda3\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "c:\users\****\anaconda3\lib\subprocess.py", line 1238, in _readerthread
    buffer.append(fh.read())
UnicodeDecodeError: 'cp932' codec can't decode byte 0xef in position 7095: illegal multibyte sequence

Environment

  • OS: Windows 7(Japanese)
  • jupyterlab==1.0.2
  • conda-forge/win-64::conda-package-handling-1.4.1-py37_0
  • conda-forge/win-64::nodejs-12.8.1-0
  • conda-4.7.11-py37_0
  • Python 3.7.3

Notes

  • cp932 is used in the standard output of Japanese Windows computers (mainly command prompt, like anaconda prompt). So probably this error will not be occurred English environment or other OS, like Ubuntu.
  • This error happen both on the command line and JupyterLab's Extension Manager.

Temporary solution

When I use --debug argument to inspect, then build completed successfully (probably the change of the standard output contents during the build seems to solve this problem).

$ jupyter labextension install "@krassowski/jupyterlab-lsp" --debug

Consider allowing to include the markdown cells in the virtual documents

As mentioned in #18, our virtual documents do not include markdown cells. Those could be included in the future, as to allow rename action to cover references in markdown cells. It probably should be a user choice and not a default as it might be difficult to implement well in a way which is compatible with every kernel. I imagine it as the user installing a language-specific client extension (let's say jupyterlab-lsp-python) which provides:

  • sanitize_and_wrap() function to convert markdown to escaped comment or string which can be safely embedded in the source code for given language
  • unwrap_and_unsanitize() which goes the other way around.
    Probably we can think of better names for the methods later on.

jsonrpc-ws-proxy

Good afternoon! please tell me completely confused, in what order and what to install? I seem to do everything according to the instructions and in the package.json file there is no "jsonrpc-ws-proxy", and server.js, respectively

Handle IPython line magics and shell assignments

When line magics are detected in the notebook (lines starting with '%') a non-intrusive message should be shown to the user, like that:

It seems that your notebook contains IPython magics (special commands starting with %); Should the LSP linters ignore them?

with options "Ignore" and "Let the server lint lines starting with '%'". This way the few languages in which this could be a false positive would not be affected. Also, we could have a blacklist of languages for which the message would not appear in the first place.

Relative paths handling

LSP server as currently run requires absolute paths, which are not provided to the fronted. Ideally, this would be resolved on the server-side, but a quick workaround would be to add an option to prepend the custom path to the current directory.

Consider support for the languagetool-languageserver

languagetool-languageserver implements LSP for the purpose of spell- and grammar- checking. The "languagetool" supports many languages. We can utilize it to provide spell-checking in:

  • markdown cells
  • comments and docstrings

This would improve upon the existing (and already awesome) jupyterlab_spellchecker, because:

  • we would be able to get "quick fix" suggestions to quickly correct the typos
  • would be able to lint comments and other language-specific constructs (whereas the current spellchecker extension only works for the markdown cells)

This should be implemented as an extension and our task, for now, is to make it possible. The comments can be already extracted with the IForeignCodeExtractor and fed to the language server.

There are two challenges as for now:

  • the markdown cells are currently ignored in the virtual document model; maybe we could have two documents (one for markdown, one for code);
  • there are many programming languages which would need dedicated code extractors; this could be addressed:
    • requesting the language-specific extensions (e.g. jupyterlab-lsp-python) to provide "text" extractors (e.g. comments and docstrings in Python, or for non-marked text inside of HTML markers), or
    • leaving this responsibility on the future jupyterlab-lsp-languagetool extension which would let you choose one of the common comment formats from pre-defined regular expressions (e.g. detecting lines starting with # for Python and R or starting with // for JS and C)

Some events are not fired in the FileEditor

In 0.5.0 RC I see that some events (change and onCursorActivity) are not fired or not received by the adapter, therefore the auto invoke of completion after typing a dot in Python and the cursor highlighting the symbol usages do not work. May have something to do with how the events' registration is proxied.

Third-party module type annotation support

Hi.

If possible, it would be nicer to support completion of the third-party module 's type annotated object(e.g., pandas.DataFrame) :D

  • built-in object annotation completion -> Worked:

20190825_2

  • Self-defined original class -> Worked:

20190825_7

  • Third-party class -> Not invoked:

20190825_5

20190825_6

Maybe this is a issue with the python-language-server library, not this extension.
If so, I'll close this.

Thx.

No `node_modules/jsonrpc-ws-proxy/dist/server.js` in jupyterlab/staging

I have installed anaconda distribution for python and I found the staging directory
$HOME/opt/anaconda3/lib/python3.7/site-packages/jupyterlab/staging but I do not see any node_modules subdirectory here. How do I proceed? The contents of the directory are

templates  package.json       webpack.prod.config.js           yarn.js
index.js   webpack.config.js  webpack.prod.minimize.config.js  yarn.lock

LSP completer should not wait for kernel completer if it is busy

The awaiting for kernel completer should have a timeout (maybe 0.5s).

In future: once kernel finishes, it would be nice to dynamically append the suggestions from kernel to the completion list and indicate that it has been updated. There is a question if the late suggestions should go to the very end of the list or be placed as they would be placed otherwise.

before starting JupyterLab phase error

When I run this command:

node /path/to/anaconda/3/share/jupyter/lab/staging --port 3000 --languageServers servers.yml

I get this error:

`import {
^

SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:760:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
at internal/main/run_main_module.js:21:11
`

The only thing I have done was installing nodejs from conda, and my python version 3.7. I wonder if any of those can be the culprit?

Edit:

I also tried site-packages of the python3 version installed by conda but with the same result. I feel my nodejs must be the reasons but I am not sure if I had to do anything for setting it up beforehand!

Line breaks at docstring's parameters and returns section

Enhancement proposal:

If there is a line break for each argument (or return value) in the Parameters (or Returns) section of docstring, it will be easier to see.

Example

Current docstring view :

def sample_func(x, y):
    """
    Sample function.

    Parameters
    ----------
    x : int
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
        do eiusmod tempor incididunt ut.
    y : int
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
        do eiusmod tempor incididunt ut.

    Returns
    -------
    x : int
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
        do eiusmod tempor incididunt ut.
    y : int
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
        do eiusmod tempor incididunt ut.
    """
    pass
sample_func()

20190827_1

I hope there is a newline before second argument (y).

e.g.

Parameters¶

x : int Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut.

y : int Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut.

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.