Elisp: Create Function Templates
Problem
You are writing a major mode for your own language. You want function templates for your language.
suppose you want these abbrevs:
- typing “fn” becomes “function”
- typing “function” becomes “function name (x) { return x; }”
Solution
Here's the complete code for a major mode with abbrev.
;; -*- coding: utf-8; lexical-binding: t; -*- ;; sample major mode xx with abbrevs ;; clear value and all properties ;; useful during dev. ;; because this get rid of abbrev table symbol properties too (setq xx-abbrev-table nil) (define-abbrev-table 'xx-abbrev-table '(("fn" "function") ("function" "function name (x) { return x; }") ;; hundreds more ) "Abbrev table for `xx'" :case-fixed t :system t ) (define-derived-mode xx prog-mode "xx" "A major mode for xx." :abbrev-table xx-abbrev-table (abbrev-mode 1))
- Copy and paste the code into a buffer.
- Alt+x
eval-buffer - Open a new file, then turn on xx by Alt+x xx
- Alt+x
abbrev-modeto turn abbrev on if not already. - Now, type “fn”, then type space. It'll become “function”
Abbrev Table
for how abbrev works, see: