When running the command undo-tree-undo/redo successively, things are undone/redone based upon the current active branch. Although the user receives a branch point message along the way, the previous branches are ignored unless a user manually selects a different branch.

I understand that I can open the visualizer and select a different branch, however, it would be very useful to just hold down the undo/redo key and watch everything happen in the exact opposite order. Ideally, this should work irrespective of whether the visualizer buffer is open -- i.e., programmatically calculate the order from finish to start, and from start to finish.

Q:  This is essentially a feature request to extend undo-tree to permit linear successive undo/redo, irrespective of whether the visualizer buffer is open. [New functions and alternative keyboard shortcuts for this new feature are certainly acceptable.]

  • The code of undo-tree looks like it is part of the concept that you can switch freely between buffer-undo-tree and buffer-undo-list by toggling undo-tree-mode. As I understand your question the original handling of buffer-undo-list does what you want. So it suggests itself to temporarily switch off undo-tree-mode for your purpose. Pityingly the switching between buffer-undo-tree and buffer-undo-list seems to be buggy (at least for me). So maybe, the way to go would be just a bug-report to the maintainer of undo-tree. But, maybe my guess about the original concept is wrong. – Tobias Apr 6 '17 at 6:33
  • I think the best solution to your problem would be to repair undo-tree-mode such that switching between buffer-undo-tree and buffer-undo-list works flawless. Have you considered to issue a bug-report at ` toby-undo-tree@dr-qubit.org`? – Tobias Apr 13 '17 at 15:49
  • @Tobias -- I would like to see and use the visualizer of undo-tree while using the new linear feature; and, I would like the new linear feature to work without the visualizer buffer necessarily being visible. In general, I implement my own improvements/modifications to Emacs, both its built-in and optional third-party libraries. When I get stuck or I see something super-complex like the undo feature, I ask for help. A feature request to the maintainer couldn't hurt, but I would prefer to handle it here. – lawlist Apr 13 '17 at 16:05
  • @Tobias -- In looking at the undo-tree.el code today, I saw that there is a node timestamp feature. I'm not sure if each node has a valid time-stamp and whether those survive to the next Emacs session (when restoring history), but that sounds like it could be shortcut to resolving this new feature request -- i.e., sorting and selecting the previous or next in time. I haven't yet seen what the layout of the land looks like at a branch point, but ... those are my preliminary thoughts . . . . – lawlist Apr 23 '17 at 18:54
  • I think the key to a linear walk through the undo-tree is undo-list-rebuild-from-tree. One should let-bind the variable buffer-undo-list and let undo-list-rebuild-from-tree do its work. Afterwards copy that value into another local variable, say my-undo-list, and leave the let-form for binding buffer-undo-list. The variable my-undo-list dictates the linear path through the undo-tree. Having a look at undo-list-rebuild-from-tree you see that this function also uses time-stamps. I earlier considered using time-stamps. But, I had the impression that those change too often. – Tobias Apr 23 '17 at 19:09

The following is a prototype implementation of an approximation of what you want. It exploits the fact that new branches in the undo-tree are added at the left-hand side of the current node.

The key-sequence C-M-_ is bound to undo-tree-walk which walks the right-upper part of the undo tree starting at the current node.

The behavior differs from what you want if the active branch of some sub-tree on the right-hand side of the current node is not the left-most branch in that sub-tree.

You can get in such a state by non-trival undo/redo-sequences.

Just try it for yourself to see whether that is sufficient for your application.

(defvar-local undo-tree-walk
  "Possible values:
nil: not in undo/redo-chain
undo: traversing undo tree upwards
redo: traversing undo tree downwards

(setq undo-tree-walk nil)

(defun undo-tree-walk ()
  "Walk the right-upper part of the undo-tree starting at the current node."
  (when (eq buffer-undo-list t)
    (user-error "No undo information."))
  (unless undo-tree-mode
    (user-error "`undo-tree-walk' should only be used with `undo-tree-mode'."))
  (set-transient-map undo-tree-walk-map t #'undo-tree-walk-off)
  (let ((num-branches (undo-tree-num-branches)))
     ((= num-branches 0) ; arrived at leaf
      (setq undo-tree-walk 'undo))
     ((> num-branches 1) ; 
      (let ((branch (undo-tree-node-branch (undo-tree-current buffer-undo-tree))))
    (setf (undo-tree-node-branch (undo-tree-current buffer-undo-tree))
          (if (>= (1+ branch) (undo-tree-num-branches))
            (setq undo-tree-walk 'undo)
            (1- (undo-tree-num-branches)))
        (setq undo-tree-walk 'redo)
        (1+ branch))))
      ;; no state change for (= num-branches 1)
  (case undo-tree-walk
    (setq undo-tree-walk 'undo)
  (let ((curbuf (current-buffer)))
    (switch-to-buffer-other-window curbuf)))

(defun undo-tree-walk-off ()
  "Switch `undo-tree-walk' off."
  (setq undo-tree-walk nil))

(defvar undo-tree-walk-map
  "Keymap active while `undo-tree-walk'.")

(define-key undo-tree-walk-map (kbd "C-M-_") #'undo-tree-walk)

(global-set-key (kbd "C-M-_") #'undo-tree-walk)

Note, that I added undo-tree-visualize to the end of undo-tree-walk to display the consequences of walking the undo-tree with undo-tree-walk. Feel free to modify the code to your likings.

Note also, that I had to choose this most simple approximation of a solution for your problem because of time-restrictions.

  • I added the following to the outset of undo-tree-walk to get past some initial errors, perhaps because I don't have this mode globally active. (when (eq buffer-undo-list t) (user-error "No undo information.")) (undo-list-transfer-to-tree) That silenced my initial errors in a new buffer while trying this answer out. My next observation was that undo-tree-walk reaches the branch point and then switches to the branch on the right, but only goes down the branch one notch/nodule before going back up the branch to the trunk. My preferred setup creates a notch/nodule for every key stroke. – lawlist Apr 6 '17 at 2:02
  • There is absolutely no hurry on a solution. Please feel free to take all the time that you need -- beyond the bounty period is perfectly acceptable. When implemented, I am sure that I will be using this feature on a daily basis for the foreseeable future and judging by the upvotes so far, other people would like to use this feature also. – lawlist Apr 6 '17 at 2:05
  • @lawlist Pityingly, my time is restricted. If it was possible I would have written this answer rather as a comment than an answer. Hopefully, someone else comes up with something better before the bounty period ends. – Tobias Apr 6 '17 at 2:18
  • @lawlist I added undo-list-transfer-to-tree as you proposed. Before that I test whether undo-tree-mode is active otherwise undo-list-transfer-to-tree can be fatal. – Tobias Apr 6 '17 at 3:06
  • Awarded recent bounty for answers in related thread: emacs.stackexchange.com/a/32415/2287 and emacs.stackexchange.com/a/32416/2287 as they are the key ingredients to implementing the new feature. In a nutshell, each node will have a list of time-stamps -- one for each time a node becomes current after a successful undo/redo and also when initially importing. I came up with an idea for visualizing by displaying time-stamps vertically underneath each node, and lengthening the branches accordingly -- it will take some time to programmatically figure out. – lawlist Apr 30 '17 at 16:18

Special thanks to @Tobias for writing up a function to locate the next/previous timestamp in the undo/redo history: https://emacs.stackexchange.com/a/32415/2287; and, for also writing up a series of functions to copy the undo-tree: https://emacs.stackexchange.com/a/32230/2287.

As some readers may already be aware, forks are accepted by MELPA only in extreme circumstances. Creating an add-on is probably doable, but does not seem practical given the quantity of changes that have been made by @lawlist -- including, but not limited to, adding elements to the underlying data structure vectors, and changing the names of several functions/variables that did not conform to the undo-tree-... prefix naming convention, etc. @lawlist has already reached out to the original author (Dr. Cubitt) to offer this new feature, as well as various bug fixes and enhancements.

If anyone is interested, please feel free to give this new feature a whirl. The commentary contains a sample bug report submission form starting from emacs -q in the event that anyone has problems.

Source Code:  https://github.com/lawlist/undo_tree


;;; This unofficial modification by @lawlist to the `undo-tree.el` library authored
;;; by Toby Cubitt adds semi-linear undo/redo support and a corresponding visualizer
;;; view accessible with `C-u C-x u` or by using the 3-way toggle with the letter `t`
;;; in the visualization buffer.  This entire library is meant to be a replacement
;;; of the stock version of `undo-tree.el`, which would need to be completely removed
;;; from the `load-path'.  In the visualization buffer, the letters `u` / `r`
;;; or `z` / `Z` are used for semi-linear undo/redo.  In the working buffer,
;;; `super-u` / `super-r` or `super-z`/`super-Z` are used for semi-linear undo/redo.
;;; Semi-linear undo/redo also work in the classic views of the visualization buffer.
;;; All previous keyboard shortcuts remain unchanged.  The mouse can be used to
;;; select semi-linear nodes or branch-point timestamps in the visualization buffer.
;;; The term `semi-linear` was chosen because the time-line is generally structured
;;; as follows:  When undoing, the movement is in an upward direction from the
;;; leaf to the branch-point and then the previous branch begins undoing from the
;;; leaf.  When redoing, the movement is in a downward direction from the branch-
;;; point to the leaf and then the next branch begins redoing from the branch-point.
;;; It is not a situation where we walk-up and back-down the same branch, or walk-
;;; down and back-up the same branch again.  If that missing feature is useful,
;;; then perhaps it could be implemented someday....
;;; In a nutshell, the classic version of undo-tree undo/redo limits a user to
;;; the active branch (skipping over inactive branches), unless the user calls
;;; `undo-tree-switch-branch' or `undo-tree-visualize-switch-branch-right' or
;;; `undo-tree-visualize-switch-branch-left' to select an alternative branch.  This
;;; generally means a user must pop-open the visualizer buffer to see what is going
;;; on to make a proper decision.  The new semi-linear feature is essentially
;;; "mindless" where the user can just hold down the forward/reverse button and
;;; go through every node of the tree in chronological order -- i.e., all branches
;;; and nodes are visited in the process (nothing is skipped over).
;;; The labels in the visualization buffer remain the same:  `o`, `x`, `s`, register.
;;; The branches are labeled consecutively as they are drawn with lowercase letters.
;;; The branch-points are labeled consecutively as they are drawn with uppercase
;;; letters.  The branches coming off of each branch-point are labeled with the nth
;;; numeric position of the branch -- e.g., far left is always nth 0.  The nodes of
;;; each branch are numbered consecutively commencing just after the branch-point.
;;; The features that are available in `undo-tree.el` version 0.6.6 remain the same;
;;; however, some of the functions have been consolidated and the names have changed.
;;; `undo-tree-history-save' and `undo-tree-history-restore' support input/output
;;; to/from a string or a file.  The history string/file contains three components:
;;; `buffer-file-name' (if it exists; else `nil`); SHA1 string; the `undo-tree-list'.
;;; Histories created with the unmodified stock version of `undo-tree.el` contained 2
;;; components and those previous versions are no longer supported.  Saving/exporting
;;; excludes all text-properties, yasnippet entries, and multiple-cursors entries.
;;; `read' chokes when encountering #<marker in no buffer> or #<overlay in no buffer>,
;;; that can make their way into the `undo-tree-list' when killing the visualizer
;;; buffer by brute force or when using the yasnippet library.  Those two known
;;; situations have been dealt with programmatically.  However, there are surely
;;; other libraries that use markers and/or overlays that could make their way into
;;; the tree and new ways of dealing with those entries will be required.  If you
;;; encounter an error message when performing `undo-tree-history-save', please
;;; inspect the `*Messages*` buffer for clues such as the above examples.  Inasmuch
;;; as there is now a sanity check at the tail end of `undo-tree-history-save', any
;;; problems should materialize before a user actually tries to restore the history.
;;; The persistent undo storage has been expanded by adding certain features borrowed
;;; from the built-in `image-dired.el' library:
;;; `undo-tree-history-autosave':  When non-nil, `undo-tree-mode' will save undo
;;;                                history to a file when a buffer is saved; and,
;;;                                the save/restore functions attached to the
;;;                                following hooks will become active:
;;;                                -  `write-file-functions'
;;;                                -  `find-file-hook'
;;;                                To exclude certain files, users may wish to let-
;;;                                bind this variable to `nil` if it has a global
;;;                                non-nil value.  See also the next variable below.
;;; `undo-tree-history-file-exclusions':  A list of absolute file names that will be
;;;                                       excluded from the auto save/restore process.
;;; `undo-tree-history-alist':  Used when `undo-tree-history-storage' is 'classic.
;;;                             See the doc-string for customization tips/tricks.
;;; `undo-tree-history-directory':  Directory where history files are stored when
;;;                                `undo-tree-history-storage' is 'central.
;;; `undo-tree-history-storage':  How to store undo-tree history files.
;;;                               'classic:  See `undo-tree-history-alist'.
;;;                               'home (md5):  A folder in the HOME directory.
;;;                               'central (md5):  See `undo-tree-history-directory'.
;;;                               'local:  Create sub-directory in working directory.
;;; For those users who wish to use Emacs to view the saved/exported history, be
;;; aware that the undo history is one long string, and Emacs has trouble viewing a
;;; buffer with very long lines.  `(setq-default bidi-display-reordering nil)` will
;;; help permit Emacs to view buffers with very long lines without bogging down.
;;; The primary interactive functions for undo/redo in the working buffer are:
;;;   M-x undo-tree-classic-undo
;;;   M-x undo-tree-classic-redo
;;;   M-x undo-tree-linear-undo
;;;   M-x undo-tree-linear-redo
;;; The primary interactive functions for undo/redo in the visualization buffer are:
;;;   M-x undo-tree-visualize-classic-undo
;;;   M-x undo-tree-visualize-classic-redo
;;;   M-x undo-tree-visualize-linear-undo
;;;   M-x undo-tree-visualize-linear-redo
;;; If the built-in undo amalgamation business is not to your liking, it can be
;;; disabled to permit undo boundaries after every command:
;;;   ;;; https://stackoverflow.com/a/41560712/2112489
;;;   (advice-add 'undo-auto--last-boundary-amalgamating-number :override #'ignore)
;;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=27214
;;; https://emacs.stackexchange.com/q/33248/2287
;;; GARBAGE COLLECTION:  @lawlist has encountered a few situations where garbage
;;; collection truncates the `undo-tree-canary' in the `buffer-undo-list', which
;;; causes `undo-tree-transfer-list' to replace the existing `undo-tree-list'
;;; with the new tree fragment obtained from the `buffer-undo-list'.  In this
;;; circumstance, the user loses the entire undo-tree saved history!  The internal
;;; function responsible is `truncate_undo_list' in `undo.c`.  @lawlist has added a
;;; programmatic warning when loss of the existing `undo-tree-list' is about to
;;; occur; however, that does not fix the problem.  The relevant section from
;;; `truncate_undo_list' in `undo.c` is as follows:
;;;          /* When we get to a boundary, decide whether to truncate
;;;      either before or after it.  The lower threshold, undo_limit,
;;;      tells us to truncate after it.  If its size pushes past
;;;      the higher threshold undo_strong_limit, we truncate before it.  */
;;;          if (NILP (elt))
;;;     {
;;;       if (size_so_far > undo_strong_limit)
;;;         break;
;;;       last_boundary = prev;
;;;       if (size_so_far > undo_limit)
;;;         break;
;;;     }
;;; @lawlist opines that setting the `undo-limit' to the same value as
;;; `undo-strong-limit' will cause `truncate_undo_list' to preserve the
;;; `undo-tree-canary' in the `buffer-undo-list' by truncating before the boundary.
;;; This workaround is not ideal because a more recent undo would be truncated in
;;; lieu of an older undo.  One idea would be to convince the Emacs team to modify
;;; `truncate_undo_list' to preserve certain user-defined elements; e.g., a symbol
;;; of `undo-tree-canary'.
;;; The built-in function named `primitive-undo' defined in `simple.el` was used
;;; in the original version of `undo-tree.el`.  @lawlist created a modified
;;; function named `undo-tree--primitive-undo' that serves the same purpose, but
;;; permits setting a window-point in the working buffer while a user is in a
;;; different window such as the visualization buffer.  The revised version also
;;; merely reports a problem with a message instead of throwing an error when it
;;; encounters an `undo-tree-canary' in the wrong location.  This bug was noticed
;;; by @lawlist when performing undo/redo in region, and a Google search revealed
;;; that others too have experienced the same problem.  The bug is fairly easy to
;;; reproduce, but @lawlist has not yet invested the time to look for the cause
;;; and try to come up with a solution.  For anyone who wishes to work on fixing
;;; this and view other mentions of the same problem on the internet, Google:
;;;   "Unrecognized entry in undo list undo-tree-canary"
;;; The semi-linear visualization buffer view looks like this:
;;;        o-00001-a-0
;;;             |
;;;        o-br/pt-A-0
;;;         ____|_______________________________
;;;        /                                    \
;;;  o-00001-b-0                            o-00001-c-1
;;;       |                                      |
;;;  o-00002-b-0                            o-00002-c-1
;;;       |                                      |
;;;  o-00003-b-0                            o-00003-c-1
;;;                                              |
;;;                                         o-00004-c-1
;;;                                              |
;;;                                         o-br/pt-B-1
;;;         _____________________________________|________________________
;;;        /            /                        |                        \
;;;  o-00001-d-0  o-00001-e-1               o-br/pt-C-2               o-00001-f-3
;;;                    |                              |
;;;               o-00002-e-1                    o-00002-f-3
;;;              ___________|___________
;;;                    |             /           |           \             |
;;;               o-00003-e-1  o-00001-g-0  o-00001-h-1  o-00001-i-2  o-00003-f-3
;;;                    |            |            |            |            |
;;;               o-00004-e-1  x-00002-g-0  o-00002-h-1  o-00002-i-2  o-00004-f-3
;;;       23:03:45:36
;;;                    |                                      |            |
;;;               o-00005-e-1                            o-00003-i-2  o-00005-f-3
;;;                    |                                      |            |
;;;               o-00006-e-1                            o-00004-i-2  o-00006-f-3
;;;                    |                                      |            |
;;;               o-00007-e-1                            o-00005-i-2  o-00007-f-3
;;;                    |                                      |            |
;;;               o-00008-e-1                            o-00006-i-2  o-00008-f-3
;;; To check for updates, please visit the source-code of the link listed at the
;;; top and also review the "Change Log" at the bottom.
;;; Bug reports and feature requests may be submitted via email to the address at
;;; the top.  Essentially, if it breaks in half, I can guarantee that you will
;;; have 2 pieces that may not necessarily be the same size.  :)  That being said,
;;; I will certainly make efforts to fix any problem that may arise relating to
;;; the semi-linear undo/redo feature.  A step 1-2-3 recipe starting from emacs -q
;;; would be very helpful so that @lawlist can observe the same behavior described
;;; in the bug report.  Here is an example to get you started:
;;; 1.  In an internet browser, visit: https://www.lawlist.com/lisp/undo-tree.el
;;;     Select/highlight all and copy everything to the clipboard.
;;; 2.  Launch Emacs without any user settings whatsoever:  emacs -q
;;;     If possible, please use the latest stable public release of Emacs.
;;;     @lawlist is using the GUI version of Emacs 25.2.1 on OSX.
;;; 3.  Switch to the `*scratch*` buffer.
;;; 4.  Paste the entire contents of the clpipboard into the `*scratch*` buffer.
;;; 5.  M-x eval-buffer RET
;;; 6.  M-x eval-expression RET (setq undo-tree-history-autosave t) RET
;;; 7.  M-x undo-tree-mode RET
;;;     The mode-line indicates `UT`, meaning that `undo-tree-mode' is active.
;;; 8.  M-x save-buffer RET
;;;     @lawlist chose to save the file to his desktop with the name `foo`, and
;;;     also chose to overwrite the file if it already existed; i.e., `y`.
;;;     Look at the lower left-hand side of the mode-line and notice that it
;;;     indicates an unmodified state; i.e., U:--- foo ....
;;; 9.  M-x undo-tree-classic-undo RET
;;;     Look at the lower left-hand side of the mode-line and notice that it
;;;     indicates we have returned to a modified state; i.e., U:**- foo ....
;;; 10. M-x undo-tree-classic-undo RET
;;;     The `undo-tree' library that we had previously pasted to the `*scratch*`
;;;     buffer should now be completely undone; i.e., removed.
;;; 11. M-x undo-tree-classic-undo RET
;;;     The buffer should be completely empty at this point; i.e., the initial
;;;     `*scratch*` message has been removed.
;;; 12. M-x undo-tree-classic-undo RET
;;;     The following `user-error' appears:
;;;       "user-error:  undo-tree--undo-or-redo:  No further undo information."
;;;     This is exactly the behavior that @lawlist expected would happen, so
;;;     everything up to this point appears to be working correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.