惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
P
Privacy International News Feed
T
Tenable Blog
L
Lohrmann on Cybersecurity
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threat Research - Cisco Blogs
S
Securelist
C
CXSECURITY Database RSS Feed - CXSecurity.com
Cisco Talos Blog
Cisco Talos Blog
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
P
Privacy & Cybersecurity Law Blog
Vercel News
Vercel News
Cyberwarzone
Cyberwarzone
月光博客
月光博客
T
The Blog of Author Tim Ferriss
Scott Helme
Scott Helme
爱范儿
爱范儿
Stack Overflow Blog
Stack Overflow Blog
C
Cisco Blogs
aimingoo的专栏
aimingoo的专栏
博客园 - 司徒正美
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
A
Arctic Wolf
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
阮一峰的网络日志
阮一峰的网络日志
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
Security Latest
Security Latest
Blog — PlanetScale
Blog — PlanetScale
G
GRAHAM CLULEY
V
Vulnerabilities – Threatpost
博客园 - 三生石上(FineUI控件)
I
InfoQ
Spread Privacy
Spread Privacy
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog
C
CERT Recently Published Vulnerability Notes
A
About on SuperTechFans
博客园_首页
Engineering at Meta
Engineering at Meta
Project Zero
Project Zero
Latest news
Latest news

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN Mintty Tips and Configurations Generating Table of Contents for Markdown with Tagbar Convert Python Script to Exe on Windows with Pyinstaller Ubuntu on Windows Missing after Windows Update 使用代理加速 Mac 终端下载速度 My Experience with Several Zsh Plugin Managers 深圳租房小记 How to Install zplug inside Docker Container Why don't settings inside bashrc or bash_profile take effect? Setting Up Locale in Linux 谷歌 Adsense 申请及在 Hugo 中的配置 How to Write Algorithm Pseudo Code in LaTeX Nifty Nvim Techniques That Make My Life Easier -- Series 4 A Few Grammar Questions in Writing How to Read and Write Images with Unicode Paths in OpenCV Creating A Professional Table in LaTeX with booktabs How to Create Proper Folding for Vim/Nvim Configuration Linux Tips and Tricks -- s1 JPEG Image Orientation and Exif How Do I Show the Current File Path In Neovim? JPEG Image Quality in PIL Difference between view, reshape, transpose and permute in PyTorch Convert PIL or OpenCV Image to Bytes without Saving to Disk Fast Movement and Navigation Inside Vim or Neovim Unintuitive Behaviour of Case Sensitivity in Python glob Binding Keys in Zsh 几把机械键盘试用体验 Nvim Autocompletion with Deoplete Converting Markdown to Beautiful PDF with Pandoc Exclusive and Inclusive Motion in Neovim/Vim Nifty Nvim Techniques Which Make My Life Easier -- Series 3 Why Doesn't Jedi Autocompletion Work for Some Methods Vim-like Editing inside Browser Markdown 生成 HTML 时汉字之间出现多余空格问题 小米 9 安装谷歌商店(Google Play Store)与相关配置 Create Mappings That Take A Count in Neovim Spell Checking in Nvim English Words Completion inside Neovim/Vim How to Use Python Inside Vim Script with Neovim Nifty Little Nvim Techniques to Make My Life Easier -- Series 2 Setting up Ultisnips for Neovim Mac 上罗技 M590 鼠标设置 Nifty Little Nvim Techniques to Make My Life Easier -- Series 1 A Complete Guide on Writing LaTeX with Vimtex in Neovim Manipulating Images with Alpha Channels in Pillow Sublime Text Regular Expression Cheat Sheet Cropping Rotated Rectangles from Image with OpenCV Boosting Your Productivity on Terminal with Zsh and Plugins 最新版 Rime 输入法使用 (2022 更新) Display Image with Pillow inside Ubuntu on Windows Faster Directory Navigation with z.lua Cmder Advanced Configurations Nvim-qt Settings on Windows 10 Tmux Plugin Install and Management How to Debug Python Code in Terminal Markdown Writing and Previewing in Neovim -- A Complete Guide Line Number Settings for More Efficient Movement in Neovim 两个大规模中文语料库介绍以及处理 Windows 系统下几款程序员不可不用的神器 我的 2018 阅读清单 How Is Newline Handled in Python and Various Editors? Two Issues Related to ImageFont Module in PIL 在 Listary 中调用 GoldenDict 或欧路词典查单词 Reading and Writing Text Files on Windows The Mathematics behind Font Shapes --- Bézier Curves and More 快速识别图片字体:字体识别工具介绍 Deoplete Failed to Load at Startup after Updating Python neovim Package What Is The Difference between pip, pip3 and pip3.6 Shipped with Anaconda3? Windows 10 系统下 Neovim 安装与配置 How to Use shutil.move() on Windows and Linux
A Complete Guide to Neovim Configuration for Python Development
2018-12-24 · via jdhao's digital space

Change log
  • 2022-01-29: Add deprecation notice
  • 2021-01-17: Install nvim via tar ball instead of appimage
  • 2020-12-01: Add detailed guide on installing Neovim on Linux

TL;DR: My complete nvim configuration is here. Follow the guide there on how to use it. Most of the config below also applies to Windows and Mac. For how to configure Neovim on Windows, you may also be interested in this post.

2022-01-29: Note that this post is written more than three years ago. Some of the plugins mentioned here may not be maintained or may not be the best fit for Neovim, or even not needed, e.g., highlighted yank is builtin in Neovim since May 2020. I have shared some of the plugin changes in this post.

Vim is a popular code editor on Unix/Linux systems, and it is often compared with Emacs, another great code editor among programmers. The debate about which one is the best editor never cease. Vim is powerful, but it has its own shortcomings as an old editor1. Over the years, Vim’s code base has grown increasing larger, which makes it hard for maintenance and for adding new features quickly. It has only one core developer, Bram Moolenaar. Although Vim has a lot of contributors, nearly all patches are merged by Bram2. To overcome the shortcomings of Vim, preserve its advantages (i.e., compatible with Vim) and make the development of Vim faster, the Neovim project is created.

In this post, I will give a detailed guide on how to install Neovim and configure it as an IDE-like environment for Python development (in the rest of this post, I will use Neovim and Nvim interchangeably).

Install Nvim#

Neovim has pre-built binary package for Linux, you can download it from the Neovim GitHub release page:

mkdir -p $HOME/tools/ && cd $HOME/tools/
wget https://github.com/neovim/neovim/releases/download/nightly/nvim-linux64.tar.gz
tar zxvf nvim-linux64.tar.gz

The executable file is located in $HOME/tools/nvim-linux/bin/nvim.

Now, we need to add the bin directory to the system PATH. Open .bash_profile and add the following line:

export PATH=$HOME/tools/nvim-linux64/bin:$PATH

Save the file and source it to make the change take effect.

Now, Neovim has been installed on your system successfully. You can open neovim on terminal with nvim command.

Nvim configuration file#

Neovim use a different configuration file from Vim. You need to create a file named init.vim under the directory $HOME/.config/nvim (if this directory does not exist, just create one)3. All configurations can be put into this file.

Most of the configuration options for Neovim are the same with Vim. You can copy your vim configurations if you have used Vim before.

Install and use a plugin manager#

One of main reasons for the powerfulness of Vim comes from the various plugins written for it. With these plugins, you can achieve all sorts of crazy things which are hard to achieve with plain Vim. If you have installed a lot of plugins manually, you will find it difficult to manage them. Like Vim, Neovim does not have a built-in plugin manager. We need to install one ourselves.

There are two plugin managers in wide use among Nvim users. One is dein and the other is vim-plug. Vim-plug has a larger user base and seems more popular. Finally, I decided to give vim-plug a try.

Install vim-plug#

  1. Install vim-plug itself:
curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

After installing vim-plug, you may need to restart Nvim.

  1. Edit init.vim and add the configuration for vim-plug. I show an example configuration below (modified from the vim-plug GitHub page):
call plug#begin('~/.local/share/nvim/plugged')

Plug 'davidhalter/jedi-vim'

call plug#end()

Note that all the plugin installation command must be put inside the two call command above. I will not repeat that later.

How to use vim-plug#

You can execute following command in Nvim command mode:

  • Install plugins::PlugInstall
  • Update plugins::PlugUpdate
  • Remove plugins::PlugClean (First, comment the plugin install command in init.vim. Open Nvim and use :PlugClean to uninstall plugins)
  • Check the plugin status::PlugStatus
  • Upgrade vim-plug itself::PlugUpgrade

Disable a plugin only temporarily#

If you want to disable certain plugin for a while but do not want to delete it, you can try two methods:

  1. Comment out the plugin and reopen Nvim.

  2. According to discussions here, to disable plugin foo/bar, you can use the following settings:

Plug 'foo/bar', { 'on': [] }

Plugin install and settings#

Auto-completion plugin deoplete#

deoplete is an auto-completion plugin designed for Neovim:

Deoplete is the abbreviation of “dark powered neo-completion”. It provides an extensible and asynchronous completion framework for neovim/Vim8.

Strictly speaking, it is an auto-completion engine. In order to enable auto-completion for a certain programming language, you need to install the corresponding source.

Deoplete is easy to install. Use the following settings inside the vim-plug calls:

Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }

The minimum setting for deoplete is as follows:

let g:deoplete#enable_at_startup = 1

For more options and their meanings, check :h deoplete-options inside Nvim.

Install plugin deoplete-jedi#

As I have said, deoplete supports auto-completion for various languages via different sources. In order to do auto-completion for Python, we need to install deoplete-jedi. In the following, I list the steps to install deoplete-jedi.

Step 1: Install dependency packages

First we need to install pynvim

We also need to install jedi. If you happen to use the latest version of Anaconda, jedi is already installed. Otherwise, you can install jedi via pip:

Step 2: Install and set up deoplete-jedi

First, we need to install deoplete-jedi using vim-plug:

Plug 'zchee/deoplete-jedi'

After that, if nothing wrong happens, you can use auto-completion now! Open a Python source file with Nvim and start editing, you will see the auto-completion pop-up menu like what is shown in the following image:

How to use deoplete#

  1. How to navigate between the items in the auto-completion list?

According to discussions here, you can navigate through the auto-completion list with <Ctrl-N> and <Ctrl-P>.

  1. How to automatically close the method preview window?

When we navigate through the auto-completion list, a small window will appear on top of current window and gives hints about the parameters of current selected method. But this window will not disappear after auto-completion is done. According to discussions here, we can use the following setting to close the preview window automatically:

autocmd InsertLeave,CompleteDone * if pumvisible() == 0 | pclose | endif
  1. How can I open the preview window below the current window?

By default, preview windows will open on top of current window. You can change this behaviour by adding set splitbelow in the configuration file. For more info, see here.

  1. How can I navigate through the auto-completion list with Tab?

Add the following setting in the Nvim configuration file:

inoremap <expr><tab> pumvisible() ? "\<c-n>" : "\<tab>"

Status bar plugin: vim-airline#

The default status bar of Nvim is simple and can not provide much useful information like Sublime Text or other modern code editors. However, the status bar can be customized to achieve wonderful effects. An excellent plugin is called vim-airline, which can achieve the same functionalities as Sublime Text status bar. It is easy to install:

Plug 'vim-airline/vim-airline'

Use :PlugInstall to install this plugin and restart Nvim. You should be able to see the new status bar with more information displayed.

Switch vim-airlinetheme#

Vim-airline provides a lot of themes for you to customize your status bar. Check here to see what different theme looks like. Vim-airline has put the various themes in another plugin called vim-airlinetheme. To change the theme, we need to install this plugin:

Plug 'vim-airline/vim-airline-themes'

Then, in the Nvim configuration file, add the following settings:

let g:airline_theme='<theme>' " <theme> is a valid theme name

Automatic quote and bracket completion#

When input quote and bracket, we often wish to input them as pairs. Nvim does not support this feature. Auto-pairs can achieve this and much more. Simply install it:

Plug 'jiangmiao/auto-pairs'

How to use#

Let’s take manipulating double quotes as an example. In insert model, press ", it will automatically become two double quotes. At the same time, the cursor is placed between the two double quotes, waiting for input. When you finish inputting text between the quotes, you may want to place the cursor after the right quote and continue inserting text. Here comes the magic part: just press " one more time, and the cursor will be placed right behind the right quote.

comment plugin#

Different programming languages have different specifications for comment. It would be great to change the comment style for the current file based on its file type. nerdcommenter is one such plugin. Install it with vim-plug:

Plug 'scrooloose/nerdcommenter'

To comment out a single line, use <leader>cc (leader is a prefix key in Nvim, the default leader key is backslash \); to uncomment a line, use <leader>cu. To comment or uncomment several lines, add a repeating number to corresponding command, just like what you do in plain Vim. For more usages, check nerdcommenter’s documentation.

code auto-format plugin#

Neoformat can be used to format your source code. Install it with vim-plug:

For Python code, you need to install a Python code formatter to work together with neoformat. We will choose yapf. First, we install this formatter with pip:

Then, you can format Python code with yapf formatter using neoformat.

How to format code?#

In command mode, input Neoformat, neoformat will auto-format your source code.

If neoformat can not detect your file type or you haven’t installed any formatter. You can add the following command to your Nvim configuration to let neoformat do some basic format for the file:

" Enable alignment
let g:neoformat_basic_format_align = 1

" Enable tab to space conversion
let g:neoformat_basic_format_retab = 1

" Enable trimmming of trailing whitespace
let g:neoformat_basic_format_trim = 1

There is another format plugin vim-autoformat which you can try.

Code jump (go-to) plugin#

We often need to jump to the definition of class and method to check their implementation details. We can use jedi-vim to achieve this. Actually, jedi-vim can also do code auto-completion. Since we have installed deoplete and deoplete-jedi, we can disable code completion and only use the code jump function of jedi-vim. Install jedi-vim with vim-plug:

Plug 'davidhalter/jedi-vim'

Use the following simple configuration:

" disable autocompletion, because we use deoplete for completion
let g:jedi#completions_enabled = 0

" open the go-to function in split, not another buffer
let g:jedi#use_splits_not_buffers = "right"

How to use jedi-vim#

Move the cursor to the class or method you want to check, then press the various supported shortcut provided by jedi-vim:

  • <leader>d: go to definition
  • K: check documentation of class or method
  • <leader>n: show the usage of a name in current file
  • <leader>r: rename a name

File managing and exploration plugin#

Those who have been working with GUI code editors are familiar with the sidebar on the left side of the code editor, which provides an overview of files and folders in current project. How do we achieve similar functions in Nvim? You can use nerdtree. First, install it using vim-plug:

Plug 'scrooloose/nerdtree'

How to use nerdtree?#

  1. How to open file navigation window?

In command mode, input :NERDTree to open the directory your current file resides.

  1. How do I open a file in the file explorer?

Place the cursor in the file you want to open and press o to open this file in the right window.

  1. How do I switch between file window and nerdtree file navigation window?

This is the same as how you switch windows in Vim. Press ctrl and press w two times quickly to switch window. You can also press <Ctrl-w> and then press L.

  1. How do I exit or close file explorer window?

Press q while your cursor is this window? Or use NERDTreeClose command in command mode.

For more customization, refer to this post.

Code checker plugin#

Neomake is a tool for code syntax check and build automation for Nvim. Install it with vim-plug:

Neomake’s syntax check for various languages relies on various linters. After installation, you need to install linters according to your programming languages. The linter for different languages are listed here.

For Python, we can use pylint as linter. Install pylint with pip or conda:

conda install pylint
# pip install pylint

After installing pylint, we need to set it in init.vim as the Python code checker:

let g:neomake_python_enabled_makers = ['pylint']

Code checking#

In command mode, use Neomake command to start syntax check. We can also enable automatic code check. Just add the following setting in Nvim configuration file:

call neomake#configure#automake('nrwi', 500)

Pylint checks extensively on your code, which makes it a bit slow. Another code linter you can try is flake8, which is faster.

Multiple cursor editing plugin#

If you have used Sublime Text before, you must be impressed by Sublime Text’s ability to edit multiple position in the code simultaneously. This function is great when you want to refactor your code. You can achieve similar function with the help of vim-multiple-cursors. Install it with:

Plug 'terryma/vim-multiple-cursors'

How to use#

In normal mode, move the cursor to a variable you want to rename, press <Ctrl-N> and this variable will be highlighted. Continue press <Ctrl-N>, the next occurrence of this variable will be highlighted. If you want to skip a certain occurrence (for example, a string may contain a sub-string which is the same as the variable), just press <Ctrl-X> after this position has been highlighted. Continue selecting the occurrence of this variable until all its occurrence has been selected.

Now, press c (in Nvim, c means to change ) and enter insert mode. Input a new name and save.

But, I should say that this plugin is not perfect. When you have a lot of occurrences of the variable in the file, the refactor of variable name is slow.

There are some discussions about Neovim’s native support for multiple cursors. But it seems that this function is still not finished as of today. You can find relevant discussions in the following links:

Highlight your yank area#

In Nvim, if you yank (i.e., copy) a block of text, you do not get a visual hint about exactly what you have copied. Unless you are very familiar with Nvim, you may have copied less or more than what you want to copy, which is annoying. With the help of vim-highlightedyank, you can now highlight the text region which you have yanked. Handy little feature, isn’t it?

You can install it with vim-plug:

Plug 'machakann/vim-highlightedyank'

Most of the time, you do not need any further settings after installing this plugin. But, for some colorschemes, you will not be able to see the highlight colors. To fix this issue, add the following setting to Nvim configuration:

hi HighlightedyankRegion cterm=reverse gui=reverse

If you feel that the highlight duration time is too short, you can increase the highlight duration (measured in ms):

" set highlight duration time to 1000 ms, i.e., 1 second
let g:highlightedyank_highlight_duration = 1000

Code folding plugin#

For large code base, it is helpful to fold some part to get a better idea of the structure of the code. SimplyFold is nice plugin for code folding. Install it with vim-plug:

Plug 'tmhedberg/SimpylFold'

You do not need further settings. It works out of the box.

simple usage#

There are some shortcuts to manipulate code folding:

  • zo: Open fold in current cursor position
  • zO: Open fold and sub-fold in current cursor position recursively
  • zc: Close the fold in current cursor position
  • zC: Close the fold and sub-fold in current cursor position recursively

Theme install and configuration#

Before we begin#

Neovim has several built-in colorschemes or themes. You may not like them and want better themes. It is easy to install a theme. But it is little tricky to make the theme display correctly as what the theme homepage shows. A lot of themes will not display well if you use an SSH client which has poor support for true colors. For Windows system, after trying several SSH clients, I find that ZOC works best. For Mac, you can use the open source tool iTerm2. To find more SSH clients which support true colors, visit this page.

Install themes#

Gruvbox is a popular Vim colorscheme. Install it with vim-plug:

Then use :PlugInstall to install it just like you install other plugins.

In Nvim configuration file, activate this theme with the following setting:

It has two modes, i.e., dark and light, which can be switched using the following settings:

set background=dark " use dark mode
" set background=light " uncomment to use light mode

Restart Nvim and you will activate the new theme. It looks like the following on my Mac:

Other themes#

There are other themes you may want to try:

How do I change the font?#

Unlike Sublime Text, you can not set up which font to use in Nvim’s configuration. Instead, Nvim will use the font you choose for your terminal emulator. So you need to set up your favorite font in the terminal. Some good programming fonts are:

Check nerd fonts for more programming fonts.

How to find more interesting plugins?#

There is a website called vimawesome, which collects information about various Vim plugins. You can find helpful plugins on this website.

Since most Vim plugins are published on GitHub, you can also search with vim and other keywords on GitHub to find relevant plugins. For example, search vim colorschem or vim theme to find themes designed for Vim.

Builtin terminal#

Neovim has support for terminal emulator so that you can directly run a shell inside Neovim. It is handy for temporary shell operations.

To open the terminal, use :terminal or :vnew term://bash or new term://bash. After entering the terminal, you are in normal mode. Press i to start typing terminal command.

To exit insert mode in terminal emulator, press <Ctrl+\><Ctrl+N>.

To exit terminal emulator and close the window, use exit.

The difference between Nvim and Vim#

Support for bracketed paste mode#

Neovim has support for bracketed paste mode. The paste option in Vim is obsolete. Use :h paste and you will the following documentation:

This option is obsolete; bracketed-paste-mode is built-in.

Neovim is all nocompatible#

In Nvim normal mode, use :h comatible, and you will see that:

Nvim is always “nocompatible”

For more differences between Nvim and Vim, see here.

Trouble shooting#

In this part, I introduce some issues found when using Nvim and how to fix these issue.

Nvim colorscheme does not look right inside Tmux#

If your terminal supports true color, first install the latest version of tmux4, add the following config to ~/.tmux.conf (extracted from here)

set -g default-terminal "screen-256color"
set -ga terminal-overrides ",xterm-256color*:Tc"

Then the color should be fine. Otherwise, in the Nvim config file init.vim, use the following setting instead:

Also, there are some discussions here.

How do I get a log file when starting Neovim#

Use nvim -VNUMnvim.log. NUM is used to indicate verbose level, for example:

The above command creates a log file nvim.log with verbose level 10.

More reference here. See also nvim --help.

OK, that is end of this long post. You can find my complete Nvim configurations here. Happy Vimming!