How to Undo and Redo in Vi / Vim

Sometimes,when editing a file use Vi / Vim, you may delete a wrong line or change your mind about an edit, and you’ll want to revert the changes.

In this article we will show you how to undo and redo changes in Vi / Vim.

Vi is installed by default on almost all Linux distributions. Knowing the basics of Vi might be very useful when you encounter a situation where your favorite editor is not available.

Undo Changes in Vi / Vim

Vim keeps track of all the changes you made in the current session. The undo command undoes one or more changes in the order in which they were made.

To undo changes in Vi and Vim use the u, :u or :undo command:

  1. If you are in insert or any other mode, press the esc key to go back to the normal mode, which is also known as command mode.
  2. Type u to undo the last change. In Vim, the u command also accepts quantifiers. For example, if you want to undo the 4 last changes, you would use 4u.

Make sure you’re typing lowercase u, not the uppercase U command, which undo all latest changes on one line. If you accidentally type U you can undo the change with u.

Use the undo command to revert the changes made by any other command, such as delete, paste, search and replace, and so on.

When working in insert mode, all changes to the text are considered as one entry in the undo tree. For example, if you switch to insert mode and enter five lines, then go back to normal mode and press u to undo the change, all five lines are removed.

Redo Changes in Vi / Vim

The redo feature reverses the action of undo.

To redo a change in Vi and Vim use the Ctrl-R or :redo:

  1. Press the Esc key to go back to the normal mode.
  2. Use Ctrl-R (press and hold Ctrl and press r) to redo the last change. In Vim, you can also use quantifiers. For example, if you want to redo the 4 last changes, you would type 4Ctrl-R.

Each undo command can be reversed by a redo command.

Conclusion

To undo a change in Vi / Vim type u, and to redo a change which was undone use the ctrl-rkey sequence.

Leave a Reply