linux Vim打造python编辑器

1. 安装vim8.2+

  - 查看vim版本(我使用的9.0版本):
vim -version

-- VIM - Vi IMproved 9.0 (2022 Jun 28, compiled Nov 22 2022 17:34:53)
-- Garbage after option argument: "-version"
-- More info with: "vim -h"
  - 查看是否支持python3,前边没有'+'的重新安装vim  
    vim打开任意文件输入:version
  VIM - Vi IMproved 9.0 (2022 Jun 28, compiled Nov 22 2022 17:34:53)                                                                                                                                                 
    Included patches: 1-916                                                                                                                                                                                            
    Compiled by root@kali                                                                                                                                                                                              
    Huge version without GUI.  Features included (+) or not (-):                                                                                                                                                       
    +acl               -clientserver      +diff              +folding           +langmap           +mouse_dec         +num64             +reltime           +syntax            +title             +wildmenu            
    +arabic            -clipboard         +digraphs          -footer            +libcall           -mouse_gpm         +packages          +rightleft         +tag_binary        -toolbar           +windows             
    +autocmd           +cmdline_compl     -dnd               +fork()            +linebreak         -mouse_jsbterm     +path_extra        -ruby              -tag_old_static    +user_commands     +writebackup         
    +autochdir         +cmdline_hist      -ebcdic            -gettext           +lispindent        +mouse_netterm     -perl              +scrollbind        -tag_any_white     +vartabs           -X11                 
    -autoservername    +cmdline_info      +emacs_tags        -hangul_input      +listcmds          +mouse_sgr         +persistent_undo   +signs             -tcl               +vertsplit         -xfontset            
    -balloon_eval      +comments          +eval              +iconv             +localmap          -mouse_sysmouse    +popupwin          +smartindent       +termguicolors     +vim9script        -xim                 
    +balloon_eval_term +conceal           +ex_extra          +insert_expand     -lua               +mouse_urxvt       +postscript        -sodium            +terminal          +viminfo           -xpm                 
    -browse            +cryptv            +extra_search      +ipv6              +menu              +mouse_xterm       +printer           -sound             +terminfo          +virtualedit       -xsmp                
    ++builtin_terms    +cscope            -farsi             +job               +mksession         +multi_byte        +profile           +spell             +termresponse      +visual            -xterm_clipboard     
    +byte_offset       +cursorbind        +file_in_path      +jumplist          +modify_fname      +multi_lang        -python            +startuptime       +textobjects       +visualextra       -xterm_save          
    +channel           +cursorshape       +find_in_path      +keymap            +mouse             -mzscheme          +python3           +statusline        +textprop          +vreplace                               
    +cindent           +dialog_con        +float             +lambda            -mouseshape        +netbeans_intg     +quickfix          -sun_workshop      +timers            +wildignore                             
       system vimrc file: "$VIM/vimrc"                                                                                                                                                                                 
         user vimrc file: "$HOME/.vimrc"                                                                                                                                                                               
     2nd user vimrc file: "~/.vim/vimrc"                                                                                                                                                                               
          user exrc file: "$HOME/.exrc"                                                                                                                                                                                
           defaults file: "$VIMRUNTIME/defaults.vim"                                                                                                                                                                   
      fall-back for $VIM: "/usr/local/vim/share/vim"                                                                                                                                                                   
    Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -g -O2 -D_REENTRANT -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1                                                                                                          
    Linking: gcc -L/usr/local/lib -Wl,--as-needed -o vim -lm -ltinfo -lrt -ldl -L/usr/lib/python3.10/config-3.10-x86_64-linux-gnu -lpython3.10 -lcrypt -lpthread -ldl -lutil -lm -lm

  - 编译安装vim

    解压后进入vim-master执行(./configure --help可查看参数):

1. ./configure --prefix=/usr/local/vim/ --enable-python3interp  # 如果这一步出错,需要根据出错原因安装指定库
  # make clean  --清除之前编译的可执行文件及配置文件
  # make distclean  --如果make出错时执行,调整后再重新make
2. make && make install
3. ln -s /usr/local/vim/bin/vim /usr/bin/vim

2. node安装

  - 下载

    将下载的包在/usr/local下解压并创建链接:

ln -s /usr/local/node/bin/node /usr/local/bin  # 引入node
ln -s /usr/local/node/bin/npm /usr/local/bin  # 引入npm

  - 查看版本

node --version

  - 注意

    这里的安装包在解压后需要查看/usr/local/node/bin/下是否为软链接,不是的话需要删掉原来的npm,npx,corepack手动创建软链接:

    cd /usr/local/node/bin

    rm npm,npx,corepack     # 删除原来的三个文件

    ln -s ../lib/node_modules/corepack/dist/corepack.js /home/node/bin/corepack
    ln -s ../lib/node_modules/npm/bin/npm-cli.js /home/node/bin/npm
    ln -s ../lib/node_modules/npm/bin/npx-cli.js /home/node/bin/npx

    

3.  配置~/.vimrc文件

  - 修改.vimrc文件(没有的手动创建),查看文件换行符:set ff?,linux下如果结果是dos,则需要设置成unix,:set ff=unix,本来才用defx作为目录插件,但是发现在一些机器配置过程中会有问题,所以改用coc-explorer.

"-----------------------------------------------"
"               基础设置                         "
"-----------------------------------------------"

set modelines=0                          " 禁用模式行(安全措施)
syntax on                                " 语法高亮
filetype on                              " 开启文件类型检测

set encoding=utf-8                       " 编码设置
set number                               " 显示行号
set relativenumber                       " 显示相对行号
set smartindent                          " 智能缩进
set autoindent                           " 自动对齐

set smarttab
set tabstop=4                            " tab缩进
set shiftwidth=4                         " 设定自动缩进为4个字符
set expandtab                            " 用space替代tab的输入
set splitright                           " 设置左右分割窗口时,新窗口出现在右侧
set splitbelow                           " 设置水平分割窗口时,新窗口出现在底部

set nobackup                             " 不需要备份
set noswapfile                           " 禁止生成临时文件
set autoread                             " 文件自动检测外部更改

set nocompatible                         " 去除vi一致性
set ambiwidth=double                     " 解决中文标点显示的问题
set nowrap                               " 不自动折行
set mouse=a                              " 使用鼠标
set mousehide                            " 输入时隐藏光标

set sm!                                  " 高亮显示匹配括号
set hlsearch                             " 高亮查找匹配
set cursorline                           " 高亮显示当前行
set termguicolors                        " 启用终端真色

set showmatch                            " 显示匹配
set ruler                                " 显示标尺,在右下角显示光标位置
set novisualbell                         " 不要闪烁
set showcmd                              " 显示输入的命令

" 设置光标样式
let &t_SI = "\<Esc>]50;CursorShape=1\x7"
let &t_SR = "\<Esc>]50;CursorShape=2\x7"
let &t_EI = "\<Esc>]50;CursorShape=0\x7"

set completeopt=longest,menu             " 自动补全配置让Vim补全菜单行为跟IDE一致
set backspace=indent,eol,start           " 允许用退格键删除字符
let g:markdown_fenced_languages =['c', 'cpp', 'python', 'javascript']
set guifont=SimSun-ExtB:h14  " 设置字体和字体大小
" 禁止显示滚动条
set guioptions-=l
set guioptions-=L
set guioptions-=r
set guioptions-=R
" 禁止显示菜单和工具条
set guioptions-=m
set guioptions-=T

"-----------------------------------------------"
"               自定义功能                      "
"-----------------------------------------------"
" 格式化json格式--------------------
command! JsonFormat :execute '%!python -m json.tool'
  \ | :execute '%!python -c "import re,sys;chr=__builtins__.__dict__.get(\"unichr\", chr);sys.stdout.write(re.sub(r\"\\u[0-9a-f]{4}\", lambda x: chr(int(\"0x\" + x.group(0)[2:], 16)), sys.stdin.read()))"'
  \ | :%s/ \+$//ge
  \ | :set ft=javascript
  \ | :1
map <F4> <Esc>:JsonFormat<CR>

" 快捷键绑定-------------------------
let mapleader='\'
noremap <TAB>w <C-w>w
" 使用方向键切换buffer
noremap <Leader><left> :bp<CR>
noremap <Leader><right> :bn<CR>
" 使用 \ + s 保存
noremap <Leader>s :w<CR>


"-----------------------------------------------"
"               插件安装                        "
"-----------------------------------------------"

call plug#begin('~/.vim/plugged')

" if has('nvim')
"   Plug 'Shougo/defx.nvim', { 'do': ':UpdateRemotePlugins' }
" else
"   Plug 'Shougo/defx.nvim'
"   Plug 'roxma/nvim-yarp'
"   Plug 'roxma/vim-hug-neovim-rpc'
" endif
Plug 'Yggdroot/indentLine'
Plug 'morhetz/gruvbox'
Plug 'joshdick/onedark.vim'
Plug 'vim-airline/vim-airline'
Plug 'mhinz/vim-startify'
Plug 'ryanoasis/vim-devicons'
" Plug 'kristijanhusak/defx-icons'
Plug 'sbdchd/neoformat'
Plug 'beautify-web/js-beautify'
Plug 'preservim/nerdcommenter'
Plug 'mattn/emmet-vim'
Plug 'skywind3000/asyncrun.vim'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'Yggdroot/LeaderF', { 'do': ':LeaderfInstallCExtension' }

call plug#end()

"-----------------------------------------------"
"               插件设置                         "
"-----------------------------------------------"

"----------asyncrun-------------
let g:asyncrun_open=10
let g:asyncrun_save=1
noremap <silent> <F5> :call CompileRun()<CR>
func! CompileRun()
    exec "w"
    if &filetype == 'c'
        exec ':AsyncRun -mode=term -pos=hide gcc "$(VIM_FILEPATH)" -o "$(VIM_FILEDIR)/$(VIM_FILENOEXT)"'
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 $(VIM_FILEDIR)/$(VIM_FILENOEXT)"
    elseif &filetype == 'cpp'
        exec ':AsyncRun -pos=hide g++ -O3 "$(VIM_FILEPATH)" -o "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" -lpthread'
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 $(VIM_FILEDIR)/$(VIM_FILENOEXT)"
    elseif &filetype == 'python'
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 python3 $(VIM_FILEPATH)"
    elseif &filetype == 'html'
        exec ":! %"
    elseif &filetype == 'go'
        exec ":AsyncRun -mode=term -pos=hid go build $(VIM_FILEDIR)/$(VIM_FILENOEXT)"
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 go run $(VIM_FILEPATH)"
    elseif &filetype == 'javascript'
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 node $(VIM_FILEPATH)"
    endif
endfunc

"----------Startify-------------
noremap <Leader>bh :Startify<CR>

"-----------neoformat-----------
let g:neoformat_try_node_exe = 1
"保存时自动格式化代码
"这个自动命令里面用到的事件是BufWritePre,这个事件会在保存_任何_字符到文件之前触发。
augroup fmt
  autocmd!
  autocmd BufWritePre * :Neoformat
augroup END

"------------indentLine----------
"解决markdown文件*号隐藏问题
let g:markdown_syntax_conceal=0
let g:vim_json_conceal=0

"---------- set theme ------------
set vb t_vb=
set background=dark
"colorscheme gruvbox
colorscheme onedark

"----------airline------------
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#left_sep = '>'
let g:airline#extensions#tabline#left_alt_sep = '*'
let g:airline#extensions#tabline#formatter = 'unique_tail'
let g:airline#extensions#tabline#buffer_nr_show = 1        "显示buffer编号
let g:airline#extensions#tabline#buffer_nr_format = '%s:'
let g:airline#extensions#battery#enabled = 1
let g:airline_left_sep = '>'
let g:airline_left_alt_sep = '*'
let g:airline_theme='onedark'
"let g:airline#extensions#tabline#overflow_marker = '… '
" let airline#extensions#tabline#current_first = 1

"-----------defx----------------
" 使用 F3/<Leader>+f+t  切换显示文件浏览,使用 ;a 查找到当前文件位置
" let g:maplocalleader=';'
" nnoremap <silent> <F3>
" \ :<C-u>Defx -resume -toggle -buffer-name=tab`tabpagenr()`<CR>
" 
" nnoremap <silent> <Leader>ft
" \ :<C-u>Defx -resume -toggle -buffer-name=tab`tabpagenr()`<CR>
" 
" nnoremap <silent> <LocalLeader>a
" \ :<C-u>Defx -resume -buffer-name=tab`tabpagenr()` -search=`expand('%:p')`<CR>
" 
" " 初始化
" call defx#custom#option('_', {'columns': 'indent:git:icons:filename','winwidth': 28,'split': 'vertical','direction': 'topleft','listed': 1,'toggle': 1,'resume': 1,'show_ignored_files': 0,'root_marker': '[in]:'})
" 
" call defx#custom#column('indent', {'indent': '  ',})
" 
" "快捷键绑定
" autocmd FileType defx call s:defx_my_settings()
" function! s:defx_my_settings() abort
"     " Define mappings
"     nnoremap <silent><buffer><expr> <CR>
"     \ defx#do_action('multi', ['drop'])
"     nnoremap <silent><buffer><expr> c
"     \ defx#do_action('copy')
"     nnoremap <silent><buffer><expr> m
"     \ defx#do_action('move')
"     nnoremap <silent><buffer><expr> p
"     \ defx#do_action('paste')
"     nnoremap <silent><buffer><expr> l
"     \ defx#is_directory() ?
"     \ defx#do_action('open_tree', 'toggle') :
"     \ defx#do_action('multi', ['drop'])
"     nnoremap <silent><buffer><expr> E
"     \ defx#do_action('open', 'vsplit')
"     nnoremap <silent><buffer><expr> D
"     \ defx#do_action('new_directory')
"     nnoremap <silent><buffer><expr> F
"     \ defx#do_action('new_file')
"     noremap <silent><buffer><expr> r
"     \ defx#do_action('rename')
"     nnoremap <silent><buffer><expr> d
"     \ defx#do_action('remove')
"     noremap <silent><buffer><expr> B
"     \ defx#is_directory() ?
"     \ defx#do_action('cd', ['..']) :
"     \ defx#do_action('close_tree')
"     nnoremap <silent><buffer><expr> q
"     \ defx#do_action('quit')
"     nnoremap <silent><buffer><expr> .
"     \ defx#do_action('toggle_ignored_files')
" endfunction
nnoremap <F3> <Cmd>CocCommand explorer<CR>


"-----------defx-icons(defaults)---------------
" let g:defx_icons_enable_syntax_highlight = 1
" let g:defx_icons_column_length = 1
" let g:defx_icons_directory_icon = ''
" let g:defx_icons_mark_icon = '*'
" let g:defx_icons_copy_icon = ''
" let g:defx_icons_link_icon = ''
" let g:defx_icons_move_icon = ''
" let g:defx_icons_parent_icon = ''
" let g:defx_icons_default_icon = ''
" let g:defx_icons_directory_symlink_icon = ''
" let g:defx_icons_root_opened_tree_icon = ''
" let g:defx_icons_nested_opened_tree_icon = ''
" let g:defx_icons_nested_closed_tree_icon = ''

"-----------注释-------
"" Create default mappings
let g:NERDCreateDefaultMappings = 1

" Add spaces after comment delimiters by default
let g:NERDSpaceDelims = 1

" Use compact syntax for prettified multi-line comments
let g:NERDCompactSexyComs = 1

" Align line-wise comment delimiters flush left instead of following code indentation
let g:NERDDefaultAlign = 'left'

" Set a language to use its alternate delimiters by default
let g:NERDAltDelims_java = 1

" Add your own custom formats or override the defaults
let g:NERDCustomDelimiters = { 'c': { 'left': '/**','right': '*/' } }

" Allow commenting and inverting empty lines (useful when commenting a region)
let g:NERDCommentEmptyLines = 1

" Enable trimming of trailing whitespace when uncommenting
let g:NERDTrimTrailingWhitespace = 1

" Enable NERDCommenterToggle to check all selected lines is commented or not
let g:NERDToggleCheckAllLines = 1

" 快捷键 :
" <leader>ci

"---------------emmet-vim----------
let g:user_emmet_install_global = 0
autocmd FileType html,css EmmetInstall
let g:user_emmet_leader_key='<C-e>'

"-------------coc-nvim-------------
let g:coc_global_extensions = ['coc-json', 'coc-vimlsp', 'coc-pyright', 'coc-explorer', 'coc-sql']

"----------LeaderF----------------
let g:Lf_HideHelp = 1
" popup mode
let g:Lf_WindowPosition = 'popup'
let g:Lf_PreviewInPopup = 1
" 快捷键绑定
let g:Lf_ShortcutF = "<leader>ff"
let g:Lf_ShortcutB = "<leader>fb"
" 排除搜索的文件夹和文件
let g:Lf_WildIgnore = {'dir': ['.svn','.git','.hg','venv','.vscode','.SpaceVim.d'],'file': ['*.sw?','~$*','*.bak','*.exe','*.o','*.so','*.py[co]']}

  - 自动补全html标签可在.vimrc上添加下边配置

" html自动补全
autocmd BufNewFile *  setlocal filetype=html
function! InsertHtmlTag()
	let pat = '\c<\w\+\s*\(\s\+\w\+\s*=\s*[''#$;,()."a-z0-9]\+\)*\s*>'
	normal! a>
	let save_cursor = getpos('.')
	let result = matchstr(getline(save_cursor[1]), pat)
	if (search(pat, 'b', save_cursor[1]))
		normal! lyiwf>
		normal! a</
		normal! p
		normal! a>
	endif
	:call cursor(save_cursor[1], save_cursor[2], save_cursor[3])
endfunction
inoremap > <ESC>:call InsertHtmlTag()<CR>a<CR><Esc>O

  - 安装插件管理工具vim-plug

    在root目录下创建.vim文件夹,进入然后再创建autoload文件夹,然后执行(速度慢可直接下载plug.vim放到对应目录下即可):

curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

  - 插件安装  

    • 状态栏美化 vim-airline
    • 缩进线插件 indentLine
    • 代码格式化插件 neoformat
    • 异步运行插件 asyncrun.vim
    • 代码补全插件 coc.nvim
    • 模糊查找 LeaderF
    • 颜色主题 onedark.vim

    vim打开任意文件执行:PlugInstall下载相应插件(速度慢直接下载,解压后放在~/.vim/plugged/*)

  - 字体设置

:set guifont    # 查看当前字体
:set guifont=*  # 显示支持的所有字体,可以自己调节字体大小和样式后选择并在vimrc文件中配置

4.icons乱码问题

  如果你在配置中使用了特殊的icon但是显示有乱码,linux下可以执行文件,可能等待时间比较长,执行结束后会生成一个install.sh文件,执行此文件即可安装字体.

5.目录操作说明

?    显示帮助
*    选中文件或文件夹
l    打开文件夹或文件
o    关闭文件夹或打开文件夹
e    打开文件或目录
E    多文件显示
t    打开文件或目录并将当前文件夹或文件作为父目录
yp   复制绝对路径到剪切板
yn   复制文件名到剪切板
yy   复制文件
ya   追加复制的文件
p    粘贴文件
y<space>  清除文件复制
dd   剪切文件
da   追加剪切文件
d<space>  清除文件剪切
df   删除文件或目录到回收站
dF   永久删除文件或目录
a    添加新文件
A    添加新目录
r    重名文件或目录
q    退出资源管理器
gf   切换到文件根目录
gb   切换到缓冲器根目录
[[   转到上一个源
]]   转到下一个源

6.windows下gvim

  gvim9.0下载安装好后,将上边plug.vim放在gvim安装目录中的autoload下,插件放在autoload同级目录下的plugs中(没有的新建这个目录),.vimrc改名为_vimrc,放在C:\Users\Administrator\下即可.

7.效果展示

  

 

posted @ 2022-11-29 14:10  屁桃  阅读(527)  评论(0编辑  收藏  举报