Introduction to VIM Tutorial

Source: Internet
Author: User
Tags add numbers diff

1. Introduction

The Vim (vi[improved]) editor is a powerful cross-platform text file Editing tool that inherits from the Vi editor of UNIX systems and supports the LINUX/MAC OS x/windows system, which allows you to create and modify text files. To enter the VIM editing program, you can type the following command in the terminal:

$vim [filename]

Where filename is the path name of the file to be edited. If the file does not exist, it will create a new file for you. The VIM editing program has three modes of operation, called edit mode , insert mode , and command mode , and when Vim is run, it first enters edit mode.

2. Edit mode

The main purpose of the Vim editing method is to move the cursor position in the edited file. Once the cursor is moved to the desired position, you can cut and paste the body block, delete the body, and insert a new body. After all the editing work, you need to save the editor results, exit the editing program back to the terminal, you can issue a ZZ command, two times the capitalization of the Z key.

2.1 Jump

If you have a navigation key on the keyboard with the top, bottom, left, and right arrows, these keys do the cursor movement. In addition, you can use the following keys to complete the same character movement function:

k                上移;j                下移;h                左移;l                右移。

The above 4 keys move the cursor position one line or character at a time. Vim also provides commands to move the cursor a little wider:

ctrl+f        在文件中前移一页(相当于 page down);ctrl+b        在文件中后移一页(相当于 page up);

A larger range of movements:

*          当光标停留在一个单词上,* 键会在文件内搜索该单词,并跳转到下一处;#          当光标停留在一个单词上,# 在文件内搜索该单词,并跳转到上一处;(/)        移动到 前/后 句 的开始;{/}        跳转到 当前/下一个 段落 的开始。g_         到本行最后一个不是 blank 字符的位置。fa         到下一个为 a 的字符处,你也可以fs到下一个为s的字符。t,         到逗号前的第一个字符。逗号可以变成其它字符。3fa        在当前行查找第三个出现的 a。F/T        和 f 和 t 一样,只不过是相反方向;gg         将光标定位到文件第一行起始位置;G          将光标定位到文件最后一行起始位置;NG或Ngg    将光标定位到第 N 行的起始位置。

When you find the page you want in the screen, you can quickly move the cursor with the following command:

H                将光标移到屏幕上的起始行(或最上行);M                将光标移到屏幕中间;L                将光标移到屏幕最后一行。

Also pay attention to the case of letters. Hand L commands can also add numbers. If 2H you move the cursor to line 2nd of the screen, the 3L cursor is moved to the 3rd line of the screen.
When you move the cursor to the desired line, moving the cursor within the line is possible with the following command:

w                右移光标到下一个字的开头;e                右移光标到一个字的末尾;b                左移光标到前一个字的开头;0                数字0,左移光标到本行的开始;$                右移光标,到本行的末尾;^                移动光标,到本行的第一个非空字符。
2.2 Search Matches

Like many advanced editors, VIM provides powerful string search capabilities. To find where a specified word or phrase appears in a file, you can search directly with vim without having to do it manually. The search method is: Type the character / followed by the string to be searched, then press ENTER. The editor performs a forward search (that is, toward the end of the file) and, after locating the specified string, pauses the cursor to the beginning of the string; type n a command to continue the search to find the next occurrence of the string. ? / You can reverse-search (toward the beginning of the file) by using a character substitution. For example:

/str1                正向搜索字符串 str1;n                    继续搜索,找出 str1 字符串下次出现的位置;N                    继续搜索,找出 str1 字符串上一次出现的位置;?str2                反向搜索字符串 str2 。

Regardless of the direction of the search, when the end or beginning of the file is reached, the search work loops to the other end of the file and resumes execution.
The strongest place to perform search matches in Vim is to search in conjunction with regular Expressions , which will be described later.

2.3 Replacement and deletion

Vim General Delete command is d , x (the former delete , the latter delete 字符 ), combined with other features of Vim can be implemented based on the deletion function. After you position the cursor at a specified position within a file, you can replace the character pointed to by the cursor with other characters, or delete one or more characters or rows or lines from the current cursor position. For example:

rc                 用 c 替换光标所指向的当前字符;nrc                用 c 替换光标所指向的前 n 个字符;5rA                用 A 替换光标所指向的前 5 个字符;x                  删除光标所指向的当前字符;nx                 删除光标所指向的前 n 个字符;3x                 删除光标所指向的前 3 个字符;dw                 删除光标右侧的字;ndw                删除光标右侧的 n 个字;3dw                删除光标右侧的 3 个字;db                 删除光标左侧的字;ndb                删除光标左侧的 n 个字;5db                删除光标左侧的 5 个字;dd                 删除光标所在行,并去除空隙;ndd                删除(剪切) n 行内容,并去除空隙;3dd                删除(剪切) 3 行内容,并去除空隙;

Other commonly used Delete commands are:

d$                从当前光标起删除字符直到行的结束;d0                从当前光标起删除字符直到行的开始;J                 删除本行的回车符(CR),并和下一行合并。

The VIM General replacement command has c and s , in combination with other features of vim, can implement the underlying replacement function, but after the replacement command is executed, it is usually entered into insert mode by the edit mode :

s                用输入的正文替换光标所指向的字符;S                删除当前行,并进入编辑模式;ns               用输入的正文替换光标右侧 n 个字符;nS               删除当前行在内的 n 行,并进入编辑模式;cw               用输入的正文替换光标右侧的字;cW               用输入的正文替换从光标到行尾的所有字符(同 c$ );ncw              用输入的正文替换光标右侧的 n 个字;cb               用输入的正文替换光标左侧的字;ncb              用输入的正文替换光标左侧的 n 个字;cd               用输入的正文替换光标的所在行;ncd              用输入的正文替换光标下面的 n 行;c$               用输入的正文替换从光标开始到本行末尾的所有字符;c0               用输入的正文替换从本行开头到光标的所有字符。
2.4 Copy and paste

Content that is removed from the body (such as characters, words, or lines) is not really lost, but is cut and copied into a memory buffer. The user can paste it into the body at the specified location. The command to complete this operation is:

p               小写字母 p,将缓冲区的内容粘贴到光标的后面;P               大写字母 P,将缓冲区的内容粘贴到光标的前面。

If the contents of the buffer are characters or words, paste directly before or after the cursor, or if the contents of the buffer are the entire line body, the Paste command executed above will be pasted on the previous line or row of the current cursor.
Note the case of the letters in the two commands above. The Vim editor often p provides a pair of similar functions with a pair of large, lowercase letters (such as and P ). In general, the lowercase command operates behind the cursor, and the uppercase command operates in front of the cursor.

Sometimes you need to copy a piece of text to a new location while preserving the contents of the original location. In this case, you should first copy (rather than cut) the specified content to the memory buffer. The command to complete this operation is:

yy              复制当前行到内存缓冲区;nyy             复制 n 行内容到内存缓冲区;5yy             复制 5 行内容到内存缓冲区;“+y             复制 1 行到操作系统的粘贴板;“+nyy           复制 n 行到操作系统的粘贴板。
2.5 Undo and redo

In the process of editing a document, you can use the Undo command to eliminate the consequences of an erroneous edit command. In addition, if the user wants to repeat the previously executed edit command at the new cursor position, the duplicate command is available.

u               撤消前一条命令的结果;.               重复最后一条修改正文的命令。
3. Insert Mode 3.1 Enter insert mode

After you have correctly positioned the cursor in edit mode, you can switch to insert mode by using the following command:

i            在光标左侧插入正文a            在光标右侧插入正文o            在光标所在行的下一行增添新行O            在光标所在行的上一行增添新行I            在光标所在行的开头插入A            在光标所在行的末尾插入
3.2 Exit Insert mode

Exit the insert mode by pressing the ESC key or key combination Ctrl+[ , exiting insert mode and entering edit mode.

4. Command mode

In Vim's command mode, complex commands can be used. When you type in edit mode : , the cursor jumps to the last line of the screen, where the colon is displayed and the command mode is entered. The command mode is also called the last line mode , the user input content is displayed in the final line of the screen, press ENTER, Vim executes the command.

4.1 Open, Save, exit

To open a file in Vim that is already started, :e you need to use the command:

:e path_to_file/filename

To save the currently edited file, :w you need to use the command ( write the abbreviation for the word):

:w

Save the current file as file_temp :

:w file_temp

In edit mode, you can ZZ exit the VIM editing program with a command that saves the changes to the body and overwrites the original file. If you only need to exit the editing program and not save the edited content, you can use the following command:

: q                在未作修改的情况下退出;: q!               放弃所有修改,退出编辑程序。

Save and exit the two commands can be used together (note the Order of command, first save, then exit):

:wq
4.2 Line number and file

Each line in the edit has its own line number, and the following commands allow you to move the cursor to the specified line (the effect is the same as in edit mode ngg nG ):

: n             将光标移到第 n 行

Command mode, you can specify the line number range for the command operation. The value is used to specify the absolute line number; Represents the line number of the line where the cursor is located; the word character "$" represents the line number of the last line of the body; a simple expression, such as ". +5", represents the 5th row down the current line. For example:

:345                  将光标移到第 345 行:345w file            将第 345 行写入 file 文件:3,5w file            将第 3 行至第 5 行写入 file 文件:1,.w file            将第 1 行至当前行写入 file 文件:.,$w file            将当前行至最后一行写入 file 文件:.,.+5w file          从当前行开始将 6 行内容写入 file 文件:1,$w file            将所有内容写入 file 文件,相当于 :w file 命令

In command mode, the body is allowed to be read from a file, or the body is written to a file. For example:

:w                 将编辑的内容写入原始文件,用来保存编辑的中间结果:wq                将编辑的内容写入原始文件并退出编辑程序(相当于 ZZ 命令):w file            将编辑的内容写入 file 文件,保持原有文件的内容不变:a,bw file         将第 a 行至第 b 行的内容写入 file 文件:r file            读取 file 文件的内容,插入当前光标所在行的后面:e file            编辑新文件 file 代替原有内容:f file            将当前文件重命名为 file:f                 打印当前文件名称和状态,如文件的行数、光标所在的行号等
4.3 String search

In edit mode , a string search is performed, and the command pattern here can also be used for string searches, giving a string that can be searched for the string to reach the specified line. If you want to do a forward search, place the string to be searched / between two and if you want to reverse a search, place the string ? between two. For example:

:/str/                  正向搜索,将光标移到下一个包含字符串 str 的行:?str?                  反向搜索,将光标移到上一个包含字符串 str 的行:/str/w file            正向搜索,并将第一个包含字符串 str 的行写入 file 文件:/str1/,/str2/w file    正向搜索,并将包含字符串 str1 的行至包含字符串 str2 的行写
4.4 Regular Expressions in vim

When you specify a search string for vim, you can include characters with special meanings. The search string that contains these special characters is called a regular expression (Regular Expressions). For example, to search for a line of text, the beginning of the line contains struct words. The following command does not do this:

:/struct/

Because it only finds the first row contained anywhere in the row, it is not struct necessarily included at the beginning of the row struct . The solution to this problem is to precede the search string with a special character ^:

:/^struct/

^Characters compare strings at the beginning of each line. So the above command says: Find struct the line that starts with the string.
You can also use a similar method to find the word at the end of the line by adding a special character that represents the end of the line to the search string $ :

:/^struct/

The following table gives the most special characters and their meanings:

^                放在字符串前面,匹配行首的字;$                放在字符串后面,匹配行尾的字;\<               匹配一个字的字头;\>               匹配一个字的字尾;.                匹配任何单个正文字符;[str]            匹配 str 中的任何单个字符;[^str]           匹配任何不在 str 中的单个字符;[a-b]            匹配 a 到 b 之间的任一字符;*                匹配前一个字符的 0 次或多次出现;\                转义后面的字符。

So many simple, regular expression knowledge can refer to
Regular expression 30-minute primer: http://deerchao.net/tutorials/regex/regex.htm
In addition, the advanced VIM regular expression also has the introduction to the Magic mode, can refer to
A detailed description of the VIM regular expression:
http://blog.csdn.net/salc3k/article/details/8222397

4.5 Body Replacement

:sthe substitution of strings can be implemented using commands. Specific uses include:

:%s/str1/str2/        用字符串 str2 替换行中首次出现的字符串 str1:s/str1/str2/g        用字符串 str2 替换行中所有出现的字符串 str1:.,$ s/str1/str2/g    用字符串 str2 替换正文当前行到末尾所有出现的字符串 str1:1,$ s/str1/str2/g    用字符串 str2 替换正文中所有出现的字符串 str1:g/str1/s//str2/g     功能同上:m,ns/str1/str2/g     将从m行到n行的str1替换成str2

From the Replace command above you can see:

    1. gAt the end of the command, it means that each occurrence of the search string is replaced, not just the first occurrence in each row, but the substitution of the g first occurrence of the search string, and g at the beginning of the command, a substitution operation for all rows containing the search string in the body;
    2. sA command that is followed by a string of replacements;
    3. %Indicates that the replacement range is all lines, that is, full text.

Another useful command, in Vim, is to count the str1 number of occurrences of a string in the current file, which can be replaced by a variant of the command:

:%s/str1/&/gn
4.6 Delete Body

In command mode, you can also delete the contents of the body. For example:

:d                              删除光标所在行:3d                             删除 3 行:.,$d                           删除当前行至正文的末尾:/str1/,/str2/d                 删除从字符串 str1 到 str2 的所有行:g/^\(.*\)$\n\1$/d              删除连续相同的行,保留最后一行:g/\%(^\1$\n\)\@<=\(.*\)$/d     删除连续相同的行,保留最开始一行:g/^\s*$\n\s*$/d                删除连续多个空行,只保留一行空行:5,20s/^#//g                    删除5到20行开头的 # 注释

In summary, the primary Delete command for VIM is used d , and the Advanced Delete command can be executed in the form of a regular replacement .

4.7 Recovering files

When you edit a file, Vim generates a separate temporary file whose name usually begins with the end of the file . .swp . When vim exits normally, the file is deleted, and if you quit unexpectedly without saving the most recent changes to the file, you can use the Restore command :recover to recover the file or use the option to start Vim -r .

4.8 Option settings

To control the different editing functions, Vim offers many internal options. Use :set commands to set options. The basic syntax is:

:set option         设置选项 option

Common feature options include the following:

autoindent        设置该选项,则正文自动缩进ignorecase        设置该选项,则忽略规则表达式中大小写字母的区别number            设置该选项,则显示正文行号ruler             设置该选项,则在屏幕底部显示光标所在行、列的位置tabstop           设置按 Tab 键跳过的空格数。例如 :set tabstop=n,n 默认值为 8mk                将选项保存在当前目录的 .exrc 文件中
4.9 Shell Switch

When you are in the process of editing a conversation, you may need to execute some Linux commands. If you need to save the current results, exit the editing program, execute the required Linux commands, and then go back to the editing process, it becomes cumbersome. It is much more convenient to run Linux commands in an edited environment. In Vim, you can do this with the following command:

:!shell_command   执行完 shell_command 后回到Vim

This is called a shell switchover. It allows you to execute any command that can be executed at the standard shell prompt. When this command is completed, control is returned to the editing program. You can also continue editing the dialog process.

4.10 Split screen with tab page

Normal vim mode, open a VIM program can only view a file, if you want to view multiple files at the same time, you need to use the VIM split screen and tab function.
Vim of the split screen, there are two main ways: up and down split screen (horizontal split screen) and left and right split screen (vertical split screen), in the command mode to type the following commands, respectively:

:split(可用缩写 :sp)            上下分屏;:vsplit(可用缩写 :vsp)          左右分屏。

Alternatively, you can turn on the split screen operation when you start Vim in the terminal:

vim -On file1 file2...   打开 file1 和 file2 ,垂直分屏vim -on file1 file2...   打开 file1 和 file2 ,水平分屏

Theoretically, a vim window can be divided into several vim screens, which require keyboard shortcuts to switch the screen, with the following commands:

Ctrl+w+h            切换到当前分屏的左边一屏;Ctrl+w+l            切换到当前分屏的右边一屏;Ctrl+w+j            切换到当前分屏的下方一屏;Ctrl+w+k            切换到当前分屏的上方一屏。

That is, the keyboard of the h,j,k,l four vim dedicated key, with Ctrl the keys and w keys ( window the abbreviation), you can jump to the target sub-screen. In addition, you can directly press Ctrl+w+w to jump sub-screen, but the direction of the jump is in the current VIM window all sub-screen, in accordance with the direction of the 逆时针 jump.
Here are some of the things that change the size, mostly the height, you can use for the width [Ctrl+W <] or [Ctrl+W >] , but this may require the latest version to support.

Ctrl+W =            让所有的屏都有一样的高度;Ctrl+W +            增加高度;Ctrl+W -            减少高度。
tab page

Vim tab page, browser-like tab, a tabbed page opens a vim window, a vim window can support n split screen.
The command to create a new label in Vim is:

:tabnew

If you want to open a file at the same time as you create a new tab, you can include the file path directly after the command:

:tabnew filename

Each tab in VIM has a unique numeric sequence number, and the first tab is numbered 0 from left to right, plus one in turn. There are a series of operations commands on the tabs, as follows:

:tN[ext]                跳转到上一个匹配的标签:tabN[ext]              跳到上一个标签页:tabc[lose]             关闭当前标签页:tabdo                  为每个标签页执行命令:tabe[dit]              在新标签页里编辑文件:tabf[ind]              寻找 ‘path‘ 里的文件,在新标签页里编辑之:tabfir[st]             转到第一个标签页:tabl[ast]              转到最后一个标签页:tabm[ove]  N           把标签页移到序号为N位置:tabnew [filename]      在新标签页里编辑文件:tabn[ext]              转到下一个标签页:tabo[nly]              关闭所有除了当前标签页以外的所有标签页:tabp[revious]          转到前一个标签页:tabr[ewind]            转到第一个标签页
4.11 Integration with external tools

Vim can be integrated with many external programs, the functions are very powerful, such as,, and diff ctags sort xxd so on, choose a few simple introduction below.

Diff

The Linux command is diff used to compare the contents of two files, but the comparison results are displayed in the terminal, and the readability is poor. With Vim, you can enter commands directly in the terminal vimdiff , followed by two filenames as parameters:

vimdiff file1 file2

You can display two files in the vim of the comparison results of the contents of the file content of the difference, highlighting the differences in the contents of the document, you can also scroll two file content, can be modified in real-time file content, convenience and user experience greatly improved.

vimdiff a.txt b.txt

If -d the option is the same as the direct

vim -d a.txt b.txt

In addition to opening the Vimdiff function in the terminal, it is also possible to turn on vim by entering the relevant command in Vim's command mode to enable the vimdiff function:

:diffsplit abc.txt

If you have now opened a file, want Vim to help you distinguish between your file and abc.txt what is the difference, you can use VIM in diffsplit the way to open the second file, this time vim will use split (two screen) to open the second file, and through the color foldto show the difference between two files
This way, VIM will use color to help you distinguish between 2 files. If the file is larger (source) the duplicate part will help you to fold up.

:diffpatch filename

With the :diffpatch file name of your patch, you can display it in the current file plus your patch. Vim will split a new screen, display the patch information and use color to indicate the difference.
If you do not like the upper and lower contrast, like the left and right (more visual) can be added in front vert , for example:

:vert diffsplit abc.txt:vert diffpatch abc.txt

After reading the diff, :only back to the original edited file, feel the color of the diff is still where, as long as the :diffoff closure on the good.
There is also a common diff is :diffu that this is :diffupdate the shorthand, update the time used.
The functionality of Vim is shown diff as follows:


Photo from http://www.2cto.com/net/201608/536924.html

Sort

The Linux command sort compares and sorts text content by characters in a line, but uses commands to process files in the terminal sort and does not view the contents of the file in real time. Please check the manual for specific usage.

Xxd

vim+xxdLinux is the most commonly used binary text editing tools, xxd in fact, is a vim external conversion program, with the release of Vim, it is called in vim to edit binary text is very convenient.
First open a file in the terminal in binary mode:

vim -b filename

Vim's -b option is to tell vim to open a binary file, which, if not specified, is appended 0x0a with a newline character.
Then, in Vim's command mode, type:

:%!xxd

You can see the text displayed in the binary mode, which looks like this:

 0000000: 1f8b 0808 39d7 173b 0203 7474 002b 4e49  ....9..;..tt.+NI  0000010: 4b2c 8660 eb9c ecac c462 eb94 345e 2e30  K,......b..4^.0  0000020: 373b 2731 0b22 0ca6 c1a2 d669 1035 39d9  7;‘1.".....i.59

You can then edit the file in binary mode, save it after editing, and then switch from binary mode to normal mode with the following command:

:%!xxd -r

In addition, you can adjust the binary display mode, default is 2 bytes for a group, you can adjust the g number of bytes per group BY parameter:

:%!xxd -g 1         表示每1个字节为1组 :%!xxd -g 2         表示每2个字节为1组(默认) :%!xxd -g 4         表示每4个字节为1组
5. Vim Configuration

The initial installation of Vim features, feature support is relatively small, use more laborious, want to slightly "good" point, need to do some preliminary configuration. Vim configuration is mainly divided into the configuration of vim itself and the configuration of the external plug-in two parts.
Vim's configuration is usually stored in a hidden file in the user's home directory .vimrc . In terms of vim itself, the basic configuration has programming language syntax highlighting, indentation settings, line number display, search highlighting, tab settings, font settings, vim theme settings, and so on, a little more advanced programming language indentation, automatic completion of the settings, etc., specific configuration items can be self-check data, A comprehensive and detailed description of the configuration items can be found in:
"Vim Options":
Http://vimcdoc.sourceforge.net/doc/options.html#%27completeopt%27

6. Vim Plugin

The title of Vim "Editor God" is not the name of the wave, however, behind this honor, perhaps nearly half of the credit is due to the powerful plug-in support features, as well as community development of a variety of powerful plug-ins.

Usually developers commonly used plug-ins are mainly directory (file) View and management, programming language indentation and auto-completion, programming language Docs support, function jump, project management, etc., simple configuration can refer to the following:

"Vim Plugin Brief Introduction":
http://blog.segmentfault.com/xuelang/1190000000630547

Teach you to convert vim into an IDE programming environment (GRAPHIC):
http://blog.csdn.net/wooin/article/details/1858917

Transforming VIM into a powerful IDE:
Http://www.cnblogs.com/zhangsf/archive/2013/06/13/3134409.html

Of course, these plugins are given by the plugin support feature of Vim itself. Vim in order to support the rich third-party plug-in, self-defined a set of simple script development language, for programmers to develop their own needs of the plug-in, plug-in development introduction can be consulted:

"Writing Vim Plugins":
http://stevelosh.com/blog/2011/09/writing-vim-plugins/

7. Vim Complete Documentation
    1. Vim Official Document: http://vimdoc.sourceforge.net/
    2. Vim Chinese User manual 7_3.pdf:http://pan.baidu.com/s/1jgzbtbo


--------------------------------------------------------------------------------------------------------------
Turtle
Links: http://www.jianshu.com/p/bcbe916f97e1
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

Introduction to VIM Tutorial

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.