Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: Write Your Own Emacs Minor Mode (Writing Goal Tracker)

Create a real Emacs minor mode that shows word-count progress in the mode line: defcustom, define-minor-mode, keymaps, hooks and a packaging checklist.

You have used dozens of minor modes: visual-line-mode, flyspell-mode, electric-pair-mode. Writing one yourself is the clearest way to see how Emacs extensions work: a mode is a variable plus functions, a keymap, a hook and a mode-line entry. In this project you build word-goal-mode, which shows your progress toward a word target in the mode line while you write.

The Elisp code is real and complete. The runnable block is a JavaScript stand-in that models the logic (word counting and progress text) so you can see the output without Emacs; to run the real mode, paste the Elisp into a buffer and evaluate it with M-x eval-buffer.

Design

The mode should:

  1. Toggle on and off in a buffer (M-x word-goal-mode).
  2. Have a user option for the goal (word-goal-target, customizable).
  3. Count words after edits, cheaply, and show Words 312/500 (62%) in the mode line.
  4. Offer a command to set the goal interactively and a key binding.

The code

ELISP
;;; word-goal.el --- Show writing progress in the mode line  -*- lexical-binding: t; -*-

;; Version: 0.1
;; Package-Requires: ((emacs "27.1"))

;;; Commentary:
;; Enable `word-goal-mode' to see how close you are to a word target.

;;; Code:

(defgroup word-goal nil
  "Writing progress in the mode line."
  :group 'convenience)

(defcustom word-goal-target 500
  "Number of words you want to write in the buffer."
  :type 'natnum
  :safe #'natnump
  :group 'word-goal)

(defvar-local word-goal--count 0
  "Cached word count of the current buffer.")

(defvar-local word-goal--timer nil
  "Idle timer that refreshes the count.")

(defun word-goal--update (buffer)
  "Recount words in BUFFER and refresh the mode line."
  (when (buffer-live-p buffer)
    (with-current-buffer buffer
      (setq word-goal--count (count-words (point-min) (point-max)))
      (force-mode-line-update))))

(defun word-goal--schedule (&rest _)
  "Schedule a recount after Emacs has been idle briefly."
  (when (timerp word-goal--timer)
    (cancel-timer word-goal--timer))
  (setq word-goal--timer
        (run-with-idle-timer 0.5 nil #'word-goal--update (current-buffer))))

(defun word-goal--indicator ()
  "Return the mode line text for the current progress."
  (let ((percent (if (zerop word-goal-target)
                     100
                   (min 100 (/ (* 100 word-goal--count) word-goal-target)))))
    (format " Words %d/%d (%d%%)" word-goal--count word-goal-target percent)))

;;;###autoload
(defun word-goal-set-target (n)
  "Set the word goal to N for this session."
  (interactive "nNew word goal: ")
  (setq word-goal-target n)
  (word-goal--update (current-buffer)))

(defvar word-goal-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map (kbd "C-c w g") #'word-goal-set-target)
    map)
  "Keymap for `word-goal-mode'.")

;;;###autoload
(define-minor-mode word-goal-mode
  "Show progress toward `word-goal-target' in the mode line."
  :lighter (:eval (word-goal--indicator))
  :keymap word-goal-mode-map
  (if word-goal-mode
      (progn
        (add-hook 'after-change-functions #'word-goal--schedule nil t)
        (word-goal--update (current-buffer)))
    (remove-hook 'after-change-functions #'word-goal--schedule t)
    (when (timerp word-goal--timer)
      (cancel-timer word-goal--timer))))

(provide 'word-goal)
;;; word-goal.el ends here

How it works

defgroup and defcustom make the setting discoverable in M-x customize-group RET word-goal. :type 'natnum gives Customize the right widget; :safe allows the value as a file-local variable.

defvar-local creates a variable that is automatically buffer-local, so each buffer has its own count and timer.

define-minor-mode is a macro that creates the variable word-goal-mode, the toggle command of the same name, a hook word-goal-mode-hook, and a keymap entry. The body runs whenever the mode is switched, and the variable tells you the new state. Passing :lighter supplies mode-line text; because it is a (:eval ...) form, Emacs re-evaluates it each time the mode line is redrawn, so it always shows the current count. :keymap activates word-goal-mode-map while the mode is on.

after-change-functions is an abnormal hook that runs after every edit with three arguments. Our function ignores them (&rest _) and schedules a recount after half a second of idleness, so fast typing does not trigger a recount for every key. The fourth argument t in add-hook makes the hook buffer-local, and remove-hook with t cleans up when the mode turns off. This debouncing is a general pattern worth remembering.

;;;###autoload lines let Emacs know the commands exist without loading the whole file, which keeps startup fast when the file is part of a package.

JS Stand-in: the progress logic

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Test it

  1. Save the code as ~/.emacs.d/lisp/word-goal.el.
  2. Add to your init file: (add-to-list 'load-path (expand-file-name "lisp" user-emacs-directory)) and (require 'word-goal) (or use (use-package word-goal :load-path "lisp" :hook (text-mode . word-goal-mode))).
  3. Open a text buffer, run M-x word-goal-mode, type, and watch the mode line.
  4. Use C-c w g to change the target; run M-x word-goal-mode again to turn it off.
  5. M-x checkdoc verifies docstring style; M-x byte-compile-file shows warnings; M-x package-lint-current-buffer (package) checks the header for MELPA.

Next steps

  • Add a :global t variant, or make the target per file with a file-local variable (-*- word-goal-target: 1000 -*-).
  • Show an alert when the goal is reached, using message once.
  • Write tests with ERT (ert-deftest) and run them with M-x ert RET t RET.
  • To share it, add the standard header, a Commentary: section and a provide line, then publish it in a Git repository and submit it to MELPA.

A major mode would call define-derived-mode instead and give the buffer a keymap, syntax table and font-lock rules of its own. A buffer can have only one major mode but many minor modes like this one.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does define-minor-mode create automatically?

    It defines the variable, the command with the same name, and a -hook variable.
  2. 2. Why does the mode wait for an idle timer before recounting?

    Idle timers batch rapid edits so the work happens once when typing pauses.
  3. 3. What does the t in (add-hook 'after-change-functions #'fn nil t) mean?

    The fourth argument LOCAL makes the hook buffer-local.
  4. 4. What is defvar-local for?

    defvar-local makes each buffer have its own value of the variable.

Summary

  • defcustom creates a user option; define-minor-mode creates the mode, command, hook and keymap hook-up.
  • :lighter with (:eval ...) shows live information in the mode line.
  • Buffer-local variables and hooks keep each buffer independent.
  • Debounce expensive work with run-with-idle-timer.
  • Add headers, provide and autoload cookies to make a file shareable; test with checkdoc, the byte compiler and ERT.

Next: Practice: Key Drills and the Key Description Syntax