vim usage summary

vim use command

【Auto-completion operation】

  • Ctrl + n / Ctrl + p autocomplete strings
  • Ctrl +x Ctrl +f Autocomplete filename

【Multiple file operation】
Open multiple files:

  • vim file1 file2 … filen open all files you want to open in the same window
  • vim -o file1 file2 … filen Open an editing session, split the window horizontally, one file occupies one window
  • vim -O file1 file2 … filen Opens an editing session, splits the window vertically, one file occupies one window
  • vim -o5 file1 file2 will allocate 5 identical windows horizontally, 3 of which are idle

File switching:

  • :e file loads and displays the file file in the current window
  • : ls displays a list of all open files, with numbers
  • :b1~n switch to the nth file
  • :bn next file
  • :bp previous file
  • Ctrl+6 switch between two files

【Multi-window operation】
Cut window operation:

  • :sp(lit) cut the window horizontally
  • :vsp(list) cut the window vertically
  • :qa(ll) close all windows

By default, the newly created window displays the same file, but different files can be displayed by the following commands:
: [n] split(vsplit) [++opt] [+cmd] [file]

Multi-window switching:

Press and hold Ctrl + W, then add h, j, k, l to move the window to the left, down, up, and right, respectively. You can also use the up, down, left, and right keys.

  • Ctrl + w + h: move the window to the left
  • Ctrl + w + j: move the window down
  • Ctrl + w + j: move the window up
  • Ctrl + w + l: move the window to the right

  • Ctrl + w + w: This command will cycle through all windows

  • Ctrl + w + t: move to the top left window
  • Ctrl + w + b: Move to the bottom right window
  • Ctrl + w + p: move to the previously visited window

【Resize window】

Change the size of the current window, and of course also affect other windows.
In gvim and vim, you can use the mouse to click on the white bar at the top of the window and resize the window directly.

You can also use the command directly. The resize command also starts with Ctrl + W:

  • Ctrl + W + = : make all windows resize to the same size (evenly divided)
  • Ctrl + W + -: reduce the height of the current window by one line, also in the ex command, :resize -4 explicitly specify the reduced size
  • Ctrl + W + +: Increase the height of the current window by one line. Also in the ex command, :resize +n explicitly specifies to increase the size

  • Ctrl + W + < : reduce the width of the current window

  • Ctrl + W + > : Increase the width of the current window

  • Ctrl + W + |: Adjust the width of the current window to the maximum, or you can change the width explicitly through the ex command: vertical resize n

skills

[Automatically add headers to new files]

autocmd BufNewFile *.sh,*.py,*.c,*.h,*.cpp exec ":call SetFileHeaderComment()"

func s:SetCommentLine(pre, comment)
    normal o
    call setline(line("."), a:pre.a:comment)
endfunc

func s:SetCommonComment(pre)
    call s:SetCommentLine(a:pre, " ")
    call s:SetCommentLine(a:pre, "      FileName: ".expand("%"))
    call s:SetCommentLine(a:pre, " ")
    call s:SetCommentLine(a:pre, "        Author: ")
    call s:SetCommentLine(a:pre, "   Description: ---")
    call s:SetCommentLine(a:pre, "  Created Time: ".strftime("%c"))
    call s:SetCommentLine(a:pre, " Last Modified: ".strftime("%Y-%m-%d %H:%M:%S"))
    call s:SetCommentLine(a:pre, " ")
endfunc

func SetFileHeaderComment()
    if expand("%:e") == "sh"
        call setline(line("."), "\#/bin/bash")
        call s:SetCommonComment("\#")
    elseif expand("%:e") == "py"
        call setline(line("."), "\#!/usr/bin/env python")
        call s:SetCommentLine("\#", " -*- coding: utf-8 -*-")
        call s:SetCommonComment("\#")
    elseif expand("%:e") == "c" || expand("%:e") == "cpp"
        call setline(line("."), "/*")
        call s:SetCommonComment(" *")
        call s:SetCommentLine(" *", "/")
    elseif expand("%:e") == "h"
        let h_macro = "__".toupper(expand("%:r"))."_H_INCLUDED"
        call setline(line("."), "#ifndef ".h_macro)
        call s:SetCommentLine("", "#define ".h_macro)
        call s:SetCommentLine("", "#endif   /* ".h_macro." */")
        call cursor(2, len(getline(2)))
        normal o
        normal O
        normal O
    endif
    normal o
endfunc

【Multi-line and multi-column operation】

Press v to enter the visual state, select multiple lines, use > or < to indent or indent

Usually use automatic indent typesetting according to language characteristics: in the command state, use == for the current line (double click = twice), or use n== (n is a natural number) for multiple lines to indicate automatic indentation from the current line. n lines below. You can try to indent the code arbitrarily and then use n== typesetting, which is equivalent to the code format in the general IDE. Use gg=G to typeset the entire code.

:20,30 s/^/#/g Lines 20 to 30 are commented out with #.
:20,30 s/^#//g uncomment

:4,10 s/^[^I ]+// remove whitespace at the beginning of the line

:co 12 "Copy the current line to line 12.
You can see that the vim command is for the current line, and you can target multiple lines by adding a range in front.
Use . for the current line, % for the full text, and $ for the end.

:.,30 s/^/#/g

vim configuration file use

vim --versionView the functions supported by vim and the configuration file directory

set nocompatible " 关闭 vi 兼容模式
" colorscheme morning " 设定配色方案/usr/share/vim/vim74/colors
set number " 显示行号
set cursorline " 突出显示当前行
set ruler " 打开状态栏标尺
set shiftwidth=4 " 设定 << 和 >> 命令移动时的宽度为 4
set softtabstop=4 " 使得按退格键时可以一次删掉 4 个空格
set tabstop=4 " 设定 tab 长度为 4
set expandtab " 将tab键替换成空格
" :set ts=4
" :set noexpandtab
" :%retab!
" :set list 显示制表符,显示方式如下设置
" set listchars=tab:>-,trail:-
" set listchars=tab:\|\ ,trail:.,extends:>,precedes:<,eol:$

set nobackup " 覆盖文件时不备份
set autochdir " 自动切换当前目录为当前文件所在的目录
syntax on " 自动语法高亮
filetype plugin indent on " 开启插件
set backupcopy=yes " 设置备份时的行为为覆盖

set ignorecase smartcase " 搜索时忽略大小写,但在有一个或以上大写字母时仍保持对大小写敏感
set nowrapscan " 禁止在搜索到文件两端时重新搜索
set incsearch " 输入搜索内容时就显示搜索结果
set hlsearch " 搜索时高亮显示被找到的文本
set noerrorbells " 关闭错误信息响铃
set novisualbell " 关闭使用可视响铃代替呼叫
set t_vb= " 置空错误铃声的终端代码
" set showmatch " 插入括号时,短暂地跳转到匹配的对应括号
" set matchtime=2 " 短暂跳转到匹配括号的时间
set magic " 设置魔术
set hidden " 允许在有未保存的修改时切换缓冲区,此时的修改由 vim 负责保存
set guioptions-=T " 隐藏工具栏
set guioptions-=m " 隐藏菜单栏
set smartindent " 开启新行时使用智能自动缩进
set backspace=indent,eol,start " 不设定在插入状态无法用退格键和Delete 键删除回车符
set cmdheight=1 " 设定命令行的行数为 1
set laststatus=2 " 显示状态栏 (默认值为 1, 无法显示状态栏)
set statusline=\ %<%F[%1*%M%*%n%R%H]%=\ %y\ %0(%{&fileformat}\ %{&encoding}\%c:%l/%L%)\ 
" 设置在状态行显示的信息

set nofoldenable " 开始折叠
set foldmethod=syntax " 设置语法折叠
set foldcolumn=0 " 设置折叠区域的宽度
setlocal foldlevel=1 " 设置折叠层数为
" set foldclose=all " 设置为自动关闭折叠 
" nnoremap <space> @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>
" 用空格键来开关折叠

Use of vim plugin

ctags

【Install】

  • Install:yum install -y ctags

[Generate tags file]

  • ctags -R recursively generates tags files for all code files in the current directory and subdirectories
  • ctags .c .h generate tags files for some source code

In order to make field completion effective, some additional parameters are required when generating tags. The recommended C++ parameters are:
ctags -R --c++-kinds=+px --fields=+iaS --extra=+q
among them:
option c++-kinds is used to specify the type of tags record in C++ language, –c-kinds is used to specify the type of tags in C language , the general format is the --{language}-kinds
option fileds is used to specify the extension field field of each tag The
extra option is used to add extra entries: f means add one entry for each file, q adds one entry for each class

【Instructions】

When vim opens the source code, it can be used normally by specifying the tags file. Usually, it is manually specified and input on the vim command line:
:set tags=./tags(tags file in the current path)
If you want to refer to tags files in multiple different directories, you can separate them with commas.

Or, set ~/.vimrc and add a line, you don't need to manually set the tags path:
set tags=~/path/tags

To add tags of system functions or global variables, you need to execute:
ctags -I __THROW --file-scope=yes --langmap=c:+.h --languages=c,c++ --links=yes --c-kinds=+px --fields=+S -f ~/.vim/systags -R /usr/include /usr/local/include *
and add them in ~/.vimrc (you can also use the manual method described above):
set tags+=~/.vim/systags In
this way, you can enjoy System library function name completion, prototype preview and other functions are now available.

If you often look up the code in different projects, you can add in ~/.vimrc:
set tags=tags;
set autochdir

After setting the tags file, when locating the definition of a variable/function, the most commonly used shortcut keys are:
Ctrl + ]
to jump to the definition of a variable or function, or use the command
: ta name
and use the shortcut key combination
Ctrl + o/ t
returns to the position before the jump.

In addition, ctags does not generate the index of local variables, but you can use the gd key combination (quick search and positioning of the word where the cursor is located) to locate, which is also quite fast.

$ vim -t myAdd
When opening a file with vim, adding the parameter -t funcName will automatically open the file defining the function and locate the first line of the definition. The above sentence is to find the file defined by myAdd and open it and place the cursor at the first definition line.

:tags
will list the search/jump process (list of tags passed)

In addition, attach other useful shortcut keys in the vim environment:
* Navigate to the next occurrence of the word pointed to by
the current cursor # Navigate to the previous occurrence of the word pointed to by the current cursor
n Navigate to jump to The next occurrence of the marked word
shift+n to navigate to the previous occurrence of the marked word

For more detailed usage of ctags, use
: help tags in vim

taglist

[Function]
a source code browser (supports C/C++, Java, perl, Python, tcl, sql, php, etc): Provides a structured browsing function of the source code, which can convert the classes, functions, variables, etc. The tree structure shows that the hierarchical relationship can be seen at a glance, and it is easy to locate and view quickly.

[Download and install]
The taglist plugin exists in the form of a vim script, so you only need to download it and put it in the corresponding directory. Taglist is based on ctags to function, so make sure you have installed ctags before using taglist.

Download address (one of the two can be selected):
Official site http://vim-taglist.sourceforge.net/
VIM online http://www.vim.org/scripts/script.php?script_id=273

Put the file in the folder corresponding to /usr/share/vim/vim74

Configure the taglist option in the vim configuration file:

"如果ctags不在Path路径下,则配置ctags的路径
if MySys() == "windows"
 let Tlist_Ctags_Cmd = 'ctags'
elseif MySys() == "linux"
 let Tlist_Ctags_Cmd = '/usr/bin/ctags'
endif

let Tlist_Show_One_File = 1        "不同时显示多个文件的tag,只显示当前文件的
let Tlist_Exit_OnlyWindow = 1      "如果taglist窗口是最后一个窗口,则退出vim
let Tlist_Use_Right_Window = 1     "在右侧窗口中显示taglist窗口
let Tlist_Sort_Type = "name"       "taglist以tag名字进行排序,缺省是按tag在文件中出现的顺序进行排序
let Tlist_Use_SingleClick = 1      "设置单击tag就跳转到定义处,确实双击
let Tlist_Auto_Open=1              "启动vim自动打开taglist窗口
let Tlist_Close_On_Select=1        "在选择了tag后自动关闭taglist窗口
let Tlist_File_Fold_Auto_Close=1   "当同时显示多个文件中的tag时,可使taglist只显示当前文件tag,其它文件的tag都被折叠起来。
let Tlist_GainFocus_On_ToggleOpen=1"在使用:TlistToggle打开taglist窗口时,输入焦点在taglist窗口中
let Tlist_Process_File_Always=1    "taglist始终解析文件中的tag,不管taglist窗口有没有打开
let Tlist_Use_Horiz_Window = 1     "设置taglist窗口横向显示
" Tlist_WinHeight和Tlist_WinWidth可以设置taglist窗口的高度和宽度

Shortcuts available in the taglist window:

hot key Function Description
CR Jump to the position defined by the tag under the cursor, and double-click the tag with the mouse.
O Show the tag under the cursor in a newly opened window
Space Displays the prototype definition of the tag under the cursor
u Update tags in the taglist window
s Change the sorting method, switching between sorting by name and sorting by appearance
x The taglist window zooms in and out for easy viewing of longer tags
+ Open a fold, same as zo
- Fold the tag, same as zc
* Open all folds, same as zR
= Fold all tags, same as zM
[[ skip to previous file
]] skip to next file
q close the taglist window
F1 show help

cscope

  • Install:yum install -y cscope

Introduction to configuration file syntax

shortcut keymap

[vim mode]
There are many modes in Vim, but these are generally mentioned:

  • Normal Mode
    is the most common normal mode. After entering vim by default, it is in this mode.

  • Visual Mode
    is generally translated as visual mode, in which some characters, rows, and columns are selected.
    In normal mode, you can press v to enter.

  • Insert Mode
    Insert mode actually refers to the state of editing input. In normal mode, you can press i to enter.

  • Select Mode
    is a commonly used mode under gvim, which can be called selection mode. When you drag an area with the mouse, you enter the selection mode.
    Unlike visual mode, in this mode, after selecting the highlighted area, pressing any key will directly input and replace the selected text.
    It has the same effect as the editor selected under Windows. In normal mode, you can press gh to enter.

  • Command-Line/Ex Mode
    is called Command-Line Mode and Ex Mode. The two are slightly different. In normal mode, press the colon (:) to enter Command-Line mode, you can enter various commands and
    use various powerful functions of vim. In normal mode, press Q to enter Ex mode, which is actually a multi-line Command-Line mode.

【Basic Concepts of Map】


Combinations of Commands Like other commands in Vim, command names often consist of several paragraphs. The prefix acts as a modifier on the command itself, fine-tuning the effect of the command.
For map, there may be such prefixes

  • nore
    means non-recursive, see the introduction below
  • n
    means to take effect in normal mode
  • v
    means to take effect in visual mode
  • i
    means to take effect in insert mode
  • c
    means to take effect in command line mode

[Shortcut key mapping example]

Auto-completion of closing parentheses:

  • inoremap ( ()<ESC>i
  • inoremap [ []<ESC>i
  • inoremap { {}<ESC>i<CR><ESC><S-o>
  • inoremap < <><ESC>i
  • inoremap " ""<ESC>i
  • inoremap ' ''<ESC>i

refer to

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325689036&siteId=291194637
Recommended