Elisp: Create Function Templates

By Xah Lee. Date: . Last updated: .

Problem

You are writing a major mode for your own language. You want function templates for your language.

suppose you want these abbrevs:

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))
  1. Copy and paste the code into a buffer.
  2. Alt+x eval-buffer
  3. Open a new file, then turn on xx by Alt+x xx
  4. Alt+x abbrev-mode to turn abbrev on if not already.
  5. Now, type “fn”, then type space. It'll become “function”

Abbrev Table

for how abbrev works, see

Emacs lisp, writing a major mode. Essentials