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?


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))
    (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))))))
  • Thanks for the function. Any idea how I can incorporate this into regular abbrevs?
    – Malabarba
    Feb 17 '15 at 18:32
  • Nope, I have no idea how regular abbrevs work.
    – abo-abo
    Feb 17 '15 at 18:36

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.