1. 程式人生 > 其它 >Neovim開發環境搭建(2021.07.01)

Neovim開發環境搭建(2021.07.01)

Neovim開發環境搭建(2021.07.01)

目錄

一、搭建環境

  • Ubuntu 21.04
  • Neovim 0.4.4

二、Neovim安裝

# 下載 neovim,如遇網路問題可以採用 https://hub.fastgit.org 映象進行加速下載
# curl -LO https://hub.fastgit.org/neovim/neovim/releases/latest/download/nvim.appimage
$ curl -LO https://github.com/neovim/neovim/releases/latest/download/nvim.appimage

# 為 neovim 新增執行許可權
$ chmod +x nvim.appimage

# 將 neovim 移至 /usr/local/bin 目錄下,並重命名為 nvim
$ sudo mv nvim.appimage /usr/local/bin/nvim

# 測試 neovim 使用
$ nvim

# 配置 vim 和 vi 使用 nvim(可選)
# 為 vi 和 vim 新增 nvim 可選項
$ sudo update-alternatives --install /usr/bin/vi vi /usr/local/bin/nvim 30
$ sudo update-alternatives --install /usr/bin/vim vim /usr/local/bin/nvim 30
# 配置 vi 和 vim 使用 nvim,選擇列表中 nvim 對應的序號即可
$ sudo update-alternatives --config vi
$ sudo update-alternatives --config vim

三、vim-plug安裝

vim-plug是一個極簡的 vim 外掛管理工具,通過它我們可以非常方便的安裝外掛。

3.1 安裝

3.1.1 Vim

# 使用 vim 的安裝方式,如遇網路問題可以採用 https://raw.fastgit.org 映象加速下載
# curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
#     https://raw.fastgit.org/junegunn/vim-plug/master/plug.vim
$ curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
      https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

3.1.2 Neovim

# 使用 neovim 的安裝方式,如遇網路問題可以採用 https://raw.fastgit.org 映象加速下載
# sh -c 'curl -fLo "${XDG_DATA_HOME:-$HOME/.local/share}"/nvim/site/autoload/plug.vim --create-dirs \
#        https://raw.fastgit.org/junegunn/vim-plug/master/plug.vim'
$ sh -c 'curl -fLo "${XDG_DATA_HOME:-$HOME/.local/share}"/nvim/site/autoload/plug.vim --create-dirs \
         https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'

3.3 使用

新增vim-plug的配置到neovim的配置檔案~/.config/nvim/init.vim中(vim配置檔案路徑為~/.vimrc)。

  1. call plug#begin('~/.vim/plugged')開始;
  2. Plug命令列出所有需要安裝外掛;
  3. call plug#end()結束;

示例:

" ~/.vim/plugged 為外掛儲存的路徑,可自定義
call plug#begin('~/.vim/plugged')

" 用 Plug 命令列出所有需要安裝的外掛
Plug 'jiangmiao/auto-pairs' " 自動補全括號外掛
Plug 'neoclide/coc.nvim', {'branch': 'release'} " lsp語言服務協議

" 結束
call plug#end()

重新載入配置檔案通過:PlugInstall命令來安裝外掛。

四、開發環境搭建

4.1 coc.nvim

4.1.1 安裝

coc.nvim擴充套件使neovim(或者vim)支援各種語言服務協議,從而實現智慧提示等功能。

採用vim-plug的方式進行安裝,在.vimrc或者init.vim檔案中新增以下內容:

Plug 'neoclide/coc.nvim', {'branch': 'release'}

重新載入配置檔案通過:PlugInstall命令來安裝外掛。

注:coc.nvim 需要依賴 node, 關於 node 的安裝請自行查閱,此處不再贅述。

4.1.2 配置

coc.nvim的配置較為複雜,此處採用預設配置,如有需求可以自行修改。

.vimrc或者init.vim新增以下配置,以使 coc.nvim更好的工作:

" Set internal encoding of vim, not needed on neovim, since coc.nvim using some
" unicode characters in the file autoload/float.vim
set encoding=utf-8

" TextEdit might fail if hidden is not set.
set hidden

" Some servers have issues with backup files, see #649.
set nobackup
set nowritebackup

" Give more space for displaying messages.
set cmdheight=2

" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience.
set updatetime=300

" Don't pass messages to |ins-completion-menu|.
set shortmess+=c

" Always show the signcolumn, otherwise it would shift the text each time
" diagnostics appear/become resolved.
if has("nvim-0.5.0") || has("patch-8.1.1564")
  " Recently vim can merge signcolumn and number column into one
  set signcolumn=number
else
  set signcolumn=yes
endif

" Use tab for trigger completion with characters ahead and navigate.
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config.
inoremap <silent><expr> <TAB>
      \ pumvisible() ? "\<C-n>" :
      \ <SID>check_back_space() ? "\<TAB>" :
      \ coc#refresh()
inoremap <expr><S-TAB> pumvisible() ? "\<C-p>" : "\<C-h>"

function! s:check_back_space() abort
  let col = col('.') - 1
  return !col || getline('.')[col - 1]  =~# '\s'
endfunction

" Use <c-space> to trigger completion.
if has('nvim')
  inoremap <silent><expr> <c-space> coc#refresh()
else
  inoremap <silent><expr> <c-@> coc#refresh()
endif

" Make <CR> auto-select the first completion item and notify coc.nvim to
" format on enter, <cr> could be remapped by other vim plugin
inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm()
                              \: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"

" Use `[g` and `]g` to navigate diagnostics
" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list.
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)

" GoTo code navigation.
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)

" Use K to show documentation in preview window.
nnoremap <silent> K :call <SID>show_documentation()<CR>

function! s:show_documentation()
  if (index(['vim','help'], &filetype) >= 0)
    execute 'h '.expand('<cword>')
  elseif (coc#rpc#ready())
    call CocActionAsync('doHover')
  else
    execute '!' . &keywordprg . " " . expand('<cword>')
  endif
endfunction

" Highlight the symbol and its references when holding the cursor.
autocmd CursorHold * silent call CocActionAsync('highlight')

" Symbol renaming.
nmap <leader>rn <Plug>(coc-rename)

" Formatting selected code.
xmap <leader>f  <Plug>(coc-format-selected)
nmap <leader>f  <Plug>(coc-format-selected)

augroup mygroup
  autocmd!
  " Setup formatexpr specified filetype(s).
  autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
  " Update signature help on jump placeholder.
  autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end

" Applying codeAction to the selected region.
" Example: `<leader>aap` for current paragraph
xmap <leader>a  <Plug>(coc-codeaction-selected)
nmap <leader>a  <Plug>(coc-codeaction-selected)

" Remap keys for applying codeAction to the current buffer.
nmap <leader>ac  <Plug>(coc-codeaction)
" Apply AutoFix to problem on the current line.
nmap <leader>qf  <Plug>(coc-fix-current)

" Map function and class text objects
" NOTE: Requires 'textDocument.documentSymbol' support from the language server.
xmap if <Plug>(coc-funcobj-i)
omap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap af <Plug>(coc-funcobj-a)
xmap ic <Plug>(coc-classobj-i)
omap ic <Plug>(coc-classobj-i)
xmap ac <Plug>(coc-classobj-a)
omap ac <Plug>(coc-classobj-a)

" Remap <C-f> and <C-b> for scroll float windows/popups.
if has('nvim-0.4.0') || has('patch-8.2.0750')
  nnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  nnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
  inoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(1)\<cr>" : "\<Right>"
  inoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(0)\<cr>" : "\<Left>"
  vnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  vnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
endif

" Use CTRL-S for selections ranges.
" Requires 'textDocument/selectionRange' support of language server.
nmap <silent> <C-s> <Plug>(coc-range-select)
xmap <silent> <C-s> <Plug>(coc-range-select)

" Add `:Format` command to format current buffer.
command! -nargs=0 Format :call CocAction('format')

" Add `:Fold` command to fold current buffer.
command! -nargs=? Fold :call     CocAction('fold', <f-args>)

" Add `:OR` command for organize imports of the current buffer.
command! -nargs=0 OR   :call     CocAction('runCommand', 'editor.action.organizeImport')

" Add (Neo)Vim's native statusline support.
" NOTE: Please see `:h coc-status` for integrations with external plugins that
" provide custom statusline: lightline.vim, vim-airline.
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}

" Mappings for CoCList
" Show all diagnostics.
nnoremap <silent><nowait> <space>a  :<C-u>CocList diagnostics<cr>
" Manage extensions.
nnoremap <silent><nowait> <space>e  :<C-u>CocList extensions<cr>
" Show commands.
nnoremap <silent><nowait> <space>c  :<C-u>CocList commands<cr>
" Find symbol of current document.
nnoremap <silent><nowait> <space>o  :<C-u>CocList outline<cr>
" Search workspace symbols.
nnoremap <silent><nowait> <space>s  :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent><nowait> <space>j  :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent><nowait> <space>k  :<C-u>CocPrev<CR>
" Resume latest coc list.
nnoremap <silent><nowait> <space>p  :<C-u>CocListResume<CR>

4.2 Python補全支援

coc.pyrightcoc.nvim的一個外掛,通過它可以實現python語言的智慧提示等。

  1. 通過以下命令安裝擴充套件;

    :CocInstall coc-pyright
    
  2. 配置python開發環境(如果已經配置跳過此步);

  3. 開啟.py檔案即可自動識別實現提示補全等功能;

4.2 Java補全支援

coc-javacoc.nvim的一款外掛,通過它可以實現java語言的智慧提示等。

  1. 通過以下命令安裝擴充套件;

    :CocInstall coc-java
    
  2. 安裝 JDK 並正確配置環境變數(如果已經配置跳過此步);

  3. 開啟.java檔案將會自動啟用;

注1:當沒有發現 jdt.ls 時,該擴充套件會自動進行下載。

注2:如果jdt下載較慢,可以手動下載 jdt 並解包到coc-java的資料資料夾下,可以在neovim(或者vim)中通過:echo coc#util#extension_root().'/coc-java-data/server'命令獲取檔案路徑。

五、其它擴充套件

5.1 coc.nvim

5.1.1 coc-json

json語言服務,安裝命令如下:

:CocInstall coc-json

5.1.2 coc-sh

sh語言服務,安裝命令如下:

:CocInstall coc-sh

5.2 auto-pairs

自動插入或者刪除另一半括號,vim-plug方式安裝:

Plug 'jiangmiao/auto-pairs'

5.3 rawbow

巢狀彩虹括號,vim-plug方式安裝:

Plug 'luochen1990/rainbow'

相關配置:

let g:rainbow_active = 1 " 啟用rainbow

5.4 vim-startify

檔案開啟記錄,vim-plug方式安裝:

Plug 'mhinz/vim-startify'

5.5 vim-airline

狀態列外掛,vim-plug方式安裝:

Plug 'vim-airline/vim-airline'

相關配置:

let g:airline_theme = 'nord' " 設定airline使用的主題
let g:airline_powerline_fonts = 1 " 使airline正常顯示箭頭

" 設定 neovim 或者 vim 的 tabline
let g:airline#extensions#coc#enabled = 1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#tab_nr_type = 1
let g:airline#extensions#tabline#show_tab_nr = 1
let g:airline#extensions#tabline#formatter = 'default'
let g:airline#extensions#tabline#buffer_nr_show = 0
let g:airline#extensions#tabline#fnametruncate = 16
let g:airline#extensions#tabline#fnamecollapse = 2
let g:airline#extensions#tabline#buffer_idx_mode = 1

5.6 vim-airline-themes

狀態列主題外掛,vim-plug方式安裝:

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

5.7 nord-vim

nord配色主題外掛,vim-plug方式安裝:

Plug 'arcticicestudio/nord-vim'

5.8 gruvbox

gruvbox配色主題外掛,vim-plug方式安裝:

Plug 'morhetz/gruvbox'

5.9 indentLine

縮排線外掛,vim-plug方式安裝:

Plug 'Yggdroot/indentLine'

5.10 nerdcommenter

註釋外掛,支援多語言,vim-plug方式安裝:

Plug 'preservim/nerdcommenter'

相關配置:

let g:NERDSpaceDelims = 1 " 設定在註釋分隔符後新增空格
let g:NERDCompactSexyComs = 1 " 設定多行使用簡潔語法註釋
let g:NERDTrimTrailingWhitespace = 1 " 設定允許註釋清理行尾的空格

5.11 tabular

文字對齊外掛,vim-plug方式安裝:

Plug 'godlygeek/tabular'

5.12 vim-gitgutter

git diff外掛,vim-plug方式安裝:

Plug 'airblade/vim-gitgutter'

5.13 neoformat

程式碼格式化外掛,支援多語言,vim-plug方式安裝:

Plug 'sbdchd/neoformat'

5.14 nerdtree

檔案目錄樹外掛,vim-plug方式安裝:

Plug 'preservim/nerdtree'

5.15 sonokai

程式碼高亮配色主題,vim-plug方式安裝:

Plug 'sainnhe/sonokai'

5.16 codi.vim

實時顯示python指令碼執行結果,vim-plug方式安裝:

Plug 'metakirby5/codi.vim'

5.17 vim-pydocstring

自動生成python文件字串,vim-plug方式安裝:

Plug 'heavenshell/vim-pydocstring'

相關配置:

let g:pydocstring_doq_path = '~/.local/share/virtualenvs/python3.8/bin/doq' " pydocstring依賴doq的路徑

5.18 tagbar

顯示檔案類結構層次,vim-plug方式安裝:

Plug 'preservim/tagbar'

相關配置:

let g:tagbar_ctags_bin = '/usr/bin/ctags' " tagbar依賴ctags的路徑

5.19 vimspector

類似vscode佈局的 GUI 除錯擴充套件,vim-plug方式安裝:

Plug 'puremourning/vimspector'

相關配置:

let g:vimspector_enable_mappings = 'VISUAL_STUDIO' " vimspector快捷鍵方案

5.20 vim-easycomplete

自動補全擴充套件,功能類似coc.nvimvim-plug方式安裝:

Plug 'jayli/vim-easycomplete'

5.21 ultisnips

程式碼片段,vim-plug方式安裝:

Plug 'SirVer/ultisnips'

5.22 vim-snippets

程式碼片段,vim-plug方式安裝:

Plug 'honza/vim-snippets'

六、其它配置

set relativenumber " 設定顯示相對行號
set number " 設定顯示行號
set expandtab " 設定TAB使用空格
set tabstop=4 " 設定TAB縮排的空格數量
set shiftwidth=4 " 自動縮排的寬度
set fileencodings=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936 " 解決中文亂碼
set termencoding=utf-8
set encoding=utf-8

" 插入模式鍵對映
inoremap kk <Esc>

" 普通模式鍵對映
" 開啟檔案樹
nnoremap <leader>e :CocCommand explorer<CR>
" 儲存
nnoremap <leader>w :w<CR>
" 刪除buffer
nnoremap <leader>bd :bd<CR>
" 下一個buffer
nnoremap <leader>bn :bn<CR>
" 上一個buffer
nnoremap <leader>bp :bp<CR>
" 關閉tab
nnoremap <leader>tc :tabclose<CR>