Skip to content

coc.nvim

G. Bai edited this page Apr 26, 2021 · 2 revisions

This is a coc.nvim setup procedure that works for Neovim, which aims to:

  • Provide static type checking from a Python virtualenv (e.g. I have created a venv called coc with pyenv, which resides in ~/.pyenv/versions, I'll use this as an example).

  • Format with black manually and automatically on save.

This page is based on my answer of a question in Vi and Vim Stack Exchange. So here is my setup procedure:

  1. Configure venv in coc-settings.json:

    {
      "python.venvPath": "/Users/gbai/.pyenv/versions"
    }

    Here an absolute path is necessary for now, see this issue comment.

    Update: You could use ${env:HOME} (no space after :!) to replace ~:

    {
      "python.venvPath": "${env:HOME}/.pyenv/versions"
    }
  2. Choose a Python language server:

    Per coc.nvim's official doc section, I installed coc-pyright as language server by

    :CocInstall coc-pyright
    

    It has its own config file pyrightconfig.json per project, and should be placed at project root. I simply put this line in pyrightconfig.json:

    {
      "venv": "coc"
    }

    Of course for different project, the venv differs.

  3. Configure black

    Install black in the venv (coc in my config), and add these to coc-settings.json:

    {
      "python.formatting.provider": "black",
      "python.formatting.blackPath": "~/.pyenv/versions/coc/bin/black"
    }

    Interestingly, I can use relative path ~ here without problem.

  4. Formatting

    As per this issue comment:

    • Use "coc.preferences.formatOnType": true to enable format on type feature.

    • Use "coc.preferences.formatOnSaveFiletypes": ["python"] to include filetypes you want format on save.

    • Use :call CocAction('format') to format currrent document.

    • Use

      xmap <leader>f  <Plug>(coc-format-selected)
      nmap <leader>f  <Plug>(coc-format-selected)
      

      to format selected range.

    To inspect if formatting went well, as per this issue comment:

    coc-pyright v1.1.97 adds more formatting logs, you can get it by: :CocCommand workspace.showOutput - coc-pyright-formatting.

    through which you can tell if black is loaded and run correctly.

  5. Some more info

    Apart from using "coc.preferences.formatOnSaveFiletypes": ["python"] as mentioned above, also see this issue comment and another issue comment:

    The latest coc has added coc.preferences.willSaveHandlerTimeout, the default is 500ms, you can increase this time limitation.

    This is useful especially when you have very large files, which takes long to format.

Clone this wiki locally