Vim editor

Before introducing the more command, the VI editor is displayed on the interface of the more command.

In that article I gave a brief introduction and demonstration of the VI editor.

What this article should do is to fill in the holes left by VI at that time;

After filling in the holes, we will introduce vim, the main character of this article. Read on.

Vi and vim

Vi is an informal abbreviation of “Visual”, derived from the command Visual of another text editor, ex.

Almost all Linux distributions (or Unix-like systems) come with a built-in VI editor, and many programs use vi as the default editor by default.

Vi is an old-fashioned text editor, but it's actually quite functional.

Vim is a modified VERSION of VI that not only supports text editing extensions but can even be used as an IDE (although that’s not all it does).

Many additional features have been added to Vim, such as support for regular expressions, multi-file editing, and block copying…..

This is a huge help when we do some configuration file customization on Linux.

Vim is a text editor developed from VI.

Its code completion, compilation, error jump and other convenient programming functions are particularly rich, widely used in programmers.

Tied with Emacs as the most popular editor for Unix-like system users

System understanding of VI

Since most of the functions supported by VI are also supported by VIm, it is necessary for us to understand the VI system before we understand VIM.

A correction here is that VI has a command line mode in addition to (normal) command mode and edit mode

I did not mention the command line pattern before, but included it in the general command pattern, which is not rigorous.

Let’s introduce each of the three modes

General command mode:

  • We are in this mode, also known as general command mode, when we bring up the VI editor by default.
  • In this mode you can use the arrow keys of the keypad or h, J, K, or L (left, down, up, or right) to move the cursor

  • In this mode you can use some function buttons to delete characters or entire lines, and you can also use copy and paste to manipulate the contents of your files

Command line mode:

  • Enter “:”, “? “, “/” Either can enter the command line mode
  • Enter this mode and the cursor moves to the bottom
    • In this mode, we can search, read, replace, display line numbers, exit VI, save the edited text, and so on

Insert mode:

  • In general command mode, we can enter editing mode by pressing any button [I, I, O, O, A, A, R, R]
  • In Linux, when you enter this mode, the words “INSERT” or “REPLACE” appear at the bottom left of the screen, allowing you to edit the text
  • To switch from this mode to command mode we can press the [Esc] key
    • Unable to save and exit vi in edit mode, we need to switch to command mode first
    • Enter the CLI mode from the command modewqCommand to save and exit

Use VI for text editing

Now that we know about the three modes, we can edit some simple text files

I’m not going to be the cute newbie who calls up VI and plays it as a random string generator.


After jumping to the specified working path, we can open the file using vi + file name and enter vi’s general command mode.

The file name parameter can be an existing file or a non-existing file. If it is an existing file, vi will open the file.

If the file does not exist, vi creates the corresponding file and opens the empty file.

After creating an empty file, exit without any text editing. The file will not be created

After opening the file, we press I to enter the editing mode and edit the new text content in the editing mode.

After editing, press [Esc] to switch to general command mode. To switch from the common command mode to the CLI mode, save the changes and exit the (wq) vi editor

If you do not have the permission to write files when you run the wq command, run the wq! Command. ; Add “! “after wq “Indicates that the operation is forcibly performed.

Of course, he needs you to be the owner or administrator of the current file.

Using the cat command, you can see that the text content is edited.


Error when executing vi + file name, it may be because you are not the administrator.

Because the vi editor of common users has been replaced with vim by default, you need to use the absolute path: /bin/vi + file name.

Of course, if it still does not work, you can directly skip the use of vi, vim is :vim + file name, the two are not much different.


Function keys that may be used in vi

Although you can already edit text with the VI editor, there are a lot of buttons associated with the VI function.

These buttons are like a “black box” to a novice, with no idea what happens when you press them. Let alone use it wisely.

Here I will be possible to use some of the functional keys are listed again, can be a familiar; Rote learning is not recommended. I still recommend checking when you need it.


The following are the function keys that can be used in the common command mode

Move the cursor:

The keys role
“K” or keypad arrow key “↑” The cursor moves up one character
“J” or keyboard arrow key “↓” Move the cursor down one character
“H” or keypad arrow key “←” The cursor moves one character to the left
“L” or small keyboard arrow key “→” The cursor moves one character to the right

To use these keys, enter num and the desired action, for example, [20 + “L” or “→”], which moves 20 characters to the right


The keys role
[Ctrl] + [f] Move the screen down a page, equivalent to [pageDowm]
[Ctrl] + [b] The screen moves up a page, equivalent to
[Ctrl] + [d] The screen moves down half a page
[Ctrl] + [u] The screen moves up half a page
+ The cursor moves to the next line that is not a space
The cursor moves to the line above that is not a space
Num + space The cursor will move the line to the rightnumCharacters, such as 5 + space; That’s five characters on the line where the cursor moves to the right
H The cursor moves to the first character on the top line of the screen
M The cursor moves to the first character of the line in the middle of the screen
L The cursor moves to the first character at the bottom of the screen line
G Move to the last line of the file
num + G Move to the first part of the filenumLines, such as 10G, move to line 10 of the file
gg Move to the first line of this file, equivalent to 1G command
Num + enter Cursor downnum4. Often used.

Find and replace

The keys role
/ + string Find the specified string under the cursor.
? + string Find the specified string above the cursor.
n Press thenAfter the key, the previous lookup operation is repeated. For example, the last time /test was executed; To find the string test under the cursor, pressnI can then go down and look up the test string, and if I do the other way around, okay? The test; It looks up the test string
N A capitalN(Opening the uppercase lock or holding Shift allows us to type uppercase N) works with lowercasenQuite the opposite, that is, if the previous lookup was up, press uppercaseNA lookup down operation is performed
:num1,num2s/ string 1/ string 2/g This is a little bit harder to understand,It replaces string 1 with string 2 between the line numbers of numbers 1 and 2So, let’s say we put in: 10, 20 / test/test/g; It replaces all test strings in lines 10 through 20 with test. “Common”
:1,$s/ string 1/ string 2/g Similar to the previous one, but it specifies the range of line numbers; Replace all string 1 with string 2 from the first line to the last (full) line.
:1,$s/ string 1/ string 2/gc Same as before, but with a c it’s going to ask the user when it makes the substitution

Delete, copy and paste

The keys role
X and x lowercasexThe delete () function deletes a character backwards; That is, the same function as the [Delete] key. The capital ofXBackspace: Backspace: Backspace: Backspace: Backspace: Backspace: Backspace
num + x / X ifnumIt’s followed by lowercasexIndicates a sequential backward deletionnumA character, if uppercaseXIt indicates that the vm is continuously deletednumA character
dd To delete (cut) the entire line where the cursor is located.
num + dd That is, delete (cut) the mum line down from the current cursor. For example, 10 dd; Means to cut down ten lines
d1G Deletes all data from the current cursor position to the first line
dG Deletes all data from the current cursor position to the last line
d$ Deletes the current cursor position to the end of the line, that is, only the content before the cursor is retained
D0 (number zero) Deletes the current cursor position to the beginning of the line, that is, only the content after the cursor is retained
yy Copy the entire contents of the current cursor line.
num + yy Copy all contents of the num line down where the current cursor is; Such as 10 yy. Indicates that all contents of the ten lines below the current cursor are copied
y1G Copy all data from the cursor row to the first row
yG Copy all data from the cursor row to the last row
y0 Copies all data from the cursor character to the beginning of the line
y$ Copies all data from the cursor character to the end of the line
P and p lowercasepPastes the copied content after the current cursor line, in uppercasePThe not; Pastes before the current cursor line. Let’s say I copied 10 lines, and the cursor is currently at line 20; If I use lowercasepThe ten lines will be pasted from line 21; Instead, you paste it from line 19. “Common”
J Merges the contents of the current cursor line with the contents of the next line
c Deduplication of multiple data, such as ten rows down [10cj]
u undo3. Previous operation often used.
[Ctrl] + r redoPrevious operation common
(Decimal point) repeatFor the previous operation, if you want to duplicate delete or duplicate paste you can press “.”

The following are the key functions that may be used to switch from general command mode to edit mode

The keys role
I and I Enter insert mode for both upper and lower case “I”; The lower case “I” is pressed to enter insertion mode starting at the current cursor position, and the upper case “I” is inserted from the first non-space character on the current cursor line.
A and a Enter insert mode for both upper and lower case “A”; The lower case “A” press inserts from the next character on the current cursor, the upper case “a” inserts from the end of the current line.
O and o Enter insert mode, both upper and lower case “O” can enter this mode; The lower case “O” press inserts a new line from the line below the current cursor, and the upper case “O” inserts a new line from the line above the current cursor.
R and r. Go to Replace Mode, which can be used for both upper and lower case “r”; The lowercase “O” press replaces the current cursor character only once, whereas the uppercase “R” press replaces the cursor character consistently until [Esc] is pressed.
Esc Switch from Edit mode to General command mode

The following are key functions that may be used in general command mode

The keys role
:w 3. To write an edit to a hard disk file. Often used.
:w! If you do not have the write permission on the file, you need to be the root user or the owner of the file to use this command.
:q Exit vi
:q! Forcibly Exiting the VI
:wq Exit vi after saving the configuration
:wq! Forcibly save the configuration and exit vi
ZZ Two uppercase “Z”, this command can only exit if the file content is not modified. If yes, save the Settings and exit.This command is usually used in general command mode. Why write it here? Because I'm too lazy to change“Common”
:w [fileName] Save the contents of the edited file as another file (similar to saving as)
:r [fileName] Read the data from the file [fileName] into the edited file content. The read content is inserted after the cursor line
:num1,num2 w [fileName] Save the contents of lines num1 through num2 of the current edit file into a file named [fileName] (which may not exist)

Vim environment modification

The keys role
:set nu Displays the line number, which is prefixed for each line
:set nonu Cancels the line number, as opposed to the previous command

In vi [number] is very meaningful, and numbers usually represent how many times to repeat; To the number or something.

For example, if you want to delete 50 lines, you can use 50DD, and if you want to move 20 lines down, you can use 20j(↓).

OK, this time look down all remember is certainly not realistic; Remember some commonly used can, can understand is the best, do not understand it does not matter how long.

You can save the post address and come back to it when you need it

Additional features of Vim

In fact, most current Linux distributions have replaced vi functionality with vim.

When you use vi and see the line number in the lower right corner of the screen showing the current cursor position, your VI has been replaced by Vim.

The use of vim and VI is basically similar. If you want to use Vim to edit files, you can use vim + file name to open the files to be edited (the premise is that you must be in the corresponding working directory or use absolute path).

The diagram above shows the viM interface

Visual Block

When listing vi buttons, almost all of the actions mentioned are in terms of behavioral actions.

What if we want to operate on a block (that is, in column units of operation) scale? Like this:

192.168.1.[num] host[num].class.net host[num]]

In this situation, except vim, I only know IDEA can be easily done. Let’s see how to use Vim to meet our needs.

In Vim, when we press V, V, or [Ctrl] + V, the place where the cursor moved begins to reflect white; Let’s take a look at the three functional buttons

The keys role
v Character selection, will be the cursor over the place selection
V Line selection, will reverse the cursor over the line selection
[Ctrl] + v Visual block, you can select the content in a rectangular way
y I’m going to make a copy of that
d Delete the backwhite areas
p Paste the copied block in the position of the cursor

Try using:

By doing this, you can copy a block and paste it in a block range.

This is a very useful feature

Multifile editing

Our needs change; We want to copy the IP from host. TXT to another file.

We know that we can use :r[fileName]; Reading the contents of a file into another file, but reading the entire contents of the file is not optimal.

At this point, vim’s multi-file editing function is very useful, we can use Vim to open multiple files as above;

Function keys needed:

The keys role
:n Edit the next file
:N Edit the previous file
:files Lists all files currently open in this VIm

Presentation:

Open multiple files using Vim and view them

After confirming that multiple files have been successfully opened, let’s meet the requirements mentioned above

Multi-file editing allows you to quickly copy the data you need into the correct file.

Of course, this function can also be achieved by using the window interface, which is the multi-window function mentioned below.

Multi-window function

To perform the split screen operation, switch to the command line mode and run :sp{fileName}. This “fileName” is not required if fileName is not written; The file currently edited by Vim opens in a different window.

The picture shows the effect of opening test. TXT in two Windows without writing fileName.

To switch Windows, press [Ctrl] + W first. Use arrow keys “↑” and “↓” on the small keyboard to switch Windows (only one time)

Function keys that may be used in multi-window situations

The keys role
:sp{fileName} Open a new window, if fileName does not write, a new window is opened for the currently edited file (the contents of the two are synchronized); If fileName is a concrete file (it can be a nonexistent file, vim will create a new file for you), the file will be opened in a new window
[Ctrl] + w + j (↓) The usage of combination keys is: hold down [Ctrl] first, press W while holding down [Ctrl], release all keys; Press J or ↓ to move the cursor to the lower window
[Ctrl] + w + k (↑) As above, this key combination moves the cursor to the upper window
[Ctrl] + w + q To end the window, you can first move to the window to be closed and press the combination key to close it. Similar to the key combination above. You can also use:closeReplace the combination key

I have to say, the multi-window feature is also very useful.

Keyword completion function

We know that you can use the [TAB] key to complete commands, arguments, and file names under bash.

Vim is an extended editor that can be used as an IDE, so there’s no reason not to support completion; However, using vim’s completion function requires remembering a few more key combinations

Vim completion function combination keys that need to be memorized

The keys role
[Ctrl] + x –>[Ctrl] + n Complete with the content of the file currently being edited as the keyword
[Ctrl] + x –>[Ctrl] + f The file name in the current directory is used as the keyword to complete the file
[Ctrl] + x –>[Ctrl] + o Use the extension as a syntax supplement, complete with viM built-in keywords

There is only a third estimate that needs elaboration, for example:

If you’re writing an HTML file using VIm, add a background color to a tag. So we’re going to write background

This is a relatively long English word, and although it is not difficult to remember, it is hard not to doubt whether it is written correctly.

At this point, we can try to use vim’s completion function to make sure that we get it right because it’s painful to get a letter wrong.

Using this completion requires that you write the extension correctly and that vim has the keyword built in

Vim environment Settings

When we look for a string in vim, the string is inverted; The next time we open the file with vim editing we’ll find that the backwhite is still there.

Even the cursor position stays on the same line as when vim was last closed, in which case Vim is actively recording what we did.

The record file is your current user working directory. Viminfo, yes, a hidden file

[root@izbp1az353cisf510keg74z /]# cd /root
[root@izbp1az353cisf510keg74z ~]# ls
# View hidden files in the current directory
[root@izbp1az353cisf510keg74z ~]# ls -a
																 # This file exists
.              .bash_profile  .docker            .pki              .viminfo
..             .bashrc        .lesshst           .pydistutils.cfg
.bash_history  .cache         .oracle_jre_usage  .ssh
.bash_logout   .cshrc         .pip               .tcshrc
Copy the code

This file will be automatically generated by Vim, you do not need to manually create; Everything you do with Vim can be traced in this file.

Because the ViM environment used by each Linux distribution may be different, Vim supports user customization of the environment to meet individual usage habits.

There are many environment parameters that can be set. You can run the set all command to view all parameters. And since there are so many arguments you can’t say all of them conventionally, right? Let’s just look at the usual ones

The command role
:set nu Mentioned, not explained
:set nonu Same (default)
:set hlsearch Hl is short for T of high ligh. Hlsearch stands for highlighted search, which is the anti-white function for searching strings (default).
:set nohlsearch Reverse the above, which is to turn off highlighting lookup
:set autoindent Turn on auto indent
:set noautoindent Turn off auto indentation (default)
:set backup Whether to automatically save backup files; Usually noBackup, if you enable this function every time you modify a file, the source file will be backed up
:set ruler Whether to show the status bar in the lower right corner or not. If you want to make it not show ruler, add no in front of it
:set showmode If you want to display –INSTER–, you can also use no to disable it
:set backspace=[num] Set the Backspace key, or Backspace, to delete those characters when entering insert mode; It is generally allowed to delete any character, but some Linux distributions are slightly different. ** For example, only newly inserted characters are allowed to be deleted. Contents existing in the source file cannot be deleted. ** In this case we can set this parameter to enable VIM to delete all characters using the backspace key; When the input:set backspace=2When vim allows the backspace key to delete all characters, while= 0or= 1Vim only allows us to delete newly inserted characters.
:set all Displays all current environment parameter Settings
:set Displays Settings that are different from the default values, usually the ones you set
:syntax on Whether to display different colors according to program syntax. For example, when editing a plain text file, if you start with “#”, the line will turn blue. If you know how to program, this feature can also help you troubleshoot errors; But if you’re just using Vim to write plain text, you can change on to off to avoid color interference or something, right:syntax offTo turn off the function.

These Settings may be helpful or unhelpful according to personal preference, but in any case are only set in command line mode; After you restart Vim, this setting is restored to the default.

Obviously we don’t have the patience to hang around with Vim, and we both want to get it over with.

At this point, we can permanently modify the default parameters of vim by configuring the vimrc file in /etc.

What I suggest is that you create a new.vimrc file in your working directory and modify the parameters you need to modify

Presentation:

[root@izbp1az353cisf510keg74z moluu]# vim ~/.vimrc
Copy the code

Vim Chinese coding problem

Many friends often cry, how can their vim inside the normal display of Chinese?

In fact, this is most likely due to coding problems

Because Chinese coding Big5, GBK and UTF-8 and so on.

So if your file uses GBK encoding and vim’s terminal interface uses UTF-8; Different encoding used, Chinese garbled is not surprising.

How to solve it? Here are some things to consider:

  1. The language family data your Linux system supports by default: this is related to /etc/locale.conf
  2. Your terminal (bash) language: This is related to the variables LANG, LC_ALL
  3. The encoding you use for your files
  4. Open the terminal software, such as the GNOME window

In fact, the most important points are the third and fourth points, and as long as the codes of these two points are consistent, the garble problem can be solved.

Generally speaking, Chinese coding is recommended to use UTF-8, but some Chinese Windows software coding is often GBK, which causes a series of coding problems.

So far, the study of VIm has come to an end, because I also have limited ability and need to keep learning to enrich myself to continue to write articles.

Coupled with the recent relatively cold lazy disease attack to write things greatly reduced efficiency, hope understanding.


Relax your eyes

Original picture P station address

Painters home page