3

I would like expand-abbrev to operate differently depending on what is just after the abbreviation to be expanded. In particular, if there is a space after the cursor, then expand-abbrev should not insert an additional space.

For example (assuming | is the cursor, _ is a space, a expands into alpha, and a space is typed):

insertion at the end of line:          a|      --> alpha_
insertion in the middle of a sentence: a| beta --> alpha_beta (not alpha__beta)
  • 2
    Wouldn't it be simpler just to call expand-abbrev? – Dan Jun 9 '15 at 19:57
5

You could use a pre-abbrev-expand-hook to delete the extra space before the abbrev is expanded like this:

(defun delete-preceding-space-before-expand ()
  (when (and (= (char-after) ?\s)
             ;; only do if expanded with space
             (= last-command-event ?\s)
             (abbrev--before-point))
    (message "%S" last-command-event)
    (delete-char 1)))

(add-hook 'pre-abbrev-expand-hook 'delete-preceding-space-before-expand)

Expanding on the given code:

The code above is written to only work when abbrevs are expanded with space you could also modify this to work with any non-word character so that something like a|-bar expanded with - would expand to alpha-bar instead of alpha--bar which would be useful in lisps and elsewhere. You could do this by comparing (char-after) and last-command-event for equality instead of checking if they are space.

If you want to delete all existing spaces (not just one) and ensure there is only a single space between the expansion and the next word, you could replace (delete-char 1) in the function with (just-one-space 0)

This way a| foobar would expand to alpha foobar

  • Nice. The only change I would do is to put abbrev--before-point at the end of the and, so that this (CPU consuming) function is called less frequently. – scaramouche Jun 10 '15 at 12:48
  • Good idea, I edited the code. – Jordon Biondo Jun 10 '15 at 13:05
  • On Emacs 24.5.1, I get an error wrong type argument: number-or-marker-p, nil anytime I hit - or space. It appears that the hook is firing even if there's no abbrev match. This is with abbrev-mode on. – ragerdl Aug 10 '16 at 0:27

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.