ResultsMotivated.com

Quickstart primer on transient menus in Emacs

<2024-06-22>

1. What is a transient in emacs?

At a high level, is a just a pop-up menu where you hit a key to select an option. If you've ever used Magit, you've used transients before. In fact, the package Transient was specifically invented for use in Magit.

2. Implementing transient menus: A quickstart

Transient menus are a simple concept, but the official documentation is somewhat complicated. For those who want to use transients and don't care about the details, allow me to save you a lot of time by providing a minimal example of how to implement a transient in Emacs:

(defun callback1 ()
  (interactive)
  (message "callback1"))

(defun callback2 ()
  (interactive)
  (message "callback2"))

(defun callback3 ()
  (interactive)
  (message "callback3"))

(transient-define-prefix demo-transient ()
  "Insert docstring here."
  [["This is a transient:"
    ("1" "opt1" callback1)
    ("2" "opt2" callback2)
    ("3" "opt3" callback3)
    ("q" "exit" transient-noop)
    ]])

(global-set-key (kbd "C-c <f1>") #'demo-transient)

This is a versatile recipe that you can adapt to cover about 90% of practical use-cases. Here's a more involved example (from transient-showcase) that demonstrates how to use some of the other features that transient provides:

;; infix defined with a macro
(transient-define-argument tsc--exclusive-switches ()
  "This is a specialized infix for only selecting one of several values."
  :class 'transient-switches
  :argument-format "--%s-snowcone"
  :argument-regexp "\\(--\\(grape\\|orange\\|cherry\\|lime\\)-snowcone\\)"
  :choices '("grape" "orange" "cherry" "lime"))

(transient-define-prefix tsc-basic-infixes ()
  "Prefix that just shows off many typical infix types."
  ["Infixes"
   ;; shorthand definitions
   ("-b" "switch with shortarg" ("-w" "--switch-short"))
   ;; note :short-arg != :key
   ("-s" "switch" "--switch")
   ( "n" "no dash switch" "still works")
   ("-a" "argument" "--argument=" :prompt "Let's argue because: ")
   ;; a bit of inline EIEIO in our shorthand
   ("-n" "never empty" "--non-null=" :always-read t  :allow-empty nil
    :init-value (lambda (obj) (oset obj value "better-than-nothing")))
   ("-c" "choices" "--choice=" :choices (foo bar baz))]
  ["Show Args"
   ("s" "show arguments" tsc-suffix-print-args)])

(tsc-basic-infixes)

If that wasn't boring enough, you can go read about transient prefixes, infixes, postfixes, and so on here.


Modified: 2024-09-10 10:09:59 EDT

Emacs 29.1.50 (Org mode 9.7.6)