How To Undo and Redo In Vi/Vim?

The vim editor provides the ability to undo and redo changes. The undo operation will revert back to the recently changed and the redo operation will do the reverse of the undo which means changes will be restored back from undoing operations.

Make Some Changes

For this tutorial, we will open a file with vim and then make some changes in this file. The file is named “test.txt“. We will add numbers from 0 to 9 and then make undo and redo operations in the next steps

$ vim test.txt
  • Press i to change into insert mode and put “0 1 2 3 4 5 6 7 8 9”.
  • Then press ESC key.
Make Some Changes In Vim

Undo Changes in Vi/Vim

In Vim or Vi, the undo changes operation can be done with the u key like below. Alternatively the :u or :undo commands can be also used to undo changes. A single u key will make a single undo for a change and alternatively, the number of the changes to undo can be specified like 5u .

  • Press ESC key to change into normal mode which is also called command mode.
  • Type u for a single time. We will see the following screen where the lines from 4 to 9 will be removed. We can also see some information about change like 6 fewer lines which means with the last undo 6 lines are removed.
Undo Changes in Vi/Vim

Redo Changes in Vi/Vim

The redo action is the reverse of the undo action which will simply revert back to the made changes. The redo action can be done with the CTRL+R key or with the :redo command.

  • First the ESC key is pressed first to change to normal mode.
  • Then use CTRL+R to redo last change. You can also revert back for specified of changes by providing the count of the changes before the CTRL+R like 4+CTRL+R .
Redo Changes in Vi/Vim

List Changes with Undolist

During editing a text file there will be a lot of changes that can be done at different times. These changes can be listed for the undo operation with the :undolist command like below.

  • First press ESC key for normal mode.
  • Then put the :undolist command like below. Which will list the recent changes with number, count, date information.
List Changes with Undolist

Revert Back To Specific Change

After listing the Undolist we can revert back to the specific state by specifying the undo number. From the undo list we can see that there are 5 states and the date and time of each state are displayed. Also, the change count is provided for each state. In order to revert back to change 3 use the following Vim/Vi command.

  • Press ESC.
  • Type :3u

After the undo operation information about the undo is displayed at the bottom of the Vim/Vi like below. In the following case, we are informed that the undo operation added 12 more lines after the undolist state numbered 3. which reverts back to the time 20:50:00.

Revert Back To Specific Change

Leave a Comment