Vim has been a controversial topic among programmers. Some think it is the god of editors, others think it is outdated, far less than IDE, or graphical text editor represented by the popular vscode. Whether we love her or hate her, our development work, from remote login server coding, to modifying config files, to git commit message, is more or less always contact her.

The reason for writing this blog is that I find the vim tutorial blogs that abound on all platforms to be rather unfriendly, mostly command-heavy with little interpretation of ideas. As a result, many engineers are always in awe of Vim, or even if some people can use ViM, they just use their own inherent thinking and combine viM’s commands to operate, without really mastering the essence of ViM. Therefore, I try to use my own way to help everyone to systematically establish viM’s knowledge system.

The main structure of the paper is as follows:

  • First introducedvimThe editor is the simplest, basic operation that allows you to quickly get started in the encountervimWhen, can not panic, calmly complete the task. If you think of certain operations, such as the common copy and paste operations, you can go to Part 2 to find the corresponding higher-order operations and use them step by stepvim.
  • Next, it will be introducedvimA series of advanced operations to maximize our efficiency. Note: This part is very informative. It is recommended that you quickly browse the unfamiliar commands after reading this part to get a good idea of them. Then you can move on to part 3; Go back and take it step-by-step. Learn as you go.
  • Finally, try to tellvimThe essence of thought is what makes us truly rightvimThis integration allows us to apply these ideas to other IDES/editors, and even to our own design and implementation of features and components. That’s when you really have the artifactvim.

model

Vim has three modes, namely normal (normal) mode, insert mode and command mode.

  • Common mode: Browse files and copy, paste, and divide files.
  • Insert mode: mainly used to input, modify, delete characters, at this time of operation, in addition to the mouse, with our daily operation in the editor. In common mode, yesiEnter insert mode.
  • Command mode: To execute some input and execute some instructions provided by VIM or plug-in. Input in normal mode:After, you can find that the lower right corner of the screen will appear:“Then the command mode is entered. This article uses:The command at the beginning is considered input:Enter the following characters to run the command.

This is where many people’s first doubts about Vim come from. We’re used to the graphical editor being inserted all the time. In VIM, however, for the most part, we’ll be in normal mode. Enter insert mode only when characters need to be entered; Enter command mode when you need to use a command. In insert and command mode, type Esc to return to normal mode. A diagram is summarized as follows:

Note: If there is no special explanation, the operation is in normal mode.

Basic operation

If you do not pursue efficiency, just want to complete the task of modifying the file, save and exit, only need to master the following three commands:

  1. Mobile:h j k lThe simplest movement, which corresponds to the arrow keys on the keyboard, corresponds to the lower left, upper right.
  2. Enter insert mode:i
  3. Save exit:ZZ(Case sensitive)

The process is as follows:

  1. In common mode, yesh j k lMove to the position you want to modify
  2. The inputiEnter letters, digits, and symbols, and delete Backspace to complete basic modification operations
  3. EscBack to normal mode,ZZTo save the Settings and exit.

Advanced: Command form

In common mode, vim commands are classified into the following three types:

  1. Actions to move the cursor or define the scope of the action; Such as:

    1. h: Defines the operation range as one space. When used alone, move the cursor one space to the left.
    2. w: Defines the scope of action as a word and moves the cursor to the beginning of the next word.
  2. Operations, which need to be followed by instructions indicating the scope of operations;

    1. d, delete, followed by the range of operations of a wordw, i.e.,dwIs deleted to the end of the current word.
    2. c, modified, followed by that indicating the scope of operation of a wordw, i.e.,cwIs used to modify the current word. (Editor behavior is to delete to the current end of the word and enter insert mode).
  3. Commands, directly executed commands, part of which, after executing the command, directly into the editing mode; Such as:

    1. DTo the end of the line.
    2. ITo enter insert mode at the beginning of the line. There are three main ways to use it: command, action and operation + action. In addition, inactionClass command, plusnumberIs optional and can be implementedRepeated n timesThe effect of:
  4. [number] + h/j/k/ L Move number characters left/down/up/right. For example, ‘2j’, move the cursor down 2 characters.

  5. For example, d is delete, w is word, dw is delete one word, d2w is delete two words. The command behind, most can be used in this form of combination, we pay more attention to develop this operation + [times] + range of thinking mode, by drawing infersions from one another, can play the greatest effect.

Move into the order

Word level movement

There are two groups of commands with different case only. The function of the two groups of commands is the same: to move the cursor to the corresponding position. But the corresponding units are different, which are word and string respectively. The specific differences are:

  • Strings are separated by Spaces only;

  • Word is separated by characters other than alphanumeric.

    Take this string for example: hello world-hehe111 abcde

  • Word has 5, respectively hello World, -, hehe111 and abcde.

  • The string has three characters: hello world-hehe111 and abcDE.

Two sets of commands are as follows :(jump cursor to)

  • wNext word begins
  • eEnd of current or next word
  • bThe beginning of the current or previous word
  • geThe end of the last word
  • WThe beginning of the next string
  • EEnd of current or next string
  • BThe beginning of the current or previous string
  • GEThe end of the previous string

For example, when the cursor is on the first character h of hehe111, the following word/string information precedes it:

Before a The current After a
The word hehe111 abcde
string hello world-hehe111 abcde

The result of each of the above commands is clear (bold text indicates the cursor position after the command is executed) :

Sentence, paragraph level movement

  • 0 moves to the head of the current line

  • ^ Moves to the first non-null character of the current line

  • $moves to the end of the current line

  • Jump to the beginning of the current or previous sentence

  • ) Jump to the end of the current or next sentence

  • {jump to the beginning of the current or previous paragraph

  • } Jump to the end of the current or next paragraph

  • The paragraph here is easy to understand, separated by a blank line. Sentences are more complicated and are counted by periods.

  • Remember to add d before these commands to see what happens, and master the action + range command form.

Page level movement

Move the cursor by row
  • ggMove to the beginning of the first line of text
  • GMove to the bottom line of the text
  • [n] + %: Approximates a percentage to a line located in the entire filen%place
  • [n] + gg/GJump to the firstnOk, often.

To use these commands well, there are two simple tips:

  1. Combined command:ctrl-g. This command displays the position of the current line (line number, as a percentage of the total number of lines of text).
  2. Enter the following command in command mode, or~/.vimrcAdd the following code snippet to
Set cursorline </pre>Copy the code
Move the cursor within the page
  • H: The top line of the screen
  • M: Central bank chief on screen
  • L: First line at the bottom of the screen
Scrolling and page-turning
  • ctrl-d/u: Half a page forward/back
  • ctrl-f/b: Full page forward/back
  • ctrl+e: Roll a line up
  • ctrl+y: Scroll down a row
  • zt: Move the cursor to the top of the screen (everything moves)
  • zz: Moves the cursor to the center of the screen (everything moves)
  • zb: Move the cursor to the bottom of the screen (everything moves)

matching

  • F + A single character: Moves to the right of the specified character on the line
  • F+ A single character: Moves to the left of the specified character on the line
  • T + a single character: Moves to the right on the line before the specified character
  • T+ a single character: Moves to the left on the line before the specified character
  • %: Toggles between the beginning and end of (), [], and {} symbols
  • *#: Matches the word where the cursor is currently, and moves the cursor to the next (or previous) matching word (* is next, # is last).

Mark

  • m+[a~z]: Marks the current cursor, such as MA
  • '+[mark]: returns the line where the specified marker is, as in'a, the cursor returns to the tagaIn the beginning of a line
  • “‘ “+[mark] : The cursor returns to the specified mark
  • ctrl+o: Jumps back to one position before the cursor
  • ctrl+i: Jumps back to the new cursor position
  • You are advised to combine the following two commands in command mode for better experience:
    • :marks: Displays all marks
    • :delmarks [mark]: Deletes the mark

Edit the advanced

Go into insert mode

Enter insert mode at different locations
  • i: Inserts characters before the cursor
  • I: Inserts a character at the beginning of the line
  • a: Inserts characters after the cursor
  • A: Inserts a character at the end of the line
  • o: Inserts a blank line under the cursor
  • O: Inserts a blank line above the cursor
Use the modify command to enter insert mode
  • C: Modify, need to be followed by the range

  • C + W: Deletes the cursor position word and enters insert mode

  • C + L/S: Deletes cursor position characters and enters insert mode

  • C + C/S: Deletes the line where the cursor is located and enters the insert mode

  • C +$/ c: Deletes the character where the cursor is at the end of the line and enters insert mode

  • R: replaces the current character.

  • R :(into replace mode) continue to replace the character where the cursor is until ESC is used to exit replace mode.

delete

  • X: Deletes characters at the current position or the next position.

  • D: Delete, belong to action instruction, need to add operation instruction after. For example:

    • de: Deletes the end of the current word.
    • dw: Delete to start with the next word.
    • Note that here anddeThe difference is,dwDeletes Spaces between words.
    • daw: Removes a word, including word boundaries (Spaces).
    • d0: Deleted to the beginning of the line.
    • d$ / D: Deletes to the end of the line.
  • Da [: removes [] the entire block, including the symbol itself;

  • Di [: removes the [] block, excluding the symbol itself;

  • Da /di + ‘” {(etc., also similar to the line [, delete the whole block. The only thing to note is, “and’ only in line.

  • Dt [x] : On this line, delete to [x]. For example, dt” to double quotes, DTF, to the letter F. D /foo: In full text, delete to “foo”.

shear

The cut operation is actually the delete we talked about earlier. So that’s d. Deleted content is saved to the clipboard by default. That’s the same thing as cutting.

Advanced operators

As you can see from this, I and A have a special role, representing some kind of operation related to the block. The difference is that I does not contain a block boundary symbol. Contains a. These two operators are important and will be used later in the copy operation. And then there’s t, PI over PI. In addition, I and A can be followed by T, where T represents a pair of XML tags. I: block, without boundary. A: Blocks, containing boundaries. T: “to”, where do I go? / : Matching, full text to where.

paste

  • p: Paste after the cursor or on the next line.
  • P: Pastes to the front of the cursor or the previous line.

Why is there a line before or after the cursor? Because what we copy or cut might be a string or an entire line:

  • If the content is a string, paste it before and after the cursor.
  • When the content is copied as a whole line, paste to the top/bottom line.

copy

  • y, replication, belongs to the operation, must be followed by action to identify the scope of replication. Such as:
    • yw: Copies to end of current word.
    • ye: copies to the last character of the word from the current position.
    • y$: copies to the end of the current line.
    • yyorY: Copies the current row.
    • nyy: Copies the n lines from the cursor, noting that n is first.

Y $: command means:

  • 0→ First to the wardrobe
  • y→ Copy from here
  • $→ Copy to last character on line

You can also use the advanced operators we just introduced:

  • yi": Copies between two quotes
  • yit: Copies between two XML tags
  • y/[x]: Copy to x.

clipboard

Vim has 12 shear plates, which are 0, 1, 2… A + b + c + D :reg: View the contents of each clipboard. Y, p defaults to “clipboard content. “[n]y: Copy to clipboard N.” [n]p: Paste the content in clipboard N.

Check whether the system clipboard is supported:

vim --version | grep "clipboard"
Copy the code

Watch the output to see if the clipboard is preceded by + or -. If the value is -, the system clipboard is not supported. The + shear plate is a special system shear plate for interaction with other applications in the system:

  • "+y, copy the content to the system clipboard,CTRL + vPaste it into another application, for examplevs code.
  • "+p, paste content copied from other applications into VIm.

Visual model

V: Enter visual mode. V: Enter the row selection mode. Crtl + V: Enter the block selection mode.

Once you’re in visual mode, you can select from the previous move. For example: HJKL: front, back, left and right. $: Selects to the end of the line. I “: Select between two quotation marks.

After selection, you can use it

  • dTo delete/cut,
  • yMake a copy.
  • You can also use the following interesting commands:
    • gU: Uppercase.
    • gu: Write smaller.
    • J: Join all the lines together.
    • <>: Indent left and right.
    • =: Automatic indentation.

formatting

= : Adjusts formatting indentation. Gg =G: Full-text code formatting.

  • gg“To the beginning of the article
  • =, adjust the format
  • G“To the end of the article.

Automatic completion

In edit mode, Ctrl + N/P will prompt you, and the option of completion will appear. Hold Down Ctrl and iterate through the options with n and P. When you reach the desired option, continue typing without further action.

undo

  • u: Undoes the previous action
  • U: Undoes a sequence of actions for the current row
  • CTRL-RRedo means I don’t want to Redo it.

To find the replacement

  • /: Search. Terminal will appear at the lower left corner/, enter the content you want to find in the back, press Enter.
  • ?: Reverse lookup, same thing, will appear in the lower left corner?.
  • /[search]\c: Case is ignored. Such as:/test\c, find test, ignore case
  • n: Next match
  • N: Matches the previous one

In command mode:

  • s/old/new/:newreplaceold
  • s/old/new/g: global replacement
  • set hlsearch:The highlightedThe search results

Macro recording

Qa operation sequence Q, @ A, @@

  • qaRecord your operation in a registerA.
  • so@aReplay recorded macros.
  • @ @Is a shortcut used to replay newly recorded macros.

The command

  • :w: Save the changes
  • :wq: Save the Settings and exit
  • ZZ: Save the Settings and exit
  • q!: Forcibly exits without saving the modification
  • e!: Forcibly opens the current file without saving the modification

As you can see,! And that’s what it does. In addition, it has another very powerful function, which is to execute shell commands. For more information, you can read the next section.

  • .: Repeat the previous command. This command is flexible and useful, so try it more often.
  • :help [command]In addition, execute the following command from the command line to enter the vim tutorial.
vimtutor
Copy the code

External command

This is an amazing feature of Vim that allows you to interact with external text and even execute shell commands while editing.

  • :w [file-name] : outputs the current content to a specified file

  • :r [file-name] : outputs the contents of another file to the current location

  • :e filename: vim Opens the specified text

  • CTRL + W, S: Split window horizontally

  • CTRL + W, V: Split the window vertically

  • CTRL + W, ARROW(h,j, K, L or ARROW keys) : Toggles the cursor between Windows.

  • CTRL + W, w: Toggles the cursor between Windows.

  • : QA: Close all Windows.

  • :saveas :saveas.

  • :n/bn/bp: toggles between open files.

  • :! [command] : Executes a shell command in vim.

  • Such as:! Ls, which temporarily switches to the shell and outputs the file name of the current directory. Enter enter at this point to return to the current vim edited file.

If that’s not enough for you, Vim also offers a way to leave the current work scene and go straight to the shell. A typical working scenario of this command is that when we edit a file and find it cannot be saved (without write permission), we can first enter shell and run a command like chmod u+w [filename] to obtain write permission for the file for the current user, and then go back to Vim to save the modification. There are two methods:

  1. :shell:sh, when exiting the current shell (e.gexit), will return to VIm.
  2. ctr-zInto the shell,fgReturn the vim.

Config

This section is mainly some vim config. You can directly command mode input, or save to ~/. Vimrc, you can open vim automatic application every time. (Some of the commands are conflicting, please choose the ones that are useful).

Nonu [mber] # Hide line number set cursorLine # Highlight current line set ruler # show cursor position information set noruler # Hide cursor position information set HLSearch # highlight match set NohlSearch # unhighlight match nohlsearch # temporarily unhighlight (unhighlight query only once) set IncSearch # Display match point set during input string Set IC /noignorecase) # noic/noignorecase # case sensitive </pre>Copy the code

VIM thought

This part is mainly about my thoughts and feelings in the process of using VIM, and I try my best to explain them. If you can have some thinking and harvest, it shows that my thinking is meaningful. If you have different views, very welcome clap brick exchange.

Why Normal

  • Why would viM give up the insertion mode that people are used to and use the command mode? If you think about it, the reason is simple: before the mouse, people had to rely on the keyboard to move the cursor and modify text.
  • Why do we use normal mode now that we have a mouse?
    1. Work content coverage. Every one of us thinks that the job of an engineer is to write code. However, our main job is actually to read, or understand, code. According to a survey of engineers, the ratio of reading to writing Code in their daily work is 10:1 (see Clean Code). Therefore, the default common mode mainly meets the larger proportion of “read”; When you need to modify, enter the edit mode.
    2. Lots of shortcuts. I believe everyone knows at least one set of shortcut keys:ctrl-c/vCopy & paste every time you copy and paste. Every time you copy and paste, you’ll copy and pastectrl-a/x/s/wAnd so on. I don’t know if you’ve noticed, but a lot of the shortcuts I’ve just listed are made up ofSpecial command character + letterComposition. Because at this point, most of the keys on the keyboard are okCharacters entered into text. And in thevimCannot directly enter these characters into the file, equivalent toDon’t press thectrlAnd other special command charactersYou can directly use these keys as command shortcuts.

Reasonable keyboard shortcuts

  • Shortcuts in VIm, the layout is very reasonable. Adjust the distance from hand to hand according to the frequency of use. For example, the most basic movement operation, keep at handHJKL. While moving your hand to the d-pad on the keyboard doesn’t really waste much time, it disrupts your thinking and can be very inefficient.
  • Shortcut key Settings, is also very reasonable, combined with the meaning of the word, pronunciation, very easy to remember. Such as:
    • d delete
    • c change
    • w word
    • e end
    • b back
    • I edit
    • f find
    • r replace

Fine, multi-dimensional command

There are keyboard shortcuts, all dimensions of movement, and the user’s mind can be almost anywhere. For example, move, delete, copy, etc., can be combined with refined location, according to the different dimensions of the human mind, operation. For example, characters, words, lines, articles, screens, matches (positions, text, symbols), and marks like bookmarks.

Atomic, combined commands

Most of vim’s shortcut keys are atomic operation, and through the combination of scope, permutation and combination, flexible, complete a variety of powerful functions. This also fits with the main Unix idea: do each command well, and only do the same thing. At the same time, by replacing meaningless repetition with numbers and macros. In addition, for some common operations, provide ready-made macros, easy to operate. For example, dd, which deletes an entire line, can also be done directly with D. I, A, and so on.

External command

Similar to the stack idea, you can drop the current operation, save the scene, and then enter another operation. When the operation is complete, return to the current site.

Thinking mode

Vim’s shortcuts, or commands, not only fit our minds, they expand our minds to a great extent. Take moving the cursor, which is the most common operation in editing code. It turns out that our movement is basically through the arrow keys of the keyboard, up and down around, or through the mouse, to move to the desired position. In vim, you will find that the cursor is in addition to the up and down or so, you can also move to the first word, suffix, foregrounding, the other end, the beginning of a line, the end of each line, page first, central page, page tail, document first, document the tail, document any one line, you can even move to a specified letters, a tag, matching large, medium and small brackets. After the initial discomfort, through deliberate practice and daily use, the muscles form memories so that they do not have to recall what command was used, but do it subconsciously. Once you’ve mastered these commands, you’ll look for these shortcuts when using the original editor. This not only provides efficiency when using Vim, but also improves overall productivity by raising awareness and thinking about editing operations.

After using Vim for a while, when I was editing in other tools, the editor couldn’t stand it anymore and moved the cursor one by one. So will also take the initiative to find the word, line level movement of the shortcut key.

  • Mac system
    • Please CMD + / - >Move to: start/end of current line
    • Alt + please / -Move to: start/end of current word
  • Iterm:
    • ctrl + f/bOne character forward/back
    • Esc + f/bOne word forward/backward
    • ctrl + a/eStart/end of line
    • ctrl + h/dDeletes the character before/after the cursor
    • ctrl + wDelete the word before the cursor
    • ctrl + k/uDelete everything before and after the cursor
    • ctrl + yPaste previously deleted content

Afterword.

Here is the end of this article, written so much, a read down to accept, difficult; It’s harder to master just by reading. To really use VIM and master ideas, more thinking and practice are needed. But trust me, it’s worth it. Not only does it give you a development tool, but it also gives you valuable ideas.