Vim editor

更新时间:
复制 MD 格式

Vim is a popular text editor in Linux, commonly used for tasks such as system operations and maintenance and writing shell scripts. This topic describes the basic commands and how to switch between modes in Vim to help you get started quickly.

Installation

The Vim tool is installed by default on most Linux systems. You do not need to install it. You can run vim --version in the terminal to view the Vim version information. This topic uses Vim 8.0 as an example. The commands and features may differ in other versions.

VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Aug 10 2022 11:26:47)
Included patches: 1-1763
Modified by OpenAnolis Community
Compiled by OpenAnolis Community
Enormous version without GUI.  Features included (+) or not (-):
+acl               +farsi             +mouse_sgr         -tag_any_white
 ......

Switching modes

Run the vim filename command to open a file and enter Normal mode. If the file does not exist, Vim creates a new file. The following table describes the modes in Vim and how to switch between them.

image

Mode

Function

Mode switching

Normal mode

(Normal Mode)

In this mode, you can copy, paste, and delete characters or lines.

  • When you run vim <filename> to open a file, you enter Normal mode.

  • In other modes, press the Esc key to return to Normal mode.

Insert mode

(Insert Mode)

In this mode, you can insert characters.

In Normal mode, press any of the following keys to enter Insert mode: i,I,a,A,o,O.

Note

After you enter Insert mode, -- INSERT -- appears in the lower-left corner of the editor.

Replace mode

(Replace Mode)

In this mode, you can replace characters.

In Normal mode, press R to enter Replace mode.

Note

After you enter Replace mode, -- REPLACE -- appears in the lower-left corner of the editor.

Visual mode

(Visual Mode)

In this mode, you can select text. Commands, such as copy, replace, and delete, apply only to the selected text.

In Normal mode, press v to enter Visual mode.

Note

After you enter Visual mode, -- VISUAL -- appears in the lower-left corner of the editor.

Command mode

(Command Mode)

In this mode, you can find strings, replace strings, show line numbers, save changes, and exit the editor.

In Normal mode, press : to enter Command mode.

Basic commands

Opening files

  • vim filename: Opens a single file. You enter Normal mode. If the file does not exist, Vim creates a new file.

  • vim filename1 filename2: Opens multiple files.

    • By default, Vim opens `filename1`. After you edit the file, run :w to save it. Then, run :bn to switch to the next file, `filename2`. After you edit `filename2`, run :w to save it.

    • Run :bp to switch to the previous file, `filename1`.

    • Run :ls to view the list of files that are being edited.

  • :open filename3: In Command mode, you can run this command to open a new file for editing. Before you run this command, run :w to save the current file.

Moving the cursor

  • In Normal mode

    • Up arrow/k: Move the cursor up.

    • Down arrow/j: Move the cursor down.

    • Left arrow/h: Move the cursor left.

    • Right arrow/l: Move the cursor right.

  • In Insert mode

    • You can only use the arrow keys to move the cursor.

Inserting content

In Normal mode, press any of the following keys to enter Insert mode: i,I,a,A,o,O.

  • i: Insert text to the left of the cursor.

  • I: Insert text at the beginning of the current line.

  • a: Insert text to the right of the cursor.

  • A: Insert text at the end of the current line.

  • o: Insert a new line below the current line.

  • O: Insert a new line above the current line.

Copying and pasting

These commands are similar to Ctrl+C and Ctrl+V in a word processor. In Normal mode:

  • yy: Copies the current line. You can then use p to paste it.

  • nyy: `n` is a number. For example, 2yy copies the current line and the line below it, for a total of two lines.

  • p: Pastes the copied content to the line below the cursor.

  • P: Pastes the copied content to the line above the cursor.

Delete

  • In Normal mode

    • Delete a single character: Press the x key to delete the character at the cursor's position.

    • Delete an entire line: Press dd to delete the current line. This is similar to Ctrl+X in a word processor. You can then use p to paste the deleted line.

    • To delete the current line and the line above it, press dk.

    • To delete the current line and the line below it, press dj.

    • dG: Deletes from the current line to the end of the document.

    • nx: `n` is a number. Deletes the character at the cursor and the next `n-1` characters.

    • ndd: `n` is a number. Deletes the current line and the `n-1` lines below it. This is similar to Ctrl+X in a word processor. You can then use p to paste the deleted lines.

  • In Insert mode

    • Use the Delete key to delete characters.

Searching

In Normal mode

  • /text: Searches for `text`. By default, the search is an exact match. Press Enter to highlight the matching characters.

    • To perform a case-insensitive search, first run :set ignorecase. To return to exact matching, run :set noignorecase.

  • n: Goes to the next match.

  • N: Goes to the previous match.

Replacing

  • In Normal mode

    • r: Replaces the single character at the cursor.

    • R: Enters Replace mode to continuously replace characters. Press the Esc key to exit.

    • cc: Deletes the current line and enters Insert mode.

    • :%s/oldtext/newtext/g: Finds all instances of `oldtext` and replaces them with `newtext`. The /g flag means that all instances on a line are replaced. Without this flag, only the first match on each line is replaced.

  • In Insert mode

    • Replace content by deleting the old content and inserting the new content.

Undoing and redoing

In Normal mode

  • u: Undoes an insertion or modification. This is similar to Ctrl+Z in a word processor.

  • U: Undoes all recent changes on the current line.

  • Ctrl+r: Redoes the last undone change. This is equivalent to Ctrl+Y in a word processor.

Indenting and formatting

  • In Normal mode

    • >>: Indents the current line to the right. The default indent is 8 spaces, which is the width of a tab character.

    • <<: Indents the current line to the left.

  • In Command mode

    • :ce: Center-aligns the current line.

    • :le: Left-aligns the current line.

    • :ri: Right-aligns the current line.

Commenting code

Note
  • Back up the file: Before you perform a large-scale replacement, back up the file or use the undo command (u) to prevent mistakes. For example, run sudo cp /etc/text.txt /etc/text.txt.bak to back up a file.

  • Regular expressions: Make sure you understand Vim's regular expression syntax to avoid accidentally deleting content. In Vim regular expressions, the / character must be escaped as \/. If you are not familiar with regular expressions, you can use tools such as Regex101 to practice and test.

  • Comment styles for different languages: Adjust the comment symbol in the replacement command based on the programming language you are using.

  • In Visual mode

    • Comment out multiple consecutive lines of code

      1. Move the cursor up or down to select the lines to comment out.

      2. Press : to enter Command mode. Vim automatically enters :'<,'>, which indicates that the operation applies to the selected range.

      3. Enter the replacement command. For example, to add # to the beginning of each line, enter s/^/#/ and press Enter.

    • Comment out all code: Run the replacement command :%s/^/#/g to comment out the entire file using #.

  • In Insert mode

    Manually insert comment symbols to comment out code.

Saving and exiting

  • Save the file: In Normal mode, enter :w and press Enter.

  • Exit Vim: Enter :q and press Enter.

  • Save and exit: Enter :wq or :x and press Enter, or use the ZZ command.

  • Force exit without saving: Enter :q! and press Enter.

  • Force save and exit: Enter :wq! and press Enter.

Encrypting documents

  • Encrypt a document: vim -x filename. After you set a password, Vim enters Normal mode. You must save the file for the encryption to take effect. When you open the file again, you are prompted to enter the password to authenticate.

  • Cancel document encryption.

    1. In Vim, run the command :set key= to cancel encryption. This command clears the encryption key for the current file, which removes the encryption setting.

    2. Use the :wq command to save and exit.

    3. Run vim filename again to open the file. You are no longer prompted for a password.

Executing commands

  • !pwd: Shows the current working directory without exiting Vim.

  • !ls: Lists the files and folders in the current directory without exiting Vim.

Multi-window editing

  • vim -o filename1 filename2: Opens two files in separate windows at the same time. To exit, you must run the exit command in each window.

  • :n: Switches to the next file window.

  • :N: Switches to the previous file window.

Help documents

  • In the terminal, run vim --help to view help information about Vim command syntax.

  • In Normal mode

    • :help: Views the Vim help document. The help document is read-only. Run :q to exit the help document.

    • :help i: Shows the help document for i.

    • :help yy: Shows the help document for yy.

    • :set nu: Shows line numbers.

Examples

Modify a configuration file

This example shows how to insert Location on the first line of the example.conf configuration file. The steps are as follows:

  1. Run the vim example.conf command to open the file and enter Normal mode.

  2. With the cursor on the first character of the file, press the i key to enter Insert mode.

  3. Enter Location and press Enter to start a new line.

  4. Press the Esc key to return to Normal mode.

  5. Enter :wq to save the file and exit.

    example-1-1-2.gif

Insert content on a target line

This example shows how to insert # at the beginning of line 10 in the example.conf configuration file. The steps are as follows:

  1. Run the vim example.conf command to open the file and enter Normal mode.

  2. Run :10 to move the cursor to line 10.

  3. Press the i key to enter Insert mode.

  4. Enter #.

  5. Press the Esc key to return to Normal mode.

  6. Enter :wq to save the file and exit.

    example-2-1-2.gif

Find and insert content

In the example.conf configuration file, insert LoadModule rewrite_module modules/mod_rewrite.so after the Include conf.modules.d/*.conf line. The steps are as follows:

  1. Run the vim example.conf command to open the file and enter Normal mode.

  2. Run /Include conf.modules.d/*.conf to find the target line.

  3. Press i to enter insert mode.

  4. Enter LoadModule rewrite_module modules/mod_rewrite.so.

  5. Press the Esc key to return to Normal mode.

  6. Run :wq to save the file and exit.

    example-3-1-2.gif

Delete content

In the example.conf configuration file, delete the # from the beginning of the #Listen 12.34.XX:XX:80 line and delete the Listen 80 line. The steps are as follows:

  1. Run the vim example.conf command to open the file and enter Normal mode.

  2. Run /#Listen 12.34.XX:XX:80 to find the target line. The cursor is positioned on the # character.

  3. Press the x key to delete #.

  4. Move the cursor to the Listen 80 line and press dd to delete the line.

  5. Enter :wq to save the file and exit.

    delete-1.gif

Edit Docker.yaml

Create and edit the docker-compose.yaml file. The following is an example.

vim docker-yaml-2.gif

Remove multi-line comments

  1. Assume the comment character # is at the beginning of a line, and may be preceded by spaces and indents:

    # This is a comment
        # Another comment
    # Yet another comment
  2. Run the following command:

    :%s/^\s*#\s\?//

    Description:

    • ^: Matches the beginning of a line.

    • \s*: Matches any number of whitespace characters (for handling indentation).

    • #: The comment symbol.

    • \s\?: Matches one optional space after the comment symbol.

    • //: Replaces the matched content with nothing, which deletes it.

    This command traverses the entire file. After the command is run, the file looks like this:

    This is a comment
    Another comment
    Yet another comment

Upgrade Vim

If the version of Vim on your operating system does not meet your needs, you can run the following commands to upgrade it.

Alibaba Cloud Linux 3 and 2

sudo yum update vim

CentOS 7 and 8

sudo yum update vim

Fedora

sudo yum update vim

Ubuntu and Debian

sudo apt upgrade vim

openSUSE

sudo zypper update vim

Common errors

  • The "No write since last change" prompt appears on exit:

    • Cause: The file was modified but not saved.

    • Solution: Run :wq to save and exit, or run :q! to discard the changes and exit.

  • Cannot enter text:

    • Cause: You may be in a mode other than Insert mode, such as Visual mode.

    • Solution: Press the Esc key to return to Normal mode, and then enter Insert mode.

  • Cannot save the file:

    • Cause: You may not have the required permissions. The current user does not have write permissions for the target file or its directory. For example, system configuration files, such as /etc/hosts and /etc/nginx/nginx.conf, usually require superuser permissions to modify.

    • Solution 1: Use the sudo command to start Vim with superuser permissions. For example, sudo vim example.conf.

    • Solution 2: Use :w !sudo tee % to save the current file with administrative permissions. To change the permissions or ownership of the configuration file, you can also use commands such as sudo chown or sudo chmod.

  • A file with the ".swp" suffix exists:

    • The file is open in another Vim session.

    • Solution: Confirm that no other terminal is editing the file. If not, you can use ll -a to find and delete the .swp file, and then reopen the file for editing. Alternatively, you can use the :recover command to recover the file from the swap file before editing.