Advanced undo/redo with undo-tree

In emacs, by default C-/ runs the command undo, which does what you would expect and undoes your changes to the current buffer. However, there is a really great upgrade to this called undo-tree which records and visualises your undo history as a branching tree. Install this package, and then add the following to your emacs config file

;; undo tree mode                                                         ;;
;;turn on everywhere
(global-undo-tree-mode 1)
;; make ctrl-z undo
(global-set-key (kbd "C-z") 'undo)
;; make ctrl-Z redo
(defalias 'redo 'undo-tree-redo)
(global-set-key (kbd "C-S-z") 'redo)

Now you can use C-z for undo and C-Z for redo. Even better though is using C-x u to run undo-tree-visualize which opens a second buffer displaying a tree view of your undo history in a buffer. You can navigate this with the arrow keys and watch the main buffer change through its previous states, and hit q to exit when you have the buffer the way you wanted it, or C-q to quit without making any changes.

In this simple illustration, I do the following:

  • type some text and then undo some of that typing
  • type some new text
  • use undo-tree to undo the new text and then switch branches to redo the old text


Undo-tree can do other neat things too – see the web page for details.