vi yes linux And unix Common text editor under , Its operation is stable , Easy to use , This article will be divided into two parts: the configuration and the common operation skills , It refers to some articles on the Internet , Thank you to the author

PART1  Operation skills

explain :

In the following example  xxx  It means input in command mode  xxx  And return

In the following example  :xxx  Represents input in extended mode  xxx  And return

() The commands in represent related commands .[] The command is equivalent to

The command entered in edit mode or visual mode will be noted separately .

Move the cursor

stay  vi  in ,  Moving the cursor and editing are two things ,  Because of the distinction ,  So it is very convenient for optical calibration

Bit and edit .  So it's useful to move the cursor a little faster .

w               Move the cursor to the beginning of the next word .

e                Move the cursor to the end of the next word

b                Move the cursor to the previous word .

0                Move the cursor to the beginning of the line .

^                Move the cursor to the beginning of the line .

$                Move the cursor to the end of the line .

A                Move the cursor to the end of the line and in “ Additional ” state , Direct editing

H                Move the cursor to the first line of the screen .

M                Move the cursor to the middle line of the screen .

L                Move the cursor to the end of the screen .

gg               Move the cursor to the first line of the document .

G                Move the cursor to the end of the document .

:n               Jump to the first place n That's ok

ctrl + f         Page down   Same as  page down.

ctrl + b         Page up   Same as  page up.

ctrl + d         Turn down half the page   This is useful

ctrl + u         Turn up half the page   This is useful

ctrl + e         Turn down a line

ctrl + y         Up the line

[[               Go to the previous... In the first column “{”

]]               Go to the next one in the first column “}”

{                Go to the last blank line

}                Go to the next blank line

''    Two single quotes   This command is quite useful ,  It moves the cursor to the previous marker ,  For example, use  gd, *  After finding a word ,  Enter this command again to return to the last stop position .

'.    A little bit     This order is quite effective ,  It moves the cursor to the last modified line .

`.    A little bit of the upside down   This command is quite powerful ,  It moves the cursor to the last modification point .


/xxx(?xxx)       Indicates to search for a match throughout the document xxx String , /  Indicates to look down , ?  Express

Upward search . among xxx It can be a normal expression , I won't say much about the normal form .

Generally speaking, it is case sensitive ,  To be case insensitive ,  You have to type in first

:set ignorecase

After finding out ,  Input again  n  Find the next match ,  Input  N  Search in the opposite direction .

*(#)             When the cursor is over a word ,  Enter this command to find the... That matches the word

Next ( On ) A word .  Again ,  Input again  n  Find the next match ,  Input  N  con side

Find from .

g*(g#)           This command is similar to the previous one ,  But it doesn't exactly match the word where the cursor is ,  and

Is to match all strings containing the word .

gd               This command finds the word that matches the word where the cursor is located ,  And hover the cursor over the non

Where the word first appears in the comment section .  Used to find local variables and so on

%                This command finds the reverse bracket that matches the cursor ,  Include  () [] { }

f(F)x            This command means to search in the line where the cursor is located ,  Find the cursor right ( Left ) Fang is the first x character .

After finding :

Input  ;  Keep looking down

Input  ,  Indicates a reverse direction search


The replacement is  vi  The strengths of , Use “:s/ Pattern / character string / sign ” Replace , Among them “ Pattern ” Is a regular expression , Can be used to match strings . Here are a few examples .

:s/aa/bb/g        Put all the contents in the line where the cursor appears  aa  In the string of  aa  Replace with  bb

:s/\<aa\>/bb/g     Place the cursor on all the lines that appear  aa  Replace with  bb,  Replace only  aa  The word

:%s/aa/bb/g      Include all the items in the document  aa  In the string of  aa  Replace with  bb

:12,23s/aa/bb/g   Will be taken from 12 Row to 23 All occurrences in the line contain  aa  In the string of  aa  Replace with  bb

:12,23s/^/#/      Will be taken from 12 Row to 23 Add... At the beginning of the line  #  character

:%s= *$==      Remove any extra space at the end of the line

:%s/\s\+$//      Remove any extra space at the end of the line

:g/^\s*$/d           Will all contain no characters ( Spaces also don't contain ) Delete the blank line of

:%s/\(\s*\n\)\+/\r/     Will all contain no characters ( Spaces also don't contain ) Delete the blank line of .

:%s!\s*//.*!!         Get rid of all “//” notes

notes :Vim  Text that matches successfully is highlighted during search and replace , After the search and replace task has been completed , Sometimes this kind of highlighting will hinder the display .Vim  There is a special command to cancel the highlighting ( Until the user uses the search or replace command again ):“:nohlsearch”. It is recommended that users create a keyboard map (key mapping) Add to

.vimrc in , Such as :     nmap :nohlsearch

Special editor

ga               Displays the character indicated by the cursor encoding  code , such as ASCII code

guw              The character after the cursor is lowercase

gUw              The character after the cursor is capitalized



Copy ,  Delete and paste

stay  vi  in  y  It means copy , d  Said to delete , p  It means paste .  Copy and delete are related to the cursor movement command

The combination of ,  Just look at a few examples .

yw               Means to copy the content from the current cursor to the end of the word where the cursor is located .

dw               Delete the content from the current cursor to the end of the word where the cursor is located .

daw               Delete the word where the cursor is located , No matter where the cursor is in this word

y0               Indicates to copy the contents from the current cursor to the beginning of the cursor line .

d0               Delete the contents from the current cursor to the beginning of the cursor line .

y$               Means to copy the contents from the current cursor to the end of the line where the cursor is located .

d$[D]            Delete the content from the current cursor to the end of the line where the cursor is located .

Specifically :

yy               Represents the line where the copy cursor is located .

dd               Delete the line where the cursor is located .

D                Delete the content from the current cursor to the end of the line where the cursor is located .

xp               Represents the position of the swap cursor and the character after it

ddp              Indicates that the cursor line is swapped with the next line

J                Indicates that the cursor line is merged with the next line

About copying ,  The complex use of delete and paste has to do with registers ,  You can check by yourself .

VISUAL Pattern

Visual  Patterns are used to select multiple lines of text or blocks of text , Start and end by yourself , It's like choosing with a mouse .

v  Choose multiple lines , It's custom-made

ctrl + v  Select the rectangular block , It's kind of like UE Column patterns in ,O,o You can position the cursor to four endpoints

use visual The selected block can be regarded as a basic unit , Delete and copy everything can be used directly

Numbers and orders

stay  vi  The combination of number and command often means to repeat the command ,  If it appears at the beginning of the extended pattern, it means line

It's positioning .  Such as :

5yy[y5y]         Below the copy cursor  5  That's ok .

5dd[d5d]         Below the delete cursor  5  That's ok .

:12,24y          It means to copy the second 12 Go to the first place 24 Between lines .

:12,y            It means to copy the second 12 Line to the line of the cursor .

:,24y            Indicates to copy the cursor line to 24 Between lines .  Delete something like .

5fx              Indicates the second time after the cursor is found  5  individual  x  character .

5w(e)            Move the cursor to the head of the next five words ( The tail ).

Automatic completion and path setting

stay  vi  in ,  You are not required to enter every character ,  There are many ways to quickly enter some characters .

ctrl+p(ctrl + n)     In edit mode ,  Enter a few characters and then enter this command  vi  Start up ( Next ) search

Find the words that match the beginning of the line ,  If you input this command continuously, you will find it circularly .  This command

It's going to be all over this  vim  All open files in the program .

ctrl + x + l        In edit mode ,  Complete the whole line ,  But only in the documents that appear in this window .

ctrl + x + f        In edit mode ,  This command means to complete the file name .  Such as the input :

/usr/local/tom  Then enter this command and it will automatically match :


abbr             It's abbreviated .  This is a macro operation ,  You can use one abbreviation instead of another in edit mode

character string .  For example, writing java File input  System.out.println,  It's very

It's trouble ,  So abbreviations should be used to reduce typing .  You can do that :

:abbr sprt System.out.println

I'll input it later sprt Then enter other non alphabetic symbols ,  It will automatically expand to System.


When keyword matching is finished , If there is no desired result in the current file and other open files ,Vim

Will automatically arrive “#include” For further search in the file ( Why “#include” Well ? Please refer to

“:help 'include'”), The search directory is determined by the options  path  decision , The default value is  Unix( contain

Linux) for “.,/usr/include,,”, The directory representing the search is the directory of the file in turn 、/usr/include

And the current directory . According to the actual situation , You may need to be in  .vimrc File , Add the project related inclusion Directory , Pay attention to the last one “,,”, Unless you don't need to search in the current directory .

Set up the right path after , Another convenience is that you can use “gf” The command easily jumps to the file represented by the file name under the cursor . In the example above , Move the cursor to “stdio.h” On any character of , type

“gf”, be  Vim It will turn on automatically  /usr/include/stdio.h file . Use “Ctrl-O”( See “:helpCTRL-O”) You can go back to the original file .

Multi file editing

In a  vim  It's very convenient to open many files for editing in the program .

vi file1 file2 file3 ...

After editing and saving a file (:w), Enter command

:n You can edit the next file ,

:N Just go to the previous file and edit it

If you want to edit a file, use

:e  file name   Specify file edit

Or use :ls[:files]  from vi List the file names , such as   At the bottom of the screen

The following data will be displayed :

1   %a      "usevim.html"          That's ok  162

2   #       "xxxxxx.html"          That's ok  0

among :

1                Represents the serial number of the open file ,  This serial number is very useful .

%a               Indicates the document code , %  Represents the currently edited file ,

#  Represents the last edited file

"usevim.html"    For file name .

That's ok  162           Indicates cursor position .

then  :b Serial number , open :ls Command to specify the serial number of the file ,

In this way, you can copy and paste in multiple files

Other operating

:sp(:vsp)  file name     vim  Will be split into a horizontal ( longitudinal ) To the window ,  And open a new file in this window .

from  vim6.0  Start ,  The file name can be the name of a directory ,  such , vim  Meeting

Open the directory and display the list of files ,  Press enter on the file name to type

Open the file ,  If input  O  Open the file in a new window ,  Input  ?  You can see

To help information .

ctrl +w +w          vim  How to split several windows ?  Enter this command to cycle the cursor

Into the windows .

:set diff            This command is used to compare two files ,  It can be used

:vsp filename

Command to open another file ,  Then enter this command in each file window , You can see

It's working .


TAB  It's the tab ,  Take it out for a section because it's really useful .

<<                   Enter this command to move the cursor line one to the left  tab.

>>                   Enter this command to move the cursor line one to the right  tab.

5>>                  Enter this command, the cursor will be behind  5  The line moves one to the right  tab.

:12,24>              This command will 12 Row to 14 The data of each row moves one to the right  tab.

:12,24>>             This command will 12 Row to 14 The data of each row moves two to the right  tab.

So how to define it  tab  The size of ?  Someone is willing to use  8  A space bit ,  Someone uses it 4 individual ,  Some use 2 individual .

Some people want to  tab  Replace... Entirely with spaces ,  Some people hope that  tab  Namely  tab.  No problem , vim  can

To help you . The following settings are usually written to the configuration file first ,  So as not to knock .

:set shiftwidth=4    Set auto indent  4  A space ,  Of course, set auto indent first .

:set sts=4           Setting the  softtabstop  by  4.  Input  tab  And then I jumped  4  grid .

:set tabstop=4       Actually  tab  That is to say  4  A space ,  Instead of the default  8  individual .

:set expandtab       In the input  tab  after , vim  Fill in this with the appropriate space  tab.

File jump and tags

File jump to use tags file , The generation method is  ctags -R *, ctags For external orders .

Usage method :

(1) Move the cursor over the variable name or function , Press

ctrl+ ]  Jump to the definition of a variable or function , Press

ctrl+ t  Return to the original file

You can jump and return many times

(2) stay vi in :ta[:tag] You can jump directly to the definition of a variable or function

(3)vi -t  Variable or function name , Open the file of variable or function definition directly

The other options

:tselect [ keyword ]  Display and “ keyword ” List of matching tags , Enter a number to jump to the specified tag

:tjump [ keyword ]

Be similar to “:tselect”, But when there is only one match, jump to the mark instead of displaying the list

:tn                Jump to the next matching tag

:tp                Jump to the previous matching tag

Make  and  grep

Make [17]  and grep [18]  It should be  Unix  It's the basic tool that everyone in the world knows . Very natural ,Vim

There is special support for them . This support is mainly through access to a special quick fix window (quickfix

window) To achieve . Directly in  Vim  Enter the corresponding... In the command mode of  make  or  grep  command ( Such as “:grep


*.c”) You can put the execution result of the command into this window , At the same time, jump to the first error according to the returned result (make

The situation of ; In the use of  grep  When it comes to matching success ). The following are common “ Quick revision ” command :

:cn( Show the next error )

:cp( Show last error )

:cl( List all errors and their numbers )

:cc( Jump to specified number error )

:copen( Open the quick fix window , Show all errors in it , You can double-click on the error or press enter to jump to

This error ; See figure for an example  4)

Execute external command

stay “:make” In such an order ,Vim Will automatically call external programs . Users can also execute external programs themselves : It is estimated that many people already know how to use “:! command ” Can be in  Vim Execute an external command in . however , I guess most people don't know , There are other commands that can execute external commands , also , Even if “:!” There are also some techniques in the command . The most formal way to execute external commands , As mentioned earlier , Namely “:!”. such as , We want to display all the files in the current directory , It can be executed directly :“:!ls”.Vim File list will be done in a terminal window , Then prompt us to press the key to return to  Vim in .

in fact , This way is good for “cp”、“rm” This basically does not need to output the command is more practical , And for “ls” This kind of output focused command doesn't work very well . If you want to insert the result of external command execution into the current edit buffer , Consider using “:r!”. such as , We use “:r!ls”, You can put the “ls” The execution result of the command is inserted under the line of the cursor in the buffer . When using macros , This can be particularly useful .

Vim Of “:!” Command has a particularly powerful technique to use . Take a practical example , We need to insert a number before each line of a file , How do you do that ?—— use  Vim Macro or script can do this , But it's not the most efficient 、 The most flexible way to work .Linux It's usually with  GNU  Of nl, It can be done in a very flexible way —— To number all non empty lines , It only needs “:%!nl”; To number all lines that contain empty lines ?OK,“:%!nl -ba”.

A little explanation . When you use visual mode to select a line of text and type “:!”( On the command line “:'<,'>!

”, Indicates that the scope of the command is the selected text ), Or use “:%!”( Indicates that the scope of the command is in the entire buffer

The text of ),Vim When executing the following command , The text line in the command range will be used as the standard input for the command to be executed later , And replace these lines of text in the current buffer with the standard output of the command execution . This is how the above command line works .

############################## senior ###########################################  Macro replace

vi  Not only can it be used  abbr  To replace words ,  You can also define the macro of the command .  It's hard to lose some orders ,

So I define them as  -  On ,  It's very convenient . These configurations can be written in advance to  ~/.vimrc

(windows  for  $VIM/_vimrc)  in ,  You don't have to write the colon in front of it .

:nmap :nohls               Unhighlight the searched string

:nmap w                   Move the cursor to a different window in command mode

:imap                 Run in input mode

:nmap :%s= *$==           Remove all extra spaces at the end of the line .

:imap               ditto


This command is very powerful ,  You can use this command to apply different configurations to different file formats ;  Sure

Automatically add a copyright notice when creating a new file, etc .  These commands are generally defined in  ~/.vimrc  Such a configuration file

Inside .  Because he's powerful ,  So I can't give a very specific explanation ,  Just a few examples ,  Please see help for details .

:autocmd!                Delete all previous autocommands .

autocmd FileType        java  source ~/.vim/files/java.vim

autocmd FileType        java  source ~/.vim/files/jcommenter.vim

The above two commands let me open  java  The two configuration files mentioned later will be applied only when using the file .

autocmd BufNewFile      *.java  0r ~/.vim/files/skeletons/java.skel

The above command makes me create a new  java  Automatically add to the file  java.skel  The content of the document .

autocmd BufNewFile      *.java  normal gnp

The above command makes me create a new  java  Automatically run on file  gnp  command ,  This command makes some specialization

Handle ,  For example, new  java  In the document  __date__  Replace it with today's date or something .

PARTII  The configuration file

At startup vim Will read  /etc/vimrc  and  ~/.vimrc ( in other words ,  Global settings vimrc  And user settings ). In general, users set their own settings home The directory .vimrc It's enough

“ Behavior comment line starting with double quotes , The same below

“ Get rid of the annoying ones vi Consistency patterns , Avoid some of the previous versions of bug And limitations

set nocompatible

“ According to the line Numbers

set nummber

“ Detect the type of file

filetype on

“ The number of lines recording history

"set history=1000

“ The background is black

set background=dark

" High brightness display

syntax on

“ The next two lines of code , It's very useful in formatting ;

“ first line ,vim Use auto alignment , That is to apply the matching format of the current line to the next line ;

“ The second line , According to the above format , The intelligent choice of the right way , For similar C It's very useful in language writing

set autoindent

set smartindent

"C Language alignment , It's best to use it

set cindent

“ The first line sets tab The key is 4 A space , The second line is set to be used when interleaving between lines 4 A space

set tabstop=4

set shiftwidth=4

" Replace... With a space tab, Be careful make Sometimes documents have to be used tab, It can't be replaced by spaces

"set expandtab

“ Set match mode , Similarly, when a left bracket is entered, the corresponding right bracket will be matched

set showmatch

“ In the editing process , Show the status line of the cursor position in the lower right corner

set ruler

“ By default , Looking for a match is high brightness display , This setting turns off highlighting , It's better to define shortcuts

"set nohls

" Turn on the highlight

set hlsearch

“ It's very convenient to query , To find book word , When input to /b when , Will automatically find the first

“ individual b The first word , When input to /bo when , The first one will be found automatically bo The first word , In accordance with the

“ Secondary analogy , When searching , Use this setting to quickly find out , When you look for words to match

“ when , Don't forget to return

set incsearch

" Set backspace key

set backspace=2

"set backspace =indent,eol,start

" No file backup

set nobackup

" Don't exchange files

set noswapfile

“ Remove vim Of GUI In version toolbar

"set guioptions-=T

“ When vim When editing , If the command is wrong , It makes a noise , This setting removes the noise

"set vb t_vb=

" Set file encoding type , Completely solve the problem of Chinese coding

let &termencoding=&encoding

set fileencodings=utf-8,gbk,ucs-bom,cp936

set fenc=utf-8 " default fileencoding

set fencs=utf-8,gb18030,gbk,gb2312,cp936,ucs-bom,euc-jp

:set list Can be used to display invisible characters

Reference material

1、vim You can find the Chinese Manual of

You can plant one of them PDF edition , It's very detailed , Strongly recommend :)

2、CU Post of

Reprint :

vim More articles about common operation and skills

  1. VIM Common operation manual

    VIM Common operation manual 1. Multi line operation , Multiline comment , Multi line uncomment 2. Common operations ...

  2. vim Common operation skills and configuration

    vi yes linux And unix Common text editor under , Its operation is stable , Easy to use , This article will be divided into two parts: the configuration and the common operation skills , It refers to some articles on the Internet , Thank you to the author PART1  Operation skills explain : In the following example   ...

  3. [ Editor ]vim Common operations

    I am a ide Users of , about vim One stays in : open . see . Write . Turn off basic operations , Because now more contact linux The server , So in order to improve efficiency , The use of good vim It's a necessary skill ! Here is a list of vim Common operations of , Use it as a reminder ( Constantly updated ): ...

  4. VIM Summary of common operations

    VIM The commonly used model is not the same on the Internet , But it's the same , Let's roughly divide it here , It is convenient to summarize later 1. General pattern The default mode after opening the file , You can only move the cursor at this time , Cannot edit 2. The input mode General mode press i, You can enter input mode , Input ...

  5. 【linux】vim Common operations and vim Plug in installation and use

    vim yes linux The next great text editor , stay linux The developer should be familiar with vim Common commands . 1.  Open on page n That's ok vim +143 filename.txt 2. Read only mode on vim -R / ...

  6. Linux(Ubuntu) Common commands ( 5、 ... and )—— vi/vim Common operations

    vi/vim Common commands vim In fact, that is vi Upgraded version ,vi All the orders in the book vim You can use it all in , Generally speaking, it makes little difference . notes : This article is case sensitive ! vi / vim The relationship of the three-level model : Command line mode anytime , No matter ...

  7. Linux Next Vim Common operations

    linux Next Vim Common operations of linux ​ First \(ctrl+Alt+t\) Open the little box ​ \(./\): It's the equivalent of \(home\) key ​ \(ls\): The contents of the current folder ​ \(mkdir\) ...

  8. Vim Common operations - Merger line .

    Rigid contact Vim I think its learning curve is very steep , There are a lot of commands to remember . So the sharing of this series , It won't teach you how to configure it , It's about teaching you how to use it quickly . In development, for the sake of code beauty , You often display attributes in a newline way . <el-di ...

  9. 【Linux】 Text editor Vim Introduction to common operations

    Linux Common text editors :Vi & Eamcs Vim -- Vi Updated version of Vim One .3 Working mode Command line mode (Command Mode) Insertion mode (Insert Mode) -- key ...

Random recommendation

  1. Java Common classes that you must understand in

    1.Java The wrapper class We are all familiar with the basic data types , for example :int.float.double.boolean.char etc. , Basic data types don't have the characteristics of objects , Cannot call method , Generally, the functions that can be realized are relatively simple , In order to get the basic data ...

  2. sqlserver Spatial data types

    --. Create a table with spatial data create table x ( v ,) primary key, geog geography not null, geogWKT as geog.STAsText() ...

  3. Python3 Learn the third bullet : How to deal with the abnormal situation ?

    python The way we deal with errors : 1> Assertion assert condition amount to if not condition: crash program The purpose of assertion setting is to make the program crash later , ...

  4. Trie Tree template ~~~

    * + ; ; // The alphabet is all lowercase letters Trie struct Trie { int ch[maxnode][sigma_size]; int val[maxnode]; int sz; // junction ...

  5. css Remove webkit The default style of the kernel

    As a friend of mobile terminal, you should know ,iphone The default button is a disgusting fillet ,select Drop down boxes also have default styles that cannot be modified . You can use -webkit-appearance:none // Remove the default sample On the button and sel ...

  6. SRAM And SDRAM Comparison ( turn )

    original text : Memory plays an important role in the computer , Semiconductor memory cells are commonly used , Including random access memory (RAM), Read only storage ...

  7. CodeIgniter combination Bootstrap

    CodeIgniter-Bootstrap Combined with the cI and bootstrap Strengths , One focuses on the server side , One focuses on ui, This one 2 It's a combination of . Frame address : http://www.andyhawthorne ...

  8. POJ 2635 The Embarrassed Cryptographer( Large number complement )

    The question : Give a large number , This large number is obtained by multiplying two prime numbers , Let's see if one of the prime numbers is better than L smaller , If both are small , The one with the smaller output . analysis : The method of finding the remainder of a large number : For example in the title ,143 11, We can do this ,1 % 11 ...

  9. VS 2017 Development ASP.NET Core Web One of the major problems found in the application process Bug

    Try to use it today VS 2017 To develop a .net core project , I want to have a look .net core Development and MVC5 What's the difference between development , And then I found one VS2017 Of Bug. First , We're building new projects ,ASP.NET Cor ...

  10. ASP.NET There is no magic —— first ASP.NET application 《MyBlog》

    Create a ASP.NET MVC Applications In the previous article, I introduced ASP.NET Provided in 3 A framework for developing dynamic web pages , Namely Web Form.MVC as well as Web Pages, It also introduces their characteristics . among MVC For its ...