Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Emacs determines a unit of work to undo

Tags:

emacs

When you enter the command C-/, Emacs undoes some part of your recent changes to a buffer. When you enter C-/ again, it undoes another chunk of work.

I have read the Emacs manual entry on Undo but it is vague about exactly how it works. The manual says "Consecutive character insertion commands are usually grouped together into a single undo record" but it does not explain how it decides the number of character insertion commands that constitute a group. The number of characters it puts in a group seems random.

Can anyone explain the algorithm Emacs uses to group characters into undo records?

like image 679
John D. Cook Avatar asked Jul 06 '11 02:07

John D. Cook


People also ask

What is the Emacs command to undo?

The command C-x u or C-_ is how you undo. The first time you give this command, it undoes the last change.

How do I undo an undo in Emacs?

Just move the cursor in any direction, and type C-x u again. Emacs redoes the last command you undid. You can repeat it to redo previous undos. Although undo is an important command, it can be slow if you want to undo a large number of changes.

How do you redo doom in Emacs?

By default, redo in Emacs requires pressing C-g, then undo.

What does buffer mean in Emacs?

Buffers in Emacs editing are objects that have distinct names and hold text that can be edited. Buffers appear to Lisp programs as a special data type. You can think of the contents of a buffer as a string that you can extend; insertions and deletions may occur in any part of the buffer.


1 Answers

The logic for setting undo boundaries is mostly in self-insert-command which is implemented in cmds.c. You'll have to read the code for the full story, but basically:

  • As long as you are just typing characters, there's an undo boundary every 20 characters you type.
  • But if you issue a different editing command (you kill a word, for example), this causes an undo boundary to be added immediately, resetting the character count.
  • Certain "hairy" insertions (as determined by internal_self_insert) cause an an undo boundary to be added immediately, and the character count to be reset. Reading the code, it looks as though these are: (1) in overwrite-mode, if you overwrote a character with one that has a different width, e.g. typing over a tab; (2) if the character you inserted caused an abbreviation to be expanded; (3) if the character you typed caused auto-fill-mode to insert indentation.
  • In addition, any editing command that decides it would be a good idea to have an undo boundary can request it by calling undo-boundary. This does not cause the character count to be reset.
like image 71
Gareth Rees Avatar answered Oct 02 '22 14:10

Gareth Rees