Every programmer has a code editor they dream about. In front of the many glamorous editor idol groups, Vim looks like an unvarnished country girl, so simple and unpretentious at first glance, it is hard to fall in love with her. But as long as a little closer, to a close contact, and will be captured by her like water tender feelings.

This is from Qingbi’s own experience. The company’s technical director is parachuted in from Tencent and occasionally shares his development tips. “I love Vim!” he says of the editor, a faint blush on his face. . Despite the fact that we all introduced him to vscode, the beauty and talent of the moment. But he still had a heart, unmoved.

Many times, I wondered what magic this “plain looking” Vim had that could hold the director’s heart firmly. After I really went into her heart and spent many nights with her. I finally fell in love with her freshness.

Let’s learn more about this mysterious woman.

1. The history of vim

Here is a picture found online. If you are interested in the history of VIm, you can refer to the Wikipedia entry vim (Text Editor).

En.wikipedia.org/wiki/Vim_ (t…

The standard editor on early UNIX operating systems was Ed, a line-oriented editor that showed only the currently edited line. In 1976, Bill Joy extended Ed to support full-screen display and editing, named EX. Ex is a superset of Ed, and the extended function is enabled by entering the command vi on EX. Later, this command was used so often that it was isolated from the command line editor vi that is now preinstalled on Linux (including macOS) systems. It wasn’t until 1991 that Bram Moolenaar developed an improvement version of VI, called VIM (meaning: VI Improvement), and released the first version of VIM on November 4 of that year. Below is a news item from the front page of vim.org, vim’s 27th birthday was celebrated on November 4 last year.

2. Built-in tutorials

Vim comes with a tutorial for beginners. The tutorial can be started with a standalone subroutine, vimTutor.

If you already have Vim installed on your system (macOS comes with Vim and some Linux distributions may need to install it manually), you can start the tutorial by typing the vimTutor command directly on your terminal.

vimtutor
Copy the code

The tutorial is actually using Vim to open a text file on the system. File is usually in/usr/share/vim/vim80 / tutor/directory. Of course, there are a number of files in this directory, each containing a different language version of the tutorial. The difference with VimTutor is that you can automatically open the language version of the user’s location.

The simplified Chinese see above is the actual file/usr/share/vim/vim80 / tutor/tutor. Zh_cn. Utf-8.

So, you can make a copy of it and put it in your current directory, open it with Vim, practice, and edit it as you like.

cp /usr/share/vim/vim80/tutor/tutor.zh_cn.utf-8 ./
vim tutor.zh_cn.utf-8
Copy the code

But if you follow the tutorial, you feel most comfortable using it: Open both terminals at the same time, one uses VimTutor to open the local tutorial for viewing, the other copies the English version of the tutorial to the current directory, and then uses Vim to practice editing on the English version of the tutorial (since our actual application scenario is mostly in English, including editing code and configuration files).

Copy the English version of this tutorial and edit it:

cp /usr/share/vim/vim80/tutor/tutor ./
vim tutor
Copy the code

3. Working mode

For developers who are used to GUI editors, it’s easy to get confused by the way Vim works when they’re new to it, and they’re likely to abandon it altogether. But if you do, you take everything for granted. According to Wikipedia, vim has 12 different modes, but only 6 basic modes. The remaining 6 are variations of the basic mode. However, there are only two types of modes that we encounter most often: command mode and edit mode. The command mode is subdivided into Normal (default) mode and Cmdline (bottom command line) mode. Normal mode is the default mode for starting vim, and in any mode, pressing ESC (top left of the keyboard) will return you to this mode, similar to the Home button on your phone. Therefore, when you start to get confused about what mode you are in, the best thing to do is to press ESC to return to Normal mode. Most of the commands we use with Vim run in Normal mode, whereas the Cmdline mode is usually only used for exit and save, so when we talk about command mode, we are referring to Normal mode unless otherwise specified. In addition, this article refers to Cmdline collectively as the command line pattern.

The following figure shows the three modes of switching:

If I had to summarize the usage scenarios of these three modes, it would be: cursor navigation, copy and paste delete, undo redo, and find and replace in command mode; In edit mode, write code or create; In command line mode, enter q to exit, w to save, and wq to save and exit. Of course, this is not the whole operation, but familiar with the operation, you will be able to use ViM in a comfortable way.

4. Command mode

4.1 Moving the Cursor

To skillfully edit code and text with Vim, you first need to be able to accurately and quickly position the cursor where you want to edit. The basic thing is to move the cursor up and down. This can of course be done using the keyboard’s four arrow keys. But it’s more common to use four consecutive keys h, J, K, L in the alphabetic input field. In fact, when you touch the keyboard with a standard gesture, your right index finger touches the J key (it has a bump). Therefore, under the gesture of you to keep the normal input, let nature take its course on the index finger, you can move the cursor down one line, and close to the middle finger contact k key, and j is the opposite of the operation, the cursor move up a line, you will find this very convenient to use, it is to understand why use a letter keys to move the cursor operation. Of course, in command mode, pressing the letter key will not change the edit as input.

  • h: Moves one character to the left
  • l: Moves one character to the right
  • j: Moves a row down
  • k: Moves up a row

Although you can use the h and L on the left and right sides of j and k to move the cursor left and right. This is also handy when moving only one character at a time. But if you move a word to the left or right (word), using h and L is a little clunky. The way to move a word left (back) and right (forward) is as follows:

  • w: Moves a word to the right or forward with the cursor at the beginning of the word
  • b: Moves a word to the left or back with the cursor at the beginning of the word

Command mode Press the letter W to move the cursor one word to the right:

Command mode Press the letter B to move the cursor one word to the left:

To further enlarge the range of a single cursor movement, move the cursor forward and backward by sentence and paragraph. Two pairs of brackets (and) move the cursor backward and forward by one sentence, and two brackets {and} move the cursor backward and forward by one paragraph, respectively.

  • (: Move a sentence backwards with the cursor at the beginning of the sentence
  • ): Move a sentence forward with the cursor at the beginning of the sentence
  • {: Move a paragraph backwards with the cursor at the beginning of the paragraph
  • }: Moves a paragraph forward with the cursor at the beginning of the paragraph

Command mode press) and (move forward and backward a sentence:

Command mode Press} and {move a paragraph forward and backward:

You can also quickly move the cursor around the screen. Use capital H, M, L, respectively. However, these three types of positioning are not very precise, and are usually used for fast large-scale positioning, and then use the previous command for more precise positioning. Readers can try it for themselves.

  • H: Position the cursor to the far left of the top line of the screen
  • M: Moves the cursor to the middle line of the screen
  • L: Moves the cursor to the bottom line of the screen

Another familiar scenario is that when the debugger throws an exception, the line number of the exception is displayed, and you need to quickly position the cursor to the specified position based on the line number. This command is a bit more complicated than the previous one, requiring you to enter one or more numbers representing the line number and then press the capital G to do so. For example, move the cursor to line 80 of the file. Type 80 in command mode and then quickly press G.

4.2 Delete/Revoke

One of the reasons for putting delete and undo together is to consider the fear of trying to delete because you don’t know how to undo the delete yet (although we have made a backup beforehand, this should be a common psychology and human fear of losing). We know we can undo, so we feel “safe” about deleting. You may not think so, but it still helps us practice and remember better (we can do erasure over and over again).

Like cursor movement, deletion can be done in different granularity. Delete single characters, words, lines, sentences, paragraphs, and screen ends. The delete operation consists of the letter D followed by an identifier indicating the scope of the delete. At the same time, the specific range of deletion is also determined by the specific position of the cursor. For example, if the cursor appears on the second character e of the word hello, press D and W continuously in command mode to delete the entire word starting from e, but the h before e will not be deleted. The result of deleting the word is that there is only one letter H left. Other granular deletions follow a similar pattern.

Delete a single character

There are two ways to delete a single character. Both are equivalent in that they delete the character where the cursor is, but using x is easier because you only need to type one letter.

  • x
  • dl

Delete the word

  • dw: Deletes to the end of the word (including the character where the cursor is located), starting at the cursor position
  • dbAnd:dwDelete in the opposite direction, that is, delete the character before the cursor position (excluding the character at the cursor position)

Delete rows

  • dd: Deletes the line where the cursor is located
  • 3dd: Delete 3 lines starting from the cursor, of course this is an example, you can change the preceding number to delete any number of lines

Delete 3 lines at a time:

Delete to end of line

If you don’t want to delete the whole line. Instead, the characters from the cursor to the end of the line can be implemented directly with a capital D.

Delete characters from cursor position to end of line using uppercase D:

Delete from the beginning of the line

Instead of deleting to the end of a line, use d0 to delete from the beginning of a line:

D ^ and $d

If you are familiar with regular expressions, it should be easy to guess what both mean. D0, d0, d0, d0, d0, d0, d0, d0

  • d^: Deletes the character before the cursor that knows the beginning of the line,Don’tContains space at the beginning of the line
  • d$: removes characters from the end of the line from the cursor,Don’tContains Spaces at the end of lines

Delete sentences and paragraphs

Familiar with the previous deletion, the following sentences and paragraphs can be similarly deleted. The only difference is in the granularity of deletion.

  • d(: Clause head deleted
  • d): delete to the end of the sentence
  • d{: deleted from the beginning of the paragraph
  • d}: Delete to the end of the paragraph

Replace: Delete and enter

When we talk about delete we have to talk about replace. Because the two are like brothers, the actual replacement is like deleting the older brother, only one step more than deleting the younger brother. Is immediately after the deletion into the edit mode, in the deleted place to edit. These two combinations are just substitutions. Note also that the substitution changes the current working mode into edit mode, as discussed below, so after typing, you need to press ESC to return to command mode. The corresponding replacement command for deleting D is c. Therefore, replacing d with c in all operations described in delete is the corresponding replacement operation, of course, the details of the implementation will be a little different. But the difference is easy to understand after you’ve tried it yourself, so I won’t talk too much about it. Readers can try it for themselves.

Cancel the operation

In command mode, press the lowercase letter u (undo). You can press multiple times in a row to quickly undo multiple historical operations.

4.3 Copy/Paste

Copy of y

Copy using the letter Y. The usage is similar to that of delete d, except that y copies instead of deletes.

The following is an example of replication behavior. Replication of other granularity is similar to delete operation D.

The operation of copying the current line corresponding to DD deleting the current line is YY. Of course, multiple lines can also be copied, and the format is similar to deleting multiple lines. Prefix YY with the number of lines to be copied. For example, 3yy copies the three lines starting with the cursor.

  • yy: Copies the line where the cursor is located
  • 3yy: copies the three lines starting with the cursor. This is just an example. It can be any number of lines

Paste the p

The paste command is much easier. It doesn’t have that much granularity, and just inserts what has been copied after or before the current cursor. Use lowercase p and uppercase P.

  • p: Inserts the copied content after the cursor
  • P: Inserts the copied content before the cursor

4.4 Searching for a String

Enter a slash/(look down) or question mark in command mode? Move the cursor to the bottom line of the terminal, type the string you want to search for, and then press RETURN. First locate the found string, then press lowercase N to search for the next one, and uppercase N to search for the previous one.

5. Enter the editing mode

All of the commands described above are executed in command mode. If you want to start writing code or other text editing, you need to enter edit mode from the command line mode. Otherwise, any letters you enter (except those that can enter edit mode) will be treated as commands and not edited into the file.

The following six methods are available to enter the editing mode. The difference is only the position of the cursor after entering the editing mode.

  • i: Inserts before the current cursor
  • I: Insert at the beginning of the line
  • a: Appends after the current cursor
  • A: appends to the end of the line
  • o: in the line where the cursor isafterAdd a new row
  • O: in the line where the cursor isbeforeAdd a new row

6. Command line mode

In command mode, press colon: to display an input line at the bottom of the terminal, indicating that the terminal is in command line mode. Many of the commands supported by Vim itself can be used in command line mode. As already mentioned, the most commonly used are exit and save.

  • :q+ RETURN: Exit editing
  • :w+ RETURN: Save and do not exit
  • :wq+ RETURN: Save and exit

Also commonly used is setting vim. To run the following commands, press RETURN after entering them (similar to running commands on the terminal).

  • :syntax on: Turns on syntax highlighting
  • :set number: Displays the line number
  • :set tabstop=4: Sets the width of the Tab key
  • :set expandtab: Uses Spaces instead of tabs
  • :set softtabstop=4: Sets the software Tab (automatic Tab) width to 4
  • :set shiftwidth=4: Set the auto indentation width to 4
  • :set autoindent: Enables automatic indentation, usually used in programming

Of course, the above Settings for VIM only affect the viM currently open. To use the same Settings every time you open it, you need to save the Settings commands to the vim configuration file ~/.vimrc, as described in the next section.

In addition, you can use help to get help. For example, enter help user-manual + RETURN to view the user manual.

If the above are viM internal execution commands, then in the command line mode, it is also possible to call external shell commands. The method is an exclamation point! At the beginning, mark the exclamation mark! The command that follows is an external shell command. For example, to view files in the current directory, :! The ls -l. Press RETURN for the first time to hide the current editing area and display the terminal interface. Press RETURN for the second time to RETURN to the VIM editing interface.

7. Configuration file

As mentioned above, if you want to use the same interface and Settings every time you open Vim, you need to save the Settings commands in the configuration file. On Linux (including macOS), the recommended path is ~/. Vimrc. If it has never been set, the file may not exist yet. So we need to create one first. To not overwrite an existing one, we can use the following command:

test -f ~/.vimrc || vim ~/.vimrc
Copy the code

The shell command checks to see if ~/. Vimrc exists, creates a blank configuration file if it does not, and opens it using vim.

Alternatively, you can copy a configuration file on the system and add and overwrite the default configuration.

test -f ~/.vimrc || cp /usr/share/vim/vimrc ~/.vimrc
Copy the code

Here is a reference to qingbi’s own configuration file:

colorscheme default     "Set color theme syntax on"Syntax highlighting FileType on" 检测文件的类型
set number              "According to the line Numbersset ruler               "During editing, display the status line set lastStatus =2 with the cursor position in the lower right corner."Display status bar (default is 1, cannot display status bar)set statusline=\ %<%F[%1*%M%*%n%R%H]%=\ %y\ %0(%{&fileformat}\ %{&encoding}\ %c:%l/%L%)                        "Set tabstop=4"Width of the Tab keyset expandtab           Set softtabStop =4 set Shiftwidth =4"Uniformly indent to 4set autoindent          "Vim uses automatic alignment, that is, applying the alignment of the current line to the next line (automatic indentation) set cindent"Cindent is an automatic indentation for C syntax.set smartindent         "According to the above alignment format, intelligent choice of alignment, for similar C programming useful set scrolloff=3"Keep the cursor 3 lines away as it moves to the top and bottom of the bufferset incsearch           "Display search results when entering search content set hlSearch"Highlight the text found when searchingset foldmethod=indent   "Set indent foldlevel=99"Nnoremap <space> @=((foldclosed(line('. ')) < 0)?'zc' : 'zo')<CR>
                        "Use the space bar to switch on and off folding."Automatically jumps to the last exit positionif has("autocmd")
    au BufReadPost * if line("' \" ") > 1 && line("' \" ") <= line("$") | exe "normal! g'\"" | endif
endif
Copy the code

More information about configuration files can also be found in vim’s built-in help manual. The configuration manual is USR_05. To open the manual, type :help usr_05 (colon for command line mode, press Enter).

conclusion

This paper starts from the development history of VIM and takes the basic operations of mastering viM editor to meet the daily code writing as the main line. It explains the necessary skills such as mode switching, cursor navigation, delete, undo, replace, copy, paste, text insertion, and configuration editor appearance Settings in VIM. Of course, vim supports many more operations and commands. This article only covers the basics. But it’s the feature we use most often for code editing. Once you’re good at it, you can look into the manual for more tips. The way to view the manual has been given above. On the CLI, enter: :help user-manual and press Enter.

If this article can let you know vim again, this fresh and pure and kind “girl”, and then have a unique love for her, it is the biggest harvest of this article creation ^^.



This article was first published with a public number