How to use Undo in Vim

When editing with Vim on Linux, it's easy to make mistakes. Luckily, undoing them is also easy. Here's how to quickly undo your edits in the popular Linux editor Vim.

When editing with Vim on Linux, it's easy to make mistakes. Luckily, undoing them is also easy. Here's how to quickly undo your edits in the popular Linux editor Vim.

How to undo Vim edits

Vim's simple undo operations are similar to the undo functions you may have used in modern word processors like Microsoft Word, LibreOffice Writer, or Google Docs. Vim keeps track of the changes you make to a file and can restore it if needed.

Vim considers anything you do in Insert mode or any command in Command mode as changes. For example:

  1. If you type multiple lines in Insert mode, when you perform the undo operation immediately, those lines will be deleted.
  2. If you enter a line, switch to Command mode, then switch back to Insert mode and enter some more text, you will make two changes. Undo will remove each separately.

You can also repeat Vim commands like "3dd" to delete 3 lines. If you issue one of these cmdlets, it will also be redeployed as the latest change. You can keep undoing until you get back to where you started, when you opened or created the file.

If you realize you've made an edit in Vim that you don't want to make, undoing that edit is a simple two-step process:

  1. Press Esc to make sure you are in Command mode.
  2. Press u to undo the previous change.

It is done! You'll see a notification about changes made, such as "n fewer lines".

 

Picture 1 of How to use Undo in Vim

If you want to undo multiple changes, you can do that too. Just prefix the undo command with the amount of changes you want to undo, as you can do with most other Vim commands. For example, if you wanted to undo two changes, you would press:

2u

How to redo in Vim

You may find that your undo command does something unexpected or you change your mind. In this case, you can issue the redo command to return your file to its previous state.

Because Vim keeps track of your changes, it also keeps track of your undo operations. So you can undo undo operations if you need to do them again. Remember, Vim considers multiple lines entered in Input mode as one change, so if you redo an operation, you'll get back several lines in one command.

The command to do this is Ctrl + r, which means "redo". Make sure you are in Command mode by pressing Esc. Redo works on the same principle as undo; For example, you can repeat a redo operation by preset the number of redos you want to perform.

Picture 2 of How to use Undo in Vim

Like undo, you will see a brief message about the redo changes, such as the number of lines added to the file. You can redo it as many times as you want until you return to the current state of the file.

Update 19 February 2024
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile