undotree Documentation

The undo history visualizer for VIM

4,556 stars Vim Script 2 files ยท ~7,433 tokens
RAW Doc

Technical Documentation: mbbill/undotree

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

[Project on Vim.org](http://www.vim.org/scripts/script.php?script_id=4177)

Screenshot

Table of Contents

[!Note]
If you are using Vim version 9.0 or higher, you can try out this plugin for an experience with Vim9 script.

Description

Undotree visualizes the undo history and makes it easy to browse and switch between different undo branches. You may be wondering, what are undo "branches" anyway? They're a feature of Vim that allow you to go back to a prior state even after it has been overwritten by later edits. For example: In most editors, if you make some change A, followed by change B, then go back to A and make another change C, normally you wouldn't be able to go back to change B because the undo history is linear. That's not the case with Vim, however. Vim internally stores the entire edit history for each file as a single, monolithic tree structure; this plug-in exposes that tree to you so that you can not only switch back and forth between older and more recent edits linearly but can also switch between diverging branches.

Note: use :help 'undolevels' in Vim for information on configuring the size of the undo history

How it works

Some users may have questions about whether file contents change when switching between undo history states. With undotree, you don't need to worry about data loss or disk writes. The plugin will never save your data or write to disk. Instead, it modifies the current buffer temporarily, just like auto-completion plugins do. This means that any changes made by undotree are reversible with a single click, allowing you to easily revert to any prior state.

Vim's undo/redo feature is a great way to protect your work from accidental changes or data loss. Unlike other editors, where undoing and then accidentally typing something can cause you to lose your edits, Vim allows you to revert to previous states without losing any data, as long as you keep the Vim session alive. If you want to keep your undo history permanently, Vim offers a persistent undo feature. This feature saves your undo history to a file on disk, allowing you to preserve your undo history across editing sessions. To enable persistent undo, refer to the instructions below. This can be a useful option for those who want to maintain a long-term undo history for a file or project.

Persisting the undo history

Undo/redo functionality is a useful feature for most editors, including Vim. However, by default, Vim's undo history is only available during the current editing session, as it is stored in memory and lost once the process exits. While tools such as undotree can aid in accessing historical states, it does not offer a permanent solution. For some users, it may be safer or more convenient to persist the undo history across editing sessions, and that's where Vim's persistent undo feature comes in.

Persistent undo saves the undo history in a file on disk, rather than in RAM. Whenever a change is made, Vim saves the edited file with its current state, while also saving the entire undo history to a separate file on disk that includes all states. This means that even after exiting Vim, the undo history is still available when you reopen the file, allowing you to continue to undo/redo changes. The undo history file is incremental and saves every change permanently, similar to Git.

If you're worried about the potential storage space used by persistent undo files, undotree provides an option to clean them up. Additionally, undotree is written in pure Vim script, making it lightweight, simple, and fast, and only runs when needed. To enable persistent undo, simply type :h persistent-undo in Vim, or follow the instructions provided in the Usage section below.

Download and Install

Using Vim's built-in package manager:

sh
mkdir -p ~/.vim/pack/mbbill/start
cd ~/.vim/pack/mbbill/start
git clone https://github.com/mbbill/undotree.git
vim -u NONE -c "helptags undotree/doc" -c q

Use whatever plug-in manager to pull the master branch. I've included 2 examples of the most used:

  • Vundle: Plugin 'mbbill/undotree'
  • Vim-Plug: Plug 'mbbill/undotree'
  • Packer: use 'mbbill/undotree'

And install them with the following:

  • Vundle: :PluginInstall
  • Vim-Plug: :PlugInstall
  • Packer: :PackerSync

Usage

  1. Use :UndotreeToggle to toggle the undo-tree panel.

You may want to map this command to whatever hotkey by adding the following line to your vimrc, take F5 for example.

vim
nnoremap <F5> :UndotreeToggle<CR>

Or the equivalent mapping if using Neovim and Lua script.

lua
vim.keymap.set('n', '<leader><F5>', vim.cmd.UndotreeToggle)
  1. Markers
    • Every change has a sequence number and it is displayed before timestamps.
    • The current state is marked as > number <.
    • The next state which will be restored by :redo or <ctrl-r> is marked as { number }.
    • The [ number ] marks the most recent change.
    • The undo history is sorted by timestamps.
    • Saved changes are marked as s and the big S indicates the most recent saved change.
  2. Press ? in undotree window for quick help.
  3. Persistent undo
    • Usually, I would like to store the undo files in a separate place like below.
vim
if has("persistent_undo")
   let target_path = expand('~/.undodir')

    " create the directory and any parent directories
    " if the location does not exist.
    if !isdirectory(target_path)
        call mkdir(target_path, "p", 0700)
    endif

    let &undodir=target_path
    set undofile
endif
text
* Alternatively, if you wish to persist the undo history for a currently
   open file only, you can use the `:UndotreePersistUndo` command.

Configuration

Here is a list of options.

Debug

  1. Create a file under $HOME with the name undotree_debug.log
    • $touch ~/undotree_debug.log
  2. Run vim, and the log will automatically be appended to the file, and you may watch it using tail:
    • $tail -F ~/undotree_debug.log
  3. If you want to disable debug, just delete that file.

License

BSD

Author

Ming Bai <mbbill AT gmail DOT COM>


Doc Undotree (`doc/undotree.txt`)

undotree.txt The undo history visualizer for VIM

Author: Ming Bai
Licence: BSD
Homepage: https://github.com/mbbill/undotree/

==============================================================================
CONTENTS undotree-contents

text
1. Intro ................................ |undotree-intro|
2. Usage ................................ |undotree-usage|
3. Configuration ........................ |undotree-config|
    3.1  undotree_WindowLayout .......... |undotree_WindowLayout|
    3.2  undotree_CustomUndotreeCmd...... |undotree_CustomUndotreeCmd|
         undotree_CustomDiffpanelCmd..... |undotree_CustomDiffpanelCmd|
    3.3  undotree_SplitWidth ............ |undotree_SplitWidth|
    3.4  undotree_DiffpanelHeight ....... |undotree_DiffpanelHeight|
    3.5  undotree_DiffAutoOpen .......... |undotree_DiffAutoOpen|
    3.6  undotree_SetFocusWhenToggle .... |undotree_SetFocusWhenToggle|
    3.7  undotree_TreeNodeShape ......... |undotree_TreeNodeShape|
         undotree_TreeVertShape ......... |undotree_TreeVertShape|
         undotree_TreeSplitShape ........ |undotree_TreeSplitShape|
         undotree_TreeReturnShape ....... |undotree_TreeReturnShape|
    3.8  undotree_DiffCommand ........... |undotree_DiffCommand|
    3.9  undotree_RelativeTimestamp ..... |undotree_RelativeTimestamp|
    3.10 undotree_ShortIndicators ....... |undotree_ShortIndicators|
    3.11 undotree_HighlightChangedText .. |undotree_HighlightChangedText|
    3.12 undotree_HighlightSyntaxAdd .... |undotree_HighlightSyntaxAdd|
         undotree_HighlightSyntaxChange . |undotree_HighlightSyntaxChange|
    3.13 undotree_SignAdded ............. |undotree_SignAdded|
         undotree_SignModified .......... |undotree_SignModified|
         undotree_SignDeleted ........... |undotree_SignDeleted|
         undotree_SignDeletedEnd ........ |undotree_SignDeletedEnd|
    3.14 Undotree_CustomMap ............. |Undotree_CustomMap|
    3.15 undotree_HelpLine .............. |undotree_HelpLine|
    3.16 undotree_CursorLine ............ |undotree_CursorLine|
    3.17 undotree_StatusLine ............ |undotree_StatusLine|
    3.18 undotree_DisabledFiletypes...... |undotree_DisabledFiletypes|
    3.19 undotree_DisabledBuftypes....... |undotree_DisabledBuftypes|
    3.20 undotree_UndoDir................ |undotree_UndoDir|
4. Bugs ................................. |undotree-bugs|
5. Changelog ............................ |undotree-changelog|
6. License .............................. |undotree-license|

==============================================================================

  1. Intro undotree-intro

The plug-in visualizes undo history and makes it easier to browse and switch
between different undo branches. You might wonder what are undo "branches"?
It's vim feature that allows you to go back to a state when it is overwritten
by a latest edit. For most editors, if you make a change A, then B, then go
back to A and make change C, normally you won't be able to go back to B
because undo history is linear. That's not the case for Vim because it
internally keeps all the edit history like a tree structure, and this plug-in
exposes the tree to you so that you not only can switch back and forth but
also can switch between branches.

Some people have questions about file contents being changed when switching
between undo history states. Don't worry, undotree will NEVER save your data
or write to disk. All it does is to change the current buffer little bit, just
like those auto-completion plug-ins do. It just adds or removes something in
the buffer temporarily, and if you don't like you can always go back to the
last state easily. Let's say, you made some change but didn't save, then you
use undotree and go back to an arbitrary version, your unsaved change doesn't
get lost - it stores in the latest undo history node. Clicking that node on
undotree will bring you back instantly. Play with undo/redo on other editors
is always dangerous because when you step back and accidentally typed
something, boom! You lose your edits. But don't worry, that won't happen in
Vim. Then you might ask what if I make some changes without saving and switch
back to an old version and then exit? Well, imagine what would happen if you
don't have undotree? You lose your latest edits and the file on disk is your
last saved version. This behaviour remains the same with undotree. So, if you
saved, you won't lose anything.

We all know that usually undo/redo is only for the current edit session. It's
stored in memory and once the process exits, the undo history is lost.
Although undotree makes switching between history states easier, it doesn't do
more than that. Sometimes it would be much safer or more convenient to keep
the undo history across edit sessions. In this case you might need to enable a
Vim feature called persistent undo. Let me explain how persistent undo works:
instead of keeping undo history in RAM, persistent undo keeps undo history in
file. Let's say you make a change A, then B, then go back to A and make change
C, then you save the file. Now Vim save the file with content state C, and in
the mean time it saves the entire undo history to a file including state A, B
and C. Next time when you open the file, Vim will also restore undo history.
So you can still go back to B. The history file is incremental, and every
change will be recorded permanently, kind of like Git. You might think that's
too much, well, undotree does provide a way to clean them up. If you need to
enable persistent undo, type :h persistent-undo or follow the instructions
below.

Undotree is written in pure Vim script and doesn't rely on any third party
tools. It's lightweight, simple and fast. It only does what it supposed to do,
and it only runs when you need it.

==============================================================================
2. Usage undotree-usage

Use :UndotreeToggle to toggle the undo-tree panel. You may want to map this
command to whatever hotkey by adding the following line to your vimrc, take F5
for example.

text
nnoremap <F5> :UndotreeToggle<cr>

<
Markers

  • Every change has a sequence number and it is displayed before timestamps.

  • The current state is marked as > number <.

  • The next state which will be restored by :redo or is marked as
    { number }.

  • The [ number ] marks the most recent change.

  • The undo history is sorted by timestamps.

  • Saved changes are marked as s and the big S indicates the most recent
    saved change.

  • The = number = marks user chosen change. When this mark is set the
    diff panel displays diff between current seq and marked seq.

  • Press ? in undotree window for quick help.

Persistent undo

Usually I would like to store the undo files in a separate place like below.

text
if has("persistent_undo")
   let target_path = expand('~/.undodir')

    " create the directory and any parent directories
    " if the location does not exist.
    if !isdirectory(target_path)
        call mkdir(target_path, "p", 0700)
    endif

    let &undodir=target_path
    set undofile
endif

<
Alternatively, the persistent undofile can be activated by using the
:UndotreePersistUndo command. This will enable the undofile for the current
buffer only, as undotree utilizes the setlocal undofile function. Once this
command is executed and the persistence undofile is created, the "setlocal
undofile" function will automatically be executed the next time the file is
reopened.

See |undotree_UndoDir|

You may want to map the command to whatever hotkey by adding this following
line to your vimrc, for instance:

text
`nnoremap <F6> :UndotreePersistUndo<cr>`

==============================================================================
3. Configuration undotree-config


3.1 g:undotree_WindowLayout undotree_WindowLayout

Set the undotree window layout.

Style 1

text
+----------+------------------------+
|          |                        |
|          |                        |
| undotree |                        |
|          |                        |
|          |                        |
+----------+                        |
|          |                        |
|   diff   |                        |
|          |                        |
+----------+------------------------+

<
Style 2

text
+----------+------------------------+
|          |                        |
|          |                        |
| undotree |                        |
|          |                        |
|          |                        |
+----------+------------------------+
|                                   |
|   diff                            |
|                                   |
+-----------------------------------+

<
Style 3

text
+------------------------+----------+
|                        |          |
|                        |          |
|                        | undotree |
|                        |          |
|                        |          |
|                        +----------+
|                        |          |
|                        |   diff   |
|                        |          |
+------------------------+----------+

<
Style 4

text
+------------------------+----------+
|                        |          |
|                        |          |
|                        | undotree |
|                        |          |
|                        |          |
+------------------------+----------+
|                                   |
|                            diff   |
|                                   |
+-----------------------------------+

<
Default: 1


3.2 g:undotree_CustomUndotreeCmd undotree_CustomUndotreeCmd
g:undotree_CustomDiffpanelCmd undotree_CustomDiffpanelCmd

Set up custom window layout.

Setting |undotree_CustomUndotreeCmd| will ignore |undotree_SplitWidth|, and
setting |undotree_CustomDiffpanelCmd| will ignore |undotree_DiffpanelHeight|.

An |undotree_CustomUndotreeCmd| will always open the undotree window relative
to the tracked window and |undotree_CustomDiffpanelCmd| will always open the
diffpanel relative to the undotree window.

Useful when

  • absolute positioning commands (|topleft|, |botright|) don't play well
    with other plugins

  • you have a preferred split window layout and would like to use
    UndoTree relative to one specific window only

Examples:

  • To recreate Style 1:
text
let g:undotree_CustomUndotreeCmd  = 'topleft vertical 30 new'
let g:undotree_CustomDiffpanelCmd = 'belowright 10 new'

<

  • To recreate Style 2:
text
let g:undotree_CustomUndotreeCmd  = 'topleft vertical 30 new'
let g:undotree_CustomDiffpanelCmd = 'botright 10 new'

<

  • A custom layout example:
text
+------------------------+----------+
|                        |          |
|                        |    w     |
|                        |    i     |
|                        |    n     |
|   window_1             |    d     |
|                        |    o     |
|                        |    w     |
|                        |    |     |
|                        |    2     |
|                        |          |
+------------------------+----------+
|                                   |
|         window_3                  |
|                                   |
+-----------------------------------+

<
Using the following setup wouldn't mess up the current layout as it
does not use absolute positioning:

text
let g:undotree_CustomUndotreeCmd = 'vertical 32 new'
let g:undotree_CustomDiffpanelCmd= 'belowright 12 new'

<
Issuing :UndotreeToggle now in window_1 would result in:

text
+--------+---------------+----------+
|        |               |          |
|   u    |               |    w     |
|   n    |               |    i     |
|   d    |               |    n     |
|   o    |   window_1    |    d     |
|        |               |    o     |
+--------+               |    w     |
|        |               |    |     |
|  diff  |               |    2     |
|        |               |          |
+--------+---------------+----------+
|                                   |
|         window_3                  |
|                                   |
+-----------------------------------+

<
Executing :UndotreeToggle again would turn off UndoTree (independently
of which window was active at the time). Moving between window1, window_2
and window_3 would result in showing the respective window's changelog
in the undotree panel.

text
CAVEAT: To avoid the Vim's default behaviour of equalizing window sizes
        when closing a window, set the 'noequalalways' option.

3.3 g:undotree_SplitWidth undotree_SplitWidth

Set the undotree window width.

Default: 30


3.4 g:undotree_DiffpanelHeight undotree_DiffpanelHeight

Set the diff window height.

Default: 10


3.5 g:undotree_DiffAutoOpen undotree_DiffAutoOpen

Set this to 1 to auto open the diff window.

Default: 1


3.6 g:undotree_SetFocusWhenToggle undotree_SetFocusWhenToggle

If set to 1, the undotree window will get focus after being opened, otherwise
focus will stay in current window.

Default: 0


3.7 g:undotree_TreeNodeShape undotree_TreeNodeShape
g:undotree_TreeVertShape undotree_TreeVertShape
g:undotree_TreeSplitShape undotree_TreeSplitShape
g:undotree_TreeReturnShape undotree_TreeReturnShape

Set the characters used to draw the tree. Although you can put any character
you want in these shape variables, the only Unicode box drawing characters
that work well are these three. Make sure your font will render them; you can
easily see if that's the case in the last column of this table.

Variable | Default | Unicode Box Character
---------------------------+---------------+-----------------------
g:undotree_TreeNodeShape | * |
g:undotree_TreeReturnShape | \ (backslash) | โ•ฒ (U+2572)
g:undotree_TreeVertShape | | (pipe) | โ”‚ (U+2502)
g:undotree_TreeSplitShape | / (slash) | โ•ฑ (U+2571)


3.8 g:undotree_DiffCommand undotree_DiffCommand

Set the command used to get the diff output.

Default: "diff"


3.9 g:undotree_RelativeTimestamp undotree_RelativeTimestamp

Set to 1 to use relative timestamp.

Default: 1


3.10 g:undotree_ShortIndicators undotree_ShortIndicators

Set to 1 to get short timestamps when |undotree_RelativeTimestamp| is also
enabled:

text
Before     |  After
===========================
(5 seconds ago) |  (5 s)
----------------|----------
 (1 minute ago) |  (1 m)
----------------|----------
(2 minutes ago) |  (2 m)
----------------|----------
  (1 hour ago)  |  (1 h)
----------------|----------
   (Original)   |  (Orig)

<
Default: 0


3.11 g:undotree_HighlightChangedText undotree_HighlightChangedText

Set to 1 to highlight the changed text.

Default: 1


3.12 g:undotree_HighlightSyntaxAdd undotree_HighlightSyntaxAdd
g:undotree_HighlightSyntaxDel undotree_HighlightSyntaxDel
g:undotree_HighlightSyntaxChange undotree_HighlightSyntaxChange

Set the highlight linked syntax type.
You may chose your favorite through ":hi" command.

Default: "DiffAdd", "DiffDelete" and "DiffChange"


3.13 g:undotree_SignAdded undotree_SignAdded
g:undotree_SignModified undotree_SignModified
g:undotree_SignDeleted undotree_SignDeleted
g:undotree_SignDeletedEnd undotree_SignDeletedEnd

Set the signs to display in the gutter where the file has been changed.

SignDeletedEnd is used when the last line of the buffer has been deleted;
it is not possible to display SignDeleted since the deleted text is actually
beyond the end of the current buffer version and therefore it is not possible
to place a sign on the exact line - because it doesn't exist.
Instead, a special delete sign is placed on the (existing) last line of the
buffer

Default: "++", "~~", "--" and "-v"


3.14 g:Undotree_CustomMap Undotree_CustomMap

There are two ways of changing the default key mappings:
The first way is to define global mappings as the following example:

text
nmap  J UndotreeNextState
nmap  K UndotreePreviousState

<
A better approach is to define the callback function g:Undotree_CustomMap().
The function will be called after the undotree windows is initialized, so the
key mappings only works on the undotree windows.

text
function g:Undotree_CustomMap()
    nmap  J UndotreeNextState
    nmap  K UndotreePreviousState
endfunc

<
List of the commands available for redefinition.

text
UndotreeHelp
UndotreeClose
UndotreeFocusTarget
UndotreeClearHistory
UndotreeTimestampToggle
UndotreeDiffToggle
UndotreeNextState
UndotreePreviousState
UndotreeNextSavedState
UndotreePreviousSavedState
UndotreeRedo
UndotreeUndo
UndotreeEnter
UndotreeDiffMark
UndotreeClearDiffMark

<


3.15 g:undotree_HelpLine undotree_HelpLine

Set to 0 to hide "Press ? for help".

Default: 1


3.16 g:undotree_CursorLine undotree_CursorLine

Set to 0 to disable cursorline.

Default: 1


3.17 g:undotree_StatusLine

By default, Undotree will override your statusline option while in the
Undotree buffer.
Set to 0 to disable this.

Default: 1


3.18 g:undotree_DisabledFiletypes undotree_DisabledFiletypes

List of filetypes that Undotree will ignore.

Default: empty


3.19 g:undotree_DisabledBuftypes undotree_DisabledBuftypes

List of filetypes that Undotree will ignore.

Default: ['terminal', 'prompt', 'quickfix']


3.20 g:undotree_UndoDir undotree_UndoDir

Set the path for the persistence undo directory. Due to the differing formats
of the persistence undo files between nvim and vim, the default undodir for
both has been intentionally given different paths. This ensures that users who
use both nvim and vim do not accidentally lose their persistence undo files
due to the different ways in which vim and nvim handle these files.

If the g:undotree_UndoDir is not set and undodir has been set to "." (vim's
default undodir value), then the g:undotree_UndoDir value will be set to:

text
-  vim: $HOME/.local/state/undo/vim/
- nvim: $HOME/.local/state/undo/nvim/

==============================================================================
4. Bugs undotree-bugs

Post any issue and feature request here:
https://github.com/mbbill/undotree/issues

==============================================================================
5. Changelog undotree-changelog

Further changes will not be recorded. Please go to github page for more
information.

4.4 (2017-10-15)
- Autoload plugin functions

4.3 (2013-02-18)
- Several fixes and enhancements.

4.2 (2012-11-24)
- Fixed some small issue.

4.1 (2012-09-05)
- Enhanced tree style.
- Multi-window switching support.

4.0 (2012-08-30)
- Live updated highlight for changed text.
- Customizable key mappings.
- Fixed some minor bugs.

3.1 (2012-08-25)
- Add saved status.
- Add relative timestamp.
- Add ability of clear undo history.

3.0 (2012-08-24)
- Add diff panel.
- Performance improvement.

2.2 (2012-08-21)
- Stable version.

2.1 (2012-08-20)
- Fixed some annoying issues.

2.0 (2012-08-19)
- Hotkey support.
- Handle undo levels.
- Auto refresh.
- And so on.

1.0 (2012-08-18)
- Initial upload

==============================================================================
6. License undotree-license

BSD

vim:tw=78:ts=8:ft=help:norl:


--- METRICS ---