如何配置Neovim为LaTeX编辑器!

发布于 2022-07-17 08:57:40

如何配置Neovim & vimtex For LaTeX

第一步 : 下载Neovim并解压到想要安装的位置,下载.msi时可以直接安装

第二步 : 在D:/plugged下安装插件,记住此处就是插件库路径

第三步 : (环境配置) 下载并安装Python3Node.js的最新版本,路径默认即可. ! 谨记 : “必须勾选安装窗口中的为所有用户安装且将安装路径写入环境变量”的选项!!切记!!

第四步 : 下载plug.vim文件并放置在"C:\Program Files\Neovim\share\nvim\runtime\autoload\plug.vim",其中C:\Program Files是Neovim安装路径

第五步 : 把以下代码保存为init.vim并放置在C:/用户/~/AppData/Local/nvim下面,~是用户名

""""""""""""""""""""""""""""""""""""""""""""""""""""
"                    General                       "
""""""""""""""""""""""""""""""""""""""""""""""""""""

" 设置256色
if (empty($TMUX))
    if (has("nvim"))
        let $NVIM_TUI_ENABLE_TRUE_COLOR=1
    endif
    if (has("termguicolors"))
    set termguicolors
    endif
endif

set clipboard+=unnamedplus  " 剪贴板与系统共享



set number                  " 显示行号
set relativenumber          " 显示相对行号
set cursorline                " 高亮当前行
set cursorcolumn            " 高亮当前列
set scrolloff=10            " 垂直滚动时,光标距离顶部/底部的位置

set autoread                " 打开文件监视,如果编辑中文件发生外部改变就进行提示
set noautowrite             " 移开焦点时不自动保存

set laststatus=2            " 是否显示状态栏。0 表示不显示,1 表示只在多窗口时显示,2 表示显示

set showmode                " 在底部显示,当前处于命令模式还是插入模式
set showcmd                 " 命令模式下,在底部显示,当前键入的指令

set mouse=a                 " 支持鼠标

set encoding=utf-8          " 使用 utf-8 编码
" 打开文件时会逐一尝试这些进行解码,要把更严格的解码方式放在前面
set fileencodings=ucs-bom,utf-8,gbk,gb2312,cp936,gb18030,big5,euc-jp,euc-kr,latin1    
scriptencoding utf-8

set autoindent              " 按下回车键后,下一行的缩进会自动跟上一行的缩进保持一致
set tabstop=4               " 按下 Tab 键时,Vim 显示的空格数
set shiftwidth=4            " 按下>>(增加一级缩进)、<<或者==(取消全部缩进)时每一级的字符数
set smarttab                " 根据文件中其他地方的缩进空格数来确定一个tab是多少个空格
set expandtab               " 自动将 Tab 转为空格
set softtabstop=4           " Tab 转为多少个空格

set wrap                    " 自动折行
set linebreak               " 只有遇到指定的符号才自动折行
set showbreak=>>
" set textwidth=80            " 超过这个数字会自动换行
set colorcolumn=100         " 在这个地方画一条线

set ignorecase              " 搜索忽略大小写
set smartcase               " 只有一个大写字母的搜索词,将大小写敏感;其他情况都是大小写不敏感
set hlsearch                " 高亮显示匹配结果
set incsearch               " 输入搜索模式时,每输入一个字符,就自动跳到第一个匹配的结果
set showmatch               " 高亮匹配的括号

" 如果行尾有多余的空格(包括 Tab 键),该配置将让这些空格显示成可见的小方块。
set list
set listchars=tab:▸\ ,eol:\ ,trail:·,extends:↷,precedes:↶
set fillchars=vert:│,fold:·

set nofoldenable            " 代码不折叠
set foldmethod=syntax       " 按语法结构进行折叠
set foldlevelstart=2
" set conceallevel=1          " 自动隐藏字符

set nobackup                " 不创建备份
set nowritebackup
set undofile                " 保留撤销历史
" 保存当前会话时保存的内容,下次打开时会恢复。
set sessionoptions=buffers,curdir,folds,tabpages,winpos,winsize

" 命令模式下显示自动补全候选
set wildmenu
set wildmode=longest,full
set completeopt=menu,menuone    " 自动补全显示菜单

" use scriptencoding when multibyte char exists
scriptencoding utf-8

filetype plugin indent on " 针对不同文件类型加载对应插件
"开启文件类型侦测
if !exists('g:syntax_on') 
    syntax enable
endif

"""============= 以上为基础配置 ====================="""
""" LaTeX配置
call plug#begin('D:/plugged')
" Plug 'author/plug-name'        " 这里就是单引号内就是要装的插件
"" 单引号的内容是 GitHub 上的仓库名,比如插件的 github 地址是 https://github.com/Yggdroot/indentLine,
" 那么放在单引号里的内容就是 Yggdroot/indentLine。看下面装的插件就明白了。修改配置文件后,重启 nvim,然后输入指令 :PlugInstall,即可完成插件的安装,然后就可以对插件进行配置。
" rakr/vim-one:一款我觉得好看的主题插件,有深色和浅色两种;
" luochen1990/rainbow:彩虹括号;
" lukas-reineke/indent-blankline.nvim:提供可视化的缩进、换行和空格等;
" defx.nvim:一个较新的文件资源管理器,另外三个插件可以提供图标支持:
" Plug 'kristijanhusak/defx-icons'
" Plug 'kristijanhusak/defx-git'
" Plug 'ryanoasis/vim-devicons'
" vim-airline/vim-airline:标签栏;
" mhinz/vim-startify:一个是好用且好看的开始界面;
" tyru/caw.vim:自动注释插件,需要依赖 Shougo/context_filetype.vim 插件;
" neoclide/coc.nvim:自动补全插件。
" SirVer/ultisnips:自定义代码片段插件
    Plug 'rakr/vim-one'
    Plug 'luochen1990/rainbow'
    Plug 'lukas-reineke/indent-blankline.nvim'
    Plug 'shougo/defx.nvim'
    Plug 'kristijanhusak/defx-icons'
    Plug 'kristijanhusak/defx-git'
    Plug 'ryanoasis/vim-devicons'
    Plug 'vim-airline/vim-airline'
    Plug 'mhinz/vim-startify'
    Plug 'Shougo/context_filetype.vim'
    Plug 'lervag/vimtex'
    Plug 'xuhdev/vim-latex-live-preview',{'for':'tex'} 
    Plug 'neoclide/coc.nvim', {'branch': 'release'}
    Plug 'SirVer/ultisnips'
    let g:UltiSnipsExpandTrigger="<tab>"   
    let g:UltiSnipsJumpForwardTrigger="<c-b>"   
    let g:UltiSnipsJumpBackwardTrigger="<c-z>"      
    " If you want :UltiSnipsEdit to split your window.     
    let g:UltiSnipsEditSplit="vertical" 
    Plug 'honza/vim-snippets'
    Plug 'jiangmiao/auto-pairs'
    Plug 'morhetz/gruvbox'
call plug#end()
"" ================================== ""
""                                插件配置                                             ""
"" ================================== ""
autocmd vimenter * ++nested colorscheme gruvbox
set bg=light
" LaTeX配置
let g:tex_flavor = 'latex'      " 设置 Tex 文档是 LaTeX 语法风格的文档:
let g:vimtex_quickfix_mode = 0 " 设置不自动弹出报错窗口,可以通过 :copen 来手动打开
" 这两行可以让文中的一些符号以一种更直观的方式显示出来
" let g:tex_conceal='abdmg'
" set conceallevel=1
"" 设置 LaTeX 编译器
let g:vimtex_compiler_latexmk = {
            \ 'build_dir' : {-> 'out'},     
            \ 'executable' : 'latexmk',
            \ 'options' : [
            \   '-xelatex',
            \   '-file-line-error',
            \   '-synctex=1',
            \   '-interaction=nonstopmode',
            \ ],
            \}
" use vimtex as default compiler
" let g:vimtex_compiler_latexmk_engines={'_':'-xelatex'}
" let g:vimtex_compiler_latexrun_engines={'_':'xelatex'}

let g:vimtex_texcount_custom_arg='-ch -total'     
"映射VimtexCountWords! 使\lw命令可统计中英文字符的个数  
au FileType tex map <buffer> <silent> <leader>lw :VimtexCountWords! <CR><CR>  

"下面对LaTex的编译引擎进行设置,默认的编译方式为-xelatex     
"“vimtex提供了magic comments 来为文件设置编译方式 
"i.e.在tex文件开头输入 % !TEX program =xelatex    
"即指定xelatex编译器编译文件         
let g:vimtex_compiler_latexmk_engines = {    
                        \'_'                  : '-xelatex',    
                        \'pdflatex'           : '-pdf',          
                        \'dvipdfex'           : '-pdfdvi',  
                        \'lualatex'           : '-lualatex',    
                        \'xelatex'            : '-xelatex',   
                        \'context (pdftex)'   : '-pdf -pdflatex=texexec',  
                        \'context (luatex)'   : '-pdf -pdflatex=context',  
                        \'context (xetex)'    : '-pdf -pdflatex=''texexec --xtx''', 
                        \}  
" 这里使用 latexmk 作为编译工具,并且设置了编译的选项,用 XeLatex 进行编译。
" 第2行是设置编译产生的中间文件放在根目录下的 out 文件夹内,这样可以使目录看上去更加整洁干净。
" 为了能够更好的编译中文,需要在 ~/.latexmkrc 文件中写入如下配置:
" $pdf_mode=5;
" 表示我们是使用 XeLatex 进行编译。
" """""""""""""
" 设置退出时自动清理中间编译的文件:
augroup vimtex_config
    autocmd!
    autocmd User VimtexEventQuit call vimtex#compiler#clean(0)
augroup END
"==================="
" 设置目录显示内容和显示宽度,并设置目录的自动刷新,设置后使用快捷键 \ +l+t (即敲入\lt)就可以打开目录。
let g:vimtex_toc_config = {
            \ 'name' : 'TOC',
            \ 'layers' : ['content', 'todo', 'include'],
            \ 'split_width' : 30,
            \ 'todo_sorted' : 0,
            \ 'show_help' : 1,
            \ 'show_numbers' : 1,
            \}
augroup VimTeX
    autocmd!
    autocmd BufWritePost *.tex call vimtex#toc#refresh()
augroup END
""===========================""
" 设置预览 PDF 的工具是 sumatra(zathura) 阅读器

function! s:write_server_name() abort
    let nvim_server_file = (has('win32') ? $TEMP : '/tmp') . '/vimtexserver.txt'
    call writefile([v:servername], nvim_server_file)
endfunction

augroup vimtex_common
    autocmd!
    autocmd FileType tex call s:write_server_name()
augroup END

" let g:vimtex_view_general_viewer = 'sumatraPDF'
" let g:vimtex_view_method = 'sumatraPDF'
" let g:vimtex_compiler_progname = 'nvr'    " 这一行默认就是这个值,但如果编译出现问题,可以手动指定试一试。
" 安装上面的 nvr,也就是 neovim-remote,在系统终端运行:
" pip3 install neovim-remote  "" 注意要在你使用 nvim 的 python 环境下进行这个包的安装。
""===========================""
" 接下来配置 Zathura 阅读器,在其配置文件 ~/.config/zathura/zathurarc 下加入如下内容:
" set synctex true
" set synctex-editor-command "nvr --remote-silent %f -c %l"
""=================== 自定义代码片段 ====================="""
" 为了更好的自动补全,我们还需要提供贴合 Tex 的补全内容,而有人已经为我们总结好了,
" 只需要用 :CocInstall coc-vimtex 指令安装专门为 vimtex 设计的 coc.nvim 插件即可。
" 写 Tex 如果能实时预览那一定会好用不少。实际上 vimtex 插件在点击 \+l+l 按键后就会开始实时侦测文档的变化,
" 当检测到变化后就会自动编译文档并生成新的 PDF。我们其实只要实现自动保存功能就好,使用如下配置可以在
" 文本变化的时候自动保存:
" autocmd TextChanged,TextChangedI <buffer> silent write
" 但就我个人而言,有时编辑文件并不想让其自动保存,这样在编辑出问题后还可以回退到最开始的文件。
" 所以就设置为只有文件类型为 tex 时才自动保存。首先在配置文件中加入:
" filetype plugin indent on
" 打开文件类型检测。然后在与配置文件相同的目录下,新建一个名为 ftplugin 的目录,
" 目录下新建 tex.vim 的文件。将上面的配置语句放入该文件,则只对类型为 tex 的文件生效。

" 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>" :
      \ CheckBackspace() ? "\<TAB>" :
      \ coc#refresh()
inoremap <expr><S-TAB> pumvisible() ? "\<C-p>" : "\<C-h>"

function! CheckBackspace() 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 ShowDocumentation()<CR>

function! ShowDocumentation()
  if CocAction('hasProvider', 'hover')
    call CocActionAsync('doHover')
  else
    call feedkeys('K', 'in')
  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)

" Run the Code Lens action on the current line.
nmap <leader>cl  <Plug>(coc-codelens-action)

" 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 CocActionAsync('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     CocActionAsync('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>



set guifont=Consolas:h18
let g:python3_host_prog = 'C:\Users\AlgebraicGeometry\AppData\Local\Programs\Python\Python310\python.exe'





5. 第六步 : 打开nvim-qt.exe,并在Normal模式下输入:PlugInstall

第七步 : 在Normal模式下输入:Cocnvim coc-vimtex命令,并等待执行完毕

第八步 : 将zyt-snippet-master/下面的文件按照文件夹名称对应着复制到"D:\plugged\vim-snippets"下面,主要是以下几个文件需要对应复制

需要复制的文件文件复制后路径
"zyt-snippet-master\autoload\snip_util.vim""D:\plugged\vim-snippets\autoload\snip_util.vim"
"zyt-snippet-master\plugin\zyt-snippet.vim""D:\plugged\vim-snippets\plugin\zyt-snippet.vim"
"zyt-snippet-master\pythonx\snippet_helpers.py""D:\plugged\vim-snippets\pythonx\snippet_helpers.py"
"zyt-snippet-master\UltiSnips\markdown.snippets"D:\plugged\vim-snippets\UltiSnips\markdown.snippets
"zyt-snippet-master\UltiSnips\mathtex.snippets"类似
"zyt-snippet-master\UltiSnips\python.snippets"类似
"zyt-snippet-master\UltiSnips\snippets.snippets"类似
"zyt-snippet-master\UltiSnips\temp_markdown.snippets"类似
"zyt-snippet-master\UltiSnips\tex.snippets"类似
"zyt-snippet-master\UltiSnips\vim.snippets"类似

Enjoy LaTeX Editing!

1 条评论

发布
问题