user673592
user673592

Reputation: 2120

Prevent Abbrev expansion after certain symbols in Emacs

Is there a way to prevent automatic expansion of an abbreviation in the built-in abbrev-mode after certain symbols? E.g. I want my abbrev to expand after whitespace, newline, comma etc., but not after a dash or underscore.

I know I can hit C-q before typing the (say) underscore, but an automatic solution would be much nicer since this occurs for me very often.

There are some abbrev hooks in the manual, but since I am a total beginner with Elisp I don't see an obvious solution...

Thank you very much!

Upvotes: 3

Views: 436

Answers (2)

Drew
Drew

Reputation: 30708

Make underscore be a word-constituent character for the current mode. From the Emacs manual, node Expanding Abbrevs:

[A]ny character that is not a word constituent expands an abbrev, and any word-constituent character can be part of an abbrev.

Use function modify-syntax-entry to modify the syntax class of _, to make it a word constituent:

(modify-syntax-entry ?_ "w")

This solution is useful only if it is not otherwise bothersome for _ to be a word-constituent character. Do you want _ to act as if it is a part of a word or not? That's the first question.

Upvotes: 1

user673592
user673592

Reputation: 2120

OK, so a hint of the solution was already in the question itself. This is what works for me:

(defun protect-underscore ()
 (interactive)
 (insert "_"))

(defun protect-dash ()
 (interactive)
 (insert "-"))

(defun protect-equal ()
 (interactive)
 (insert "="))

(global-set-key (kbd "_") 'protect-underscore)
(global-set-key (kbd "-") 'protect-dash)
(global-set-key (kbd "=") 'protect-equal)

I am sure there has to be a more elegant solution... thanks goes to Magnar.

Upvotes: 0

Related Questions