Login

How to Undo and Redo Changes in Vim or Vi

Vim and Vi include powerful undo and redo features that make it easy to manage your edit history. Whether you are editing code or configuration files, learning these commands helps you work faster and recover from mistakes easily.

Basic Undo and Redo Commands

Undo Changes

  • u – Undo the last change
  • U – Undo all changes made to the current line since it was opened

Redo Changes

  • Ctrl + R – Redo the most recently undone change
  • :redo – An alternative command for redoing changes

Advanced Undo and Redo Techniques

Multiple Undos

  • 5u – Undo the last five changes
  • :undolist – Display the list of undo branches

Undo Branches
Vim allows you to navigate a branching undo history, letting you move through different edit versions.

  • :earlier 10m – Revert the file to its state 10 minutes ago
  • :later 5m – Move forward 5 minutes in the edit history
  • g- – Move backward through undo branches
  • g+ – Move forward through undo branches

Enabling Persistent Undo

Persistent undo allows Vim to save your undo history between editing sessions. This means you can close and reopen files without losing your undo history.

Add the following lines to your .vimrc file:

set undodir=~/.vim/undodir

set undofile

set undolevels=1000

set undoreload=10000

Benefits of Persistent Undo:

  • Keeps undo history even after closing Vim
  • Lets you recover changes made in previous sessions
  • Ideal for long-term file editing and configuration work

Common Undo and Redo Use Cases

Recovering Deleted Content

  • Use u to undo a deletion instantly
  • If you undo too far, use Ctrl + R to redo the change

Exploring Edit History

  1. Make several edits in a file
  2. Use u repeatedly to step back through your changes
  3. Use Ctrl + R to move forward again through the history

Best Practices for Undo and Redo in Vim

  • Use undo regularly to test different edits safely
  • Run :undolist to view your edit branches and navigate easily
  • Enable persistent undo to save time and maintain consistency across sessions

Troubleshooting Undo and Redo

If undo is not working as expected:

  • Make sure you are in Normal mode (press Esc)
  • Check your Vim version (persistent undo requires version 7.3 or later)
  • Review your .vimrc configuration for errors

Conclusion

Mastering undo and redo in Vim or Vi can greatly improve your editing efficiency. By learning these commands and enabling persistent undo, you can confidently manage your edit history and recover changes at any point.

Sarang Khedkar

How to Undo and Redo Changes in Vim or Vi
Table of Contents
    ×