Elisp: Abbrev Expand Function
Abbrev Expand Function
An abbrev can expand to arbitrary dynamic text at expansion time, by writing your own function.
If you want your own expansion function, in your major mode activation function, you need to set the variable abbrev-expand-function as local var, and with value to your own expansion function.
- abbrev-expand-function
-
Variable. Value is a function. This function is called to expand abbrev.
- The function takes no argument.
- The return value of the expansion function should be non-nil if abbrev is considered expanded. Else, nil.
The default value is
abbrev--default-expand
.(make-local-variable 'abbrev-expand-function) (setq abbrev-expand-function 'xx-expand-abbrev)
Example: Abbrev Expand Function
;; -*- coding: utf-8; lexical-binding: t; -*- ;; example of a major mode, using abbrev as function template system ;; allowing abbrev to contain dot, for names like ;; a.f expanding to Array.from (defun xx--expand-abbrev () "Expand the word before cursor. Word here is letters and dot. Returns the abbrev symbol if there's a expansion, else nil." (let ((xsyntax-state (syntax-ppss))) ;; abbrev property :enable-function is ignored, if you define your own expansion function ;; check whether to expand ;; don't expand if inside string or comment (when (not (or (nth 3 xsyntax-state) (nth 4 xsyntax-state))) (let (xp1 (xp2 (point)) xabrStr xabrSymbol) ;; get the word to the left of cursor, includig dot (save-excursion (skip-chars-backward ".a-zA-Z") (setq xp1 (point))) (setq xabrStr (buffer-substring-no-properties xp1 xp2)) (setq xabrSymbol (abbrev-symbol xabrStr)) (if xabrSymbol (progn (abbrev-insert xabrSymbol xabrStr xp1 xp2) (when (search-backward "▮" xp1 t) (delete-char 1)) xabrSymbol ) nil))))) (defun xx--abhook () "Abbrev hook function, used for `define-abbrev'. with property `no-self-insert'." t) (put 'xx--abhook 'no-self-insert t) ;; HHHH--------------------------------------------------- ;; if still dev, it's convenient to start fresh. this also removes properties (setq xx-abbrev-table nil) (define-abbrev-table 'xx-abbrev-table '( ;; expand abbrev words to full words ("a.f" "Array.from" xx--abhook) ("a.i" "Array.isArray" xx--abhook) ("a.o" "Array.of" xx--abhook) ;; expand function names to templates ("Array.from" "Array.from(▮xlist, ?f, ?thisbinding)" xx--abhook) ("Array.isArray" "Array.isArray(▮xlist)" xx--abhook) ("Array.of" "Array.of(▮xlist)" xx--abhook) ) "Abbrev table for `xx'" ) (abbrev-table-put xx-abbrev-table :case-fixed t) (abbrev-table-put xx-abbrev-table :system t) (define-derived-mode xx prog-mode "xx" "A major mode for xx" :abbrev-table xx-abbrev-table (make-local-variable 'abbrev-expand-function) (setq abbrev-expand-function 'xx--expand-abbrev) (abbrev-mode 1))
The actual insertion of the abbrev string's expanded string, is by calling
abbrev-insert
.
There are several other functions that help you write the expansion, such as what's the last abbrev used.