Write C + + server by hand: always drop God VIM (source code installation, plug-in management, color theme, code highlighting, shortcut key setting, search and replacement, environmental protection)

Posted by Pests on Wed, 02 Feb 2022 06:44:44 +0100

If a worker wants to do well, he must first sharpen his tools. vim, as a sharp tool for development, is an essential weapon for server-side programming. This blog post was originally published in: https://github.com/whuwzp/vim_config , start the vim journey.

vim learning

  1. Introduction: source code compilation uses vim and its plug-ins
  2. The content includes the compilation and installation of vim, the compilation and installation of llvm clang, the compilation and installation of plug-in youcompleteme, and the use of other plug-ins of vim
  3. Setting up environment: ubuntu18 04.4 Server Version (desktop version should also apply)
  4. Environment restore method:
    • Save on nut cloud: The compressed package of vim files to avoid having to download when changing the environment in the future. When using it, unzip it directly to ~ / vim
    • Save on GitHub: vimrc, .clang-format, .ycm_extra_conf.py and other configuration files, address: https://github.com/whuwzp/vim_config
  5. The main reference websites are as follows, basically referring to the official methods, rather than picking up people's wisdom on the blog website:
    • vim source code compilation: https://github.com/ycm-core/YouCompleteMe/wiki/Building-Vim-from-source
    • llvm clang compilation: https://llvhttps://m.org/docs/GettingStarted.html#getting-started-with-llvm
    • youcompleteme is compiled using: https://github.com/ycm-core/YouCompleteMe#linux-64-bit
    • Other c + + plug-ins: https://github.com/yangyangwithgnu/use_vim_as_ide .
  6. 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. Compilation and installation of vim source code

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

  1. 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
    
  2. Download and compile the latest version of vim

    git clone git@github.com: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
    
  3. testing

    vim --version
    # As of 20200301, the latest version of this method is 8.2
    

be careful:

  1. Only one installation can be selected for python2 and python3: there is a problem that some blogs enable python2 and python3 at the same time in the configure step (refer to the website for installation). Python3 is selected here. Later, python3 needs to be used in youcompleteme, and python3 is a trend, so python3 is selected here (if you want to select python2, just change python3 above to python)
  2. with-python3-config-dir: the view method of this is: command line python --version, mine is 3.6, so it is in / usr / lib / python3 6 / similar config-3.6m-x86_ In short, a folder named 64 Linux GNU is to ensure that the python 3 version and path are consistent and correct

2. Compile and install llvm clang

Reference website: https://llvhttps://m.org/docs/GettingStarted.html#getting-started-with-llvm

  1. Installation Preparation Environment

    # The compilation of clang requires gcc and so on
    sudo apt install gcc
    sudo apt install g++
    sudo apt install make
    sudo apt install cmake 
    
  2. 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
    
  3. test

    clang --version
    # As of 20200301, the latest version is 11.0
    

be careful:

  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 website selection, and generally choose clang; libcxx; libcxxabi; compiler-rt; Clang tools extra, I'm afraid I'll have trouble installing it later, so I chose lldb (debugging) and LLD (link optimization)

3. Compile and install youcompleteme

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

  1. Install plug-in manager vundle
    git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
    # At ~ / vimrc adds relevant configuration information
    
    " vundle Environment settings
    filetype off
    set rtp+=~/.vim/bundle/Vundle.vim
    " vundle The list of managed plug-ins must be in vundle#begin() and vundle#Between end()
    call vundle#begin()
    Plugin 'VundleVim/Vundle.vim'
    Plugin 'ycm-core/YouCompleteMe'
    
    " End of plug-in list
    call vundle#end()
    filetype plugin indent on
    
  2. Open vim, enter pluginstall, and download YouCompleteMe
  3. install
    # Dependency
    sudo apt install build-essential cmake python3-dev
    cd ~/.vim/bundle/YouCompleteMe
    # If you want to choose other language support, you can choose it. It is available in the reference website
    python install.py --clang-completer
    
  4. Edit the file and create a new one in the project directory ycm_extra_conf.py, we only need to change the directory of the header file in flags. The contents are as follows (refer to https://github.com/yangyangwithgnu/use_vim_as_ide):
    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 https://github.com/whuwzp/vim_config Saved in

be careful:

  1. .ycm_ extra_ Adding method of header file in conf.py: I installed clang with the default path / usr/local, so I added '- issystem', '/ usr/local / include / C + + / V1 /'
    • '- issystem', '/ usr / include /': This is the system header file
    • '- issystem', '/ usr /': This is also the of the system
    • '-isystem','/usr/include/x86_ 64 linux GNU / ': This is linux
  2. If you find that a function cannot be completed or an error is reported, you can find a solution
    First look at the header file to which the function belongs, then go to / usr/include in Baidu or directly, and then add it to ycm_extra_conf.py, for example sys / socket H is not automatically completed. Baidu found it in / usr/include / x86_ 64 Linux GNU /, and then add '- issystem', '/ usr/include / x86_ 64 Linux GNU / '
  3. It is strongly recommended not to copy header files to / usr/include
    This diagram is convenient for a while, but it is all confused. It is best to use the method in the previous step, which is also convenient for you to understand the location of each header file
  4. Solution of ycm server shutdown
    Need to enter ~ / install in vim/bundle/youcompleteme directory, as follows:
    # If this step is not performed, an error will be reported in the next step
    git submodule update --init --recursive
    # Then install
    sudo ./install.sh --clang-completer
    # If regex or cregex is missing in the error report in the previous step, that is, git submodule update --init --recursive has not been completely downloaded, then go to the directory to find it. For example, my regex is. I find thrid/ycmd/third/regex under the GitHub of youcompleteme, and then find the address of the sub project https://github.com/ycm-core/regex.git Then, you can download git clone and manually copy it to that directory, such as git clone https://github.com/ycm-core/regex.git
    
  5. Cannot complete a custom class in another file
    YCM only triggers semantic completion in the following two scenarios: first, the file where the completion identifier is located must be in the buffer (that is, the file has been opened); First, type. After the object After the pointer, type - >, and after the namespace, type::.
    So you have to open that file
  6. If there is no boost
    Then download and install boost yourself
    The following references: https://www.cnblogs.com/smallredness/p/9245127.html
    Unzip to a directory
    tar -zxvf boost_1_66_0.tar.gz
    1,Normal compilation:
    get into boost_1_66_0 In the directory
    cd boost_1_66_0
    ./bootstrap.sh --with-libraries=all --with-toolset=gcc
    --with-liraries: Libraries to compile
    --with-toolset: Compiler used at compile time
     install boost library
    ./b2 install --prefix=/usr
    
  7. For compilation warnings, see: https://blog.csdn.net/qq_17308321/article/details/79979514

4. Plug in

Mainly related to c + +. ~ / vimrc files are on GitHub: https://github.com/whuwzp/vim_config
Refer to the following: https://github.com/yangyangwithgnu/use_vim_as_ide

4.1 vundle plug-in manager

git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
  1. Yes vimrc adds relevant configuration information

    " vundle Environment settings
    filetype off
    set rtp+=~/.vim/bundle/Vundle.vim
    " vundle The list of managed plug-ins must be in vundle#begin() and vundle#Between end()
    call vundle#begin()
    Plugin 'VundleVim/Vundle.vim'
    Plugin 'dyng/ctrlsf.vim'
    
    " End of plug-in list
    call vundle#end()
    filetype plugin indent on
    
    

    Among them, each plugin 'dyng / Ctrl SF VIM 'corresponds to a plug-in (which is similar to the mechanism of go language to manage different code bases). If there are new plug-ins in the future, just add them to the list.

  2. Install plug-ins:
    First find it in GitHub COM, and then add the configuration information to it Between call vunder #begin() and call vunder #end() in vimrc, such as plugin 'dyng / Ctrl SF vim ', and finally enter vim to execute: pluginstall

  3. Delete plug-in
    To uninstall the plug-in, first Comment or delete the corresponding plug-in configuration information in vimrc, and then execute:: PluginClean in vim to delete the corresponding plug-in.

  4. Update plug-in
    The update frequency is high. Almost every other month, you should see which plug-ins have launched new versions and update them in batches. Just execute PluginUpdate.

4.2 complementary plug-ins

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

4.2.1 semantic completion of youcompleteme

See above for installation The following is the configuration:

" Youcompleteme                                    Semantic completion
" menu
highlight Pmenu ctermfg=2 ctermbg=3 guifg=#005f87 guibg=#EEE8D5
" Selected item
highlight PmenuSel ctermfg=2 ctermbg=3 guifg=#AFD700 guibg=#106900
" The completion function is also effective in comments
let g:ycm_complete_in_comments=1
" allow vim load .ycm_extra_conf.py File, no more prompts
let g:ycm_confirm_extra_conf=0
" open YCM Tag completion engine
let g:ycm_collect_identifiers_from_tags_files=1
" introduce C++ Standard library tags
" set tags+=/usr/include/c++/7/stdcpp.tags, I only use clang Just the right one
set tags+=/usr/local/include/c++/v1/clang.tags
" set tags+=/usr/include/sys.tags,This is too big
" YCM integrate OmniCppComplete Complete the engine and set its shortcut keys
inoremap <leader>; <C-x><C-o>
" The completed content does not appear in the form of split sub window, only the completed list is displayed
set completeopt-=preview
" List matches from the first character you type
let g:ycm_min_num_of_chars_for_completion=1
" Prohibit caching matches and regenerate matches every time
let g:ycm_cache_omnifunc=0
" Syntax keyword completion           
let g:ycm_seed_identifiers_with_syntax=1
let OmniCpp_DefaultNamespaces = ["_GLIBCXX_STD"]
" Set the shortcut key used to close the completion list. The default is ctrl+y, Change to;'
let g:ycm_key_list_stop_completion = ["<leader>'"]

4.2.2 completion of vim protodef interface

to configure

Declare in h, and then use the plug-in in cpp to help us generate the shell of the implementation function

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

" set up pullproto.pl Script path
" This is the original blog,But my path is vim-protodef,So I changed it
" let g:protodefprotogetter='~/.vim/bundle/protodef/pullproto.pl'
let g:protodefprotogetter='~/.vim/bundle/vim-protodef/pullproto.pl'
" The implementation order of member functions is consistent with the declaration order
let g:disable_protodef_sorting=1

Use example:

  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_;
    };
    
  2. Create a new cpp file with the same name
    With the shortcut key p, our setting is; P can generate the following contents:
    int MyClass::getSize(void) const
    {
        return 0;
    }
    
    void MyClass::youprint(int)
    {
    }
    
    MyClass::~MyClass()
    {
    }
    
  • Advantage 1: virtual, default parameters and other keywords that should appear in the function declaration rather than in the function definition. protodef has filtered for you;
  • Advantage 2: pure virtual functions such as doNothing() should not be implemented and should be automatically ignored by protodef

use
Define a class in h, and then create a cpp with the same name. Use the shortcut key < leader > pp. my is; PP generates the corresponding cpp content

4.2.3 completion of ultisnips template

to 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, reset it
let g:UltiSnipsExpandTrigger=""
let g:UltiSnipsJumpForwardTrigger=""
let g:UltiSnipsJumpBackwardTrigger=""

Note: edit ~ / mysnippets/cpp.snippets can modify the template to this position, which is equivalent to the separation of program and configuration. In this way, it can be easily pushed to GitHub for storage, and can be used directly in another environment

use
According to the blog settings, press< Tab > is OK. Press it again to jump to the next position, such as if(1){2}
According to the settings of this blog, 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 (use case for to combine multiple scenarios, try it)
  • : try catch
  • set map lst vec: just try it. The corresponding container
  • cl: class
  • b: ()
  • st: []
  • br: {}
  • q: ""
  • se: ''
  • Ar: - >, this is arrow

The rest of the feeling is not effective, so I don't remember it here

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

4.3 theme color

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

4.3.1 VIM airline and VIM airline themes

to configure

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

4.3.2 molokai

to configure

set background=dark
set t_Co=256
colorscheme molokai

4.4 code highlight annotation 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 Syntax highlighting 
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:
"Enable file type detection filetype on" loads the corresponding plug-in filetype plugin on according to the detected different types

4.4.2 VIM indent guides indent

" vim-indent-guides                                   Indent display                                                         
let g:indent_guides_enable_on_vim_startup=1
" Visual indentation from the second level
let g:indent_guides_start_level=2
" Color block width
let g:indent_guides_guide_size=1
" Shortcut key i open/Turn off indent visualization
nmap <silent> <Leader>i <Plug>IndentGuidesToggle

4.4.3 clang format formatting

"clang-format                                          Code style formatting
" map to <Leader>cf in C++ code
" Can be in~/.clang-format Edit more detailed settings in
set ts=4
" sign out insert Auto format in mode, If you add this, then ultisnip The plug-in will be affected,Because the template will be completed by insert Become select,This will trigger at the same time clang-format and 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>

be careful:

  1. Clang format needs to be installed
    apt install clang-format
    
  2. You can create a new ~ / For the specific configuration format of clang format, the reference file is saved in: https://github.com/whuwzp/vim_config

4.4.4 nerdcommenter code comments

" default<leader>cc, <leader>cu

4.5 content search and replacement

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                          Select multiple selections
" Default is ctrl+N,It is not modified here
" let g:multi_cursor_next_key='<S-n>'
" let g:multi_cursor_skip_key='<S-k>'

I want to change the collective name of prtHelpInfo() to showHelpInfo(), first find all prtHelpInfo in the project through Ctrl SF, then directly select the first ptr in the sub window of Ctrl SF, and then select the second ptr through VIM multiple cursors (press CTRL+n in the sub window to select the next one), then ESC and insert to enter the editing mode, then delete ptr and type show uniformly, Finally, save and reload the replaced file (: wq, Y, L).

4.5.2 ctrlsf.vim lookup

" ctrlsf.vim                                      search               
" The plug-in finds the keyword where the cursor is located globally in the project and sets shortcut keys. Shortcut shorthand: search in project
noremap <Leader>sp :CtrlSF<CR>

Note: the grep ack tool needs to be installed
sudo apt install grep-ack

4.6 ctags tag bookmark related

" ctags Tag bookmark related
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. install
    sudo apt install ctags
    
  2. 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 and enter in vim command mode:
    :set tags+=/data/workplace/example/tags
    
  3. use
    First add the above sentence to the vim command mode
    • CTRL +]: jump forward to the definition
    • CTRL+t: jump back
    • g] Select the definition (go) of search function, etc., list several, and enter numbers:
    • ; tn: forward traversal of labels with the same name
    • ; tp: reverse traversal of tags with the same name

The following are shortcut keys for tn and tp:

" Forward traversal of labels with the same name
nmap <Leader>tn :tnext<CR>
" Reverse traversal of labels with the same name
nmap <Leader>tp :tprevious<CR>

4.6.1 indexer automatically updates labels

With this, you don't have to manually generate and update tags files

" modify ctags generate tags File parameters
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: the indexer also needs its own configuration file to set the root directory path of each project. The configuration file is located in ~ / indexer_files, the content can be set as:
--------------- ~/.indexer_files --------------- [foo] /data/workplace/foo/src/ [bar] /data/workplace/bar/src/
The update tags file will be generated automatically only when the directory is added (it is estimated in the buffer that it is not implemented as a file)

Note: the full path must be used. Never use ~ / test /, but / home/username/test/

4.6.2 tagbar tab

" tagbar                                              Label window
" set up tagbar The position of the sub window appears on the left of the main editing area
let tagbar_left=1
" Set display/Hide shortcut keys for label list sub windows. Shorthand: tag bar
nnoremap <Leader>tb :TagbarToggle<CR>
" Sets the width of the label sub window
let tagbar_width=16
" tagbar Redundancy help information is not displayed in the sub window 
let g:tagbar_compact=1
" Auto focus tagbar
let g:tagbar_autofocus = 1 
" Set auto on tagbar
" autocmd BufReadPost *.cpp,*.c,*.h,*.hpp,*.cc,*.cxx call tagbar#autoopen()                          

ZA, Zr and ZM are the same as the previous folding and expansion. 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 labels in the preview window;
  • : skip to the next parent tag;
  • : skip to the previous parent tag;
  • : display label definition;

4.6.3 signature bookmark collection

" vim-signature                                   Bookmark collection
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 of the current row named x
  • m. : automatically set the next available Book signature
  • mn: jump to the next bookmark
  • mp: jump to previous bookmark
  • mda: delete all bookmarks, marks del all

4.6.4 LeaderF document and buffer search

Note: since the leader will take that directory as the current default directory after searching a directory, it is difficult to switch back once searching in other directories. The improvement is that%: h here represents the directory path of the current file

" Find in current directory
nnoremap <leader>fl :LeaderfFile %:h<cr>
" Find in current user directory
nnoremap <leader>fu :LeaderfFile ~<cr>
" Custom find location, Can enter../Something like that
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>']}
" Exclude files
let g:Lf_WildIgnore = {
            \ 'dir': ['.svn','.git'],
            \ 'file': ['*.bak','*.a','*.o','*.so']
            \}
  • ; f: Find file
  • ; b: Find buffer

4.7 pairing

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

4.7.1 wildfire.vim pairing content selected

Shortcut key
map (wildfire-fuel)
vmap (wildfire-water)
"For which pairs
let g:wildfire_objects = ["i'", 'i"', "i)", "i]", "i}", "ip", "it"]

I just need to press the space (in normal mode) to automatically select the text in the nearest layer of the pairing character in the cursor area. If there is no pairing character, I will select the nearest paragraph.

use:

  • < space >: in normal mode (because it is nmap), select the first layer and press several times to select the upper layer
  • ;< Space >: uncheck (the original blog is), but it is estimated that the shortcut key shift+space is occupied

4.7.2 VIM surround the selected content plus a pair

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

Select the content, and then press the desired pairing character

4.8 others

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

4.8.1 VIM fswitch switching between h and cpp

" *.cpp and *.h Inter switching
nmap <silent> <Leader>sw :FSHere<cr>

In the initial state, open the interface file MyClass h. Type; After sw, vim opens the implementation file MyClass. In the new buffer CPP and display it in the current window; Type again; sw, the current window switches back to the interface file.

4.8.2 viewing nerdtree project documents

LeaderF is convenient in function and presentation. Instead of using nerdtree, LeaderF is used. One major disadvantage of nerdtree is that it occupies the buffer and brings trouble to buffer switching

Plugin 'scrooloose/nerdtree'
" use NERDTree Plug in to view project files. Set shortcut keys, shorthand: file list
nmap <Leader>fl :NERDTreeToggle<CR>
" The following is a new addition,stay nerdtree github Found in description,Set as vim Start auto open list
autocmd vimenter * NERDTree

Common commands:
After typing fl, the sub window on the right is the list of project files. Other uses are as follows:

  • Enter: opens the selected file
  • r: Refresh project directory file list
  • I (uppercase): Show / hide 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 adjacent words
  • b: move backward to the first character of adjacent words
  • e: move forward to the last character of adjacent words
  • ge: move backward to the last character of adjacent words
  • fa: move forward to the first character a
  • Fa: move backward to the first character a
  • 8w: move forward to the first character separated by eight words
  • 4Fa: move backward to the fourth a character
  • 0: end of line
  • $: beginning of line
  • gg: jump to file header
  • Shift+g: jump to the end of the file

5.1.2 editing

  • u: undo the previous step
  • Ctrl+r: restores the operation that was undone in the previous step
  • CTRL+s: locked
  • Ctrl+Q: to unlock

5.1.3 window movement

CTRL+w to switch between the tagbar and the search window

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

5.2 folding code

" Code folding based on indentation or syntax
"set foldmethod=indent
set foldmethod=syntax
" start-up vim Close fold code when
set nofoldenable

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

5.3 highlight homonyms

  • gd: highlight all the same words
  • shift + "*": look down for the same word and highlight it
  • shift + "#": look up the same word and highlight it
  • : noh: output in command line mode: the "noh" command removes highlighting
" Unhighlight words
nnoremap <leader>no :noh<CR>

5.4 replacement

  1. You can also specify the line range. For example, replace my in the third line to the fifth line with your, and flag is confirm or not
    :3,5s/my/your/[flags]
    
  2. Replace selected content
    First enter the visual mode, select it, and then enter:, and then the system defaults to: '<,' >, so we only need to enter:
    s/my/your/[flags]
    
  3. If all files in the project are replaced, first: args * * / cpp **/. H inform vim of the scope and then perform the replacement

5.5 environmental protection

Make sure your vim supports these two features:

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

" Set environment save item
set sessionoptions="blank,buffers,globals,localoptions,tabpages,sesdir,folds,help,options,resize,winpos,winsize"
" preservation undo history
set undodir=~/.undo_history/
set undofile
" Save shortcut
map <leader>ss :mksession! my.vim<cr> :wviminfo! my.viminfo<cr>
" Restore shortcut
map <leader>rs :source my.vim<cr> :rviminfo my.viminfo<cr>

use:

  • ; ss: protect the environment
  • ; rs: restore environment

5.6 compilation execution

  1. txt editor doesn't say much
  2. makefile: vim internal pass! Prefix can execute shell commands,:! cmake CMakeLists.txt
  3. Set shortcut keys; m. make

Delete the main program and recompile

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

CMakeLists.txt file. See the following for compilation options: 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

  • For horizontal separation, you can use: nwinc + / - to increase and decrease the height of the current active window by n characters, such as 10winc+
  • For vertical separation, you can use: nwinc > / < increase and decrease the width of the current active window by n characters, such as: 5winc >

5.8 reproduction of pure text

From link: https://blog.csdn.net/Liu_jalon/article/details/88657513

We often encounter the problem of disordered format when copying and pasting code in linux vim editor, which will affect our work efficiency. Here is a solution to this problem:
Run the following command to enter the paste mode: set paste
After entering the paste mode, press the i key to enter the insertion mode, and then paste. The text format will not be disordered. After entering the paste mode, you need to press the paste: normal command to enter the paste mode.

" Set plain text copy and paste
map <F9> :set paste<CR>i
map <F10> :set nopaste<CR>

5.9 system shear plate

Add the following to vimrc:

" Set the shortcut key to copy the selected text block to the system clipboard
vnoremap <Leader>y "+y
" Set shortcut keys to paste the contents of the system clipboard into vim
nmap <Leader>p "+p

The following is taken from: https://blog.csdn.net/u014104588/article/details/81071479
The causes of the problems are ~ / viminfo is owned by root, so executing the following command will ~ / viminfo owner changed to current user.

# Change username to your own username
sudo chown username ~/.viminfo 

5.10 man support

  1. install
    The following is taken directly from the blog:

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

    https://www.cnblogs.com/lymboy/p/8143569.html , the IP is directly found in the to avoid being unable to resolve, http://216.165.129.141/pub/sourceware.org/libstdc++/doxygen/

  2. use

    • : Man fork: manual input
    • ; Man: the word where the cursor is located will be passed to the: man command. You don't have to type it manually

Topics: Linux