VIM Note ======== ###### tags: `linux-usage` - Document: https://vimhelp.org/usr_toc.txt.html - Basic configuration: http://wiki.csie.ncku.edu.tw/vim/vimrc - Advance turoial: - [vi/vim使用进阶: 目录](https://blog.easwy.com/archives/advanced-vim-skills-catalog/) - [Learn Vimscript the Hard Way](https://github.com/ivito/cookbook/blob/master/VIM/Learn%20Vimscript%20the%20Hard%20Way.pdf) - [Vim 8 下 C/C++ 开发环境搭建](http://www.skywind.me/blog/archives/2084) - [Vim 8 中 C/C++ 符号索引:GTags 篇](https://zhuanlan.zhihu.com/p/36279445) - [自动索引gutentags, linting: ALE](https://www.zhihu.com/question/47691414/answer/373700711) - References - https://vimawesome.com/ - AWESOME VIM PLUGINS from ACROSS THE UNIVERSE - Split/Tab: https://archer1609wp.wordpress.com/2017/07/17/vim-split-tab/ - Tab - `:tabe` -> create tab - `:gt` -> next tab, `{n}gt` -> go to tab {n} - Split - Ctrl-W followed by (capital) H, J, K or L to move current split to leftmost/bottom/top/rightmost - Adjust split window size: https://vim.fandom.com/wiki/Resize_splits_more_quickly - `{n} Ctrl-w +`, `{n} Ctrl-w -`, increase/decrease by n rows - `{n} Ctrl-w <`, `{n} Ctrl-w >`, increase/decrease by n cols - `Ctrl-w =` -> set all equal - `Ctrl-w _` -> maximize height - `Ctrl-w |` -> maximize width - Plugin management - vim-plug: https://github.com/junegunn/vim-plug (recommanded) - vundle: https://github.com/VundleVim/Vundle.vim - Plugins - LeaderF: https://github.com/Yggdroot/LeaderF - An efficient fuzzy finder that helps to locate files, buffers, mrus, gtags, etc. on the fly. - YouCompleteMe: [YCM Note](/WbikYsD1TQiQUYr_FuOwAw) - auto completion - vim-cpp-enhanced-highlight: https://github.com/octol/vim-cpp-enhanced-highlight - beautiful colors for c++ - nerdcommenter: https://github.com/preservim/nerdcommenter - multi-line comment/un-comment - tabulous: https://github.com/webdevel/tabulous - show tab bar and indicatore of current tab on top - tagbar: https://github.com/majutsushi/tagbar - side column for code structural navigation (class, method, members..) in current file - better to use in couple with universal-ctags to achieve best interpretation - vim-multiple-cursors: https://github.com/terryma/vim-multiple-cursors - multiple cursor editing - highlight.vim: https://www.vim.org/scripts/script.php?script_id=1599 - highlight lines or patterns of interest in different colors - vim-searchindex: https://github.com/google/vim-searchindex - show current/total number of current search pattern - bufferlist.vim: https://www.vim.org/scripts/script.php?script_id=1325 - side column to navigate opened buffers - abolish: https://github.com/tpope/vim-abolish/blob/master/doc/abolish.txt - Work with several variants of a word at once - Multiple search/replace - Pluins to try - ultisnips: code snippets manager - https://mednoter.com/UltiSnips.html - https://github.com/SirVer/ultisnips - C/Cpp tag/trace tools - universal-ctags: https://github.com/universal-ctags/ctags - up to date ctag tool - cscope: http://cscope.sourceforge.net/ - example of generate tags and cscope databases ```sh #!/bin/sh -fx SCAN_PATHS="." ctags -R --c++-kinds=+p --fields=+iaS --extra=+q $SCAN_PATHS #find find $SCAN_PATHS -type f -name "*.cpp" -o -name "*.c" -o -name "*.cc" -o -name "*.h" > cscope.files cscope -Rbq ``` - example with specified/excluded paths ```sh #!/bin/csh -fx if ( $1 == 'all') then set SCAN_PATHS = "." else set SCAN_PATHS = "xdi xdt xdump xwd" endif ctags -R --c++-kinds=+p --fields=+iaS --extra=+q $SCAN_PATHS --exclude=3rdParty --exclude=jemalloc #find find $SCAN_PATHS -type f -name "*.cpp" -o -name "*.c" -o -name "*.cc" -o -name "*.h" > cscope.files cscope -bq ``` - File explorer: - `:Explorer` or `:Ex` -> open in current window - `:Vexplorer` or `:Vex` -> open in new vertical splitted window - Reload vimrc without restart - `:source ~/.vimrc` - or `:source $MYVIMRC` - Vimrc - keymapping settings - use `:map` and `:!map` to check current mappings - noremap是不会递归的映射 - inoremap就只在插入(insert)模式下生效 - vnoremap只在visual模式下生效 - nnoremap就在normal模式下(狂按esc后的模式)生效 - to type special character - e.g. to type 'ESC' (shown as '^[' in literal): `ctrl+v` then `esc`. - Reload file - use `:e` command or `set autoread` in vimrc for auto reload - Pasting text - use `:r!cat`, then `shift+insert` to paste, `Ctrl+d` to terminate cat, avoiding auto indention [ref link](https://stackoverflow.com/a/2545242/4362197) - `:r` inserts the contents of a file into the current document. - `!cat` says, run cat which essentially opens stdin (*nix shells) - (shift + insert) paste the contents of the clipboard to the terminal - CTRL+D is end-of-file - Search highlighting - `:set hlsearch!` to toggle highlighting search results - bind to hotkey is a good try ([ref link](https://stackoverflow.com/a/3431203/4362197)) - Visual mode ([ref link](https://opensource.com/article/19/2/getting-started-vim-visual-mode)) - switch to visual mode - `v` to enter charactor mode - `V` to enter line mode - `ctrl+v` to enter block mode - `y` to copy (yank) - `p` to paste - Multiple cursor editing - vim-multiple-cursors ([link](https://github.com/terryma/vim-multiple-cursors)) - Marks: (https://vim.fandom.com/wiki/Using_marks) - Check current file path: `Ctrl-g` - Multi-line commenting (https://github.com/scrooloose/nerdcommenter) - `<leader>cc` to comment - `<leader>ci` to uncomment - about `<leader>` key: https://stackoverflow.com/questions/1764263/what-is-the-leader-in-a-vimrc-file - Highlight current word (https://vim.fandom.com/wiki/Auto_highlight_current_word_when_idle) - `z/` to toggle highlight - Replace (http://www.study-area.org/tips/vim/Vim-5.html) - `:[range]s/pattern/string/[c,e,g,i]` - range 指的是範圍,1,7 指從第一行至第七行,1,$ 指從第一行至最後一行,也就是整篇文章,也可以 % 代表 - `%s/pattern/string/[c,e,g,i]` means whole file replacement - % 是目前編輯的文章,# 是前一次編輯的文章。 - pattern 就是要被替換掉的字串,可以用 regexp 來表示。 - string 將 pattern 由 string 所取代。 - c confirm,每次替換前會詢問。 - e 不顯示 error。 - g globe,不詢問,整行替換。 - i ignore 不分大小寫。 - g 大概都是要加的,否則只會替換每一行的第一個符合字串。可以合起來用,如 cgi,表示不分大小寫,整行替換,替換前要詢問是否替換。 - regex in VIM - use `(` & `)` for literal parenthesis, for capturing group, use `\(` & `\)` - use `\r` for new line - Open tag in new tab - https://stackoverflow.com/a/6069388/4362197 - Concept of buffer, window, tab - https://blog.csdn.net/jy692405180/article/details/79775125 - `bd` to close buffer - Plugin: Ctrl-P - fast file/function search - https://wxnacy.com/2017/09/23/vim-plugin-ctrlp/ - Grep in VIM - ref: https://superuser.com/questions/248734/when-using-grep-from-vim-how-to-jump-to-results - `:grep` is a vim editor command (it's different from shell cmd grep) - `:grep -r <pattern> .` search for current path recursively - in result view, `:copen` to open a window of result list with jump functionality - Operation on all buffers - `:bufdo <cmd>` - e.g. `:bufdo e` to reload all buffers - https://vi.stackexchange.com/questions/458/how-can-i-reload-all-buffers-at-once - Un-map key bindings - `:unmap <key>` - variants in each mode: `:iunmap`, `:nunmap`, `vunmap` - Check highlight rule of current word - `:echo synIDattr(synID(line("."), col("."), 1), "name")` - https://stackoverflow.com/questions/10101631/vim-view-highlight-rules-acting-on-current-word-character - Coloring - Vim manual of coloring - `:help usr_06.txt` - Tutorial - http://alvinalexander.com/linux/vi-vim-editor-color-scheme-syntax - How to know current coloring settings - use command`:highlight` to show all highlight settings - How to force background be transparant - `hi Normal ctermbg=NONE guibg=NONE` - `hi NonText ctermbg=NONE guibg=NONE` - Color table - https://i.imgur.com/okBgrw4.pngkjj - Multiple Highlight - https://www.vim.org/scripts/script.php?script_id=1599 - others - https://stackoverflow.com/questions/704434/is-there-any-way-to-highlight-multiple-searches-in-gvim - Folding - `zf`: make fold - Could combine with motino, e.g. `zfi}`: fold content between {, } - `zm`: fold - `zr`: unfold - `:set foldColumn=N`: display fold-column with depth N - http://yyq123.blogspot.com/2011/09/vim-fold.html - https://vim.fandom.com/wiki/Folding - Adv. Navigation - https://vimhelp.org/motion.txt.html#object-motions - `'[`, `']` go to start/end of last change - example: after paste, `'[` -> `V` -> `']` will select pasted lines in visual mode - `cd` to directory of current file - `cd %:h` - where `%` is reserved variable for path of current file - where `:h` extract the "directory" part of the path - Quickfix - https://blog.easwy.com/archives/advanced-vim-skills-quickfix-mode/ - https://blog.easwy.com/archives/advanced-vim-skills-cscope/ - `:set cscopequickfix=g-,s-,c-` to let cscope search put in quickfix - ref: `:help cscopequickfix` - `:cw` open quickfix window - `:cclose`/`:ccl` close quickfix window - File/Content search plugin - LeaderF (better than CtrlP) - https://github.com/Yggdroot/LeaderF - Assign the file type (syntax highlighting) - https://stackoverflow.com/a/782421/4362197 - `:set ft=asm` to - Command line efficiently - `q:` for quick search command history - Tap `ctrl+f` while in command-line mode (just after :). There you'll get command-line window which could be edited&navigated as a regular vim window (hjkl etc.). - grep/vimgrep and quick fix 1. `vimgrep` or `grep` will auto fill into quickfix window, examples as follows - `grep foo ./src/bar.cc` searchs pattern foo in ./src/bar.cc - `grep <cword> **/*.{cc,h}` searchs pattern "foo" in all files with extension .cc or .h in current folder recursively, where - ** stands for recursively - {cc,h} is for specifying multi-pattern in OR-ed relationship 2. `:copen` to open quickfix window - references: - grep foo - https://chienweichih.github.io/vimcdoc/doc/quickfix.html#grep - https://blog.stevenocchipinti.com/2011/10/recursive-search-with-vimgrep.html/ - https://medium.com/usevim/vim-101-quickfix-and-grep-c782cb65e524 - https://vi.stackexchange.com/questions/16523/how-to-use-vimgrep-recursively-for-specific-file-extensions - Diff with vim ([reference](https://stackoverflow.com/questions/9529934/how-to-use-vimdiff-in-vim-command-mode)) - 1st way: invoke vimdiff in shell - `vimdiff file1 file2` - 2nd way: open diff view in Vim - use `diffsplit` ``` vim :e file1 :vert diffsplit file2 ``` - or perform `:diffthis` on the window to diff - List current Vim settings, mappings ``` :abbreviate - list abbreviations :args - argument list :augroup - augroups :autocmd - list auto-commands :buffers - list buffers :breaklist - list current breakpoints :cabbrev - list command mode abbreviations :changes - changes :cmap - list command mode maps :command - list commands :compiler - list compiler scripts :digraphs - digraphs :file - print filename, cursor position and status (like Ctrl-G) :filetype - on/off settings for filetype detect/plugins/indent :function - list user-defined functions (names and argument lists but not the full code) :function Foo - user-defined function Foo() (full code list) :highlight - highlight groups :history c - command history :history = - expression history :history s - search history :history - your commands :iabbrev - list insert mode abbreviations :imap - list insert mode maps :intro - the Vim splash screen, with summary version info :jumps - your movements :language - current language settings :let - all variables :let FooBar - variable FooBar :let g: - global variables :let v: - Vim variables :list - buffer lines (many similar commands) :lmap - language mappings (set by keymap or by lmap) :ls - buffers :ls! - buffers, including "unlisted" buffers :map! - Insert and Command-line mode maps (imap, cmap) :map - Normal and Visual mode maps (nmap, vmap, xmap, smap, omap) :map<buffer> - buffer local Normal and Visual mode maps :map!<buffer> - buffer local Insert and Command-line mode maps :marks - marks :menu - menu items :messages - message history :nmap - Normal-mode mappings only :omap - Operator-pending mode mappings only :print - display buffer lines (useful after :g or with a range) :reg - registers :scriptnames - all scripts sourced so far :set all - all options, including defaults :setglobal - global option values :setlocal - local option values :set - options with non-default value :set termcap - list terminal codes and terminal keys :smap - Select-mode mappings only :spellinfo - spellfiles used :syntax - syntax items :syn sync - current syntax sync mode :tabs - tab pages :tags - tag stack contents :undolist - leaves of the undo tree :verbose - show info about where a map or autocmd or function is defined :version - list version and build options :vmap - Visual and Select mode mappings only :winpos - Vim window position (gui) :xmap - visual mode maps only ``` - regexp search/replace - `\_.` for any characther including newline - `\{-}` for non-greedy search - e.g. `s/{\_.\{-}}//g`: replaces any closure of curly braces as empty - e.g. replace all comment in code to first letter capitalized ([reference](https://vim.fandom.com/wiki/Changing_case_with_regular_expressions)) - `:%s/\/\/\( \?[a-z]\)/\/\/\U\1\E/` (for //...) - `%s/\/\*\( *[a-z]\)/\/*\U\1\E/` (for /* ... */)