Handwriting C++ Server (9): Always Dishen vim (source code installation, plug-in management, color themes, code highlighting, shortcut key settings, search and replacement, environmental protection)

Foreword: If you want to do well, you must first sharpen your tool. As a development tool, vim is an indispensable weapon for server-side programming. This blog post was originally published at: https://github.com/whuwzp/vim_config , let’s start the vim journey.

Article Directory

vim learning

  1. Introduction: Source code compilation uses vim and its plugins.
  2. The content includes: the compilation and installation of vim, the compilation and installation of llvm clang, the compilation and installation of the plugin youcompleteme, and the use of other plugins in vim.
  3. Build environment: Ubuntu18.04.4 server version (desktop version should also be applicable)
  4. Environmental restoration method:
  • Save on Nuts Cloud: .vimThe compressed file of the file, so as not to have to download it when changing the environment in the future, and directly unzip it when using it.~/.vim
  • Save on GitHub: .vimrc, .clang-format, .ycm_extra_conf.pyand other configuration files, Address: https://github.com/whuwzp/vim_config
  1. The main reference URLs are as follows, basically refer to the official method, rather than picking up people's teeth on the blog site:
  • Vim source code compilation: https://github.com/ycm-core/YouCompleteMe/wiki/Building-Vim-from-source
  • llvm clang编译: https://llvhttps://m.org/docs/GettingStarted.html#getting-started-with-llvm
  • youcompleteme compile and use: https://github.com/ycm-core/YouCompleteMe#linux-64-bit
  • Other C++ plugins: https://github.com/yangyangwithgnu/use_vim_as_ide.
  1. Real-time update description address:
  • https://www.cnblogs.com/whuwzp/p/ubuntu_vim_0.html
  • https://whuwzp.gitee.io/tech-6-vim%E4%BD%BF%E7%94%A8.html

1. Vim source code compilation and installation

Reference URL: https://github.com/ycm-core/YouCompleteMe/wiki/Building-Vim-from-source

Install various dependent libraries

sudo apt install libncurses5-dev libgnome2-dev libgnomeui-dev \
libgtk2.0-dev libatk1.0-dev libbonoboui2-dev \
libcairo2-dev libx11-dev libxpm-dev libxt-dev python-dev \
python3-dev ruby-dev lua5.1 liblua5.1-dev libperl-dev git

Download the latest version of vim and compile

git clone [email protected]:vim/vim.git
cd vim/

./configure --with-features=huge \
--enable-multibyte \
--enable-rubyinterp=yes \
--enable-python3interp=yes \
--with-python3-config-dir=/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu \
--enable-perlinterp=yes \
--enable-luainterp=yes \
--enable-gui=gtk2 \
--enable-cscope \
--enable-multibyte \
--prefix=/usr/local

make
make install

Detect

vim --version
# 截至20200301, 此方法最新版是8.2

note:

  1. You can only choose one installation for python2 and python3: Some blogs have problems with enabling python2 and python3 at the same time in the configure step (refer to the installation reference URL). Here, python3 is selected, and python3 is required in youcompleteme later, and python3 is the trend , So choose python3 here. (If you want to choose python2, just change the above python3 to python)
  2. with-python3-config-dir: The way to view this is: command line python --version, mine is 3.6, so just /usr/lib/python3.6/look for a config-3.6m-x86_64-linux-gnufolder with a name like this in it, in short, make sure: the python3 version and the path are the same, and the path is correct.

2. Compile and install llvm clang from source code

参考网址: https://llvhttps://m.org/docs/GettingStarted.html#getting-started-with-llvm

Installation preparation environment

# clang的编译需要gcc等
sudo apt install gcc
sudo apt install g++
sudo apt install make
sudo apt install cmake 

Download and compile

git clone https://github.com/llvm/llvm-project.git
cd llvm-project
mkdir build
cd build

cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release ../llvm -DLLVM_ENABLE_PROJECTS="clang;libcxx;libcxxabi;compiler-rt;clang-tools-extra;openmp;lldb;lld" 

make -j2
make install

test

clang --version
# 截至20200301最新版是11.0

note:

  1. cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release ../llvm: Don't change this step
  2. DLLVM_ENABLE_PROJECTS: Select the options to be installed here, separated by semicolons, refer to the URL selection, generally selected clang;libcxx;libcxxabi;compiler-rt;clang-tools-extra, I am afraid that it will be troublesome to install later, so I chose lldb (debugging), lld (link optimization)

3. Youcompleteme compile and install

Reference URL: https://github.com/ycm-core/YouCompleteMe#linux-64-bit It is
recommended not to use this blog method: https://github.com/yangyangwithgnu/use_vim_as_ide

  1. Install plugin manager vundle
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
# 在 ~/.vimrc 增加相关配置信息

" vundle 环境设置
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
" vundle 管理的插件列表必须位于 vundle#begin() 和 vundle#end() 之间
call vundle#begin()
Plugin 'VundleVim/Vundle.vim'
Plugin 'ycm-core/YouCompleteMe'

" 插件列表结束
call vundle#end()
filetype plugin indent on
  1. Open vim, enter :PluginInstall, download YouCompleteMe
  2. installation
# 依赖项
sudo apt install build-essential cmake python3-dev
cd ~/.vim/bundle/YouCompleteMe
# 如果要选择其他语言支持可以选, 参考网址里有
python install.py --clang-completer
  1. The edited file is created in the project directory .ycm_extra_conf.py. We only need to change the directory of the header file in flags. The content is as follows (refer to https://github.com/yangyangwithgnu/use_vim_as_ide for this content):
import os 
import ycm_core 
flags = [ 
    '-std=c++11', 
    '-O0', 
    '-Werror', 
    '-Weverything', 
    '-Wno-documentation', 
    '-Wno-deprecated-declarations', 
    '-Wno-disabled-macro-expansion', 
    '-Wno-float-equal', 
    '-Wno-c++98-compat', 
    '-Wno-c++98-compat-pedantic', 
    '-Wno-global-constructors', 
    '-Wno-exit-time-destructors', 
    '-Wno-missing-prototypes', 
    '-Wno-padded', 
    '-Wno-old-style-cast',
    '-Wno-weak-vtables',
    '-x', 
    'c++', 
    '-I',
    '.',
    '-isystem', 
    '/usr/local/include/c++/v1/',
    '-isystem',
    '/usr/include/',
    '-isystem',
    '/usr/',
    '-isystem',
    '/usr/include/x86_64-linux-gnu/',
] 
compilation_database_folder = '' 
if compilation_database_folder: 
database = ycm_core.CompilationDatabase( compilation_database_folder ) 
else: 
database = None 
SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ] 
def DirectoryOfThisScript(): 
return os.path.dirname( os.path.abspath( __file__ ) ) 
def MakeRelativePathsInFlagsAbsolute( flags, working_directory ): 
if not working_directory: 
    return list( flags ) 
new_flags = [] 
make_next_absolute = False 
path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ] 
for flag in flags: 
    new_flag = flag 
    if make_next_absolute: 
    make_next_absolute = False 
    if not flag.startswith( '/' ): 
        new_flag = os.path.join( working_directory, flag ) 
    for path_flag in path_flags: 
    if flag == path_flag: 
        make_next_absolute = True 
        break 
    if flag.startswith( path_flag ): 
        path = flag[ len( path_flag ): ] 
        new_flag = path_flag + os.path.join( working_directory, path ) 
        break 
    if new_flag: 
    new_flags.append( new_flag ) 
return new_flags 
def IsHeaderFile( filename ): 
extension = os.path.splitext( filename )[ 1 ] 
return extension in [ '.h', '.hxx', '.hpp', '.hh' ] 
def GetCompilationInfoForFile( filename ): 
if IsHeaderFile( filename ): 
    basename = os.path.splitext( filename )[ 0 ] 
    for extension in SOURCE_EXTENSIONS: 
    replacement_file = basename + extension 
    if os.path.exists( replacement_file ): 
        compilation_info = database.GetCompilationInfoForFile( replacement_file ) 
        if compilation_info.compiler_flags_: 
        return compilation_info 
    return None 
return database.GetCompilationInfoForFile( filename ) 
def FlagsForFile( filename, **kwargs ): 
if database: 
    compilation_info = GetCompilationInfoForFile( filename ) 
    if not compilation_info: 
    return None 
    final_flags = MakeRelativePathsInFlagsAbsolute( 
    compilation_info.compiler_flags_, 
    compilation_info.compiler_working_dir_ ) 
else: 
    relative_to = DirectoryOfThisScript() 
    final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to ) 
return { 
    'flags': final_flags, 
    'do_cache': True 
}

This is saved in https://github.com/whuwzp/vim_config

note:

  1. .ycm_extra_conf.pyThe method of adding header files in: I installed clang with the default path /usr/local, so I added'-isystem', '/usr/local/include/c++/v1/'
  • '-isystem','/usr/include/': This is the system header file
  • '-isystem','/usr/': This is also systematic
  • '-isystem','/usr/include/x86_64-linux-gnu/': This is for linux
  1. If you find that a function cannot be completed or reported an error solution,
    first look at the header file that the function belongs to, then go to Baidu or directly to /usr/include, look for it in other locations, and then add it to .ycm_extra_conf.pyit, for example, sys/socket.hthere is no automatic completion, Baidu found /usr/include/x86_64-linux-gnu/, and then added '-isystem','/usr/include/x86_64-linux-gnu/'to
  2. It is strongly recommended not to copy the header files to /usr/include.
    This diagram is convenient for a while, but it is all messed up. It is best to use the method of the previous step, and it is also easy to understand the location of each header file.
  3. The solution for ycm server shutdown
    needs to enter the ~/.vim/bundle/youcompletemedirectory, install, as follows:
# 如果不执行这一步,下一步就报错
git submodule update --init --recursive
# 然后install
sudo ./install.sh --clang-completer
# 如果上一步报错缺少regex或者cregex,那就是git submodule update --init --recursive没有完全下载,那就去目录下找,例如我的是regex,到youcompleteme的github下找到了thrid/ycmd/third/regex,然后发现子项目的地址https://github.com/ycm-core/regex.git,然后自己git clone下来,手动拷贝到那个目录就好,例如git clone https://github.com/ycm-core/regex.git
  1. Cannot complete a custom class
    YCM in another file, only triggers semantic completion in the following two scenarios: one is that the file where the completion identifier is located must be in the buffer (that is, the file is already open); the other is to type after the object ., after the pointer, type ->, after the name space, type::.
    So that file must be opened.
  2. If you don't have boost,
    then download and install boost yourself.
    Refer to the following: https://www.cnblogs.com/smallredness/p/9245127.html
解压到一个目录
tar -zxvf boost_1_66_0.tar.gz
1、正常编译:
进入boost_1_66_0目录中
cd boost_1_66_0
./bootstrap.sh --with-libraries=all --with-toolset=gcc
--with-liraries:需要编译的库
--with-toolset:编译时使用的编译器
安装boost库
./b2 install --prefix=/usr
  1. For compilation warnings, please refer to: https://blog.csdn.net/qq_17308321/article/details/79979514

4. Plug-ins

Mainly related to C++. The ~/.vimrcfiles are available on GitHub: https://github.com/whuwzp/vim_config The
following content is referenced: https://github.com/yangyangwithgnu/use_vim_as_ide

4.1 vundle plugin manager

git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim

Add relevant configuration information in .vimrc


" vundle 环境设置
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
" vundle 管理的插件列表必须位于 vundle#begin() 和 vundle#end() 之间
call vundle#begin()
Plugin 'VundleVim/Vundle.vim'
Plugin 'dyng/ctrlsf.vim'

" 插件列表结束
call vundle#end()
filetype plugin indent on

Among them, each item Plugin 'dyng/ctrlsf.vim'corresponds to a plug-in (this is similar to the go language's mechanism for managing different code bases). If there are new plug-ins in the future, you only need to add them to the list.

Install the plug-in:
first find its address on github.com, then add the configuration information between call vundle#begin() and call vundle#end() in .vimrc, for example Plugin 'dyng/ctrlsf.vim', finally enter vim to execute:PluginInstall

Deleting a plug-in
To uninstall a plug-in, first comment or delete the corresponding plug-in configuration information in .vimrc, and then execute it in vim: :PluginCleanyou can delete the corresponding plug-in.

Update plug-ins The
update frequency is relatively high. You should check which plug-ins have a new version almost every other month, batch update, just execute :PluginUpdate.

4.2 Completion plug-ins

Plugin 'Valloric/YouCompleteMe'
Plugin 'derekwyatt/vim-protodef'
Plugin 'SirVer/ultisnips'

4.2.1 YouCompleteMe semantic completion

See above for installation. The following is the configuration:

" Youcompleteme                                    语义补全
" 菜单
highlight Pmenu ctermfg=2 ctermbg=3 guifg=#005f87 guibg=#EEE8D5
" 选中项
highlight PmenuSel ctermfg=2 ctermbg=3 guifg=#AFD700 guibg=#106900
" 补全功能在注释中同样有效
let g:ycm_complete_in_comments=1
" 允许 vim 加载 .ycm_extra_conf.py 文件,不再提示
let g:ycm_confirm_extra_conf=0
" 开启 YCM 标签补全引擎
let g:ycm_collect_identifiers_from_tags_files=1
" 引入 C++ 标准库tags
" set tags+=/usr/include/c++/7/stdcpp.tags, 我只使用clang中的就好
set tags+=/usr/local/include/c++/v1/clang.tags
" set tags+=/usr/include/sys.tags,这个太大了了
" YCM 集成 OmniCppComplete 补全引擎,设置其快捷键
inoremap <leader>; <C-x><C-o>
" 补全内容不以分割子窗口形式出现,只显示补全列表
set completeopt-=preview
" 从第一个键入字符就开始罗列匹配项
let g:ycm_min_num_of_chars_for_completion=1
" 禁止缓存匹配项,每次都重新生成匹配项
let g:ycm_cache_omnifunc=0
" 语法关键字补全           
let g:ycm_seed_identifiers_with_syntax=1
let OmniCpp_DefaultNamespaces = ["_GLIBCXX_STD"]
" 设置用于关闭补全列表的快捷键,默认为ctrl+y, 改为了;'
let g:ycm_key_list_stop_completion = ["<leader>'"]

4.2.2 Vim-protodef interface implementation completion

Configuration

Declared in h, and then use plug-ins in cpp to help us generate shells that implement functions.

Plugin 'derekwyatt/vim-fswitch'
Plugin 'derekwyatt/vim-protodef'

" 设置 pullproto.pl 脚本路径
" 原博客是这个,但是我的路径是vim-protodef,所以改了
" let g:protodefprotogetter='~/.vim/bundle/protodef/pullproto.pl'
let g:protodefprotogetter='~/.vim/bundle/vim-protodef/pullproto.pl'
" 成员函数的实现顺序与声明顺序一致
let g:disable_protodef_sorting=1

Example of use:

  1. Edit h file
class MyClass 
{
    public:
        void printMsg (int = 16);
        virtual int getSize (void) const;
        virtual void doNothing (void) const = 0;
        virtual ~MyClass ();
    private:
        int num_;
};
  1. Create a new cpp file
    with the same name and use the shortcut key P, our setting is ;Pto generate the following content:
int MyClass::getSize(void) const
{
    return 0;
}

void MyClass::youprint(int)
{
}

MyClass::~MyClass()
{
}
  • Advantage 1: Virtual, default parameters, etc. should be in the function declaration and should not appear in the function definition keywords, protodef has already filtered for you;
  • Advantage 2: doNothing() such pure virtual functions should not be automatically ignored by protodef if they are implemented

Use
to define the class in h, then create a new cpp with the same name, use the shortcut key <leader>PP, mine is to ;PPgenerate the corresponding cpp content.

4.2.3 ultisnips template completion

Configure
"SirVer/ultisnips template completion
" mysnippets default path: ~/.vim/bundle/ultisnips/mysnippets/cpp.snippets
let g:UltiSnipsSnippetDirectories=["~/.mysnippets"]
"The tab key of UltiSnips conflicts with YCM, please try again Set
let g:UltiSnipsExpandTrigger=""
let g:UltiSnipsJumpForwardTrigger=""
let g:UltiSnipsJumpBackwardTrigger=""

Note: The editor ~/.mysnippets/cpp.snippetscan modify the template and change it to this location, which is equivalent to separating the program and configuration, so that it can be easily pushed to GitHub for storage, and it can be used directly in another environment.

Use
to set according to the blog, press ;<tab>it, press again to skip to the next position, such as if(1){2}.
According to the blog settings, there are the following shortcuts:

  • INC: #include""
  • inc: #include<>
  • if: if statement
  • ei: else if statement
  • el: else statement
  • re: return
  • do: do while statement
  • wh: while statement
  • sw: switch statement
  • for: for statement (case for combining a variety of scenarios, try)
  • : try catch
  • set map lst vec: Try it and you will know, the corresponding container
  • cl: class
  • b: ()
  • st: []
  • br: {}
  • q: “”
  • se: ‘’
  • ar: ->, this is arrow

The remaining feeling is not very effective, I don't remember it here.

Note: snippet b "bracket" IThe I here means that it will be completed only when it encounters the whole word b, and printfb will not be completed. If it is changed to i, it will be completed when it encounters the character b.

4.3 Theme color class

Plugin 'vim-airline/vim-airline'                                      
Plugin 'vim-airline/vim-airline-themes'
Plugin 'tomasr/molokai'

4.3.1 vim-airline和vim-airline-themes

Configuration

let g:airline#extensions#tabline#enabled = 1
let g:airline_theme='molokai'

4.3.2 molokai

Configuration

set background=dark
set t_Co=256
colorscheme molokai

4.4 Code highlighting comment formatting class

Plugin 'octol/vim-cpp-enhanced-highlight'
Plugin 'nathanaelkane/vim-indent-guides'
Plugin 'crooloose/nerdcommenter'
Plugin 'vim-clang-format'

4.4.1 vim-cpp-enhanced-highlight

" vim-cpp-enhanced-highlight                        cpp语法高亮
let g:cpp_class_scope_highlight = 1
let g:cpp_member_variable_highlight = 1
let g:cpp_class_decl_highlight = 1
let g:cpp_posix_standard = 1
let g:cpp_concepts_highlight = 1
let g:cpp_no_function_highlight = 1 
let g:cpp_experimental_simple_template_highlight = 1
syntax keyword cppSTLtype initializer_list

Note: You need to ensure the following:
" 开启文件类型侦测 filetype on " 根据侦测到的不同类型加载对应的插件 filetype plugin on

4.4.2 vim-indent-guides indentation

" vim-indent-guides                                   缩进显示                                                         
let g:indent_guides_enable_on_vim_startup=1
" 从第二层开始可视化显示缩进
let g:indent_guides_start_level=2
" 色块宽度
let g:indent_guides_guide_size=1
" 快捷键 i 开/关缩进可视化
nmap <silent> <Leader>i <Plug>IndentGuidesToggle

4.4.3 clang-format format

"clang-format                                          代码风格格式化
" map to <Leader>cf in C++ code
" 可以在~/.clang-format中编辑更加详细的设置
set ts=4
" 退出insert模式时自动格式化, 如果加了这个那么ultisnip插件就会受影响,因为模板补全后会由insert变为select,这样会同时触发clang-format和ultisnip 
" let g:clang_format#auto_format_on_insert_leave=1
autocmd FileType c,cpp,objc nnoremap <buffer><Leader>cf :<C-u>ClangFormat<CR>
autocmd FileType c,cpp,objc vnoremap <buffer><Leader>cf :ClangFormat<CR>

note:

  1. Need to install clang-format
apt install clang-format
  1. You can create a new ~/.clang-formatspecific configuration format, and the reference file is saved at: https://github.com/whuwzp/vim_config

4.4.4 nerdcommenter code comments

" 默认<leader>cc, <leader>cu

4.5 Content Search and Replace

Plugin 'dyng/ctrlsf.vim' 
Plugin 'mileszs/ack.vim'
Plugin 'yegappan/grep'
Plugin 'terryma/vim-multiple-cursors'
Plugin 'Yggdroot/LeaderF'

4.5.1 vim-multiple-cursors multiple selection

" vim-multiple-cursors                          选中多选
" 默认是ctrl+N,这里不修改
" let g:multi_cursor_next_key='<S-n>'
" let g:multi_cursor_skip_key='<S-k>'

I want to rename prtHelpInfo() collectively to showHelpInfo(), first find all prtHelpInfo in the project through ctrlsf, then directly select the first ptr in the ctrlsf sub-window, and then select the second ptr through vim-multiple-cursors (in the sub-window) Press the window to CTRL+nselect the next one), then ESC, insert, enter the editing mode, then delete ptr uniformly and type show uniformly, and finally save and reload the replaced file (:wq, Y, L).

" ctrlsf.vim                                      搜索               
" 插件在工程内全局查找光标所在关键字,设置快捷键。快捷键速记法:search in project
noremap <Leader>sp :CtrlSF<CR>

Note: Need to install grep-ack tool
sudo apt install grep-ack

" ctags标签书签相关
Plugin 'majutsushi/tagbar'
Plugin 'vim-scripts/indexer.tar.gz'
Plugin 'vim-scripts/DfrankUtil'
Plugin 'vim-scripts/vimprj'
Plugin 'kshenoy/vim-signature'
Plugin 'ludovicchabant/vim-gutentags'
Plugin 'skywind3000/gutentags_plus'

Note: ctags needs to be installed, sudo apt install ctags

The principle is to generate a file named tags in the project directory and jump according to the file.

  1. installation
sudo apt install ctags
  1. Generate tags file
cd /data/workplace/example/
ctags -R --c++-kinds=+p+l+x+c+d+e+f+g+m+n+s+t+u+v --fields=+liaS --extra=+q --language-force=c++

This command is to generate tags files, there are many more, refer to: https://blog.csdn.net/foreverling/article/details/80329586
Then let vim know the tags path, enter in vim command mode:

:set tags+=/data/workplace/example/tags
  1. To use,
    first add the above sentence in the vim command mode.
  • CTRL+]: Jump forward, jump to the definition
  • CTRL+t: Jump backward
  • g]: Find definitions of functions, etc. (go), will list a few, enter a number to choose
  • ;tn: Forward traversal of tags with the same name
  • ;tp: Reverse traversal of tags with the same name

The following are the shortcut keys set for tn and tp:

" 正向遍历同名标签
nmap <Leader>tn :tnext<CR>
" 反向遍历同名标签
nmap <Leader>tp :tprevious<CR>

4.6.1 Indexer automatically updates tags

With this, there is no need to manually generate and update the tags file.

" 修改ctags生成tags文件的参数
let g:indexer_ctagsCommandLineOptions="--c++-kinds=+p+l+x+c+d+e+f+g+m+n+s+t+u+v --fields=+iaSl --extra=+q"

Note: indexer also needs its own configuration file, which is used to set the root directory path of each project. The configuration file is located ~/.indexer_files. The content can be set as:
--------------- ~/.indexer_files --------------- [foo] /data/workplace/foo/src/ [bar] /data/workplace/bar/src/
Only when the directory is added will the updated tags file be automatically generated (the estimate in the buffer is, no Landed into documents).

Note: The full path must be used, never use it ~/test/, use it/home/username/test/

4.6.2 tagbar

" tagbar                                              标签窗口
" 设置 tagbar 子窗口的位置出现在主编辑区的左边
let tagbar_left=1
" 设置显示/隐藏标签列表子窗口的快捷键。速记:tag bar
nnoremap <Leader>tb :TagbarToggle<CR>
" 设置标签子窗口的宽度
let tagbar_width=16
" tagbar 子窗口中不显示冗余帮助信息 
let g:tagbar_compact=1
" 自动设置焦点在tagbar
let g:tagbar_autofocus = 1 
" 设置自动打开tagbar
" autocmd BufReadPost *.cpp,*.c,*.h,*.hpp,*.cc,*.cxx call tagbar#autoopen()                          

za, zr, zm are the same as the previous folding and unfolding, the shortcut keys are as follows, refer to: http://aiezu.com/article/linux_vim_golang_tagbar_nerdtree.html

Common commands

  • Enter: Go to the label definition, and the cursor jumps to the label definition;
  • p: Go to the tag definition, but the cursor stays in the Tagbar window;
  • P: Display the label in the preview window;
  • : Skip to the next superior label;
  • : Jump to the previous upper label;
  • : Display label definition;

4.6.3 signature bookmark collection

" vim-signature                                   收藏书签
let g:SignatureMap = {
        \ 'Leader'             :  "m",
        \ 'PlaceNextMark'      :  "m,",
        \ 'ToggleMarkAtLine'   :  "m.",
        \ 'PurgeMarksAtLine'   :  "m-",
        \ 'DeleteMark'         :  "dm",
        \ 'PurgeMarks'         :  "mda",
        \ 'PurgeMarkers'       :  "m<BS>",
        \ 'GotoNextLineAlpha'  :  "']",
        \ 'GotoPrevLineAlpha'  :  "'[",
        \ 'GotoNextSpotAlpha'  :  "`]",
        \ 'GotoPrevSpotAlpha'  :  "`[",
        \ 'GotoNextLineByPos'  :  "]'",
        \ 'GotoPrevLineByPos'  :  "['",
        \ 'GotoNextSpotByPos'  :  "mn",
        \ 'GotoPrevSpotByPos'  :  "mp",
        \ 'GotoNextMarker'     :  "[+",
        \ 'GotoPrevMarker'     :  "[-",
        \ 'GotoNextMarkerAny'  :  "]=",
        \ 'GotoPrevMarkerAny'  :  "[=",
        \ 'ListLocalMarks'     :  "ms",
        \ 'ListLocalMarkers'   :  "m?"
        \ }

Common commands:

  • mx: set/cancel the label named x in the current line
  • m,: automatically set the next available book signature
  • mn: jump to the next bookmark
  • mp: jump to the previous bookmark
  • mda: delete all bookmarks, marks del all
Note: Since leaderf will use that directory as the current default directory after searching in a directory, it is difficult to switch back once it is searched in other directories. The improvement is: here %:his the directory path of the current file
" 在当前目录查找
nnoremap <leader>fl :LeaderfFile %:h<cr>
" 在当前用户目录查找
nnoremap <leader>fu :LeaderfFile ~<cr>
" 自定义查找位置, 可以输入../之类的
nnoremap <leader>fc :LeaderfFile 

" don't show the help in normal mode
let g:Lf_HideHelp = 1
let g:Lf_UseCache = 0
let g:Lf_UseVersionControlTool = 0
let g:Lf_IgnoreCurrentBufferName = 1
" popup mode
let g:Lf_WindowPosition = 'popup'
let g:Lf_PreviewInPopup = 1
let g:Lf_StlSeparator = { 'left': "\ue0b0", 'right': "\ue0b2", 'font': "DejaVu Sans Mono for Powerline" }
let g:Lf_PreviewResult = {'Function': 0, 'BufTag': 0 }

let g:Lf_CommandMap = {'<C-K>': ['<Up>'], '<C-J>': ['<Down>']}
" 排除文件
let g:Lf_WildIgnore = {
            \ 'dir': ['.svn','.git'],
            \ 'file': ['*.bak','*.a','*.o','*.so']
            \}
  • ;f: Find files
  • ;b: Find buffer

4.7 Pair symbol correlation

Plugin 'gcmt/wildfire.vim'
Plugin 'tpope/vim-surround'

4.7.1 Wildfire.vim pair symbol content selection

"Shortcut key
map (wildfire-fuel)
vmap (wildfire-water)
" is applicable to which
pairing symbols let g:wildfire_objects = ["i'",'i"', "i)", "i]", "i} ”, “ip”, ​​“it”]

I only need to press the space (in normal mode) to automatically select the text in the nearest layer of pairing in the area where the cursor is located. If there is no pairing, then the nearest paragraph will be selected.

use:

  • <space>: In normal mode (because it is nmap) space, select the first layer, press a few times to select the previous layer
  • ;<space>: Uncheck (the original blog is), but it is estimated that the shortcut key of shift+space is occupied

4.7.2 vim-surround selected content to add pairing

vmap " S"
vmap ' S'
vmap ` S`
vmap [ S[
vmap ( S(
vmap { S{
vmap } S}
vmap ] S]
vmap ) S)
vmap > S>

Select the content and press the pairing symbol you want.

4.8 Other

Plugin 'derekwyatt / vim-fswitch'
Plugin 'scrooloose / nerdtree'

4.8.1 vim-fswitch switch between h and cpp

" *.cpp 和 *.h 间切换
nmap <silent> <Leader>sw :FSHere<cr>

In the initial state, the interface file MyClass.h is opened first, and after typing ;sw, vim opens the implementation file MyClass.cpp in the new buffer and displays it in the current window; after typing ;sw again, the current window switches back to the interface file.

4.8.2 Viewing the nerdtree project documentation

Because the function and display of LeaderF are more convenient and better, nerdtree is no longer used, and LeaderF is used instead.One of the major disadvantages of nerdtree is that it occupies the buffer, which brings trouble to buffer switching.
Plugin 'scrooloose/nerdtree'
" 使用 NERDTree 插件查看工程文件。设置快捷键,速记:file list
nmap <Leader>fl :NERDTreeToggle<CR>
" 以下是新加的,在nerdtree github说明中找到的,设置成vim启动自动打开列表
autocmd vimenter * NERDTree

Commonly used commands: After
typing fl, the right sub-window is the project file list, other uses are as follows:

  • Enter: open the selected file
  • r: refresh the project directory file list
  • I (uppercase): show/hide hidden files
  • m: A list of create/delete/cut/copy operations appears

5. Use

5.1 Shortcut keys and settings

5.1.1 Cursor movement

  • w : Move forward to the first character of the adjacent word
  • b : Move backward to the first character of the adjacent word
  • e : Move forward to the end character of the adjacent word
  • ge : Move backward to the end character of the adjacent word
  • fa : Move forward to the first character a
  • Fa : Move backward to the first character a
  • 8w : Move forward to the first character of eight words apart.
  • 4Fa : Move backward to the fourth a character
  • 0 : End of line
  • $ : Start of line
  • gg : Jump to the file header
  • Shift+g : Jump to the end of the file

5.1.2 Edit operation

  • u : Undo the operation of the previous step
  • Ctrl+r : Resume the operation that was undone in the previous step
  • CTRL+s : Locked
  • Ctrl+Q : To unlock

5.1.3 Window movement

Just press CTRL+w, the above tagbar and search window will switch each other.

  • ;wh : Switch windows to the left
  • ;wj : Switch window down
  • ;wk : Switch window up
  • ;wl : Switch window to the right

5.2 Folding code

" 基于缩进或语法进行代码折叠
"set foldmethod=indent
set foldmethod=syntax
" 启动 vim 时关闭折叠代码
set nofoldenable

Operation: za, open or close the current fold; zm, close all folds; zr, open all folds.

5.3 Highlight synonymous nouns

  • gd : Highlight all the same words
  • shift + "*" : Find the same word down and highlight it
  • shift + "#" : Find the same word up and highlight it
  • :noh : Output in command line mode: "noh" command cancels highlighting
" 取消高亮单词
nnoremap <leader>no :noh<CR>

5.4 Replace

  1. You can also specify the range of lines. For example, replace my with your in the third to fifth lines, and the flag is whether to confirm.
:3,5s/my/your/[flags]
  1. To replace the selected content,
    first enter the visual mode to select, then enter :, and then the system defaults to it :'<,'>, so we only need to enter again:
s/my/your/[flags]
  1. If all the files within the project to be replaced, first :args **/.cpp **/.htold vim range, then perform the replacement.

5.5 Environmental protection

Please make sure your vim supports these two features:

vim --version | grep mksession
vim --version | grep viminfo

" 设置环境保存项
set sessionoptions="blank,buffers,globals,localoptions,tabpages,sesdir,folds,help,options,resize,winpos,winsize"
" 保存 undo 历史
set undodir=~/.undo_history/
set undofile
" 保存快捷键
map <leader>ss :mksession! my.vim<cr> :wviminfo! my.viminfo<cr>
" 恢复快捷键
map <leader>rs :source my.vim<cr> :rviminfo my.viminfo<cr>

use:

  • ;ss: protect environment
  • ;rs: Restore environment

5.6 Compile and execute

  1. txt editor not much to say
  2. makefile: inside vim, shell commands can be executed through the! prefix, :!cmake CMakeLists.txt
  3. Set the shortcut key ;m,, namely make

Delete the main program and recompile.

nmap <Leader>make :!rm -rf main<CR>:wa<CR>:make<CR><CR>:cw<CR>

The content of the CMakeLists.txt file, and the compilation options are detailed at: https://www.jianshu.com/p/cbd1f2e52542

PROJECT(main) 
SET(SRC_LIST server.cpp) 
SET(CMAKE_CXX_COMPILER "clang++") 
SET(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libc++ -Werror -Weverything -Wno-deprecated-declarations -Wno-disabled-macro-expansion -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -Wno-old-style-cast -Wno-unreachable-code")
SET(CMAKE_EXE_LINKER_FLAGS "-lc++ -lc++abi") 
SET(CMAKE_BUILD_TYPE Debug) 
ADD_EXECUTABLE(server ${SRC_LIST})

5.7 Window size modification

  • If it is horizontal separation, you can use: nwinc +/- to increase or decrease the height of the currently active window by n characters, for example: 10winc +
  • If it is a vertical separation, you can use: nwinc >/< to increase or decrease the width of the currently active window by n characters, for example: 5winc>

5.8 Pure text copy

Taken from the link: https://blog.csdn.net/Liu_jalon/article/details/88657513

We often encounter the problem of malformed formatting when copying and pasting code in the linux vim editor, which will affect the efficiency of our work. Here is a way to solve this problem:
run the following command to enter paste mode: :set paste
enter paste After the mode, press the i key to enter the insert mode, and then paste, the text format will not be confused. But the paste also need to press to enter normal mode and execute the following command to end the paste mode: :set nopaste.

" 设置纯文本复制粘贴
map <F9> :set paste<CR>i
map <F10> :set nopaste<CR>

5.9 System Clipboard

Add the following to vimrc:

" 设置快捷键将选中文本块复制至系统剪贴板
vnoremap <Leader>y "+y
" 设置快捷键将系统剪贴板内容粘贴至 vim
nmap <Leader>p "+p

The following is an excerpt from: https://blog.csdn.net/u014104588/article/details/81071479 The
cause of the problem is that the owner of ~/.viminfo is root, so execute the following command to change the owner of ~/.viminfo to the current user .

# 把username改为自己的用户名
sudo chown username ~/.viminfo 

5.10 man support

Installation The
following is taken directly from the blog:

To use this function, the corresponding man must be installed in the system. Install Linux system function man, first download (https://www.kernel.org/doc/man-pages/download.html), unzip, copy man1/ to man8/ to /usr/share/man/, run man Fork confirm whether the installation is successful. Install the C++ standard library man, first download (ftp://GCC.gnu.org/pub/GCC/libstdc++/doxygen/ ), select the latest libstdc+±api-XXXman.tar.bz2, unzip and copy man3/ to /usr /share/man/, run man std::vector to confirm whether the installation is successful.

https://www.cnblogs.com/lymboy/p/8143569.html, I found the IP directly, so as not to resolve it, http://216.165.129.141/pub/sourceware.org/libstdc++/doxygen/

use

  • :Man fork: Manual input
  • ;man: The word under the cursor will be passed to the :Man command, no need to type it manually.