6

Very occasionally, hit SPC during regular typing and get an unexpected abbrev expansion. What I usually do in this case is undo (which reverts the expansion and the inserted space) and then manually C-q SPC to add the space again.

It would be really useful if, when I hit undo, only the expansion would get reverted, but the space would stay. Then, hitting undo a second time could revert the space insertion too. This is what you usually see in editors with auto-correction features (the first undo affects the correction, the second affects the space you typed).

How can I achieve this?

Malabarba
  • 22,878
  • 6
  • 78
  • 163

1 Answers1

2

You need undo-boundary.

For example:

(defun abel-expand ()
  "Expand the abbrev before point."
  (when (= (length (this-command-keys-vector)) 1)
    (insert-char (aref (this-command-keys-vector) 0))
    (undo-boundary)
    (backward-delete-char 1))
  (unless (memq (aref (this-command-keys-vector) 0) '(?- ?+ ?/ ?_))
    (when (looking-at "[])} ]")
      (let ((pt (point)))
        (skip-chars-backward "[[:alnum:]]")
        (let* ((name (buffer-substring-no-properties (point) pt))
               (body (gethash name abel--table)))
          (delete-region (point) pt)
          (insert body))))))
abo-abo
  • 13,943
  • 1
  • 29
  • 43