How to Perform Undo and Redo Operations in Vim and Vi

Suraj Joshi Feb 02, 2024
  1. Undo Changes in Vim/Vi
  2. Redo Changes in Vim/Vi
How to Perform Undo and Redo Operations in Vim and Vi

Vim and Vi are one of the most popular text editors among Linux and Mac users.

We use the u, :u or :undo commands to undo changes in Vim. Similarly, we use the CTRL+R or :redo command to redo the changes.

Undo Changes in Vim/Vi

Vim observes all changes that we have made to a particular file. The undo command can revert one or more changes. The latest changes will be undone first and then then the previous changes. To undo changes in Vim, we use the u, :u or :undo commands.

Steps to Undo Changes in Vim/Vi:

  • We must make sure that we are in normal mode to execute the commands in Vim. If we are not in the normal mode, we can press the Esc key to switch to the normal mode.
  • To undo the latest change, use the u command.
  • To undo multiple changes at once, we use u commands with numbers also. nu command will undo the latest n changes.

We must be cautious with the case of u. If we accidentally hit U, it will undo all the latest changes on one line. If we hit U, we can use u to revert the changes.

If we edit a file in the insert mode, all the changes made during the session are treated as a single entry in the undo tree.

If we delete two lines after switching to the insert mode and then use the u command after switching back to the normal mode, both lines will be restored.

Redo Changes in Vim/Vi

The redo action is the opposite of the undo action. To redo the undone changes in a file, we use the CTRL+R or :redo command.

Steps to Redo Changes in Vim/Vi:

  • We must make sure that we are in normal mode to execute the commands in Vim. If we are not in the normal mode, we can press the Esc key to switch to the normal mode.
  • To redo the changes, we use the CTRL+R(simultaneously press Ctrl and r key) or :redo command after entering to normal mode.
  • To redo multiple changes at once, we use numbers with the CTRL+R command. 3 Ctrl-R (Press 3 and then simultaneously press Ctrl and r key), and then the command will redo the latest 3 changes.

We can use undo and redo commands in a cycle to undo changes and then redo undone changes.

Author: Suraj Joshi
Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn

Related Article - Linux Vim