LSP-pyright

repository·master·Indexed 41 days ago

https://github.com/sublimelsp/lsp-pyright

Python language server support for Sublime Text via the Microsoft Pyright language server. Integrates with the Sublime LSP plugin to provide autocompletion, type checking, and diagnostics. Features include automatic virtual environment detection via venvStrategies, custom status bar templates using Jinja2, and support for pyrightconfig.json configuration files.

Tokens
3.1K
Snippets
14
Records
16
Agent score
50%

What's inside LSP-pyright

  1. Restore default diagnostic severity overrides in LSP-pyright

    master

    As of version 1.3.4, LSP-pyright no longer includes default values for python.analysis.diagnosticSeverityOverrides. If you want to restore the previous behavior where specific diagnostic rules were set to warning or information, you must manually add them to your settings configuration.

    "python.analysis.diagnosticSeverityOverrides": {
      "reportDuplicateImport": "warning",
      "reportImplicitStringConcatenation": "warning",
      "reportUnboundVariable": "warning",
      "reportUnusedClass": "information",
      "reportUnusedFunction": "information",
      "reportUnusedImport": "information",
      "reportUnusedVariable": "information",
    }
  2. Install LSP-pyright

    master

    To set up Python support in Sublime Text using Pyright, follow these steps:

    1. Install the LSP package via Package Control.
    2. Install the LSP-pyright package via Package Control.
    3. (Optional but recommended) Install LSP-file-watcher-chokidar via Package Control to enable file system notifications for the server.
    4. Restart Sublime Text.

    Prerequisites:

    • Node.js is required. Ensure node is in your $PATH and is at least version 14. If it is not found, the package will suggest installing a local Node.js runtime automatically.
  3. Migrate dev_environment setting to the new pyright namespace

    master

    In version 1.1.68, the dev_environment setting was moved into the settings object under the pyright.dev_environment key. This change enables overriding the development environment in project-specific settings. If you are using an older configuration, you must wrap the setting as shown below to ensure compatibility.

    // Before 1.1.68
    {
      "dev_environment": "sublime_text",
    }
    
    // After 1.1.68
    {
      "settings": {
        "pyright.dev_environment": "sublime_text"
      }
    }
  4. Configure Virtual Environments for Pyright

    master

    The plugin attempts to resolve virtual environments automatically using environment variables and workspace files.

    Overriding Automatic Resolution

    To manually specify a virtual environment, you have two main options:

    1. Via LSP Settings: Set the python.pythonPath setting to point to your interpreter. This disables automatic resolution.
    2. Via pyrightconfig.json: If you use a pyrightconfig.json file at the project root, you can define venvPath and venv.

    Note: The venv option is only supported in the pyrightconfig.json file. However, venvPath can also be specified in your .sublime-project file to avoid hard-coding system-specific paths in shared projects.

    // Example: Virtual environment located in a .venv folder inside the project root
    {
        "venvPath": ".",
        "venv": ".venv"
    }
  5. Customize the status bar text with Jinja2 templates

    master

    You can customize the information displayed in the Sublime Text status bar when a virtual environment is detected. The statusText setting accepts Jinja2 template grammar. This allows you to conditionally display information such as the venv prompt, Python version, or the name of the finder that detected the environment.

    {
      "settings": {
        "statusText": "{% if venv %}venv: {{ venv.venv_prompt }}; py: {{ venv.python_version }}; by: {{ venv.finder_name }}{% endif %}"
      }
    }
  6. Configure the order of virtual environment discovery strategies

    master

    In version 1.4.0, you can customize the order in which lsp-pyright searches for virtual environments using the venvStrategies setting. By default, the plugin prioritizes .venv or venv directories located within the workspace project. You can reorder or select specific strategies to change how your environment is detected.

    {
      "settings": {
        "venvStrategies": [
          "local_dot_venv",
          "env_var_conda_prefix",
          "env_var_virtual_env",
          "rye",
          "poetry",
          "pdm",
          "hatch",
          "pipenv",
          "pyenv",
          "any_subdirectory"
        ]
      }
    }
  7. How virtual environments are configured via venvStrategies

    master

    The plugin automates the configuration of Python virtual environments. When the server requests workspace configuration, LspPyrightPlugin intercepts the response and applies the following logic based on the venvStrategies setting:

    1. Detection: It uses find_venv_by_finder_names to locate a virtual environment in the workspace.
    2. Python Path: If the configuration is for the python section and python.pythonPath is not set, it sets it to the detected virtual environment's executable.
    3. Extra Paths: If the configuration is for python.analysis, it automatically inserts the virtual environment's site-packages directory into the python.analysis.extraPaths list to ensure correct type checking and imports.
    def handle_venv_strategies(
            self, session: Session, item: ConfigurationItem, configuration_proxy: ConfigurationProxy
        ):
  8. How LspPyrightPlugin patches markdown documentation

    master

    The plugin automatically intercepts LSP responses for textDocument/hover, completionItem/resolve, and textDocument/signatureHelp. If the documentation content is markdown, it applies several regex-based transformations via patch_markdown_content to improve rendering in Sublime Text:

    • Python Syntax: Replaces ```python with ```pyright_python because standard Python fenced blocks may not be valid for Pyright's specific syntax highlighting.
    • Horizontal Rules: Ensures a double newline before horizontal rules (---) following a fenced code block to prevent rendering issues.
    • Docstring Field Mapping: Converts Sphinx-style docstring fields into bold markdown:
      • :field name: becomes __Field:__ name``
      • :returns: becomes __Returns:__
      • :rtype: becomes __Returntype:__
      • :deprecated: becomes ⚠️ __Deprecated:__
    def patch_markdown_content(self, content: str) -> str:
  9. Configure LSP-pyright settings

    master

    You can configure LSP-pyright settings through several methods:

    • Global Settings: Navigate to Preferences > Package Settings > LSP > Servers > LSP-pyright or use the Command Palette command Preferences: LSP-pyright Settings.
    • Project-specific Settings: Use the Command Palette command Project: Edit Project and add your configuration under the settings.LSP.LSP-pyright.settings key.
    • Pyright Native Configuration: Use a pyrightconfig.json file in your project root for options that are only supported by the Pyright language server itself.

    Tip: Installing the LSP-json package provides validation and auto-complete for both LSP-pyright settings and the pyrightconfig.json file.

    {
       "settings": {
          "LSP": {
             "LSP-pyright": {
                "settings": {
                   // Put your settings here
                }
             }
          }
       }
    }
  10. How the plugin handles workspace configuration requests

    master

    The plugin intercepts workspace/configuration responses to perform two main tasks:

    1. Virtual Environment Injection: It calls handle_workspace_configuration to iterate through configuration items and apply venvStrategies to ensure the language server uses the correct Python environment.
    2. Stub Path Cleanup: It calls handle_stub_path_configuration to remove the default ./typings value from stubPath if it is set to the default. This allows the Pyright server to recognize that the setting is intentionally unset, rather than explicitly set to the default, which changes its behavior.
    def handle_stub_path_configuration(self, items: list[ConfigurationItem], configurations: list[LSPAny]) -> None:
  11. Configure the statusText template

    master

    You can customize the information displayed in the Sublime Text status bar by configuring the statusText setting in your LSP-pyright configuration. This setting accepts a string template that can be rendered using specific variables.

    If you set statusText to an empty string or omit it, the status text will be cleared.

    Available template variables:

    • server_version: The version of the Pyright language server.
    • venv: An object containing virtual environment information if a workspace is detected. It includes:
      • finder_name: The name of the tool used to find the virtual environment.
      • python_version: The version of Python in the virtual environment.
      • venv_prompt: A custom prompt string associated with the environment.
    {
      "settings": {
        "statusText": "Pyright v${server_version} | Python ${venv.python_version}"
      }
    }
  12. Configure venvStrategies for automatic environment detection

    master

    To allow the plugin to automatically detect and configure your Python virtual environments, you can use the venvStrategies setting in your LSP or project configuration. The plugin will use these strategies to find the correct Python executable and site-packages for python.pythonPath and python.analysis.extraPaths.

    {
      "lsp_pyright": {
        "venvStrategies": ["venv", ".venv", "env"]
      }
    }