config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

transient.el (180533B)


      1 ;;; transient.el --- Transient commands  -*- lexical-binding:t -*-
      2 
      3 ;; Copyright (C) 2018-2024 Free Software Foundation, Inc.
      4 
      5 ;; Author: Jonas Bernoulli <emacs.transient@jonas.bernoulli.dev>
      6 ;; Homepage: https://github.com/magit/transient
      7 ;; Keywords: extensions
      8 
      9 ;; Package-Version: 0.6.0
     10 ;; Package-Requires: ((emacs "26.1") (compat "29.1.4.4") (seq "2.24"))
     11 
     12 ;; SPDX-License-Identifier: GPL-3.0-or-later
     13 
     14 ;; This file is part of GNU Emacs.
     15 
     16 ;; GNU Emacs is free software: you can redistribute it and/or modify
     17 ;; it under the terms of the GNU General Public License as published
     18 ;; by the Free Software Foundation, either version 3 of the License,
     19 ;; or (at your option) any later version.
     20 ;;
     21 ;; GNU Emacs is distributed in the hope that it will be useful,
     22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     24 ;; GNU General Public License for more details.
     25 ;;
     26 ;; You should have received a copy of the GNU General Public License
     27 ;; along with this program.  If not, see <https://www.gnu.org/licenses/>.
     28 
     29 ;;; Commentary:
     30 
     31 ;; Transient is the library used to implement the keyboard-driven menus
     32 ;; in Magit.  It is distributed as a separate package, so that it can be
     33 ;; used to implement similar menus in other packages.
     34 
     35 ;;; Code:
     36 
     37 (require 'cl-lib)
     38 (require 'compat)
     39 (require 'eieio)
     40 (require 'edmacro)
     41 (require 'format-spec)
     42 
     43 (eval-and-compile
     44   (when (and (featurep' seq)
     45              (not (fboundp 'seq-keep)))
     46     (unload-feature 'seq 'force)))
     47 (require 'seq)
     48 (unless (fboundp 'seq-keep)
     49   (display-warning 'transient (substitute-command-keys "\
     50 Transient requires `seq' >= 2.24,
     51 but due to bad defaults, Emacs' package manager, refuses to
     52 upgrade this and other built-in packages to higher releases
     53 from GNU Elpa, when a package specifies that this is needed.
     54 
     55 To fix this, you have to add this to your init file:
     56 
     57   (setq package-install-upgrade-built-in t)
     58 
     59 Then evaluate that expression by placing the cursor after it
     60 and typing \\[eval-last-sexp].
     61 
     62 Once you have done that, you have to explicitly upgrade `seq':
     63 
     64   \\[package-upgrade] seq \\`RET'
     65 
     66 Then you also must make sure the updated version is loaded,
     67 by evaluating this form:
     68 
     69   (progn (unload-feature 'seq t) (require 'seq))
     70 
     71 Until you do this, you will get random errors about `seq-keep'
     72 being undefined while using Transient.
     73 
     74 If you don't use the `package' package manager but still get
     75 this warning, then your chosen package manager likely has a
     76 similar defect.") :emergency))
     77 
     78 (eval-when-compile (require 'subr-x))
     79 
     80 (declare-function info "info" (&optional file-or-node buffer))
     81 (declare-function Man-find-section "man" (section))
     82 (declare-function Man-next-section "man" (n))
     83 (declare-function Man-getpage-in-background "man" (topic))
     84 
     85 (defvar Man-notify-method)
     86 (defvar pp-default-function) ; since Emacs 29.1
     87 
     88 (defmacro static-if (condition then-form &rest else-forms)
     89   "A conditional compilation macro.
     90 Evaluate CONDITION at macro-expansion time.  If it is non-nil,
     91 expand the macro to THEN-FORM.  Otherwise expand it to ELSE-FORMS
     92 enclosed in a `progn' form.  ELSE-FORMS may be empty."
     93   (declare (indent 2)
     94            (debug (sexp sexp &rest sexp)))
     95   (if (eval condition lexical-binding)
     96       then-form
     97     (cons 'progn else-forms)))
     98 
     99 (defmacro transient--with-emergency-exit (id &rest body)
    100   (declare (indent defun))
    101   (unless (keywordp id)
    102     (setq body (cons id body))
    103     (setq id nil))
    104   `(condition-case err
    105        (let ((debugger #'transient--exit-and-debug))
    106          ,(macroexp-progn body))
    107      ((debug error)
    108       (transient--emergency-exit ,id)
    109       (signal (car err) (cdr err)))))
    110 
    111 (defun transient--exit-and-debug (&rest args)
    112   (transient--emergency-exit :debugger)
    113   (apply #'debug args))
    114 
    115 ;;; Options
    116 
    117 (defgroup transient nil
    118   "Transient commands."
    119   :group 'extensions)
    120 
    121 (defcustom transient-show-popup t
    122   "Whether to show the current transient in a popup buffer.
    123 \\<transient-map>
    124 - If t, then show the popup as soon as a transient prefix command
    125   is invoked.
    126 
    127 - If nil, then do not show the popup unless the user explicitly
    128   requests it, by pressing \\[transient-show] or a prefix key.
    129 
    130 - If a number, then delay displaying the popup and instead show
    131   a brief one-line summary.  If zero or negative, then suppress
    132   even showing that summary and display the pressed key only.
    133 
    134   Show the popup when the user explicitly requests it by pressing
    135   \\[transient-show] or a prefix key.  Unless zero, then also show the popup
    136   after that many seconds of inactivity (using the absolute value)."
    137   :package-version '(transient . "0.1.0")
    138   :group 'transient
    139   :type '(choice (const  :tag "instantly" t)
    140                  (const  :tag "on demand" nil)
    141                  (const  :tag "on demand (no summary)" 0)
    142                  (number :tag "after delay" 1)))
    143 
    144 (defcustom transient-enable-popup-navigation t
    145   "Whether navigation commands are enabled in the transient popup.
    146 
    147 While a transient is active the transient popup buffer is not the
    148 current buffer, making it necessary to use dedicated commands to
    149 act on that buffer itself.  If this is non-nil, then the following
    150 bindings are available:
    151 
    152 \\<transient-popup-navigation-map>\
    153 - \\[transient-backward-button] moves the cursor to the previous suffix.
    154 - \\[transient-forward-button] moves the cursor to the next suffix.
    155 - \\[transient-push-button] invokes the suffix the cursor is on.
    156 \\<transient-button-map>\
    157 - \\`<mouse-1>' and \\`<mouse-2>' invoke the clicked on suffix.
    158 \\<transient-popup-navigation-map>\
    159 - \\[transient-isearch-backward]\
    160  and \\[transient-isearch-forward] start isearch in the popup buffer.
    161 
    162 \\`<mouse-1>' and \\`<mouse-2>' are bound in `transient-push-button'.
    163 All other bindings are in `transient-popup-navigation-map'.
    164 
    165 By default \\`M-RET' is bound to `transient-push-button', instead of
    166 \\`RET', because if a transient allows the invocation of non-suffixes
    167 then it is likely that you would want \\`RET' to do what it would do
    168 if no transient were active."
    169   :package-version '(transient . "0.4.0")
    170   :group 'transient
    171   :type 'boolean)
    172 
    173 (defcustom transient-display-buffer-action
    174   '(display-buffer-in-side-window
    175     (side . bottom)
    176     (dedicated . t)
    177     (inhibit-same-window . t)
    178     (window-parameters (no-other-window . t)))
    179   "The action used to display the transient popup buffer.
    180 
    181 The transient popup buffer is displayed in a window using
    182 
    183   (display-buffer BUFFER transient-display-buffer-action)
    184 
    185 The value of this option has the form (FUNCTION . ALIST),
    186 where FUNCTION is a function or a list of functions.  Each such
    187 function should accept two arguments: a buffer to display and an
    188 alist of the same form as ALIST.  See info node `(elisp)Choosing
    189 Window' for details.
    190 
    191 The default is:
    192 
    193   (display-buffer-in-side-window
    194     (side . bottom)
    195     (dedicated . t)
    196     (inhibit-same-window . t)
    197     (window-parameters (no-other-window . t)))
    198 
    199 This displays the window at the bottom of the selected frame.
    200 Another useful FUNCTION is `display-buffer-below-selected', which
    201 is what `magit-popup' used by default.  For more alternatives see
    202 info node `(elisp)Display Action Functions' and info node
    203 `(elisp)Buffer Display Action Alists'.
    204 
    205 Note that the buffer that was current before the transient buffer
    206 is shown should remain the current buffer.  Many suffix commands
    207 act on the thing at point, if appropriate, and if the transient
    208 buffer became the current buffer, then that would change what is
    209 at point.  To that effect `inhibit-same-window' ensures that the
    210 selected window is not used to show the transient buffer.
    211 
    212 It may be possible to display the window in another frame, but
    213 whether that works in practice depends on the window-manager.
    214 If the window manager selects the new window (Emacs frame),
    215 then that unfortunately changes which buffer is current.
    216 
    217 If you change the value of this option, then you might also
    218 want to change the value of `transient-mode-line-format'."
    219   :package-version '(transient . "0.3.0")
    220   :group 'transient
    221   :type '(cons (choice function (repeat :tag "Functions" function))
    222                alist))
    223 
    224 (defcustom transient-mode-line-format 'line
    225   "The mode-line format for the transient popup buffer.
    226 
    227 If nil, then the buffer has no mode-line.  If the buffer is not
    228 displayed right above the echo area, then this probably is not
    229 a good value.
    230 
    231 If `line' (the default) or a natural number, then the buffer
    232 has no mode-line, but a line is drawn is drawn in its place.
    233 If a number is used, that specifies the thickness of the line.
    234 On termcap frames we cannot draw lines, so there `line' and
    235 numbers are synonyms for nil.
    236 
    237 The color of the line is used to indicate if non-suffixes are
    238 allowed and whether they exit the transient.  The foreground
    239 color of `transient-key-noop' (if non-suffix are disallowed),
    240 `transient-key-stay' (if allowed and transient stays active), or
    241 `transient-key-exit' (if allowed and they exit the transient) is
    242 used to draw the line.
    243 
    244 Otherwise this can be any mode-line format.
    245 See `mode-line-format' for details."
    246   :package-version '(transient . "0.2.0")
    247   :group 'transient
    248   :type '(choice (const  :tag "hide mode-line" nil)
    249                  (const  :tag "substitute thin line" line)
    250                  (number :tag "substitute line with thickness")
    251                  (const  :tag "name of prefix command"
    252                          ("%e" mode-line-front-space
    253                           mode-line-buffer-identification))
    254                  (sexp   :tag "custom mode-line format")))
    255 
    256 (defcustom transient-show-common-commands nil
    257   "Whether to show common transient suffixes in the popup buffer.
    258 
    259 These commands are always shown after typing the prefix key
    260 \"C-x\" when a transient command is active.  To toggle the value
    261 of this variable use \"C-x t\" when a transient is active."
    262   :package-version '(transient . "0.1.0")
    263   :group 'transient
    264   :type 'boolean)
    265 
    266 (defcustom transient-read-with-initial-input nil
    267   "Whether to use the last history element as initial minibuffer input."
    268   :package-version '(transient . "0.2.0")
    269   :group 'transient
    270   :type 'boolean)
    271 
    272 (defcustom transient-highlight-mismatched-keys nil
    273   "Whether to highlight keys that do not match their argument.
    274 
    275 This only affects infix arguments that represent command-line
    276 arguments.  When this option is non-nil, then the key binding
    277 for infix argument are highlighted when only a long argument
    278 \(e.g., \"--verbose\") is specified but no shorthand (e.g., \"-v\").
    279 In the rare case that a short-hand is specified but does not
    280 match the key binding, then it is highlighted differently.
    281 
    282 The highlighting is done using `transient-mismatched-key'
    283 and `transient-nonstandard-key'."
    284   :package-version '(transient . "0.1.0")
    285   :group 'transient
    286   :type 'boolean)
    287 
    288 (defcustom transient-highlight-higher-levels nil
    289   "Whether to highlight suffixes on higher levels.
    290 
    291 This is primarily intended for package authors.
    292 
    293 When non-nil then highlight the description of suffixes whose
    294 level is above 4, the default of `transient-default-level'.
    295 Assuming you have set that variable to 7, this highlights all
    296 suffixes that won't be available to users without them making
    297 the same customization."
    298   :package-version '(transient . "0.3.6")
    299   :group 'transient
    300   :type 'boolean)
    301 
    302 (defcustom transient-substitute-key-function nil
    303   "Function used to modify key bindings.
    304 
    305 This function is called with one argument, the prefix object,
    306 and must return a key binding description, either the existing
    307 key description it finds in the `key' slot, or a substitution.
    308 
    309 This is intended to let users replace certain prefix keys.  It
    310 could also be used to make other substitutions, but that is
    311 discouraged.
    312 
    313 For example, \"=\" is hard to reach using my custom keyboard
    314 layout, so I substitute \"(\" for that, which is easy to reach
    315 using a layout optimized for Lisp.
    316 
    317   (setq transient-substitute-key-function
    318         (lambda (obj)
    319           (let ((key (oref obj key)))
    320             (if (string-match \"\\\\`\\\\(=\\\\)[a-zA-Z]\" key)
    321                 (replace-match \"(\" t t key 1)
    322               key)))))"
    323   :package-version '(transient . "0.1.0")
    324   :group 'transient
    325   :type '(choice (const :tag "Transform no keys (nil)" nil) function))
    326 
    327 (defcustom transient-semantic-coloring t
    328   "Whether to use colors to indicate transient behavior.
    329 
    330 If non-nil, then the key binding of each suffix is colorized to
    331 indicate whether it exits the transient state or not, and the
    332 line that is drawn below the transient popup buffer is used to
    333 indicate the behavior of non-suffix commands."
    334   :package-version '(transient . "0.5.0")
    335   :group 'transient
    336   :type 'boolean)
    337 
    338 (defcustom transient-detect-key-conflicts nil
    339   "Whether to detect key binding conflicts.
    340 
    341 Conflicts are detected when a transient prefix command is invoked
    342 and results in an error, which prevents the transient from being
    343 used."
    344   :package-version '(transient . "0.1.0")
    345   :group 'transient
    346   :type 'boolean)
    347 
    348 (defcustom transient-align-variable-pitch nil
    349   "Whether to align columns pixel-wise in the popup buffer.
    350 
    351 If this is non-nil, then columns are aligned pixel-wise to
    352 support variable-pitch fonts.  Keys are not aligned, so you
    353 should use a fixed-pitch font for the `transient-key' face.
    354 Other key faces inherit from that face unless a theme is
    355 used that breaks that relationship.
    356 
    357 This option is intended for users who use a variable-pitch
    358 font for the `default' face.
    359 
    360 Also see `transient-force-fixed-pitch'."
    361   :package-version '(transient . "0.4.0")
    362   :group 'transient
    363   :type 'boolean)
    364 
    365 (defcustom transient-force-fixed-pitch nil
    366   "Whether to force use of monospaced font in the popup buffer.
    367 
    368 Even if you use a proportional font for the `default' face,
    369 you might still want to use a monospaced font in transient's
    370 popup buffer.  Setting this option to t causes `default' to
    371 be remapped to `fixed-pitch' in that buffer.
    372 
    373 Also see `transient-align-variable-pitch'."
    374   :package-version '(transient . "0.2.0")
    375   :group 'transient
    376   :type 'boolean)
    377 
    378 (defcustom transient-force-single-column nil
    379   "Whether to force use of a single column to display suffixes.
    380 
    381 This might be useful for users with low vision who use large
    382 text and might otherwise have to scroll in two dimensions."
    383   :package-version '(transient . "0.3.6")
    384   :group 'transient
    385   :type 'boolean)
    386 
    387 (defcustom transient-hide-during-minibuffer-read nil
    388   "Whether to hide the transient buffer while reading in the minibuffer."
    389   :package-version '(transient . "0.4.0")
    390   :group 'transient
    391   :type 'boolean)
    392 
    393 (defconst transient--max-level 7)
    394 (defconst transient--default-child-level 1)
    395 (defconst transient--default-prefix-level 4)
    396 
    397 (defcustom transient-default-level transient--default-prefix-level
    398   "Control what suffix levels are made available by default.
    399 
    400 Each suffix command is placed on a level and each prefix command
    401 has a level, which controls which suffix commands are available.
    402 Integers between 1 and 7 (inclusive) are valid levels.
    403 
    404 The levels of individual transients and/or their individual
    405 suffixes can be changed individually, by invoking the prefix and
    406 then pressing \"C-x l\".
    407 
    408 The default level for both transients and their suffixes is 4.
    409 This option only controls the default for transients.  The default
    410 suffix level is always 4.  The author of a transient should place
    411 certain suffixes on a higher level if they expect that it won't be
    412 of use to most users, and they should place very important suffixes
    413 on a lower level so that they remain available even if the user
    414 lowers the transient level.
    415 
    416 \(Magit currently places nearly all suffixes on level 4 and lower
    417 levels are not used at all yet.  So for the time being you should
    418 not set a lower level here and using a higher level might not
    419 give you as many additional suffixes as you hoped.)"
    420   :package-version '(transient . "0.1.0")
    421   :group 'transient
    422   :type '(choice (const :tag "1 - fewest suffixes" 1)
    423                  (const 2)
    424                  (const 3)
    425                  (const :tag "4 - default" 4)
    426                  (const 5)
    427                  (const 6)
    428                  (const :tag "7 - most suffixes" 7)))
    429 
    430 (defcustom transient-levels-file
    431   (locate-user-emacs-file "transient/levels.el")
    432   "File used to save levels of transients and their suffixes."
    433   :package-version '(transient . "0.1.0")
    434   :group 'transient
    435   :type 'file)
    436 
    437 (defcustom transient-values-file
    438   (locate-user-emacs-file "transient/values.el")
    439   "File used to save values of transients."
    440   :package-version '(transient . "0.1.0")
    441   :group 'transient
    442   :type 'file)
    443 
    444 (defcustom transient-history-file
    445   (locate-user-emacs-file "transient/history.el")
    446   "File used to save history of transients and their infixes."
    447   :package-version '(transient . "0.1.0")
    448   :group 'transient
    449   :type 'file)
    450 
    451 (defcustom transient-history-limit 10
    452   "Number of history elements to keep when saving to file."
    453   :package-version '(transient . "0.1.0")
    454   :group 'transient
    455   :type 'integer)
    456 
    457 (defcustom transient-save-history t
    458   "Whether to save history of transient commands when exiting Emacs."
    459   :package-version '(transient . "0.1.0")
    460   :group 'transient
    461   :type 'boolean)
    462 
    463 ;;; Faces
    464 
    465 (defgroup transient-faces nil
    466   "Faces used by Transient."
    467   :group 'transient)
    468 
    469 (defface transient-heading '((t :inherit font-lock-keyword-face))
    470   "Face used for headings."
    471   :group 'transient-faces)
    472 
    473 (defface transient-argument '((t :inherit font-lock-string-face :weight bold))
    474   "Face used for enabled arguments."
    475   :group 'transient-faces)
    476 
    477 (defface transient-inactive-argument '((t :inherit shadow))
    478   "Face used for inactive arguments."
    479   :group 'transient-faces)
    480 
    481 (defface transient-value '((t :inherit font-lock-string-face :weight bold))
    482   "Face used for values."
    483   :group 'transient-faces)
    484 
    485 (defface transient-inactive-value '((t :inherit shadow))
    486   "Face used for inactive values."
    487   :group 'transient-faces)
    488 
    489 (defface transient-unreachable '((t :inherit shadow))
    490   "Face used for suffixes unreachable from the current prefix sequence."
    491   :group 'transient-faces)
    492 
    493 (defface transient-inapt-suffix '((t :inherit shadow :italic t))
    494   "Face used for suffixes that are inapt at this time."
    495   :group 'transient-faces)
    496 
    497 (defface transient-active-infix '((t :inherit highlight))
    498   "Face used for the infix for which the value is being read."
    499   :group 'transient-faces)
    500 
    501 (defface transient-enabled-suffix
    502   '((t :background "green" :foreground "black" :weight bold))
    503   "Face used for enabled levels while editing suffix levels.
    504 See info node `(transient)Enabling and Disabling Suffixes'."
    505   :group 'transient-faces)
    506 
    507 (defface transient-disabled-suffix
    508   '((t :background "red" :foreground "black" :weight bold))
    509   "Face used for disabled levels while editing suffix levels.
    510 See info node `(transient)Enabling and Disabling Suffixes'."
    511   :group 'transient-faces)
    512 
    513 (defface transient-higher-level
    514   `((t :box ( :line-width ,(if (>= emacs-major-version 28) (cons -1 -1) -1)
    515               :color ,(let ((color (face-attribute 'shadow :foreground nil t)))
    516                         (or (and (not (eq color 'unspecified)) color)
    517                             "grey60")))))
    518   "Face optionally used to highlight suffixes on higher levels.
    519 Also see option `transient-highlight-higher-levels'."
    520   :group 'transient-faces)
    521 
    522 (defface transient-delimiter '((t :inherit shadow))
    523   "Face used for delimiters and separators.
    524 This includes the parentheses around values and the pipe
    525 character used to separate possible values from each other."
    526   :group 'transient-faces)
    527 
    528 (defface transient-key '((t :inherit font-lock-builtin-face))
    529   "Face used for keys."
    530   :group 'transient-faces)
    531 
    532 (defface transient-key-stay
    533   `((((class color) (background light))
    534      :inherit transient-key
    535      :foreground "#22aa22")
    536     (((class color) (background dark))
    537      :inherit transient-key
    538      :foreground "#ddffdd"))
    539   "Face used for keys of suffixes that don't exit transient state."
    540   :group 'transient-faces)
    541 
    542 (defface transient-key-noop
    543   `((((class color) (background light))
    544      :inherit transient-key
    545      :foreground "grey80")
    546     (((class color) (background dark))
    547      :inherit transient-key
    548      :foreground "grey30"))
    549   "Face used for keys of suffixes that currently cannot be invoked."
    550   :group 'transient-faces)
    551 
    552 (defface transient-key-return
    553   `((((class color) (background light))
    554      :inherit transient-key
    555      :foreground "#aaaa11")
    556     (((class color) (background dark))
    557      :inherit transient-key
    558      :foreground "#ffffcc"))
    559   "Face used for keys of suffixes that return to the parent transient."
    560   :group 'transient-faces)
    561 
    562 (defface transient-key-exit
    563   `((((class color) (background light))
    564      :inherit transient-key
    565      :foreground "#aa2222")
    566     (((class color) (background dark))
    567      :inherit transient-key
    568      :foreground "#ffdddd"))
    569   "Face used for keys of suffixes that exit transient state."
    570   :group 'transient-faces)
    571 
    572 (defface transient-unreachable-key
    573   '((t :inherit (shadow transient-key) :weight normal))
    574   "Face used for keys unreachable from the current prefix sequence."
    575   :group 'transient-faces)
    576 
    577 (defface transient-nonstandard-key
    578   `((t :box ( :line-width ,(if (>= emacs-major-version 28) (cons -1 -1) -1)
    579               :color "cyan")))
    580   "Face optionally used to highlight keys conflicting with short-argument.
    581 Also see option `transient-highlight-mismatched-keys'."
    582   :group 'transient-faces)
    583 
    584 (defface transient-mismatched-key
    585   `((t :box ( :line-width ,(if (>= emacs-major-version 28) (cons -1 -1) -1)
    586               :color "magenta")))
    587   "Face optionally used to highlight keys without a short-argument.
    588 Also see option `transient-highlight-mismatched-keys'."
    589   :group 'transient-faces)
    590 
    591 ;;; Persistence
    592 
    593 (defun transient--read-file-contents (file)
    594   (with-demoted-errors "Transient error: %S"
    595     (and (file-exists-p file)
    596          (with-temp-buffer
    597            (insert-file-contents file)
    598            (read (current-buffer))))))
    599 
    600 (defun transient--pp-to-file (list file)
    601   (make-directory (file-name-directory file) t)
    602   (setq list (cl-sort (copy-sequence list) #'string< :key #'car))
    603   (with-temp-file file
    604     (let ((print-level nil)
    605           (print-length nil)
    606           (pp-default-function 'pp-28)
    607           (fill-column 999))
    608       (pp list (current-buffer)))))
    609 
    610 (defvar transient-values
    611   (transient--read-file-contents transient-values-file)
    612   "Values of transient commands.
    613 The value of this variable persists between Emacs sessions
    614 and you usually should not change it manually.")
    615 
    616 (defun transient-save-values ()
    617   (transient--pp-to-file transient-values transient-values-file))
    618 
    619 (defvar transient-levels
    620   (transient--read-file-contents transient-levels-file)
    621   "Levels of transient commands.
    622 The value of this variable persists between Emacs sessions
    623 and you usually should not change it manually.")
    624 
    625 (defun transient-save-levels ()
    626   (transient--pp-to-file transient-levels transient-levels-file))
    627 
    628 (defvar transient-history
    629   (transient--read-file-contents transient-history-file)
    630   "History of transient commands and infix arguments.
    631 The value of this variable persists between Emacs sessions
    632 \(unless `transient-save-history' is nil) and you usually
    633 should not change it manually.")
    634 
    635 (defun transient-save-history ()
    636   (setq transient-history
    637         (cl-sort (mapcar (pcase-lambda (`(,key . ,val))
    638                            (cons key (seq-take (delete-dups val)
    639                                                transient-history-limit)))
    640                          transient-history)
    641                  #'string< :key #'car))
    642   (transient--pp-to-file transient-history transient-history-file))
    643 
    644 (defun transient-maybe-save-history ()
    645   "Save the value of `transient-history'.
    646 If `transient-save-history' is nil, then do nothing."
    647   (when transient-save-history
    648     (transient-save-history)))
    649 
    650 (unless noninteractive
    651   (add-hook 'kill-emacs-hook #'transient-maybe-save-history))
    652 
    653 ;;; Classes
    654 ;;;; Prefix
    655 
    656 (defclass transient-prefix ()
    657   ((prototype   :initarg :prototype)
    658    (command     :initarg :command)
    659    (level       :initarg :level)
    660    (variable    :initarg :variable    :initform nil)
    661    (init-value  :initarg :init-value)
    662    (value) (default-value :initarg :value)
    663    (scope       :initarg :scope       :initform nil)
    664    (history     :initarg :history     :initform nil)
    665    (history-pos :initarg :history-pos :initform 0)
    666    (history-key :initarg :history-key :initform nil)
    667    (show-help   :initarg :show-help   :initform nil)
    668    (info-manual :initarg :info-manual :initform nil)
    669    (man-page    :initarg :man-page    :initform nil)
    670    (transient-suffix     :initarg :transient-suffix     :initform nil)
    671    (transient-non-suffix :initarg :transient-non-suffix :initform nil)
    672    (transient-switch-frame :initarg :transient-switch-frame)
    673    (refresh-suffixes     :initarg :refresh-suffixes     :initform nil)
    674    (incompatible         :initarg :incompatible         :initform nil)
    675    (suffix-description   :initarg :suffix-description)
    676    (variable-pitch       :initarg :variable-pitch       :initform nil)
    677    (column-widths        :initarg :column-widths        :initform nil)
    678    (unwind-suffix        :documentation "Internal use." :initform nil))
    679   "Transient prefix command.
    680 
    681 Each transient prefix command consists of a command, which is
    682 stored in a symbol's function slot and an object, which is
    683 stored in the `transient--prefix' property of the same symbol.
    684 
    685 When a transient prefix command is invoked, then a clone of that
    686 object is stored in the global variable `transient--prefix' and
    687 the prototype is stored in the clone's `prototype' slot.")
    688 
    689 ;;;; Suffix
    690 
    691 (defclass transient-child ()
    692   ((level
    693     :initarg :level
    694     :initform (symbol-value 'transient--default-child-level)
    695     :documentation "Enable if level of prefix is equal or greater.")
    696    (if
    697     :initarg :if
    698     :initform nil
    699     :documentation "Enable if predicate returns non-nil.")
    700    (if-not
    701     :initarg :if-not
    702     :initform nil
    703     :documentation "Enable if predicate returns nil.")
    704    (if-non-nil
    705     :initarg :if-non-nil
    706     :initform nil
    707     :documentation "Enable if variable's value is non-nil.")
    708    (if-nil
    709     :initarg :if-nil
    710     :initform nil
    711     :documentation "Enable if variable's value is nil.")
    712    (if-mode
    713     :initarg :if-mode
    714     :initform nil
    715     :documentation "Enable if major-mode matches value.")
    716    (if-not-mode
    717     :initarg :if-not-mode
    718     :initform nil
    719     :documentation "Enable if major-mode does not match value.")
    720    (if-derived
    721     :initarg :if-derived
    722     :initform nil
    723     :documentation "Enable if major-mode derives from value.")
    724    (if-not-derived
    725     :initarg :if-not-derived
    726     :initform nil
    727     :documentation "Enable if major-mode does not derive from value.")
    728    (inapt
    729     :initform nil)
    730    (inapt-face
    731     :initarg :inapt-face
    732     :initform 'transient-inapt-suffix)
    733    (inapt-if
    734     :initarg :inapt-if
    735     :initform nil
    736     :documentation "Inapt if predicate returns non-nil.")
    737    (inapt-if-not
    738     :initarg :inapt-if-not
    739     :initform nil
    740     :documentation "Inapt if predicate returns nil.")
    741    (inapt-if-non-nil
    742     :initarg :inapt-if-non-nil
    743     :initform nil
    744     :documentation "Inapt if variable's value is non-nil.")
    745    (inapt-if-nil
    746     :initarg :inapt-if-nil
    747     :initform nil
    748     :documentation "Inapt if variable's value is nil.")
    749    (inapt-if-mode
    750     :initarg :inapt-if-mode
    751     :initform nil
    752     :documentation "Inapt if major-mode matches value.")
    753    (inapt-if-not-mode
    754     :initarg :inapt-if-not-mode
    755     :initform nil
    756     :documentation "Inapt if major-mode does not match value.")
    757    (inapt-if-derived
    758     :initarg :inapt-if-derived
    759     :initform nil
    760     :documentation "Inapt if major-mode derives from value.")
    761    (inapt-if-not-derived
    762     :initarg :inapt-if-not-derived
    763     :initform nil
    764     :documentation "Inapt if major-mode does not derive from value."))
    765   "Abstract superclass for group and suffix classes.
    766 
    767 It is undefined what happens if more than one `if*' predicate
    768 slot is non-nil."
    769   :abstract t)
    770 
    771 (defclass transient-suffix (transient-child)
    772   ((definition  :allocation :class    :initform nil)
    773    (key         :initarg :key)
    774    (command     :initarg :command)
    775    (transient   :initarg :transient)
    776    (format      :initarg :format      :initform " %k %d")
    777    (description :initarg :description :initform nil)
    778    (face        :initarg :face        :initform nil)
    779    (show-help   :initarg :show-help   :initform nil))
    780   "Superclass for suffix command.")
    781 
    782 (defclass transient-information (transient-suffix)
    783   ((format :initform " %k %d")
    784    (key    :initform " "))
    785   "Display-only information, aligned with suffix keys.
    786 Technically a suffix object with no associated command.")
    787 
    788 (defclass transient-information* (transient-information)
    789   ((format :initform " %d"))
    790   "Display-only information, aligned with suffix descriptions.
    791 Technically a suffix object with no associated command.")
    792 
    793 (defclass transient-infix (transient-suffix)
    794   ((transient                         :initform t)
    795    (argument    :initarg :argument)
    796    (shortarg    :initarg :shortarg)
    797    (value                             :initform nil)
    798    (init-value  :initarg :init-value)
    799    (unsavable   :initarg :unsavable   :initform nil)
    800    (multi-value :initarg :multi-value :initform nil)
    801    (always-read :initarg :always-read :initform nil)
    802    (allow-empty :initarg :allow-empty :initform nil)
    803    (history-key :initarg :history-key :initform nil)
    804    (reader      :initarg :reader      :initform nil)
    805    (prompt      :initarg :prompt      :initform nil)
    806    (choices     :initarg :choices     :initform nil)
    807    (format                            :initform " %k %d (%v)"))
    808   "Transient infix command."
    809   :abstract t)
    810 
    811 (defclass transient-argument (transient-infix) ()
    812   "Abstract superclass for infix arguments."
    813   :abstract t)
    814 
    815 (defclass transient-switch (transient-argument) ()
    816   "Class used for command-line argument that can be turned on and off.")
    817 
    818 (defclass transient-option (transient-argument) ()
    819   "Class used for command-line argument that can take a value.")
    820 
    821 (defclass transient-variable (transient-infix)
    822   ((variable    :initarg :variable)
    823    (format                            :initform " %k %d %v"))
    824   "Abstract superclass for infix commands that set a variable."
    825   :abstract t)
    826 
    827 (defclass transient-switches (transient-argument)
    828   ((argument-format  :initarg :argument-format)
    829    (argument-regexp  :initarg :argument-regexp))
    830   "Class used for sets of mutually exclusive command-line switches.")
    831 
    832 (defclass transient-files (transient-option) ()
    833   ((key         :initform "--")
    834    (argument    :initform "--")
    835    (multi-value :initform rest)
    836    (reader      :initform transient-read-files))
    837   "Class used for the \"--\" argument or similar.
    838 All remaining arguments are treated as files.
    839 They become the value of this argument.")
    840 
    841 ;;;; Group
    842 
    843 (defclass transient-group (transient-child)
    844   ((suffixes       :initarg :suffixes       :initform nil)
    845    (hide           :initarg :hide           :initform nil)
    846    (description    :initarg :description    :initform nil)
    847    (pad-keys       :initarg :pad-keys       :initform nil)
    848    (info-format    :initarg :info-format    :initform nil)
    849    (setup-children :initarg :setup-children))
    850   "Abstract superclass of all group classes."
    851   :abstract t)
    852 
    853 (defclass transient-column (transient-group) ()
    854   "Group class that displays each element on a separate line.")
    855 
    856 (defclass transient-row (transient-group) ()
    857   "Group class that displays all elements on a single line.")
    858 
    859 (defclass transient-columns (transient-group) ()
    860   "Group class that displays elements organized in columns.
    861 Direct elements have to be groups whose elements have to be
    862 commands or strings.  Each subgroup represents a column.
    863 This class takes care of inserting the subgroups' elements.")
    864 
    865 (defclass transient-subgroups (transient-group) ()
    866   "Group class that wraps other groups.
    867 
    868 Direct elements have to be groups whose elements have to be
    869 commands or strings.  This group inserts an empty line between
    870 subgroups.  The subgroups are responsible for displaying their
    871 elements themselves.")
    872 
    873 ;;; Define
    874 
    875 (defmacro transient-define-prefix (name arglist &rest args)
    876   "Define NAME as a transient prefix command.
    877 
    878 ARGLIST are the arguments that command takes.
    879 DOCSTRING is the documentation string and is optional.
    880 
    881 These arguments can optionally be followed by key-value pairs.
    882 Each key has to be a keyword symbol, either `:class' or a keyword
    883 argument supported by the constructor of that class.  The
    884 `transient-prefix' class is used if the class is not specified
    885 explicitly.
    886 
    887 GROUPs add key bindings for infix and suffix commands and specify
    888 how these bindings are presented in the popup buffer.  At least
    889 one GROUP has to be specified.  See info node `(transient)Binding
    890 Suffix and Infix Commands'.
    891 
    892 The BODY is optional.  If it is omitted, then ARGLIST is also
    893 ignored and the function definition becomes:
    894 
    895   (lambda ()
    896     (interactive)
    897     (transient-setup \\='NAME))
    898 
    899 If BODY is specified, then it must begin with an `interactive'
    900 form that matches ARGLIST, and it must call `transient-setup'.
    901 It may however call that function only when some condition is
    902 satisfied; that is one of the reason why you might want to use
    903 an explicit BODY.
    904 
    905 All transients have a (possibly nil) value, which is exported
    906 when suffix commands are called, so that they can consume that
    907 value.  For some transients it might be necessary to have a sort
    908 of secondary value, called a scope.  Such a scope would usually
    909 be set in the commands `interactive' form and has to be passed
    910 to the setup function:
    911 
    912   (transient-setup \\='NAME nil nil :scope SCOPE)
    913 
    914 \(fn NAME ARGLIST [DOCSTRING] [KEYWORD VALUE]... GROUP... [BODY...])"
    915   (declare (debug ( &define name lambda-list
    916                     [&optional lambda-doc]
    917                     [&rest keywordp sexp]
    918                     [&rest vectorp]
    919                     [&optional ("interactive" interactive) def-body]))
    920            (indent defun)
    921            (doc-string 3))
    922   (pcase-let ((`(,class ,slots ,suffixes ,docstr ,body ,interactive-only)
    923                (transient--expand-define-args args arglist)))
    924     `(progn
    925        (defalias ',name
    926          ,(if body
    927               `(lambda ,arglist ,@body)
    928             `(lambda ()
    929                (interactive)
    930                (transient-setup ',name))))
    931        (put ',name 'interactive-only ,interactive-only)
    932        (put ',name 'function-documentation ,docstr)
    933        (put ',name 'transient--prefix
    934             (,(or class 'transient-prefix) :command ',name ,@slots))
    935        (put ',name 'transient--layout
    936             (list ,@(cl-mapcan (lambda (s) (transient--parse-child name s))
    937                                suffixes))))))
    938 
    939 (defmacro transient-define-suffix (name arglist &rest args)
    940   "Define NAME as a transient suffix command.
    941 
    942 ARGLIST are the arguments that the command takes.
    943 DOCSTRING is the documentation string and is optional.
    944 
    945 These arguments can optionally be followed by key-value pairs.
    946 Each key has to be a keyword symbol, either `:class' or a
    947 keyword argument supported by the constructor of that class.
    948 The `transient-suffix' class is used if the class is not
    949 specified explicitly.
    950 
    951 The BODY must begin with an `interactive' form that matches
    952 ARGLIST.  The infix arguments are usually accessed by using
    953 `transient-args' inside `interactive'.
    954 
    955 \(fn NAME ARGLIST [DOCSTRING] [KEYWORD VALUE]... [BODY...])"
    956   (declare (debug ( &define name lambda-list
    957                     [&optional lambda-doc]
    958                     [&rest keywordp sexp]
    959                     [&optional ("interactive" interactive) def-body]))
    960            (indent defun)
    961            (doc-string 3))
    962   (pcase-let ((`(,class ,slots ,_ ,docstr ,body ,interactive-only)
    963                (transient--expand-define-args args arglist)))
    964     `(progn
    965        (defalias ',name
    966          ,(if (and (not body) class (oref-default class definition))
    967               `(oref-default ',class definition)
    968             `(lambda ,arglist ,@body)))
    969        (put ',name 'interactive-only ,interactive-only)
    970        (put ',name 'function-documentation ,docstr)
    971        (put ',name 'transient--suffix
    972             (,(or class 'transient-suffix) :command ',name ,@slots)))))
    973 
    974 (defmacro transient-define-infix (name arglist &rest args)
    975   "Define NAME as a transient infix command.
    976 
    977 ARGLIST is always ignored and reserved for future use.
    978 DOCSTRING is the documentation string and is optional.
    979 
    980 At least one key-value pair is required.  All transient infix
    981 commands are equal to each other (but not eq).  It is meaning-
    982 less to define an infix command, without providing at least one
    983 keyword argument (usually `:argument' or `:variable', depending
    984 on the class).  The suffix class defaults to `transient-switch'
    985 and can be set using the `:class' keyword.
    986 
    987 The function definitions is always:
    988 
    989   (lambda ()
    990     (interactive)
    991     (let ((obj (transient-suffix-object)))
    992       (transient-infix-set obj (transient-infix-read obj)))
    993     (transient--show))
    994 
    995 `transient-infix-read' and `transient-infix-set' are generic
    996 functions.  Different infix commands behave differently because
    997 the concrete methods are different for different infix command
    998 classes.  In rare case the above command function might not be
    999 suitable, even if you define your own infix command class.  In
   1000 that case you have to use `transient-define-suffix' to define
   1001 the infix command and use t as the value of the `:transient'
   1002 keyword.
   1003 
   1004 \(fn NAME ARGLIST [DOCSTRING] KEYWORD VALUE [KEYWORD VALUE]...)"
   1005   (declare (debug ( &define name lambda-list
   1006                     [&optional lambda-doc]
   1007                     keywordp sexp
   1008                     [&rest keywordp sexp]))
   1009            (indent defun)
   1010            (doc-string 3))
   1011   (pcase-let ((`(,class ,slots ,_ ,docstr ,_ ,interactive-only)
   1012                (transient--expand-define-args args arglist t)))
   1013     `(progn
   1014        (defalias ',name #'transient--default-infix-command)
   1015        (put ',name 'interactive-only ,interactive-only)
   1016        (put ',name 'completion-predicate #'transient--suffix-only)
   1017        (put ',name 'function-documentation ,docstr)
   1018        (put ',name 'transient--suffix
   1019             (,(or class 'transient-switch) :command ',name ,@slots)))))
   1020 
   1021 (defalias 'transient-define-argument #'transient-define-infix
   1022   "Define NAME as a transient infix command.
   1023 
   1024 Only use this alias to define an infix command that actually
   1025 sets an infix argument.  To define a infix command that, for
   1026 example, sets a variable, use `transient-define-infix' instead.
   1027 
   1028 \(fn NAME ARGLIST [DOCSTRING] [KEYWORD VALUE]...)")
   1029 
   1030 (defun transient--default-infix-command ()
   1031   ;; Most infix commands are but an alias for this command.
   1032   "Cannot show any documentation for this transient infix command.
   1033 
   1034 When you request help for an infix command using `transient-help', that
   1035 usually shows the respective man-page and tries to jump to the location
   1036 where the respective argument is being described.
   1037 
   1038 If no man-page is specified for the containing transient menu, then the
   1039 docstring is displayed instead, if any.
   1040 
   1041 If the infix command doesn't have a docstring, as is the case here, then
   1042 this docstring is displayed instead, because technically infix commands
   1043 are aliases for `transient--default-infix-command'.
   1044 
   1045 `describe-function' also shows the docstring of the infix command,
   1046 falling back to that of the same aliased command."
   1047   (interactive)
   1048   (let ((obj (transient-suffix-object)))
   1049     (transient-infix-set obj (transient-infix-read obj)))
   1050   (transient--show))
   1051 (put 'transient--default-infix-command 'interactive-only t)
   1052 (put 'transient--default-infix-command 'completion-predicate
   1053      #'transient--suffix-only)
   1054 
   1055 (defun transient--find-function-advised-original (fn func)
   1056   "Return nil instead of `transient--default-infix-command'.
   1057 When using `find-function' to jump to the definition of a transient
   1058 infix command/argument, then we want to actually jump to that, not to
   1059 the definition of `transient--default-infix-command', which all infix
   1060 commands are aliases for."
   1061   (let ((val (funcall fn func)))
   1062     (and val (not (eq val 'transient--default-infix-command)) val)))
   1063 (advice-add 'find-function-advised-original :around
   1064             #'transient--find-function-advised-original)
   1065 
   1066 (eval-and-compile
   1067   (defun transient--expand-define-args (args &optional arglist nobody)
   1068     (unless (listp arglist)
   1069       (error "Mandatory ARGLIST is missing"))
   1070     (let (class keys suffixes docstr declare (interactive-only t))
   1071       (when (stringp (car args))
   1072         (setq docstr (pop args)))
   1073       (while (keywordp (car args))
   1074         (let ((k (pop args))
   1075               (v (pop args)))
   1076           (if (eq k :class)
   1077               (setq class v)
   1078             (push k keys)
   1079             (push v keys))))
   1080       (while (let ((arg (car args)))
   1081                (or (vectorp arg)
   1082                    (and arg (symbolp arg))))
   1083         (push (pop args) suffixes))
   1084       (when (eq (car-safe (car args)) 'declare)
   1085         (setq declare (car args))
   1086         (setq args (cdr args))
   1087         (when-let ((int (assq 'interactive-only declare)))
   1088           (setq interactive-only (cadr int))
   1089           (delq int declare))
   1090         (unless (cdr declare)
   1091           (setq declare nil)))
   1092       (cond
   1093        ((not args))
   1094        (nobody
   1095         (error "transient-define-infix: No function body allowed"))
   1096        ((not (eq (car-safe (nth (if declare 1 0) args)) 'interactive))
   1097         (error "transient-define-*: Interactive form missing")))
   1098       (list (if (eq (car-safe class) 'quote)
   1099                 (cadr class)
   1100               class)
   1101             (nreverse keys)
   1102             (nreverse suffixes)
   1103             docstr
   1104             (if declare (cons declare args) args)
   1105             interactive-only))))
   1106 
   1107 (defun transient--parse-child (prefix spec)
   1108   (cl-typecase spec
   1109     (null    (error "Invalid transient--parse-child spec: %s" spec))
   1110     (symbol  (let ((value (symbol-value spec)))
   1111                (if (and (listp value)
   1112                         (or (listp (car value))
   1113                             (vectorp (car value))))
   1114                    (cl-mapcan (lambda (s) (transient--parse-child prefix s)) value)
   1115                  (transient--parse-child prefix value))))
   1116     (vector  (and-let* ((c (transient--parse-group  prefix spec))) (list c)))
   1117     (list    (and-let* ((c (transient--parse-suffix prefix spec))) (list c)))
   1118     (string  (list spec))
   1119     (t       (error "Invalid transient--parse-child spec: %s" spec))))
   1120 
   1121 (defun transient--parse-group (prefix spec)
   1122   (setq spec (append spec nil))
   1123   (cl-symbol-macrolet
   1124       ((car (car spec))
   1125        (pop (pop spec)))
   1126     (let (level class args)
   1127       (when (integerp car)
   1128         (setq level pop))
   1129       (when (stringp car)
   1130         (setq args (plist-put args :description pop)))
   1131       (while (keywordp car)
   1132         (let ((key pop)
   1133               (val pop))
   1134           (cond ((eq key :class)
   1135                  (setq class (macroexp-quote val)))
   1136                 ((or (symbolp val)
   1137                      (and (listp val) (not (eq (car val) 'lambda))))
   1138                  (setq args (plist-put args key (macroexp-quote val))))
   1139                 ((setq args (plist-put args key val))))))
   1140       (unless (or spec class (not (plist-get args :setup-children)))
   1141         (message "WARNING: %s: When %s is used, %s must also be specified"
   1142                  'transient-define-prefix :setup-children :class))
   1143       (list 'vector
   1144             (or level transient--default-child-level)
   1145             (cond (class)
   1146                   ((or (vectorp car)
   1147                        (and car (symbolp car)))
   1148                    (quote 'transient-columns))
   1149                   ((quote 'transient-column)))
   1150             (and args (cons 'list args))
   1151             (cons 'list
   1152                   (cl-mapcan (lambda (s) (transient--parse-child prefix s))
   1153                              spec))))))
   1154 
   1155 (defun transient--parse-suffix (prefix spec)
   1156   (let (level class args)
   1157     (cl-symbol-macrolet
   1158         ((car (car spec))
   1159          (pop (pop spec)))
   1160       (when (integerp car)
   1161         (setq level pop))
   1162       (when (or (stringp car)
   1163                 (vectorp car))
   1164         (setq args (plist-put args :key pop)))
   1165       (cond
   1166        ((or (stringp car)
   1167             (and (eq (car-safe car) 'lambda)
   1168                  (not (commandp car))))
   1169         (setq args (plist-put args :description pop)))
   1170        ((and (symbolp car)
   1171              (not (keywordp car))
   1172              (not (commandp car))
   1173              (commandp (cadr spec)))
   1174         (setq args (plist-put args :description (macroexp-quote pop)))))
   1175       (cond
   1176        ((memq car '(:info :info*)))
   1177        ((keywordp car)
   1178         (error "Need command, `:info' or `:info*', got `%s'" car))
   1179        ((symbolp car)
   1180         (setq args (plist-put args :command (macroexp-quote pop))))
   1181        ((and (commandp car)
   1182              (not (stringp car)))
   1183         (let ((cmd pop)
   1184               (sym (intern
   1185                     (format "transient:%s:%s"
   1186                             prefix
   1187                             (let ((desc (plist-get args :description)))
   1188                               (if (and (stringp desc)
   1189                                        (length< desc 16))
   1190                                   desc
   1191                                 (plist-get args :key)))))))
   1192           (setq args (plist-put
   1193                       args :command
   1194                       `(prog1 ',sym
   1195                          (put ',sym 'interactive-only t)
   1196                          (put ',sym 'completion-predicate #'transient--suffix-only)
   1197                          (defalias ',sym
   1198                            ,(if (eq (car-safe cmd) 'lambda)
   1199                                 cmd
   1200                               (macroexp-quote cmd))))))))
   1201        ((or (stringp car)
   1202             (and car (listp car)))
   1203         (let ((arg pop)
   1204               (sym nil))
   1205           (cl-typecase arg
   1206             (list
   1207              (setq args (plist-put args :shortarg (car  arg)))
   1208              (setq args (plist-put args :argument (cadr arg)))
   1209              (setq arg  (cadr arg)))
   1210             (string
   1211              (when-let ((shortarg (transient--derive-shortarg arg)))
   1212                (setq args (plist-put args :shortarg shortarg)))
   1213              (setq args (plist-put args :argument arg))))
   1214           (setq sym (intern (format "transient:%s:%s" prefix arg)))
   1215           (setq args (plist-put
   1216                       args :command
   1217                       `(prog1 ',sym
   1218                          (put ',sym 'interactive-only t)
   1219                          (put ',sym 'completion-predicate #'transient--suffix-only)
   1220                          (defalias ',sym #'transient--default-infix-command))))
   1221           (cond ((and car (not (keywordp car)))
   1222                  (setq class 'transient-option)
   1223                  (setq args (plist-put args :reader (macroexp-quote pop))))
   1224                 ((not (string-suffix-p "=" arg))
   1225                  (setq class 'transient-switch))
   1226                 (t
   1227                  (setq class 'transient-option)))))
   1228        (t
   1229         (error "Needed command or argument, got %S" car)))
   1230       (while (keywordp car)
   1231         (let ((key pop)
   1232               (val pop))
   1233           (cond ((eq key :class) (setq class val))
   1234                 ((eq key :level) (setq level val))
   1235                 ((eq key :info)
   1236                  (setq class 'transient-information)
   1237                  (setq args (plist-put args :description val)))
   1238                 ((eq key :info*)
   1239                  (setq class 'transient-information*)
   1240                  (setq args (plist-put args :description val)))
   1241                 ((eq (car-safe val) '\,)
   1242                  (setq args (plist-put args key (cadr val))))
   1243                 ((or (symbolp val)
   1244                      (and (listp val) (not (eq (car val) 'lambda))))
   1245                  (setq args (plist-put args key (macroexp-quote val))))
   1246                 ((setq args (plist-put args key val)))))))
   1247     (unless (plist-get args :key)
   1248       (when-let ((shortarg (plist-get args :shortarg)))
   1249         (setq args (plist-put args :key shortarg))))
   1250     (list 'list
   1251           (or level transient--default-child-level)
   1252           (macroexp-quote (or class 'transient-suffix))
   1253           (cons 'list args))))
   1254 
   1255 (defun transient--derive-shortarg (arg)
   1256   (save-match-data
   1257     (and (string-match "\\`\\(-[a-zA-Z]\\)\\(\\'\\|=\\)" arg)
   1258          (match-string 1 arg))))
   1259 
   1260 (defun transient-command-completion-not-suffix-only-p (symbol _buffer)
   1261   "Say whether SYMBOL should be offered as a completion.
   1262 If the value of SYMBOL's `completion-predicate' property is
   1263 `transient--suffix-only', then return nil, otherwise return t.
   1264 This is the case when a command should only ever be used as a
   1265 suffix of a transient prefix command (as opposed to bindings
   1266 in regular keymaps or by using `execute-extended-command')."
   1267   (not (eq (get symbol 'completion-predicate) 'transient--suffix-only)))
   1268 
   1269 (defalias 'transient--suffix-only #'ignore
   1270   "Ignore ARGUMENTS, do nothing, and return nil.
   1271 Also see `transient-command-completion-not-suffix-only-p'.
   1272 Only use this alias as the value of the `completion-predicate'
   1273 symbol property.")
   1274 
   1275 (when (and (boundp 'read-extended-command-predicate) ; since Emacs 28.1
   1276            (not read-extended-command-predicate))
   1277   (setq read-extended-command-predicate
   1278         #'transient-command-completion-not-suffix-only-p))
   1279 
   1280 (defun transient-parse-suffix (prefix suffix)
   1281   "Parse SUFFIX, to be added to PREFIX.
   1282 PREFIX is a prefix command, a symbol.
   1283 SUFFIX is a suffix command or a group specification (of
   1284   the same forms as expected by `transient-define-prefix').
   1285 Intended for use in a group's `:setup-children' function."
   1286   (cl-assert (and prefix (symbolp prefix)))
   1287   (eval (car (transient--parse-child prefix suffix)) t))
   1288 
   1289 (defun transient-parse-suffixes (prefix suffixes)
   1290   "Parse SUFFIXES, to be added to PREFIX.
   1291 PREFIX is a prefix command, a symbol.
   1292 SUFFIXES is a list of suffix command or a group specification
   1293   (of the same forms as expected by `transient-define-prefix').
   1294 Intended for use in a group's `:setup-children' function."
   1295   (cl-assert (and prefix (symbolp prefix)))
   1296   (mapcar (apply-partially #'transient-parse-suffix prefix) suffixes))
   1297 
   1298 ;;; Edit
   1299 
   1300 (defun transient--insert-suffix (prefix loc suffix action &optional keep-other)
   1301   (let* ((suf (cl-etypecase suffix
   1302                 (vector (transient--parse-group  prefix suffix))
   1303                 (list   (transient--parse-suffix prefix suffix))
   1304                 (string suffix)))
   1305          (mem (transient--layout-member loc prefix))
   1306          (elt (car mem)))
   1307     (setq suf (eval suf t))
   1308     (cond
   1309      ((not mem)
   1310       (message "Cannot insert %S into %s; %s not found"
   1311                suffix prefix loc))
   1312      ((or (and (vectorp suffix) (not (vectorp elt)))
   1313           (and (listp   suffix) (vectorp elt))
   1314           (and (stringp suffix) (vectorp elt)))
   1315       (message "Cannot place %S into %s at %s; %s"
   1316                suffix prefix loc
   1317                "suffixes and groups cannot be siblings"))
   1318      (t
   1319       (when-let* ((bindingp (listp suf))
   1320                   (key (transient--spec-key suf))
   1321                   (conflict (car (transient--layout-member key prefix)))
   1322                   (conflictp
   1323                    (and (not (and (eq action 'replace)
   1324                                   (eq conflict elt)))
   1325                         (or (not keep-other)
   1326                             (eq (plist-get (nth 2 suf) :command)
   1327                                 (plist-get (nth 2 conflict) :command)))
   1328                         (equal (transient--suffix-predicate suf)
   1329                                (transient--suffix-predicate conflict)))))
   1330         (transient-remove-suffix prefix key))
   1331       (pcase-exhaustive action
   1332         ('insert  (setcdr mem (cons elt (cdr mem)))
   1333                   (setcar mem suf))
   1334         ('append  (setcdr mem (cons suf (cdr mem))))
   1335         ('replace (setcar mem suf)))))))
   1336 
   1337 ;;;###autoload
   1338 (defun transient-insert-suffix (prefix loc suffix &optional keep-other)
   1339   "Insert a SUFFIX into PREFIX before LOC.
   1340 PREFIX is a prefix command, a symbol.
   1341 SUFFIX is a suffix command or a group specification (of
   1342   the same forms as expected by `transient-define-prefix').
   1343 LOC is a command, a key vector, a key description (a string
   1344   as returned by `key-description'), or a coordination list
   1345   (whose last element may also be a command or key).
   1346 Remove a conflicting binding unless optional KEEP-OTHER is
   1347   non-nil.
   1348 See info node `(transient)Modifying Existing Transients'."
   1349   (declare (indent defun))
   1350   (transient--insert-suffix prefix loc suffix 'insert keep-other))
   1351 
   1352 ;;;###autoload
   1353 (defun transient-append-suffix (prefix loc suffix &optional keep-other)
   1354   "Insert a SUFFIX into PREFIX after LOC.
   1355 PREFIX is a prefix command, a symbol.
   1356 SUFFIX is a suffix command or a group specification (of
   1357   the same forms as expected by `transient-define-prefix').
   1358 LOC is a command, a key vector, a key description (a string
   1359   as returned by `key-description'), or a coordination list
   1360   (whose last element may also be a command or key).
   1361 Remove a conflicting binding unless optional KEEP-OTHER is
   1362   non-nil.
   1363 See info node `(transient)Modifying Existing Transients'."
   1364   (declare (indent defun))
   1365   (transient--insert-suffix prefix loc suffix 'append keep-other))
   1366 
   1367 ;;;###autoload
   1368 (defun transient-replace-suffix (prefix loc suffix)
   1369   "Replace the suffix at LOC in PREFIX with SUFFIX.
   1370 PREFIX is a prefix command, a symbol.
   1371 SUFFIX is a suffix command or a group specification (of
   1372   the same forms as expected by `transient-define-prefix').
   1373 LOC is a command, a key vector, a key description (a string
   1374   as returned by `key-description'), or a coordination list
   1375   (whose last element may also be a command or key).
   1376 See info node `(transient)Modifying Existing Transients'."
   1377   (declare (indent defun))
   1378   (transient--insert-suffix prefix loc suffix 'replace))
   1379 
   1380 ;;;###autoload
   1381 (defun transient-remove-suffix (prefix loc)
   1382   "Remove the suffix or group at LOC in PREFIX.
   1383 PREFIX is a prefix command, a symbol.
   1384 LOC is a command, a key vector, a key description (a string
   1385   as returned by `key-description'), or a coordination list
   1386   (whose last element may also be a command or key).
   1387 See info node `(transient)Modifying Existing Transients'."
   1388   (declare (indent defun))
   1389   (transient--layout-member loc prefix 'remove))
   1390 
   1391 (defun transient-get-suffix (prefix loc)
   1392   "Return the suffix or group at LOC in PREFIX.
   1393 PREFIX is a prefix command, a symbol.
   1394 LOC is a command, a key vector, a key description (a string
   1395   as returned by `key-description'), or a coordination list
   1396   (whose last element may also be a command or key).
   1397 See info node `(transient)Modifying Existing Transients'."
   1398   (if-let ((mem (transient--layout-member loc prefix)))
   1399       (car mem)
   1400     (error "%s not found in %s" loc prefix)))
   1401 
   1402 (defun transient-suffix-put (prefix loc prop value)
   1403   "Edit the suffix at LOC in PREFIX, setting PROP to VALUE.
   1404 PREFIX is a prefix command, a symbol.
   1405 SUFFIX is a suffix command or a group specification (of
   1406   the same forms as expected by `transient-define-prefix').
   1407 LOC is a command, a key vector, a key description (a string
   1408   as returned by `key-description'), or a coordination list
   1409   (whose last element may also be a command or key).
   1410 See info node `(transient)Modifying Existing Transients'."
   1411   (let ((suf (transient-get-suffix prefix loc)))
   1412     (setf (elt suf 2)
   1413           (plist-put (elt suf 2) prop value))))
   1414 
   1415 (defun transient--layout-member (loc prefix &optional remove)
   1416   (let ((val (or (get prefix 'transient--layout)
   1417                  (error "%s is not a transient command" prefix))))
   1418     (when (listp loc)
   1419       (while (integerp (car loc))
   1420         (let* ((children (if (vectorp val) (aref val 3) val))
   1421                (mem (transient--nthcdr (pop loc) children)))
   1422           (if (and remove (not loc))
   1423               (let ((rest (delq (car mem) children)))
   1424                 (if (vectorp val)
   1425                     (aset val 3 rest)
   1426                   (put prefix 'transient--layout rest))
   1427                 (setq val nil))
   1428             (setq val (if loc (car mem) mem)))))
   1429       (setq loc (car loc)))
   1430     (if loc
   1431         (transient--layout-member-1 (transient--kbd loc) val remove)
   1432       val)))
   1433 
   1434 (defun transient--layout-member-1 (loc layout remove)
   1435   (cond ((listp layout)
   1436          (seq-some (lambda (elt) (transient--layout-member-1 loc elt remove))
   1437                    layout))
   1438         ((vectorp (car (aref layout 3)))
   1439          (seq-some (lambda (elt) (transient--layout-member-1 loc elt remove))
   1440                    (aref layout 3)))
   1441         (remove
   1442          (aset layout 3
   1443                (delq (car (transient--group-member loc layout))
   1444                      (aref layout 3)))
   1445          nil)
   1446         ((transient--group-member loc layout))))
   1447 
   1448 (defun transient--group-member (loc group)
   1449   (cl-member-if (lambda (suffix)
   1450                   (and (listp suffix)
   1451                        (let* ((def (nth 2 suffix))
   1452                               (cmd (plist-get def :command)))
   1453                          (if (symbolp loc)
   1454                              (eq cmd loc)
   1455                            (equal (transient--kbd
   1456                                    (or (plist-get def :key)
   1457                                        (transient--command-key cmd)))
   1458                                   loc)))))
   1459                 (aref group 3)))
   1460 
   1461 (defun transient--kbd (keys)
   1462   (when (vectorp keys)
   1463     (setq keys (key-description keys)))
   1464   (when (stringp keys)
   1465     (setq keys (kbd keys)))
   1466   keys)
   1467 
   1468 (defun transient--spec-key (spec)
   1469   (let ((plist (nth 2 spec)))
   1470     (or (plist-get plist :key)
   1471         (transient--command-key
   1472          (plist-get plist :command)))))
   1473 
   1474 (defun transient--command-key (cmd)
   1475   (and-let* ((obj (transient--suffix-prototype cmd)))
   1476     (cond ((slot-boundp obj 'key)
   1477            (oref obj key))
   1478           ((slot-exists-p obj 'shortarg)
   1479            (if (slot-boundp obj 'shortarg)
   1480                (oref obj shortarg)
   1481              (transient--derive-shortarg (oref obj argument)))))))
   1482 
   1483 (defun transient--nthcdr (n list)
   1484   (nthcdr (if (< n 0) (- (length list) (abs n)) n) list))
   1485 
   1486 ;;; Variables
   1487 
   1488 (defvar transient-current-prefix nil
   1489   "The transient from which this suffix command was invoked.
   1490 This is an object representing that transient, use
   1491 `transient-current-command' to get the respective command.")
   1492 
   1493 (defvar transient-current-command nil
   1494   "The transient from which this suffix command was invoked.
   1495 This is a symbol representing that transient, use
   1496 `transient-current-prefix' to get the respective object.")
   1497 
   1498 (defvar transient-current-suffixes nil
   1499   "The suffixes of the transient from which this suffix command was invoked.
   1500 This is a list of objects.  Usually it is sufficient to instead
   1501 use the function `transient-args', which returns a list of
   1502 values.  In complex cases it might be necessary to use this
   1503 variable instead.")
   1504 
   1505 (defvar transient-exit-hook nil
   1506   "Hook run after exiting a transient.")
   1507 
   1508 (defvar transient-setup-buffer-hook nil
   1509   "Hook run when setting up the transient buffer.
   1510 That buffer is current and empty when this hook runs.")
   1511 
   1512 (defvar transient--prefix nil)
   1513 (defvar transient--layout nil)
   1514 (defvar transient--suffixes nil)
   1515 
   1516 (defconst transient--stay t   "Do not exit the transient.")
   1517 (defconst transient--exit nil "Do exit the transient.")
   1518 
   1519 (defvar transient--exitp nil "Whether to exit the transient.")
   1520 (defvar transient--showp nil "Whether to show the transient popup buffer.")
   1521 (defvar transient--helpp nil "Whether help-mode is active.")
   1522 (defvar transient--editp nil "Whether edit-mode is active.")
   1523 
   1524 (defvar transient--refreshp nil
   1525   "Whether to refresh the transient completely.")
   1526 
   1527 (defvar transient--all-levels-p nil
   1528   "Whether temporary display of suffixes on all levels is active.")
   1529 
   1530 (defvar transient--timer nil)
   1531 
   1532 (defvar transient--stack nil)
   1533 
   1534 (defvar transient--minibuffer-depth 0)
   1535 
   1536 (defvar transient--buffer-name " *transient*"
   1537   "Name of the transient buffer.")
   1538 
   1539 (defvar transient--window nil
   1540   "The window used to display the transient popup buffer.")
   1541 
   1542 (defvar transient--original-window nil
   1543   "The window that was selected before the transient was invoked.
   1544 Usually it remains selected while the transient is active.")
   1545 
   1546 (defvar transient--original-buffer nil
   1547   "The buffer that was current before the transient was invoked.
   1548 Usually it remains current while the transient is active.")
   1549 
   1550 (defvar transient--restore-winconf nil
   1551   "Window configuration to restore after exiting help.")
   1552 
   1553 (defvar transient--shadowed-buffer nil
   1554   "The buffer that is temporarily shadowed by the transient buffer.
   1555 This is bound while the suffix predicate is being evaluated and while
   1556 drawing in the transient buffer.")
   1557 
   1558 (defvar transient--pending-suffix nil
   1559   "The suffix that is currently being processed.
   1560 This is bound while the suffix predicate is being evaluated,
   1561 and while functions that return faces are being evaluated.")
   1562 
   1563 (defvar transient--pending-group nil
   1564   "The group that is currently being processed.
   1565 This is bound while the suffixes are drawn in the transient buffer.")
   1566 
   1567 (defvar transient--debug nil
   1568   "Whether to put debug information into *Messages*.")
   1569 
   1570 (defvar transient--history nil)
   1571 
   1572 (defvar transient--scroll-commands
   1573   '(transient-scroll-up
   1574     transient-scroll-down
   1575     mwheel-scroll
   1576     scroll-bar-toolkit-scroll))
   1577 
   1578 ;;; Identities
   1579 
   1580 (defun transient-prefix-object ()
   1581   "Return the current prefix as an object.
   1582 
   1583 While a transient is being setup or refreshed (which involves
   1584 preparing its suffixes) the variable `transient--prefix' can be
   1585 used to access the prefix object.  Thus this is what has to be
   1586 used in suffix methods such as `transient-format-description',
   1587 and in object-specific functions that are stored in suffix slots
   1588 such as `description'.
   1589 
   1590 When a suffix command is invoked (i.e., in its `interactive' form
   1591 and function body) then the variable `transient-current-prefix'
   1592 has to be used instead.
   1593 
   1594 Two distinct variables are needed, because any prefix may itself
   1595 be used as a suffix of another prefix, and such sub-prefixes have
   1596 to be able to tell themselves apart from the prefix they were
   1597 invoked from.
   1598 
   1599 Regular suffix commands, which are not prefixes, do not have to
   1600 concern themselves with this distinction, so they can use this
   1601 function instead.  In the context of a plain suffix, it always
   1602 returns the value of the appropriate variable."
   1603   (or transient--prefix transient-current-prefix))
   1604 
   1605 (defun transient-suffix-object (&optional command)
   1606   "Return the object associated with the current suffix command.
   1607 
   1608 Each suffix commands is associated with an object, which holds
   1609 additional information about the suffix, such as its value (in
   1610 the case of an infix command, which is a kind of suffix command).
   1611 
   1612 This function is intended to be called by infix commands, which
   1613 are usually aliases of `transient--default-infix-command', which
   1614 is defined like this:
   1615 
   1616   (defun transient--default-infix-command ()
   1617     (interactive)
   1618     (let ((obj (transient-suffix-object)))
   1619       (transient-infix-set obj (transient-infix-read obj)))
   1620     (transient--show))
   1621 
   1622 \(User input is read outside of `interactive' to prevent the
   1623 command from being added to `command-history'.  See #23.)
   1624 
   1625 Such commands need to be able to access their associated object
   1626 to guide how `transient-infix-read' reads the new value and to
   1627 store the read value.  Other suffix commands (including non-infix
   1628 commands) may also need the object to guide their behavior.
   1629 
   1630 This function attempts to return the object associated with the
   1631 current suffix command even if the suffix command was not invoked
   1632 from a transient.  (For some suffix command that is a valid thing
   1633 to do, for others it is not.)  In that case nil may be returned,
   1634 if the command was not defined using one of the macros intended
   1635 to define such commands.
   1636 
   1637 The optional argument COMMAND is intended for internal use.  If
   1638 you are contemplating using it in your own code, then you should
   1639 probably use this instead:
   1640 
   1641   (get COMMAND \\='transient--suffix)"
   1642   (when command
   1643     (cl-check-type command command))
   1644   (cond
   1645    (transient--pending-suffix)
   1646    ((or transient--prefix
   1647         transient-current-prefix)
   1648     (let ((suffixes
   1649            (cl-remove-if-not
   1650             (lambda (obj)
   1651               (eq (oref obj command)
   1652                   (or command
   1653                       (if (eq this-command 'transient-set-level)
   1654                           ;; This is how it can look up for which
   1655                           ;; command it is setting the level.
   1656                           this-original-command
   1657                         this-command))))
   1658             (or transient--suffixes
   1659                 transient-current-suffixes))))
   1660       (or (and (cdr suffixes)
   1661                (cl-find-if
   1662                 (lambda (obj)
   1663                   (equal (listify-key-sequence (transient--kbd (oref obj key)))
   1664                          (listify-key-sequence (this-command-keys))))
   1665                 suffixes))
   1666           (car suffixes))))
   1667    ((and-let* ((obj (transient--suffix-prototype (or command this-command)))
   1668                (obj (clone obj)))
   1669       (progn ; work around debbugs#31840
   1670         (transient-init-scope obj)
   1671         (transient-init-value obj)
   1672         obj)))))
   1673 
   1674 (defun transient--suffix-prototype (command)
   1675   (or (get command 'transient--suffix)
   1676       (seq-some (lambda (cmd) (get cmd 'transient--suffix))
   1677                 (function-alias-p command))))
   1678 
   1679 ;;; Keymaps
   1680 
   1681 (defvar-keymap transient-base-map
   1682   :doc "Parent of other keymaps used by Transient.
   1683 
   1684 This is the parent keymap of all the keymaps that are used in
   1685 all transients: `transient-map' (which in turn is the parent
   1686 of the transient-specific keymaps), `transient-edit-map' and
   1687 `transient-sticky-map'.
   1688 
   1689 If you change a binding here, then you might also have to edit
   1690 `transient-sticky-map' and `transient-common-commands'.  While
   1691 the latter isn't a proper transient prefix command, it can be
   1692 edited using the same functions as used for transients.
   1693 
   1694 If you add a new command here, then you must also add a binding
   1695 to `transient-predicate-map'."
   1696   "ESC ESC ESC" #'transient-quit-all
   1697   "C-g"     #'transient-quit-one
   1698   "C-q"     #'transient-quit-all
   1699   "C-z"     #'transient-suspend
   1700   "C-v"     #'transient-scroll-up
   1701   "C-M-v"   #'transient-scroll-down
   1702   "<next>"  #'transient-scroll-up
   1703   "<prior>" #'transient-scroll-down)
   1704 
   1705 (defvar-keymap transient-map
   1706   :doc "Top-level keymap used by all transients.
   1707 
   1708 If you add a new command here, then you must also add a binding
   1709 to `transient-predicate-map'.  Also see `transient-base-map'."
   1710   :parent transient-base-map
   1711   "C-u"   #'universal-argument
   1712   "C--"   #'negative-argument
   1713   "C-t"   #'transient-show
   1714   "?"     #'transient-help
   1715   "C-h"   #'transient-help
   1716   ;; Also bound to "C-x p" and "C-x n" in transient-common-commands.
   1717   "C-M-p" #'transient-history-prev
   1718   "C-M-n" #'transient-history-next)
   1719 
   1720 (defvar-keymap transient-edit-map
   1721   :doc "Keymap that is active while a transient in is in \"edit mode\"."
   1722   :parent transient-base-map
   1723   "?"     #'transient-help
   1724   "C-h"   #'transient-help
   1725   "C-x l" #'transient-set-level)
   1726 
   1727 (defvar-keymap transient-sticky-map
   1728   :doc "Keymap that is active while an incomplete key sequence is active."
   1729   :parent transient-base-map
   1730   "C-g" #'transient-quit-seq)
   1731 
   1732 (defvar transient--common-command-prefixes '(?\C-x))
   1733 
   1734 (put 'transient-common-commands
   1735      'transient--layout
   1736      (list
   1737       (eval
   1738        (car (transient--parse-child
   1739              'transient-common-commands
   1740              (vector
   1741               :hide
   1742               (lambda ()
   1743                 (and (not (memq
   1744                            (car (bound-and-true-p transient--redisplay-key))
   1745                            transient--common-command-prefixes))
   1746                      (not transient-show-common-commands)))
   1747               (vector
   1748                "Value commands"
   1749                (list "C-x s  " "Set"            #'transient-set)
   1750                (list "C-x C-s" "Save"           #'transient-save)
   1751                (list "C-x C-k" "Reset"          #'transient-reset)
   1752                (list "C-x p  " "Previous value" #'transient-history-prev)
   1753                (list "C-x n  " "Next value"     #'transient-history-next))
   1754               (vector
   1755                "Sticky commands"
   1756                ;; Like `transient-sticky-map' except that
   1757                ;; "C-g" has to be bound to a different command.
   1758                (list "C-g" "Quit prefix or transient" #'transient-quit-one)
   1759                (list "C-q" "Quit transient stack"     #'transient-quit-all)
   1760                (list "C-z" "Suspend transient stack"  #'transient-suspend))
   1761               (vector
   1762                "Customize"
   1763                (list "C-x t" 'transient-toggle-common :description
   1764                      (lambda ()
   1765                        (if transient-show-common-commands
   1766                            "Hide common commands"
   1767                          "Show common permanently")))
   1768                (list "C-x l" "Show/hide suffixes" #'transient-set-level)
   1769                (list "C-x a" #'transient-toggle-level-limit)))))
   1770        t)))
   1771 
   1772 (defvar-keymap transient-popup-navigation-map
   1773   :doc "One of the keymaps used when popup navigation is enabled.
   1774 See `transient-enable-popup-navigation'."
   1775   "<down-mouse-1>" #'transient-noop
   1776   "<up>"   #'transient-backward-button
   1777   "<down>" #'transient-forward-button
   1778   "C-r"    #'transient-isearch-backward
   1779   "C-s"    #'transient-isearch-forward
   1780   "M-RET"  #'transient-push-button)
   1781 
   1782 (defvar-keymap transient-button-map
   1783   :doc "One of the keymaps used when popup navigation is enabled.
   1784 See `transient-enable-popup-navigation'."
   1785   "<mouse-1>" #'transient-push-button
   1786   "<mouse-2>" #'transient-push-button)
   1787 
   1788 (defvar-keymap transient-resume-mode-map
   1789   :doc "Keymap for `transient-resume-mode'.
   1790 
   1791 This keymap remaps every command that would usually just quit the
   1792 documentation buffer to `transient-resume', which additionally
   1793 resumes the suspended transient."
   1794   "<remap> <Man-quit>"    #'transient-resume
   1795   "<remap> <Info-exit>"   #'transient-resume
   1796   "<remap> <quit-window>" #'transient-resume)
   1797 
   1798 (defvar-keymap transient-predicate-map
   1799   :doc "Base keymap used to map common commands to their transient behavior.
   1800 
   1801 The \"transient behavior\" of a command controls, among other
   1802 things, whether invoking the command causes the transient to be
   1803 exited or not, and whether infix arguments are exported before
   1804 doing so.
   1805 
   1806 Each \"key\" is a command that is common to all transients and
   1807 that is bound in `transient-map', `transient-edit-map',
   1808 `transient-sticky-map' and/or `transient-common-command'.
   1809 
   1810 Each binding is a \"pre-command\", a function that controls the
   1811 transient behavior of the respective command.
   1812 
   1813 For transient commands that are bound in individual transients,
   1814 the transient behavior is specified using the `:transient' slot
   1815 of the corresponding object."
   1816   "<transient-suspend>"           #'transient--do-suspend
   1817   "<transient-help>"              #'transient--do-stay
   1818   "<transient-set-level>"         #'transient--do-stay
   1819   "<transient-history-prev>"      #'transient--do-stay
   1820   "<transient-history-next>"      #'transient--do-stay
   1821   "<universal-argument>"          #'transient--do-stay
   1822   "<universal-argument-more>"     #'transient--do-stay
   1823   "<negative-argument>"           #'transient--do-minus
   1824   "<digit-argument>"              #'transient--do-stay
   1825   "<top-level>"                   #'transient--do-quit-all
   1826   "<transient-quit-all>"          #'transient--do-quit-all
   1827   "<transient-quit-one>"          #'transient--do-quit-one
   1828   "<transient-quit-seq>"          #'transient--do-stay
   1829   "<transient-show>"              #'transient--do-stay
   1830   "<transient-update>"            #'transient--do-stay
   1831   "<transient-toggle-common>"     #'transient--do-stay
   1832   "<transient-set>"               #'transient--do-call
   1833   "<transient-set-and-exit>"      #'transient--do-exit
   1834   "<transient-save>"              #'transient--do-call
   1835   "<transient-save-and-exit>"     #'transient--do-exit
   1836   "<transient-reset>"             #'transient--do-call
   1837   "<describe-key-briefly>"        #'transient--do-stay
   1838   "<describe-key>"                #'transient--do-stay
   1839   "<transient-scroll-up>"         #'transient--do-stay
   1840   "<transient-scroll-down>"       #'transient--do-stay
   1841   "<mwheel-scroll>"               #'transient--do-stay
   1842   "<scroll-bar-toolkit-scroll>"   #'transient--do-stay
   1843   "<transient-noop>"              #'transient--do-noop
   1844   "<transient-mouse-push-button>" #'transient--do-move
   1845   "<transient-push-button>"       #'transient--do-push-button
   1846   "<transient-backward-button>"   #'transient--do-move
   1847   "<transient-forward-button>"    #'transient--do-move
   1848   "<transient-isearch-backward>"  #'transient--do-move
   1849   "<transient-isearch-forward>"   #'transient--do-move
   1850   ;; If a valid but incomplete prefix sequence is followed by
   1851   ;; an unbound key, then Emacs calls the `undefined' command
   1852   ;; but does not set `this-command', `this-original-command'
   1853   ;; or `real-this-command' accordingly.  Instead they are nil.
   1854   "<nil>"                         #'transient--do-warn
   1855   ;; Bound to the `mouse-movement' event, this command is similar
   1856   ;; to `ignore'.
   1857   "<ignore-preserving-kill-region>" #'transient--do-noop)
   1858 
   1859 (defvar transient--transient-map nil)
   1860 (defvar transient--predicate-map nil)
   1861 (defvar transient--redisplay-map nil)
   1862 (defvar transient--redisplay-key nil)
   1863 
   1864 (defun transient--push-keymap (var)
   1865   (let ((map (symbol-value var)))
   1866     (transient--debug "     push %s%s" var (if map "" " VOID"))
   1867     (when map
   1868       (with-demoted-errors "transient--push-keymap: %S"
   1869         (internal-push-keymap map 'overriding-terminal-local-map)))))
   1870 
   1871 (defun transient--pop-keymap (var)
   1872   (let ((map (symbol-value var)))
   1873     (when map
   1874       (transient--debug "     pop  %s" var)
   1875       (with-demoted-errors "transient--pop-keymap: %S"
   1876         (internal-pop-keymap map 'overriding-terminal-local-map)))))
   1877 
   1878 (defun transient--make-transient-map ()
   1879   (let ((map (make-sparse-keymap)))
   1880     (set-keymap-parent map (if transient--editp
   1881                                transient-edit-map
   1882                              transient-map))
   1883     (dolist (obj transient--suffixes)
   1884       (let ((key (oref obj key)))
   1885         (when (vectorp key)
   1886           (setq key (key-description key))
   1887           (oset obj key key))
   1888         (when transient-substitute-key-function
   1889           (setq key (save-match-data
   1890                       (funcall transient-substitute-key-function obj)))
   1891           (oset obj key key))
   1892         (let* ((kbd (kbd key))
   1893                (cmd (oref obj command))
   1894                (alt (transient--lookup-key map kbd)))
   1895           (cond ((not alt)
   1896                  (define-key map kbd cmd))
   1897                 ((eq alt cmd))
   1898                 ((transient--inapt-suffix-p obj))
   1899                 ((and-let* ((obj (transient-suffix-object alt)))
   1900                    (transient--inapt-suffix-p obj))
   1901                  (define-key map kbd cmd))
   1902                 (transient-detect-key-conflicts
   1903                  (error "Cannot bind %S to %s and also %s"
   1904                         (string-trim key) cmd alt))
   1905                 ((define-key map kbd cmd))))))
   1906     (when-let ((b (keymap-lookup map "-"))) (keymap-set map "<kp-subtract>" b))
   1907     (when-let ((b (keymap-lookup map "="))) (keymap-set map "<kp-equal>" b))
   1908     (when-let ((b (keymap-lookup map "+"))) (keymap-set map "<kp-add>" b))
   1909     (when transient-enable-popup-navigation
   1910       ;; `transient--make-redisplay-map' maps only over bindings that are
   1911       ;; directly in the base keymap, so that cannot be a composed keymap.
   1912       (set-keymap-parent
   1913        map (make-composed-keymap
   1914             (keymap-parent map)
   1915             transient-popup-navigation-map)))
   1916     map))
   1917 
   1918 (defun transient--make-predicate-map ()
   1919   (let* ((default (transient--resolve-pre-command
   1920                    (oref transient--prefix transient-suffix)))
   1921          (return (and transient--stack (eq default t)))
   1922          (map (make-sparse-keymap)))
   1923     (set-keymap-parent map transient-predicate-map)
   1924     (when (or (and (slot-boundp transient--prefix 'transient-switch-frame)
   1925                    (transient--resolve-pre-command
   1926                     (not (oref transient--prefix transient-switch-frame))))
   1927               (memq (transient--resolve-pre-command
   1928                      (oref transient--prefix transient-non-suffix))
   1929                     '(nil transient--do-warn transient--do-noop)))
   1930       (define-key map [handle-switch-frame] #'transient--do-suspend))
   1931     (dolist (obj transient--suffixes)
   1932       (let* ((cmd (oref obj command))
   1933              (kind (cond ((get cmd 'transient--prefix)    'prefix)
   1934                          ((cl-typep obj 'transient-infix) 'infix)
   1935                          (t                               'suffix))))
   1936         (cond
   1937          ((oref obj inapt)
   1938           (define-key map (vector cmd) #'transient--do-warn-inapt))
   1939          ((slot-boundp obj 'transient)
   1940           (define-key map (vector cmd)
   1941             (pcase (list kind
   1942                          (transient--resolve-pre-command (oref obj transient))
   1943                          return)
   1944               (`(prefix   t ,_) #'transient--do-recurse)
   1945               (`(prefix nil ,_) #'transient--do-stack)
   1946               (`(infix    t ,_) #'transient--do-stay)
   1947               (`(suffix   t ,_) #'transient--do-call)
   1948               ('(suffix nil  t) #'transient--do-return)
   1949               (`(,_     nil ,_) #'transient--do-exit)
   1950               (`(,_     ,do ,_) do))))
   1951          ((not (lookup-key transient-predicate-map (vector cmd)))
   1952           (define-key map (vector cmd)
   1953             (pcase (list kind default return)
   1954               (`(prefix ,(or 'transient--do-stay 'transient--do-call) ,_)
   1955                #'transient--do-recurse)
   1956               (`(prefix   t ,_) #'transient--do-recurse)
   1957               (`(prefix  ,_ ,_) #'transient--do-stack)
   1958               (`(infix   ,_ ,_) #'transient--do-stay)
   1959               (`(suffix   t ,_) #'transient--do-call)
   1960               ('(suffix nil  t) #'transient--do-return)
   1961               (`(suffix nil ,_) #'transient--do-exit)
   1962               (`(suffix ,do ,_) do)))))))
   1963     map))
   1964 
   1965 (defun transient--make-redisplay-map ()
   1966   (setq transient--redisplay-key
   1967         (pcase this-command
   1968           ('transient-update
   1969            (setq transient--showp t)
   1970            (setq unread-command-events
   1971                  (listify-key-sequence (this-single-command-raw-keys))))
   1972           ('transient-quit-seq
   1973            (setq unread-command-events
   1974                  (butlast (listify-key-sequence
   1975                            (this-single-command-raw-keys))
   1976                           2))
   1977            (butlast transient--redisplay-key))
   1978           (_ nil)))
   1979   (let ((topmap (make-sparse-keymap))
   1980         (submap (make-sparse-keymap)))
   1981     (when transient--redisplay-key
   1982       (define-key topmap (vconcat transient--redisplay-key) submap)
   1983       (set-keymap-parent submap transient-sticky-map))
   1984     (map-keymap-internal
   1985      (lambda (key def)
   1986        (when (and (not (eq key ?\e))
   1987                   (listp def)
   1988                   (keymapp def))
   1989          (define-key topmap (vconcat transient--redisplay-key (list key))
   1990            #'transient-update)))
   1991      (if transient--redisplay-key
   1992          (let ((key (vconcat transient--redisplay-key)))
   1993            (or (lookup-key transient--transient-map key)
   1994                (and-let* ((regular (lookup-key local-function-key-map key)))
   1995                  (lookup-key transient--transient-map (vconcat regular)))))
   1996        transient--transient-map))
   1997     topmap))
   1998 
   1999 ;;; Setup
   2000 
   2001 (defun transient-setup (&optional name layout edit &rest params)
   2002   "Setup the transient specified by NAME.
   2003 
   2004 This function is called by transient prefix commands to setup the
   2005 transient.  In that case NAME is mandatory, LAYOUT and EDIT must
   2006 be nil and PARAMS may be (but usually is not) used to set, e.g.,
   2007 the \"scope\" of the transient (see `transient-define-prefix').
   2008 
   2009 This function is also called internally in which case LAYOUT and
   2010 EDIT may be non-nil."
   2011   (transient--debug 'setup)
   2012   (transient--with-emergency-exit :setup
   2013     (cond
   2014      ((not name)
   2015       ;; Switching between regular and edit mode.
   2016       (transient--pop-keymap 'transient--transient-map)
   2017       (transient--pop-keymap 'transient--redisplay-map)
   2018       (setq name (oref transient--prefix command))
   2019       (setq params (list :scope (oref transient--prefix scope))))
   2020      (transient--prefix
   2021       ;; Invoked as a ":transient-non-suffix 'transient--do-{stay,call}"
   2022       ;; of an outer prefix.  Unlike the usual `transient--do-stack',
   2023       ;; these predicates fail to clean up after the outer prefix.
   2024       (transient--pop-keymap 'transient--transient-map)
   2025       (transient--pop-keymap 'transient--redisplay-map))
   2026      ((not (or layout                      ; resuming parent/suspended prefix
   2027                transient-current-command)) ; entering child prefix
   2028       (transient--stack-zap))              ; replace suspended prefix, if any
   2029      (edit
   2030       ;; Returning from help to edit.
   2031       (setq transient--editp t)))
   2032     (transient--init-objects name layout params)
   2033     (transient--init-keymaps)
   2034     (transient--history-init transient--prefix)
   2035     (setq transient--original-window (selected-window))
   2036     (setq transient--original-buffer (current-buffer))
   2037     (setq transient--minibuffer-depth (minibuffer-depth))
   2038     (transient--redisplay)
   2039     (transient--init-transient)
   2040     (transient--suspend-which-key-mode)))
   2041 
   2042 (cl-defgeneric transient-setup-children (group children)
   2043   "Setup the CHILDREN of GROUP.
   2044 If the value of the `setup-children' slot is non-nil, then call
   2045 that function with CHILDREN as the only argument and return the
   2046 value.  Otherwise return CHILDREN as is."
   2047   (if (slot-boundp group 'setup-children)
   2048       (funcall (oref group setup-children) children)
   2049     children))
   2050 
   2051 (defun transient--init-keymaps ()
   2052   (setq transient--predicate-map (transient--make-predicate-map))
   2053   (setq transient--transient-map (transient--make-transient-map))
   2054   (setq transient--redisplay-map (transient--make-redisplay-map)))
   2055 
   2056 (defun transient--init-objects (&optional name layout params)
   2057   (if name
   2058       (setq transient--prefix (transient--init-prefix name params))
   2059     (setq name (oref transient--prefix command)))
   2060   (setq transient--refreshp (oref transient--prefix refresh-suffixes))
   2061   (setq transient--layout (or layout (transient--init-suffixes name)))
   2062   (setq transient--suffixes (transient--flatten-suffixes transient--layout)))
   2063 
   2064 (defun transient--init-prefix (name &optional params)
   2065   (let ((obj (let ((proto (get name 'transient--prefix)))
   2066                (apply #'clone proto
   2067                       :prototype proto
   2068                       :level (or (alist-get t (alist-get name transient-levels))
   2069                                  transient-default-level)
   2070                       params))))
   2071     (transient--setup-recursion obj)
   2072     (transient-init-value obj)
   2073     obj))
   2074 
   2075 (defun transient--init-suffixes (name)
   2076   (let ((levels (alist-get name transient-levels)))
   2077     (cl-mapcan (lambda (c) (transient--init-child levels c nil))
   2078                (append (get name 'transient--layout)
   2079                        (and (not transient--editp)
   2080                             (get 'transient-common-commands
   2081                                  'transient--layout))))))
   2082 
   2083 (defun transient--flatten-suffixes (layout)
   2084   (cl-labels ((s (def)
   2085                 (cond
   2086                  ((stringp def) nil)
   2087                  ((cl-typep def 'transient-information) nil)
   2088                  ((listp def) (cl-mapcan #'s def))
   2089                  ((cl-typep def 'transient-group)
   2090                   (cl-mapcan #'s (oref def suffixes)))
   2091                  ((cl-typep def 'transient-suffix)
   2092                   (list def)))))
   2093     (cl-mapcan #'s layout)))
   2094 
   2095 (defun transient--init-child (levels spec parent)
   2096   (cl-etypecase spec
   2097     (vector  (transient--init-group  levels spec parent))
   2098     (list    (transient--init-suffix levels spec parent))
   2099     (string  (list spec))))
   2100 
   2101 (defun transient--init-group (levels spec parent)
   2102   (pcase-let ((`(,level ,class ,args ,children) (append spec nil)))
   2103     (and-let* (((transient--use-level-p level))
   2104                (obj (apply class :level level args))
   2105                ((transient--use-suffix-p obj))
   2106                ((prog1 t
   2107                   (when (or (and parent (oref parent inapt))
   2108                             (transient--inapt-suffix-p obj))
   2109                     (oset obj inapt t))))
   2110                (suffixes (cl-mapcan
   2111                           (lambda (c) (transient--init-child levels c obj))
   2112                           (transient-setup-children obj children))))
   2113       (progn ; work around debbugs#31840
   2114         (oset obj suffixes suffixes)
   2115         (list obj)))))
   2116 
   2117 (defun transient--init-suffix (levels spec parent)
   2118   (pcase-let* ((`(,level ,class ,args) spec)
   2119                (cmd (plist-get args :command))
   2120                (key (transient--kbd (plist-get args :key)))
   2121                (level (or (alist-get (cons cmd key) levels nil nil #'equal)
   2122                           (alist-get cmd levels)
   2123                           level)))
   2124     (let ((fn (and (symbolp cmd)
   2125                    (symbol-function cmd))))
   2126       (when (autoloadp fn)
   2127         (transient--debug "   autoload %s" cmd)
   2128         (autoload-do-load fn)))
   2129     (when (transient--use-level-p level)
   2130       (let ((obj (if (child-of-class-p class 'transient-information)
   2131                      (apply class :level level args)
   2132                    (unless (and cmd (symbolp cmd))
   2133                      (error "BUG: Non-symbolic suffix command: %s" cmd))
   2134                    (if-let ((proto (and cmd (transient--suffix-prototype cmd))))
   2135                        (apply #'clone proto :level level args)
   2136                      (apply class :command cmd :level level args)))))
   2137         (cond ((not cmd))
   2138               ((commandp cmd))
   2139               ((or (cl-typep obj 'transient-switch)
   2140                    (cl-typep obj 'transient-option))
   2141                ;; As a temporary special case, if the package was compiled
   2142                ;; with an older version of Transient, then we must define
   2143                ;; "anonymous" switch and option commands here.
   2144                (defalias cmd #'transient--default-infix-command))
   2145               ((transient--use-suffix-p obj)
   2146                (error "Suffix command %s is not defined or autoloaded" cmd)))
   2147         (unless (cl-typep obj 'transient-information)
   2148           (transient--init-suffix-key obj))
   2149         (when (transient--use-suffix-p obj)
   2150           (if (or (and parent (oref parent inapt))
   2151                   (transient--inapt-suffix-p obj))
   2152               (oset obj inapt t)
   2153             (transient-init-scope obj)
   2154             (transient-init-value obj))
   2155           (list obj))))))
   2156 
   2157 (cl-defmethod transient--init-suffix-key ((obj transient-suffix))
   2158   (unless (slot-boundp obj 'key)
   2159     (error "No key for %s" (oref obj command))))
   2160 
   2161 (cl-defmethod transient--init-suffix-key ((obj transient-argument))
   2162   (if (transient-switches--eieio-childp obj)
   2163       (cl-call-next-method obj)
   2164     (unless (slot-boundp obj 'shortarg)
   2165       (when-let ((shortarg (transient--derive-shortarg (oref obj argument))))
   2166         (oset obj shortarg shortarg)))
   2167     (unless (slot-boundp obj 'key)
   2168       (if (slot-boundp obj 'shortarg)
   2169           (oset obj key (oref obj shortarg))
   2170         (error "No key for %s" (oref obj command))))))
   2171 
   2172 (defun transient--use-level-p (level &optional edit)
   2173   (or transient--all-levels-p
   2174       (and transient--editp (not edit))
   2175       (and (>= level 1)
   2176            (<= level (oref transient--prefix level)))))
   2177 
   2178 (defun transient--use-suffix-p (obj)
   2179   (let ((transient--shadowed-buffer (current-buffer))
   2180         (transient--pending-suffix obj))
   2181     (transient--do-suffix-p
   2182      (oref obj if)
   2183      (oref obj if-not)
   2184      (oref obj if-nil)
   2185      (oref obj if-non-nil)
   2186      (oref obj if-mode)
   2187      (oref obj if-not-mode)
   2188      (oref obj if-derived)
   2189      (oref obj if-not-derived)
   2190      t)))
   2191 
   2192 (defun transient--inapt-suffix-p (obj)
   2193   (let ((transient--shadowed-buffer (current-buffer))
   2194         (transient--pending-suffix obj))
   2195     (transient--do-suffix-p
   2196      (oref obj inapt-if)
   2197      (oref obj inapt-if-not)
   2198      (oref obj inapt-if-nil)
   2199      (oref obj inapt-if-non-nil)
   2200      (oref obj inapt-if-mode)
   2201      (oref obj inapt-if-not-mode)
   2202      (oref obj inapt-if-derived)
   2203      (oref obj inapt-if-not-derived)
   2204      nil)))
   2205 
   2206 (defun transient--do-suffix-p
   2207     (if if-not if-nil if-non-nil if-mode if-not-mode if-derived if-not-derived
   2208         default)
   2209   (cond
   2210    (if                  (funcall if))
   2211    (if-not         (not (funcall if-not)))
   2212    (if-non-nil          (symbol-value if-non-nil))
   2213    (if-nil         (not (symbol-value if-nil)))
   2214    (if-mode             (if (atom if-mode)
   2215                             (eq major-mode if-mode)
   2216                           (memq major-mode if-mode)))
   2217    (if-not-mode    (not (if (atom if-not-mode)
   2218                             (eq major-mode if-not-mode)
   2219                           (memq major-mode if-not-mode))))
   2220    (if-derived          (if (or (atom if-derived)
   2221                                 (>= emacs-major-version 30))
   2222                             (derived-mode-p if-derived)
   2223                           (apply #'derived-mode-p if-derived)))
   2224    (if-not-derived (not (if (or (atom if-not-derived)
   2225                                 (>= emacs-major-version 30))
   2226                             (derived-mode-p if-not-derived)
   2227                           (apply #'derived-mode-p if-not-derived))))
   2228    (default)))
   2229 
   2230 (defun transient--suffix-predicate (spec)
   2231   (let ((plist (nth 2 spec)))
   2232     (seq-some (lambda (prop)
   2233                 (and-let* ((pred (plist-get plist prop)))
   2234                   (list prop pred)))
   2235               '( :if :if-not
   2236                  :if-nil :if-non-nil
   2237                  :if-mode :if-not-mode
   2238                  :if-derived :if-not-derived
   2239                  :inapt-if :inapt-if-not
   2240                  :inapt-if-nil :inapt-if-non-nil
   2241                  :inapt-if-mode :inapt-if-not-mode
   2242                  :inapt-if-derived :inapt-if-not-derived))))
   2243 
   2244 ;;; Flow-Control
   2245 
   2246 (defun transient--init-transient ()
   2247   (transient--debug 'init-transient)
   2248   (transient--push-keymap 'transient--transient-map)
   2249   (transient--push-keymap 'transient--redisplay-map)
   2250   (add-hook 'pre-command-hook  #'transient--pre-command)
   2251   (add-hook 'post-command-hook #'transient--post-command)
   2252   (advice-add 'recursive-edit :around #'transient--recursive-edit)
   2253   (when transient--exitp
   2254     ;; This prefix command was invoked as the suffix of another.
   2255     ;; Prevent `transient--post-command' from removing the hooks
   2256     ;; that we just added.
   2257     (setq transient--exitp 'replace)))
   2258 
   2259 (defun transient--refresh-transient ()
   2260   (transient--debug 'refresh-transient)
   2261   (transient--pop-keymap 'transient--predicate-map)
   2262   (transient--pop-keymap 'transient--transient-map)
   2263   (transient--pop-keymap 'transient--redisplay-map)
   2264   (transient--init-objects)
   2265   (transient--init-keymaps)
   2266   (transient--push-keymap 'transient--transient-map)
   2267   (transient--push-keymap 'transient--redisplay-map)
   2268   (transient--redisplay))
   2269 
   2270 (defun transient--pre-command ()
   2271   (transient--debug 'pre-command)
   2272   (transient--with-emergency-exit :pre-command
   2273     ;; The use of `overriding-terminal-local-map' does not prevent the
   2274     ;; lookup of command remappings in the overridden maps, which can
   2275     ;; lead to a suffix being remapped to a non-suffix.  We have to undo
   2276     ;; the remapping in that case.  However, remapping a non-suffix to
   2277     ;; another should remain possible.
   2278     (when (and (transient--get-pre-command this-original-command 'suffix)
   2279                (not (transient--get-pre-command this-command 'suffix)))
   2280       (setq this-command this-original-command))
   2281     (cond
   2282      ((memq this-command '(transient-update transient-quit-seq))
   2283       (transient--pop-keymap 'transient--redisplay-map))
   2284      ((and transient--helpp
   2285            (not (memq this-command '(transient-quit-one
   2286                                      transient-quit-all))))
   2287       (cond
   2288        ((transient-help)
   2289         (transient--do-suspend)
   2290         (setq this-command 'transient-suspend)
   2291         (transient--pre-exit))
   2292        ((not (transient--edebug-command-p))
   2293         (setq this-command 'transient-undefined))))
   2294      ((and transient--editp
   2295            (transient-suffix-object)
   2296            (not (memq this-command '(transient-quit-one
   2297                                      transient-quit-all
   2298                                      transient-help))))
   2299       (setq this-command 'transient-set-level)
   2300       (transient--wrap-command))
   2301      (t
   2302       (setq transient--exitp nil)
   2303       (let ((exitp (eq (transient--call-pre-command) transient--exit)))
   2304         (transient--wrap-command)
   2305         (when exitp
   2306           (transient--pre-exit)))))))
   2307 
   2308 (defun transient--pre-exit ()
   2309   (transient--debug 'pre-exit)
   2310   (transient--delete-window)
   2311   (transient--timer-cancel)
   2312   (transient--pop-keymap 'transient--transient-map)
   2313   (transient--pop-keymap 'transient--redisplay-map)
   2314   (unless transient--showp
   2315     (let ((message-log-max nil))
   2316       (message "")))
   2317   (setq transient--transient-map nil)
   2318   (setq transient--predicate-map nil)
   2319   (setq transient--redisplay-map nil)
   2320   (setq transient--redisplay-key nil)
   2321   (setq transient--helpp nil)
   2322   (setq transient--editp nil)
   2323   (setq transient--prefix nil)
   2324   (setq transient--layout nil)
   2325   (setq transient--suffixes nil)
   2326   (setq transient--original-window nil)
   2327   (setq transient--original-buffer nil)
   2328   (setq transient--window nil))
   2329 
   2330 (defun transient--delete-window ()
   2331   (when (window-live-p transient--window)
   2332     (let ((remain-in-minibuffer-window
   2333            (and (minibuffer-selected-window)
   2334                 (selected-window))))
   2335       ;; Only delete the window if it has never shown another buffer.
   2336       (unless (eq (car (window-parameter transient--window 'quit-restore))
   2337                   'other)
   2338         (with-demoted-errors "Error while exiting transient: %S"
   2339           (delete-window transient--window)))
   2340       (when-let ((buffer (get-buffer transient--buffer-name)))
   2341         (kill-buffer buffer))
   2342       (when remain-in-minibuffer-window
   2343         (select-window remain-in-minibuffer-window)))))
   2344 
   2345 (defun transient--export ()
   2346   (setq transient-current-prefix transient--prefix)
   2347   (setq transient-current-command (oref transient--prefix command))
   2348   (setq transient-current-suffixes transient--suffixes)
   2349   (transient--history-push transient--prefix))
   2350 
   2351 (defun transient--suspend-override (&optional nohide)
   2352   (transient--debug 'suspend-override)
   2353   (transient--timer-cancel)
   2354   (cond ((and (not nohide) transient-hide-during-minibuffer-read)
   2355          (transient--delete-window))
   2356         ((and transient--prefix transient--redisplay-key)
   2357          (setq transient--redisplay-key nil)
   2358          (when transient--showp
   2359            (if-let ((win (minibuffer-selected-window)))
   2360                (with-selected-window win
   2361                  (transient--show))
   2362              (transient--show)))))
   2363   (transient--pop-keymap 'transient--transient-map)
   2364   (transient--pop-keymap 'transient--redisplay-map)
   2365   (remove-hook 'pre-command-hook  #'transient--pre-command)
   2366   (remove-hook 'post-command-hook #'transient--post-command))
   2367 
   2368 (defun transient--resume-override (&optional _ignore)
   2369   (transient--debug 'resume-override)
   2370   (when (and transient--showp transient-hide-during-minibuffer-read)
   2371     (transient--show))
   2372   (transient--push-keymap 'transient--transient-map)
   2373   (transient--push-keymap 'transient--redisplay-map)
   2374   (add-hook 'pre-command-hook  #'transient--pre-command)
   2375   (add-hook 'post-command-hook #'transient--post-command))
   2376 
   2377 (defun transient--recursive-edit (fn)
   2378   (transient--debug 'recursive-edit)
   2379   (if (not transient--prefix)
   2380       (funcall fn)
   2381     (transient--suspend-override (bound-and-true-p edebug-active))
   2382     (funcall fn) ; Already unwind protected.
   2383     (cond ((memq this-command '(top-level abort-recursive-edit))
   2384            (setq transient--exitp t)
   2385            (transient--post-exit)
   2386            (transient--delete-window))
   2387           (transient--prefix
   2388            (transient--resume-override)))))
   2389 
   2390 (defmacro transient--with-suspended-override (&rest body)
   2391   (let ((depth (make-symbol "depth"))
   2392         (setup (make-symbol "setup"))
   2393         (exit  (make-symbol "exit")))
   2394     `(if (and transient--transient-map
   2395               (memq transient--transient-map
   2396                     overriding-terminal-local-map))
   2397          (let ((,depth (1+ (minibuffer-depth))) ,setup ,exit)
   2398            (setq ,setup
   2399                  (lambda () "@transient--with-suspended-override"
   2400                    (transient--debug 'minibuffer-setup)
   2401                    (remove-hook 'minibuffer-setup-hook ,setup)
   2402                    (transient--suspend-override)))
   2403            (setq ,exit
   2404                  (lambda () "@transient--with-suspended-override"
   2405                    (transient--debug 'minibuffer-exit)
   2406                    (when (= (minibuffer-depth) ,depth)
   2407                      (transient--resume-override))))
   2408            (unwind-protect
   2409                (progn
   2410                  (add-hook 'minibuffer-setup-hook ,setup)
   2411                  (add-hook 'minibuffer-exit-hook ,exit)
   2412                  ,@body)
   2413              (remove-hook 'minibuffer-setup-hook ,setup)
   2414              (remove-hook 'minibuffer-exit-hook ,exit)))
   2415        ,@body)))
   2416 
   2417 (static-if (>= emacs-major-version 30) ;transient--wrap-command
   2418     (defun transient--wrap-command ()
   2419       (cl-assert
   2420        (>= emacs-major-version 30) nil
   2421        "Emacs was downgraded, making it necessary to recompile Transient")
   2422       (letrec
   2423           ((prefix transient--prefix)
   2424            (suffix this-command)
   2425            (advice
   2426             (lambda (fn &rest args)
   2427               (interactive
   2428                (lambda (spec)
   2429                  (let ((abort t))
   2430                    (unwind-protect
   2431                        (prog1 (let ((debugger #'transient--exit-and-debug))
   2432                                 (advice-eval-interactive-spec spec))
   2433                          (setq abort nil))
   2434                      (when abort
   2435                        (when-let ((unwind (oref prefix unwind-suffix)))
   2436                          (transient--debug 'unwind-interactive)
   2437                          (funcall unwind suffix))
   2438                        (advice-remove suffix advice)
   2439                        (oset prefix unwind-suffix nil))))))
   2440               (unwind-protect
   2441                   (let ((debugger #'transient--exit-and-debug))
   2442                     (apply fn args))
   2443                 (when-let ((unwind (oref prefix unwind-suffix)))
   2444                   (transient--debug 'unwind-command)
   2445                   (funcall unwind suffix))
   2446                 (advice-remove suffix advice)
   2447                 (oset prefix unwind-suffix nil)))))
   2448         (when (symbolp this-command)
   2449           (advice-add suffix :around advice '((depth . -99))))))
   2450 
   2451   (defun transient--wrap-command ()
   2452     (let* ((prefix transient--prefix)
   2453            (suffix this-command)
   2454            (advice nil)
   2455            (advice-interactive
   2456             (lambda (spec)
   2457               (let ((abort t))
   2458                 (unwind-protect
   2459                     (prog1 (let ((debugger #'transient--exit-and-debug))
   2460                              (advice-eval-interactive-spec spec))
   2461                       (setq abort nil))
   2462                   (when abort
   2463                     (when-let ((unwind (oref prefix unwind-suffix)))
   2464                       (transient--debug 'unwind-interactive)
   2465                       (funcall unwind suffix))
   2466                     (advice-remove suffix advice)
   2467                     (oset prefix unwind-suffix nil))))))
   2468            (advice-body
   2469             (lambda (fn &rest args)
   2470               (unwind-protect
   2471                   (let ((debugger #'transient--exit-and-debug))
   2472                     (apply fn args))
   2473                 (when-let ((unwind (oref prefix unwind-suffix)))
   2474                   (transient--debug 'unwind-command)
   2475                   (funcall unwind suffix))
   2476                 (advice-remove suffix advice)
   2477                 (oset prefix unwind-suffix nil)))))
   2478       (setq advice `(lambda (fn &rest args)
   2479                       (interactive ,advice-interactive)
   2480                       (apply ',advice-body fn args)))
   2481       (when (symbolp this-command)
   2482         (advice-add suffix :around advice '((depth . -99)))))))
   2483 
   2484 (defun transient--premature-post-command ()
   2485   (and (equal (this-command-keys-vector) [])
   2486        (= (minibuffer-depth)
   2487           (1+ transient--minibuffer-depth))
   2488        (progn
   2489          (transient--debug 'premature-post-command)
   2490          (transient--suspend-override)
   2491          (oset (or transient--prefix transient-current-prefix)
   2492                unwind-suffix
   2493                (if transient--exitp
   2494                    #'transient--post-exit
   2495                  #'transient--resume-override))
   2496          t)))
   2497 
   2498 (defun transient--post-command ()
   2499   (unless (transient--premature-post-command)
   2500     (transient--debug 'post-command)
   2501     (transient--with-emergency-exit :post-command
   2502       (cond (transient--exitp (transient--post-exit))
   2503             ;; If `this-command' is the current transient prefix, then we
   2504             ;; have already taken care of updating the transient buffer...
   2505             ((and (eq this-command (oref transient--prefix command))
   2506                   ;; ... but if `prefix-arg' is non-nil, then the values
   2507                   ;; of `this-command' and `real-this-command' are untrue
   2508                   ;; because `prefix-command-preserve-state' changes them.
   2509                   ;; We cannot use `current-prefix-arg' because it is set
   2510                   ;; too late (in `command-execute'), and if it were set
   2511                   ;; earlier, then we likely still would not be able to
   2512                   ;; rely on it and `prefix-command-preserve-state-hook'
   2513                   ;; would have to be used to record that a universal
   2514                   ;; argument is in effect.
   2515                   (not prefix-arg)))
   2516             (transient--refreshp
   2517              (transient--refresh-transient))
   2518             ((let ((old transient--redisplay-map)
   2519                    (new (transient--make-redisplay-map)))
   2520                (unless (equal old new)
   2521                  (transient--pop-keymap 'transient--redisplay-map)
   2522                  (setq transient--redisplay-map new)
   2523                  (transient--push-keymap 'transient--redisplay-map))
   2524                (transient--redisplay)))))))
   2525 
   2526 (defun transient--post-exit (&optional command)
   2527   (transient--debug 'post-exit)
   2528   (unless (and (eq transient--exitp 'replace)
   2529                (or transient--prefix
   2530                    ;; The current command could act as a prefix,
   2531                    ;; but decided not to call `transient-setup',
   2532                    ;; or it is prevented from doing so because it
   2533                    ;; uses the minibuffer and the user aborted
   2534                    ;; that.
   2535                    (prog1 nil
   2536                      (if (let ((obj (transient-suffix-object command)))
   2537                            (and (slot-boundp obj 'transient)
   2538                                 (oref obj transient)))
   2539                          ;; This sub-prefix is a transient suffix;
   2540                          ;; go back to outer prefix, by calling
   2541                          ;; `transient--stack-pop' further down.
   2542                          (setq transient--exitp nil)
   2543                        (transient--stack-zap)))))
   2544     (remove-hook 'pre-command-hook  #'transient--pre-command)
   2545     (remove-hook 'post-command-hook #'transient--post-command)
   2546     (advice-remove 'recursive-edit #'transient--recursive-edit))
   2547   (setq transient-current-prefix nil)
   2548   (setq transient-current-command nil)
   2549   (setq transient-current-suffixes nil)
   2550   (let ((resume (and transient--stack
   2551                      (not (memq transient--exitp '(replace suspend))))))
   2552     (unless (or resume (eq transient--exitp 'replace))
   2553       (setq transient--showp nil))
   2554     (setq transient--exitp nil)
   2555     (setq transient--helpp nil)
   2556     (setq transient--editp nil)
   2557     (setq transient--all-levels-p nil)
   2558     (setq transient--minibuffer-depth 0)
   2559     (run-hooks 'transient-exit-hook)
   2560     (when resume
   2561       (transient--stack-pop))))
   2562 
   2563 (defun transient--stack-push ()
   2564   (transient--debug 'stack-push)
   2565   (push (list (oref transient--prefix command)
   2566               transient--layout
   2567               transient--editp
   2568               :transient-suffix (oref transient--prefix transient-suffix)
   2569               :scope (oref transient--prefix scope))
   2570         transient--stack))
   2571 
   2572 (defun transient--stack-pop ()
   2573   (transient--debug 'stack-pop)
   2574   (and transient--stack
   2575        (prog1 t (apply #'transient-setup (pop transient--stack)))))
   2576 
   2577 (defun transient--stack-zap ()
   2578   (transient--debug 'stack-zap)
   2579   (setq transient--stack nil))
   2580 
   2581 (defun transient--redisplay ()
   2582   (if (or (eq transient-show-popup t)
   2583           transient--showp)
   2584       (unless
   2585           (or (memq this-command transient--scroll-commands)
   2586               (and (or (memq this-command '(mouse-drag-region
   2587                                             mouse-set-region))
   2588                        (equal (key-description (this-command-keys-vector))
   2589                               "<mouse-movement>"))
   2590                    (and (eq (current-buffer)
   2591                             (get-buffer transient--buffer-name)))))
   2592         (transient--show))
   2593     (when (and (numberp transient-show-popup)
   2594                (not (zerop transient-show-popup))
   2595                (not transient--timer))
   2596       (transient--timer-start))
   2597     (transient--show-brief)))
   2598 
   2599 (defun transient--timer-start ()
   2600   (setq transient--timer
   2601         (run-at-time (abs transient-show-popup) nil
   2602                      (lambda ()
   2603                        (transient--timer-cancel)
   2604                        (transient--show)
   2605                        (let ((message-log-max nil))
   2606                          (message ""))))))
   2607 
   2608 (defun transient--timer-cancel ()
   2609   (when transient--timer
   2610     (cancel-timer transient--timer)
   2611     (setq transient--timer nil)))
   2612 
   2613 (defun transient--debug (arg &rest args)
   2614   (when transient--debug
   2615     (let ((inhibit-message (not (eq transient--debug 'message))))
   2616       (if (symbolp arg)
   2617           (message "-- %-22s (cmd: %s, event: %S, exit: %s%s)"
   2618                    arg
   2619                    (cond ((and (symbolp this-command) this-command))
   2620                          ((fboundp 'help-fns-function-name)
   2621                           (help-fns-function-name this-command))
   2622                          ((byte-code-function-p this-command)
   2623                           "#[...]")
   2624                          (this-command))
   2625                    (key-description (this-command-keys-vector))
   2626                    transient--exitp
   2627                    (cond ((keywordp (car args))
   2628                           (format ", from: %s"
   2629                                   (substring (symbol-name (car args)) 1)))
   2630                          ((stringp (car args))
   2631                           (concat ", " (apply #'format args)))
   2632                          ((functionp (car args))
   2633                           (concat ", " (apply (car args) (cdr args))))
   2634                          ("")))
   2635         (apply #'message arg args)))))
   2636 
   2637 (defun transient--emergency-exit (&optional id)
   2638   "Exit the current transient command after an error occurred.
   2639 When no transient is active (i.e., when `transient--prefix' is
   2640 nil) then do nothing.  Optional ID is a keyword identifying the
   2641 exit."
   2642   (transient--debug 'emergency-exit id)
   2643   (when transient--prefix
   2644     (setq transient--stack nil)
   2645     (setq transient--exitp t)
   2646     (transient--pre-exit)
   2647     (transient--post-exit)))
   2648 
   2649 ;;; Pre-Commands
   2650 
   2651 (defun transient--call-pre-command ()
   2652   (if-let ((fn (transient--get-pre-command this-command)))
   2653       (let ((action (funcall fn)))
   2654         (when (eq action transient--exit)
   2655           (setq transient--exitp (or transient--exitp t)))
   2656         action)
   2657     (if (let ((keys (this-command-keys-vector)))
   2658           (eq (aref keys (1- (length keys))) ?\C-g))
   2659         (setq this-command 'transient-noop)
   2660       (unless (transient--edebug-command-p)
   2661         (setq this-command 'transient-undefined)))
   2662     transient--stay))
   2663 
   2664 (defun transient--get-pre-command (&optional cmd enforce-type)
   2665   (or (and (not (eq enforce-type 'non-suffix))
   2666            (symbolp cmd)
   2667            (lookup-key transient--predicate-map (vector cmd)))
   2668       (and (not (eq enforce-type 'suffix))
   2669            (transient--resolve-pre-command
   2670             (oref transient--prefix transient-non-suffix)
   2671             t))))
   2672 
   2673 (defun transient--resolve-pre-command (pre &optional resolve-boolean)
   2674   (cond ((booleanp pre)
   2675          (if resolve-boolean
   2676              (if pre #'transient--do-stay #'transient--do-warn)
   2677            pre))
   2678         ((string-match-p "--do-" (symbol-name pre)) pre)
   2679         ((let ((sym (intern (format "transient--do-%s" pre))))
   2680            (if (functionp sym) sym pre)))))
   2681 
   2682 (defun transient--do-stay ()
   2683   "Call the command without exporting variables and stay transient."
   2684   transient--stay)
   2685 
   2686 (defun transient--do-noop ()
   2687   "Call `transient-noop' and stay transient."
   2688   (setq this-command 'transient-noop)
   2689   transient--stay)
   2690 
   2691 (defun transient--do-warn ()
   2692   "Call `transient-undefined' and stay transient."
   2693   (setq this-command 'transient-undefined)
   2694   transient--stay)
   2695 
   2696 (defun transient--do-warn-inapt ()
   2697   "Call `transient-inapt' and stay transient."
   2698   (setq this-command 'transient-inapt)
   2699   transient--stay)
   2700 
   2701 (defun transient--do-call ()
   2702   "Call the command after exporting variables and stay transient."
   2703   (transient--export)
   2704   transient--stay)
   2705 
   2706 (defun transient--do-return ()
   2707   "Call the command after exporting variables and return to parent prefix.
   2708 If there is no parent prefix, then behave like `transient--do-exit'."
   2709   (if (not transient--stack)
   2710       (transient--do-exit)
   2711     (transient--export)
   2712     transient--exit))
   2713 
   2714 (defun transient--do-exit ()
   2715   "Call the command after exporting variables and exit the transient."
   2716   (transient--export)
   2717   (transient--stack-zap)
   2718   transient--exit)
   2719 
   2720 (defun transient--do-leave ()
   2721   "Call the command without exporting variables and exit the transient."
   2722   (transient--stack-zap)
   2723   transient--exit)
   2724 
   2725 (defun transient--do-push-button ()
   2726   "Call the command represented by the activated button.
   2727 Use that command's pre-command to determine transient behavior."
   2728   (if (and (mouse-event-p last-command-event)
   2729            (not (eq (posn-window (event-start last-command-event))
   2730                     transient--window)))
   2731       transient--stay
   2732     (setq this-command
   2733           (with-selected-window transient--window
   2734             (get-text-property (if (mouse-event-p last-command-event)
   2735                                    (posn-point (event-start last-command-event))
   2736                                  (point))
   2737                                'command)))
   2738     (transient--call-pre-command)))
   2739 
   2740 (defun transient--do-recurse ()
   2741   "Call the transient prefix command, preparing for return to active transient.
   2742 If there is no parent prefix, then just call the command."
   2743   (transient--do-stack))
   2744 
   2745 (defun transient--setup-recursion (prefix-obj)
   2746   (when transient--stack
   2747     (let ((command (oref prefix-obj command)))
   2748       (when-let ((suffix-obj (transient-suffix-object command)))
   2749         (when (memq (if (slot-boundp suffix-obj 'transient)
   2750                         (oref suffix-obj transient)
   2751                       (oref transient-current-prefix transient-suffix))
   2752                     (list t #'transient--do-recurse))
   2753           (oset prefix-obj transient-suffix t))))))
   2754 
   2755 (defun transient--do-stack ()
   2756   "Call the transient prefix command, stacking the active transient.
   2757 Push the active transient to the transient stack."
   2758   (transient--export)
   2759   (transient--stack-push)
   2760   (setq transient--exitp 'replace)
   2761   transient--exit)
   2762 
   2763 (defun transient--do-replace ()
   2764   "Call the transient prefix command, replacing the active transient.
   2765 Do not push the active transient to the transient stack."
   2766   (transient--export)
   2767   (setq transient--exitp 'replace)
   2768   transient--exit)
   2769 
   2770 (defun transient--do-suspend ()
   2771   "Suspend the active transient, saving the transient stack."
   2772   (transient--stack-push)
   2773   (setq transient--exitp 'suspend)
   2774   transient--exit)
   2775 
   2776 (defun transient--do-quit-one ()
   2777   "If active, quit help or edit mode, else exit the active transient."
   2778   (cond (transient--helpp
   2779          (setq transient--helpp nil)
   2780          transient--stay)
   2781         (transient--editp
   2782          (setq transient--editp nil)
   2783          (transient-setup)
   2784          transient--stay)
   2785         (prefix-arg
   2786          transient--stay)
   2787         (transient--exit)))
   2788 
   2789 (defun transient--do-quit-all ()
   2790   "Exit all transients without saving the transient stack."
   2791   (transient--stack-zap)
   2792   transient--exit)
   2793 
   2794 (defun transient--do-move ()
   2795   "Call the command if `transient-enable-popup-navigation' is non-nil.
   2796 In that case behave like `transient--do-stay', otherwise similar
   2797 to `transient--do-warn'."
   2798   (unless transient-enable-popup-navigation
   2799     (setq this-command 'transient-inhibit-move))
   2800   transient--stay)
   2801 
   2802 (defun transient--do-minus ()
   2803   "Call `negative-argument' or pivot to `transient-update'.
   2804 If `negative-argument' is invoked using \"-\" then preserve the
   2805 prefix argument and pivot to `transient-update'."
   2806   (when (equal (this-command-keys) "-")
   2807     (setq this-command 'transient-update))
   2808   transient--stay)
   2809 
   2810 (put 'transient--do-stay       'transient-face 'transient-key-stay)
   2811 (put 'transient--do-noop       'transient-face 'transient-key-noop)
   2812 (put 'transient--do-warn       'transient-face 'transient-key-noop)
   2813 (put 'transient--do-warn-inapt 'transient-face 'transient-key-noop)
   2814 (put 'transient--do-call       'transient-face 'transient-key-stay)
   2815 (put 'transient--do-return     'transient-face 'transient-key-return)
   2816 (put 'transient--do-exit       'transient-face 'transient-key-exit)
   2817 (put 'transient--do-leave      'transient-face 'transient-key-exit)
   2818 
   2819 (put 'transient--do-recurse    'transient-face 'transient-key-stay)
   2820 (put 'transient--do-stack      'transient-face 'transient-key-stay)
   2821 (put 'transient--do-replace    'transient-face 'transient-key-exit)
   2822 (put 'transient--do-suspend    'transient-face 'transient-key-exit)
   2823 
   2824 (put 'transient--do-quit-one   'transient-face 'transient-key-return)
   2825 (put 'transient--do-quit-all   'transient-face 'transient-key-exit)
   2826 (put 'transient--do-move       'transient-face 'transient-key-stay)
   2827 (put 'transient--do-minus      'transient-face 'transient-key-stay)
   2828 
   2829 ;;; Commands
   2830 ;;;; Noop
   2831 
   2832 (defun transient-noop ()
   2833   "Do nothing at all."
   2834   (interactive))
   2835 
   2836 (defun transient-undefined ()
   2837   "Warn the user that the pressed key is not bound to any suffix."
   2838   (interactive)
   2839   (transient--invalid "Unbound suffix"))
   2840 
   2841 (defun transient-inapt ()
   2842   "Warn the user that the invoked command is inapt."
   2843   (interactive)
   2844   (transient--invalid "Inapt command"))
   2845 
   2846 (defun transient--invalid (msg)
   2847   (ding)
   2848   (message "%s: `%s' (Use `%s' to abort, `%s' for help)%s"
   2849            msg
   2850            (propertize (key-description (this-single-command-keys))
   2851                        'face 'font-lock-warning-face)
   2852            (propertize "C-g" 'face 'transient-key)
   2853            (propertize "?"   'face 'transient-key)
   2854            ;; `this-command' is `transient-undefined' or `transient-inapt'.
   2855            ;; Show the command (`this-original-command') the user actually
   2856            ;; tried to invoke.
   2857            (if-let ((cmd (or (ignore-errors (symbol-name this-original-command))
   2858                              (ignore-errors (symbol-name this-command)))))
   2859                (format " [%s]" (propertize cmd 'face 'font-lock-warning-face))
   2860              ""))
   2861   (unless (and transient--transient-map
   2862                (memq transient--transient-map overriding-terminal-local-map))
   2863     (let ((transient--prefix (or transient--prefix 'sic)))
   2864       (transient--emergency-exit))
   2865     (view-lossage)
   2866     (other-window 1)
   2867     (display-warning 'transient "Inconsistent transient state detected.
   2868 This should never happen.
   2869 Please open an issue and post the shown command log." :error)))
   2870 
   2871 (defun transient-inhibit-move ()
   2872   "Warn the user that popup navigation is disabled."
   2873   (interactive)
   2874   (message "To enable use of `%s', please customize `%s'"
   2875            this-original-command
   2876            'transient-enable-popup-navigation))
   2877 
   2878 ;;;; Core
   2879 
   2880 (defun transient-quit-all ()
   2881   "Exit all transients without saving the transient stack."
   2882   (interactive))
   2883 
   2884 (defun transient-quit-one ()
   2885   "Exit the current transients, returning to outer transient, if any."
   2886   (interactive))
   2887 
   2888 (defun transient-quit-seq ()
   2889   "Abort the current incomplete key sequence."
   2890   (interactive))
   2891 
   2892 (defun transient-update ()
   2893   "Redraw the transient's state in the popup buffer."
   2894   (interactive)
   2895   (setq prefix-arg current-prefix-arg))
   2896 
   2897 (defun transient-show ()
   2898   "Show the transient's state in the popup buffer."
   2899   (interactive)
   2900   (setq transient--showp t))
   2901 
   2902 (defun transient-push-button ()
   2903   "Invoke the suffix command represented by this button."
   2904   (interactive))
   2905 
   2906 ;;;; Suspend
   2907 
   2908 (defun transient-suspend ()
   2909   "Suspend the current transient.
   2910 It can later be resumed using `transient-resume', while no other
   2911 transient is active."
   2912   (interactive))
   2913 
   2914 (define-minor-mode transient-resume-mode
   2915   "Auxiliary minor-mode used to resume a transient after viewing help.")
   2916 
   2917 (defun transient-resume ()
   2918   "Resume a previously suspended stack of transients."
   2919   (interactive)
   2920   (cond (transient--stack
   2921          (let ((winconf transient--restore-winconf))
   2922            (kill-local-variable 'transient--restore-winconf)
   2923            (when transient-resume-mode
   2924              (transient-resume-mode -1)
   2925              (quit-window))
   2926            (when winconf
   2927              (set-window-configuration winconf)))
   2928          (transient--stack-pop))
   2929         (transient-resume-mode
   2930          (kill-local-variable 'transient--restore-winconf)
   2931          (transient-resume-mode -1)
   2932          (quit-window))
   2933         (t
   2934          (message "No suspended transient command"))))
   2935 
   2936 ;;;; Help
   2937 
   2938 (defun transient-help (&optional interactive)
   2939   "Show help for the active transient or one of its suffixes.\n\n(fn)"
   2940   (interactive (list t))
   2941   (if interactive
   2942       (setq transient--helpp t)
   2943     (with-demoted-errors "transient-help: %S"
   2944       (when (lookup-key transient--transient-map
   2945                         (this-single-command-raw-keys))
   2946         (setq transient--helpp nil)
   2947         (let ((winconf (current-window-configuration)))
   2948           (transient-show-help
   2949            (if (eq this-original-command 'transient-help)
   2950                transient--prefix
   2951              (or (transient-suffix-object)
   2952                  this-original-command)))
   2953           (setq-local transient--restore-winconf winconf))
   2954         (fit-window-to-buffer nil (frame-height) (window-height))
   2955         (transient-resume-mode)
   2956         (message (substitute-command-keys
   2957                   "Type \\`q' to resume transient command."))
   2958         t))))
   2959 
   2960 ;;;; Level
   2961 
   2962 (defun transient-set-level (&optional command level)
   2963   "Set the level of the transient or one of its suffix commands."
   2964   (interactive
   2965    (let ((command this-original-command)
   2966          (prefix (oref transient--prefix command)))
   2967      (and (or (not (eq command 'transient-set-level))
   2968               (and transient--editp
   2969                    (setq command prefix)))
   2970           (list command
   2971                 (let ((keys (this-single-command-raw-keys)))
   2972                   (and (lookup-key transient--transient-map keys)
   2973                        (progn
   2974                          (transient--show)
   2975                          (string-to-number
   2976                           (transient--read-number-N
   2977                            (format "Set level for `%s': " command)
   2978                            nil nil (not (eq command prefix)))))))))))
   2979   (cond
   2980    ((not command)
   2981     (setq transient--editp t)
   2982     (transient-setup))
   2983    (level
   2984     (let* ((prefix (oref transient--prefix command))
   2985            (alist (alist-get prefix transient-levels))
   2986            (akey command))
   2987       (cond ((eq command prefix)
   2988              (oset transient--prefix level level)
   2989              (setq akey t))
   2990             (t
   2991              (oset (transient-suffix-object command) level level)
   2992              (when (cdr (cl-remove-if-not (lambda (obj)
   2993                                             (eq (oref obj command) command))
   2994                                           transient--suffixes))
   2995                (setq akey (cons command (this-command-keys))))))
   2996       (setf (alist-get akey alist) level)
   2997       (setf (alist-get prefix transient-levels) alist))
   2998     (transient-save-levels)
   2999     (transient--show))
   3000    (t
   3001     (transient-undefined))))
   3002 
   3003 (transient-define-suffix transient-toggle-level-limit ()
   3004   "Toggle whether to temporarily displayed suffixes on all levels."
   3005   :description
   3006   (lambda ()
   3007     (cond
   3008      ((= transient-default-level transient--max-level)
   3009       "Always displaying all levels")
   3010      (transient--all-levels-p
   3011       (format "Hide suffix %s"
   3012               (propertize
   3013                (format "levels > %s" (oref (transient-prefix-object) level))
   3014                'face 'transient-higher-level)))
   3015      ("Show all suffix levels")))
   3016   :inapt-if (lambda () (= transient-default-level transient--max-level))
   3017   :transient t
   3018   (interactive)
   3019   (setq transient--all-levels-p (not transient--all-levels-p))
   3020   (setq transient--refreshp t))
   3021 
   3022 ;;;; Value
   3023 
   3024 (defun transient-set ()
   3025   "Set active transient's value for this Emacs session."
   3026   (interactive)
   3027   (transient-set-value (transient-prefix-object)))
   3028 
   3029 (defalias 'transient-set-and-exit #'transient-set
   3030   "Set active transient's value for this Emacs session and exit.")
   3031 
   3032 (defun transient-save ()
   3033   "Save active transient's value for this and future Emacs sessions."
   3034   (interactive)
   3035   (transient-save-value (transient-prefix-object)))
   3036 
   3037 (defalias 'transient-save-and-exit #'transient-save
   3038   "Save active transient's value for this and future Emacs sessions and exit.")
   3039 
   3040 (defun transient-reset ()
   3041   "Clear the set and saved values of the active transient."
   3042   (interactive)
   3043   (transient-reset-value (transient-prefix-object)))
   3044 
   3045 (defun transient-history-next ()
   3046   "Switch to the next value used for the active transient."
   3047   (interactive)
   3048   (let* ((obj transient--prefix)
   3049          (pos (1- (oref obj history-pos)))
   3050          (hst (oref obj history)))
   3051     (if (< pos 0)
   3052         (user-error "End of history")
   3053       (oset obj history-pos pos)
   3054       (oset obj value (nth pos hst))
   3055       (mapc #'transient-init-value transient--suffixes))))
   3056 
   3057 (defun transient-history-prev ()
   3058   "Switch to the previous value used for the active transient."
   3059   (interactive)
   3060   (let* ((obj transient--prefix)
   3061          (pos (1+ (oref obj history-pos)))
   3062          (hst (oref obj history))
   3063          (len (length hst)))
   3064     (if (> pos (1- len))
   3065         (user-error "End of history")
   3066       (oset obj history-pos pos)
   3067       (oset obj value (nth pos hst))
   3068       (mapc #'transient-init-value transient--suffixes))))
   3069 
   3070 ;;;; Auxiliary
   3071 
   3072 (defun transient-toggle-common ()
   3073   "Toggle whether common commands are permanently shown."
   3074   (interactive)
   3075   (setq transient-show-common-commands (not transient-show-common-commands)))
   3076 
   3077 (defun transient-toggle-debug ()
   3078   "Toggle debugging statements for transient commands."
   3079   (interactive)
   3080   (setq transient--debug (not transient--debug))
   3081   (message "Debugging transient %s"
   3082            (if transient--debug "enabled" "disabled")))
   3083 
   3084 (transient-define-suffix transient-echo-arguments (arguments)
   3085   "Show the transient's active ARGUMENTS in the echo area.
   3086 Intended for use in prefixes used for demonstration purposes,
   3087 such as when suggesting a new feature or reporting an issue."
   3088   :transient t
   3089   :description "Echo arguments"
   3090   :key "x"
   3091   (interactive (list (transient-args transient-current-command)))
   3092   (message "%s: %s"
   3093            (key-description (this-command-keys))
   3094            (mapconcat (lambda (arg)
   3095                         (propertize (if (string-match-p " " arg)
   3096                                         (format "%S" arg)
   3097                                       arg)
   3098                                     'face 'transient-argument))
   3099                       arguments " ")))
   3100 
   3101 ;;; Value
   3102 ;;;; Init
   3103 
   3104 (cl-defgeneric transient-init-scope (obj)
   3105   "Set the scope of the suffix object OBJ.
   3106 
   3107 The scope is actually a property of the transient prefix, not of
   3108 individual suffixes.  However it is possible to invoke a suffix
   3109 command directly instead of from a transient.  In that case, if
   3110 the suffix expects a scope, then it has to determine that itself
   3111 and store it in its `scope' slot.
   3112 
   3113 This function is called for all suffix commands, but unless a
   3114 concrete method is implemented this falls through to the default
   3115 implementation, which is a noop.")
   3116 
   3117 (cl-defmethod transient-init-scope ((_   transient-suffix))
   3118   "Noop." nil)
   3119 
   3120 (cl-defgeneric transient-init-value (_)
   3121   "Set the initial value of the object OBJ.
   3122 
   3123 This function is called for all prefix and suffix commands.
   3124 
   3125 For suffix commands (including infix argument commands) the
   3126 default implementation is a noop.  Classes derived from the
   3127 abstract `transient-infix' class must implement this function.
   3128 Non-infix suffix commands usually don't have a value."
   3129   nil)
   3130 
   3131 (cl-defmethod transient-init-value :around ((obj transient-prefix))
   3132   "If bound, then call OBJ's `init-value' function.
   3133 Otherwise call the primary method according to object's class."
   3134   (if (slot-boundp obj 'init-value)
   3135       (funcall (oref obj init-value) obj)
   3136     (cl-call-next-method obj)))
   3137 
   3138 (cl-defmethod transient-init-value :around ((obj transient-infix))
   3139   "If bound, then call OBJ's `init-value' function.
   3140 Otherwise call the primary method according to object's class."
   3141   (if (slot-boundp obj 'init-value)
   3142       (funcall (oref obj init-value) obj)
   3143     (cl-call-next-method obj)))
   3144 
   3145 (cl-defmethod transient-init-value ((obj transient-prefix))
   3146   (if (slot-boundp obj 'value)
   3147       (oref obj value)
   3148     (oset obj value
   3149           (if-let ((saved (assq (oref obj command) transient-values)))
   3150               (cdr saved)
   3151             (transient-default-value obj)))))
   3152 
   3153 (cl-defmethod transient-init-value ((obj transient-argument))
   3154   (oset obj value
   3155         (let ((value (oref transient--prefix value))
   3156               (argument (and (slot-boundp obj 'argument)
   3157                              (oref obj argument)))
   3158               (multi-value (oref obj multi-value))
   3159               (case-fold-search nil)
   3160               (regexp (if (slot-exists-p obj 'argument-regexp)
   3161                           (oref obj argument-regexp)
   3162                         (format "\\`%s\\(.*\\)" (oref obj argument)))))
   3163           (if (memq multi-value '(t rest))
   3164               (cdr (assoc argument value))
   3165             (let ((match (lambda (v)
   3166                            (and (stringp v)
   3167                                 (string-match regexp v)
   3168                                 (match-string 1 v)))))
   3169               (if multi-value
   3170                   (delq nil (mapcar match value))
   3171                 (cl-some match value)))))))
   3172 
   3173 (cl-defmethod transient-init-value ((obj transient-switch))
   3174   (oset obj value
   3175         (car (member (oref obj argument)
   3176                      (oref transient--prefix value)))))
   3177 
   3178 ;;;; Default
   3179 
   3180 (cl-defgeneric transient-default-value (_)
   3181   "Return the default value."
   3182   nil)
   3183 
   3184 (cl-defmethod transient-default-value ((obj transient-prefix))
   3185   (if-let ((default (and (slot-boundp obj 'default-value)
   3186                          (oref obj default-value))))
   3187       (if (functionp default)
   3188           (funcall default)
   3189         default)
   3190     nil))
   3191 
   3192 ;;;; Read
   3193 
   3194 (cl-defgeneric transient-infix-read (obj)
   3195   "Determine the new value of the infix object OBJ.
   3196 
   3197 This function merely determines the value; `transient-infix-set'
   3198 is used to actually store the new value in the object.
   3199 
   3200 For most infix classes this is done by reading a value from the
   3201 user using the reader specified by the `reader' slot (using the
   3202 `transient-infix' method described below).
   3203 
   3204 For some infix classes the value is changed without reading
   3205 anything in the minibuffer, i.e., the mere act of invoking the
   3206 infix command determines what the new value should be, based
   3207 on the previous value.")
   3208 
   3209 (cl-defmethod transient-infix-read :around ((obj transient-infix))
   3210   "Refresh the transient buffer and call the next method.
   3211 
   3212 Also wrap `cl-call-next-method' with two macros:
   3213 - `transient--with-suspended-override' allows use of minibuffer.
   3214 - `transient--with-emergency-exit' arranges for the transient to
   3215   be exited in case of an error."
   3216   (transient--show)
   3217   (transient--with-emergency-exit :infix-read
   3218     (transient--with-suspended-override
   3219      (cl-call-next-method obj))))
   3220 
   3221 (cl-defmethod transient-infix-read ((obj transient-infix))
   3222   "Read a value while taking care of history.
   3223 
   3224 This method is suitable for a wide variety of infix commands,
   3225 including but not limited to inline arguments and variables.
   3226 
   3227 If you do not use this method for your own infix class, then
   3228 you should likely replicate a lot of the behavior of this
   3229 method.  If you fail to do so, then users might not appreciate
   3230 the lack of history, for example.
   3231 
   3232 Only for very simple classes that toggle or cycle through a very
   3233 limited number of possible values should you replace this with a
   3234 simple method that does not handle history.  (E.g., for a command
   3235 line switch the only possible values are \"use it\" and \"don't use
   3236 it\", in which case it is pointless to preserve history.)"
   3237   (with-slots (value multi-value always-read allow-empty choices) obj
   3238     (if (and value
   3239              (not multi-value)
   3240              (not always-read)
   3241              transient--prefix)
   3242         (oset obj value nil)
   3243       (let* ((enable-recursive-minibuffers t)
   3244              (reader (oref obj reader))
   3245              (choices (if (functionp choices) (funcall choices) choices))
   3246              (prompt (transient-prompt obj))
   3247              (value (if multi-value (mapconcat #'identity value ",") value))
   3248              (history-key (or (oref obj history-key)
   3249                               (oref obj command)))
   3250              (transient--history (alist-get history-key transient-history))
   3251              (transient--history (if (or (null value)
   3252                                          (eq value (car transient--history)))
   3253                                      transient--history
   3254                                    (cons value transient--history)))
   3255              (initial-input (and transient-read-with-initial-input
   3256                                  (car transient--history)))
   3257              (history (if initial-input
   3258                           (cons 'transient--history 1)
   3259                         'transient--history))
   3260              (value
   3261               (cond
   3262                (reader (funcall reader prompt initial-input history))
   3263                (multi-value
   3264                 (completing-read-multiple prompt choices nil nil
   3265                                           initial-input history))
   3266                (choices
   3267                 (completing-read prompt choices nil t initial-input history))
   3268                ((read-string prompt initial-input history)))))
   3269         (cond ((and (equal value "") (not allow-empty))
   3270                (setq value nil))
   3271               ((and (equal value "\"\"") allow-empty)
   3272                (setq value "")))
   3273         (when value
   3274           (when (and (bound-and-true-p ivy-mode)
   3275                      (stringp (car transient--history)))
   3276             (set-text-properties 0 (length (car transient--history)) nil
   3277                                  (car transient--history)))
   3278           (setf (alist-get history-key transient-history)
   3279                 (delete-dups transient--history)))
   3280         value))))
   3281 
   3282 (cl-defmethod transient-infix-read ((obj transient-switch))
   3283   "Toggle the switch on or off."
   3284   (if (oref obj value) nil (oref obj argument)))
   3285 
   3286 (cl-defmethod transient-infix-read ((obj transient-switches))
   3287   "Cycle through the mutually exclusive switches.
   3288 The last value is \"don't use any of these switches\"."
   3289   (let ((choices (mapcar (apply-partially #'format (oref obj argument-format))
   3290                          (oref obj choices))))
   3291     (if-let ((value (oref obj value)))
   3292         (cadr (member value choices))
   3293       (car choices))))
   3294 
   3295 (cl-defmethod transient-infix-read ((command symbol))
   3296   "Elsewhere use the reader of the infix command COMMAND.
   3297 Use this if you want to share an infix's history with a regular
   3298 stand-alone command."
   3299   (if-let ((obj (transient--suffix-prototype command)))
   3300       (cl-letf (((symbol-function #'transient--show) #'ignore))
   3301         (transient-infix-read obj))
   3302     (error "Not a suffix command: `%s'" command)))
   3303 
   3304 ;;;; Readers
   3305 
   3306 (defun transient-read-file (prompt _initial-input _history)
   3307   "Read a file."
   3308   (file-local-name (expand-file-name (read-file-name prompt))))
   3309 
   3310 (defun transient-read-existing-file (prompt _initial-input _history)
   3311   "Read an existing file."
   3312   (file-local-name (expand-file-name (read-file-name prompt nil nil t))))
   3313 
   3314 (defun transient-read-directory (prompt _initial-input _history)
   3315   "Read a directory."
   3316   (file-local-name (expand-file-name (read-directory-name prompt))))
   3317 
   3318 (defun transient-read-existing-directory (prompt _initial-input _history)
   3319   "Read an existing directory."
   3320   (file-local-name (expand-file-name (read-directory-name prompt nil nil t))))
   3321 
   3322 (defun transient-read-number-N0 (prompt initial-input history)
   3323   "Read a natural number (including zero) and return it as a string."
   3324   (transient--read-number-N prompt initial-input history t))
   3325 
   3326 (defun transient-read-number-N+ (prompt initial-input history)
   3327   "Read a natural number (excluding zero) and return it as a string."
   3328   (transient--read-number-N prompt initial-input history nil))
   3329 
   3330 (defun transient--read-number-N (prompt initial-input history include-zero)
   3331   (save-match-data
   3332     (cl-block nil
   3333       (while t
   3334         (let ((str (read-from-minibuffer prompt initial-input nil nil history)))
   3335           (when (or (string-equal str "")
   3336                     (string-match-p (if include-zero
   3337                                         "\\`\\(0\\|[1-9][0-9]*\\)\\'"
   3338                                       "\\`[1-9][0-9]*\\'")
   3339                                     str))
   3340             (cl-return str)))
   3341         (message "Please enter a natural number (%s zero)."
   3342                  (if include-zero "including" "excluding"))
   3343         (sit-for 1)))))
   3344 
   3345 (defun transient-read-date (prompt default-time _history)
   3346   "Read a date using `org-read-date' (which see)."
   3347   (require 'org)
   3348   (when (fboundp 'org-read-date)
   3349     (org-read-date 'with-time nil nil prompt default-time)))
   3350 
   3351 ;;;; Prompt
   3352 
   3353 (cl-defgeneric transient-prompt (obj)
   3354   "Return the prompt to be used to read infix object OBJ's value.")
   3355 
   3356 (cl-defmethod transient-prompt ((obj transient-infix))
   3357   "Return the prompt to be used to read infix object OBJ's value.
   3358 
   3359 This implementation should be suitable for almost all infix
   3360 commands.
   3361 
   3362 If the value of OBJ's `prompt' slot is non-nil, then it must be
   3363 a string or a function.  If it is a string, then use that.  If
   3364 it is a function, then call that with OBJ as the only argument.
   3365 That function must return a string, which is then used as the
   3366 prompt.
   3367 
   3368 Otherwise, if the value of either the `argument' or `variable'
   3369 slot of OBJ is a string, then base the prompt on that (preferring
   3370 the former), appending either \"=\" (if it appears to be a
   3371 command-line option) or \": \".
   3372 
   3373 Finally fall through to using \"(BUG: no prompt): \" as the
   3374 prompt."
   3375   (if-let ((prompt (oref obj prompt)))
   3376       (let ((prompt (if (functionp prompt)
   3377                         (funcall prompt obj)
   3378                       prompt)))
   3379         (if (stringp prompt)
   3380             prompt
   3381           "(BUG: no prompt): "))
   3382     (or (and-let* ((arg (and (slot-boundp obj 'argument) (oref obj argument))))
   3383           (if (and (stringp arg) (string-suffix-p "=" arg))
   3384               arg
   3385             (concat arg ": ")))
   3386         (and-let* ((var (and (slot-boundp obj 'variable) (oref obj variable))))
   3387           (and (stringp var)
   3388                (concat var ": ")))
   3389         "(BUG: no prompt): ")))
   3390 
   3391 ;;;; Set
   3392 
   3393 (cl-defgeneric transient-infix-set (obj value)
   3394   "Set the value of infix object OBJ to value.")
   3395 
   3396 (cl-defmethod transient-infix-set ((obj transient-infix) value)
   3397   "Set the value of infix object OBJ to value."
   3398   (oset obj value value))
   3399 
   3400 (cl-defmethod transient-infix-set :after ((obj transient-argument) value)
   3401   "Unset incompatible infix arguments."
   3402   (when-let* ((value)
   3403               (val (transient-infix-value obj))
   3404               (arg (if (slot-boundp obj 'argument)
   3405                        (oref obj argument)
   3406                      (oref obj argument-format)))
   3407               (spec (oref transient--prefix incompatible))
   3408               (filter (lambda (x rule)
   3409                         (and (member x rule)
   3410                              (remove x rule))))
   3411               (incomp (nconc
   3412                        (cl-mapcan (apply-partially filter arg) spec)
   3413                        (and (not (equal val arg))
   3414                             (cl-mapcan (apply-partially filter val) spec)))))
   3415     (dolist (obj transient--suffixes)
   3416       (when-let* (((cl-typep obj 'transient-argument))
   3417                   (val (transient-infix-value obj))
   3418                   (arg (if (slot-boundp obj 'argument)
   3419                            (oref obj argument)
   3420                          (oref obj argument-format)))
   3421                   ((if (equal val arg)
   3422                        (member arg incomp)
   3423                      (or (member val incomp)
   3424                          (member arg incomp)))))
   3425         (transient-infix-set obj nil)))))
   3426 
   3427 (cl-defgeneric transient-set-value (obj)
   3428   "Set the value of the transient prefix OBJ.")
   3429 
   3430 (cl-defmethod transient-set-value ((obj transient-prefix))
   3431   (oset (oref obj prototype) value (transient-get-value))
   3432   (transient--history-push obj))
   3433 
   3434 ;;;; Save
   3435 
   3436 (cl-defgeneric transient-save-value (obj)
   3437   "Save the value of the transient prefix OBJ.")
   3438 
   3439 (cl-defmethod transient-save-value ((obj transient-prefix))
   3440   (let ((value (transient-get-value)))
   3441     (oset (oref obj prototype) value value)
   3442     (setf (alist-get (oref obj command) transient-values) value)
   3443     (transient-save-values))
   3444   (transient--history-push obj))
   3445 
   3446 ;;;; Reset
   3447 
   3448 (cl-defgeneric transient-reset-value (obj)
   3449   "Clear the set and saved values of the transient prefix OBJ.")
   3450 
   3451 (cl-defmethod transient-reset-value ((obj transient-prefix))
   3452   (let ((value (transient-default-value obj)))
   3453     (oset obj value value)
   3454     (oset (oref obj prototype) value value)
   3455     (setf (alist-get (oref obj command) transient-values nil 'remove) nil)
   3456     (transient-save-values))
   3457   (transient--history-push obj)
   3458   (mapc #'transient-init-value transient--suffixes))
   3459 
   3460 ;;;; Get
   3461 
   3462 (defun transient-args (prefix)
   3463   "Return the value of the transient prefix command PREFIX.
   3464 If the current command was invoked from the transient prefix
   3465 command PREFIX, then return the active infix arguments.  If
   3466 the current command was not invoked from PREFIX, then return
   3467 the set, saved or default value for PREFIX."
   3468   (cl-mapcan #'transient--get-wrapped-value (transient-suffixes prefix)))
   3469 
   3470 (defun transient-suffixes (prefix)
   3471   "Return the suffix objects of the transient prefix command PREFIX."
   3472   (if (eq transient-current-command prefix)
   3473       transient-current-suffixes
   3474     (let ((transient--prefix (transient--init-prefix prefix)))
   3475       (transient--flatten-suffixes
   3476        (transient--init-suffixes prefix)))))
   3477 
   3478 (defun transient-get-value ()
   3479   (transient--with-emergency-exit :get-value
   3480     (cl-mapcan (lambda (obj)
   3481                  (and (or (not (slot-exists-p obj 'unsavable))
   3482                           (not (oref obj unsavable)))
   3483                       (transient--get-wrapped-value obj)))
   3484                transient-current-suffixes)))
   3485 
   3486 (defun transient--get-wrapped-value (obj)
   3487   (and-let* ((value (transient-infix-value obj)))
   3488     (pcase-exhaustive (and (slot-exists-p obj 'multi-value)
   3489                            (oref obj multi-value))
   3490       ('nil          (list value))
   3491       ((or 't 'rest) (list value))
   3492       ('repeat       value))))
   3493 
   3494 (cl-defgeneric transient-infix-value (obj)
   3495   "Return the value of the suffix object OBJ.
   3496 
   3497 This function is called by `transient-args' (which see), meaning
   3498 this function is how the value of a transient is determined so
   3499 that the invoked suffix command can use it.
   3500 
   3501 Currently most values are strings, but that is not set in stone.
   3502 Nil is not a value, it means \"no value\".
   3503 
   3504 Usually only infixes have a value, but see the method for
   3505 `transient-suffix'.")
   3506 
   3507 (cl-defmethod transient-infix-value ((_   transient-suffix))
   3508   "Return nil, which means \"no value\".
   3509 
   3510 Infix arguments contribute the transient's value while suffix
   3511 commands consume it.  This function is called for suffixes anyway
   3512 because a command that both contributes to the transient's value
   3513 and also consumes it is not completely unconceivable.
   3514 
   3515 If you define such a command, then you must define a derived
   3516 class and implement this function because this default method
   3517 does nothing." nil)
   3518 
   3519 (cl-defmethod transient-infix-value ((obj transient-infix))
   3520   "Return the value of OBJ's `value' slot."
   3521   (oref obj value))
   3522 
   3523 (cl-defmethod transient-infix-value ((obj transient-option))
   3524   "Return ARGUMENT and VALUE as a unit or nil if the latter is nil."
   3525   (and-let* ((value (oref obj value)))
   3526     (let ((arg (oref obj argument)))
   3527       (pcase-exhaustive (oref obj multi-value)
   3528         ('nil          (concat arg value))
   3529         ((or 't 'rest) (cons arg value))
   3530         ('repeat       (mapcar (lambda (v) (concat arg v)) value))))))
   3531 
   3532 (cl-defmethod transient-infix-value ((_   transient-variable))
   3533   "Return nil, which means \"no value\".
   3534 
   3535 Setting the value of a variable is done by, well, setting the
   3536 value of the variable.  I.e., this is a side-effect and does
   3537 not contribute to the value of the transient."
   3538   nil)
   3539 
   3540 ;;;; Utilities
   3541 
   3542 (defun transient-arg-value (arg args)
   3543   "Return the value of ARG as it appears in ARGS.
   3544 
   3545 For a switch return a boolean.  For an option return the value as
   3546 a string, using the empty string for the empty value, or nil if
   3547 the option does not appear in ARGS."
   3548   (if (string-suffix-p "=" arg)
   3549       (save-match-data
   3550         (and-let* ((match (let ((case-fold-search nil)
   3551                                 (re (format "\\`%s\\(?:=\\(.+\\)\\)?\\'"
   3552                                             (substring arg 0 -1))))
   3553                             (cl-find-if (lambda (a)
   3554                                           (and (stringp a)
   3555                                                (string-match re a)))
   3556                                         args))))
   3557           (or (match-string 1 match) "")))
   3558     (and (member arg args) t)))
   3559 
   3560 (defun transient-scope ()
   3561   "Return the value of the `scope' slot of the current prefix."
   3562   (oref (transient-prefix-object) scope))
   3563 
   3564 ;;; History
   3565 
   3566 (cl-defgeneric transient--history-key (obj)
   3567   "Return OBJ's history key.
   3568 If the value of the `history-key' slot is non-nil, then return
   3569 that.  Otherwise return the value of the `command' slot."
   3570   (or (oref obj history-key)
   3571       (oref obj command)))
   3572 
   3573 (cl-defgeneric transient--history-push (obj)
   3574   "Push the current value of OBJ to its entry in `transient-history'."
   3575   (let ((key (transient--history-key obj)))
   3576     (setf (alist-get key transient-history)
   3577           (let ((args (transient-get-value)))
   3578             (cons args (delete args (alist-get key transient-history)))))))
   3579 
   3580 (cl-defgeneric transient--history-init (obj)
   3581   "Initialize OBJ's `history' slot.
   3582 This is the transient-wide history; many individual infixes also
   3583 have a history of their own.")
   3584 
   3585 (cl-defmethod transient--history-init ((obj transient-prefix))
   3586   "Initialize OBJ's `history' slot from the variable `transient-history'."
   3587   (let ((val (oref obj value)))
   3588     (oset obj history
   3589           (cons val (delete val (alist-get (transient--history-key obj)
   3590                                            transient-history))))))
   3591 
   3592 ;;; Draw
   3593 
   3594 (defun transient--show-brief ()
   3595   (let ((message-log-max nil))
   3596     (if (and transient-show-popup (<= transient-show-popup 0))
   3597         (message "%s-" (key-description (this-command-keys)))
   3598       (message
   3599        "%s- [%s] %s"
   3600        (key-description (this-command-keys))
   3601        (oref transient--prefix command)
   3602        (mapconcat
   3603         #'identity
   3604         (sort
   3605          (cl-mapcan
   3606           (lambda (suffix)
   3607             (let ((key (kbd (oref suffix key))))
   3608               ;; Don't list any common commands.
   3609               (and (not (memq (oref suffix command)
   3610                               `(,(lookup-key transient-map key)
   3611                                 ,(lookup-key transient-sticky-map key)
   3612                                 ;; From transient-common-commands:
   3613                                 transient-set
   3614                                 transient-save
   3615                                 transient-history-prev
   3616                                 transient-history-next
   3617                                 transient-quit-one
   3618                                 transient-toggle-common
   3619                                 transient-set-level)))
   3620                    (list (propertize (oref suffix key) 'face 'transient-key)))))
   3621           transient--suffixes)
   3622          #'string<)
   3623         (propertize "|" 'face 'transient-delimiter))))))
   3624 
   3625 (defun transient--show ()
   3626   (transient--timer-cancel)
   3627   (setq transient--showp t)
   3628   (let ((transient--shadowed-buffer (current-buffer))
   3629         (buf (get-buffer-create transient--buffer-name))
   3630         (focus nil))
   3631     (with-current-buffer buf
   3632       (when transient-enable-popup-navigation
   3633         (setq focus (or (button-get (point) 'command)
   3634                         (and (not (bobp))
   3635                              (button-get (1- (point)) 'command))
   3636                         (transient--heading-at-point))))
   3637       (erase-buffer)
   3638       (run-hooks 'transient-setup-buffer-hook)
   3639       (when transient-force-fixed-pitch
   3640         (transient--force-fixed-pitch))
   3641       (setq window-size-fixed t)
   3642       (when (bound-and-true-p tab-line-format)
   3643         (setq tab-line-format nil))
   3644       (setq header-line-format nil)
   3645       (setq mode-line-format
   3646             (if (or (natnump transient-mode-line-format)
   3647                     (eq transient-mode-line-format 'line))
   3648                 nil
   3649               transient-mode-line-format))
   3650       (setq mode-line-buffer-identification
   3651             (symbol-name (oref transient--prefix command)))
   3652       (if transient-enable-popup-navigation
   3653           (setq-local cursor-in-non-selected-windows 'box)
   3654         (setq cursor-type nil))
   3655       (setq display-line-numbers nil)
   3656       (setq show-trailing-whitespace nil)
   3657       (transient--insert-groups)
   3658       (when (or transient--helpp transient--editp)
   3659         (transient--insert-help))
   3660       (when-let ((line (transient--separator-line)))
   3661         (insert line)))
   3662     (unless (window-live-p transient--window)
   3663       (setq transient--window
   3664             (display-buffer buf transient-display-buffer-action)))
   3665     (when (window-live-p transient--window)
   3666       (with-selected-window transient--window
   3667         (goto-char (point-min))
   3668         (when transient-enable-popup-navigation
   3669           (transient--goto-button focus))
   3670         (transient--fit-window-to-buffer transient--window)))))
   3671 
   3672 (defun transient--fit-window-to-buffer (window)
   3673   (let ((window-resize-pixelwise t)
   3674         (window-size-fixed nil))
   3675     (if (eq (car (window-parameter window 'quit-restore)) 'other)
   3676         ;; Grow but never shrink window that previously displayed
   3677         ;; another buffer and is going to display that again.
   3678         (fit-window-to-buffer window nil (window-height window))
   3679       (fit-window-to-buffer window nil 1))))
   3680 
   3681 (defun transient--separator-line ()
   3682   (and-let* ((height (cond ((not window-system) nil)
   3683                            ((natnump transient-mode-line-format)
   3684                             transient-mode-line-format)
   3685                            ((eq transient-mode-line-format 'line) 1)))
   3686              (face `(,@(and (>= emacs-major-version 27) '(:extend t))
   3687                      :background
   3688                      ,(or (face-foreground (transient--key-face nil 'non-suffix)
   3689                                            nil t)
   3690                           "#gray60"))))
   3691     (concat (propertize "__" 'face face 'display `(space :height (,height)))
   3692             (propertize "\n" 'face face 'line-height t))))
   3693 
   3694 (defmacro transient-with-shadowed-buffer (&rest body)
   3695   "While in the transient buffer, temporarly make the shadowed buffer current."
   3696   (declare (indent 0) (debug t))
   3697   `(with-current-buffer (or transient--shadowed-buffer (current-buffer))
   3698      ,@body))
   3699 
   3700 (defun transient--insert-groups ()
   3701   (let ((groups (cl-mapcan (lambda (group)
   3702                              (let ((hide (oref group hide)))
   3703                                (and (not (and (functionp hide)
   3704                                               (transient-with-shadowed-buffer
   3705                                                 (funcall hide))))
   3706                                     (list group))))
   3707                            transient--layout)))
   3708     (while-let ((group (pop groups)))
   3709       (transient--insert-group group)
   3710       (when groups
   3711         (insert ?\n)))))
   3712 
   3713 (defvar transient--max-group-level 1)
   3714 
   3715 (cl-defgeneric transient--insert-group (group)
   3716   "Format GROUP and its elements and insert the result.")
   3717 
   3718 (cl-defmethod transient--insert-group :around ((group transient-group))
   3719   "Insert GROUP's description, if any."
   3720   (when-let ((desc (transient-with-shadowed-buffer
   3721                      (transient-format-description group))))
   3722     (insert desc ?\n))
   3723   (let ((transient--max-group-level
   3724          (max (oref group level) transient--max-group-level))
   3725         (transient--pending-group group))
   3726     (cl-call-next-method group)))
   3727 
   3728 (cl-defmethod transient--insert-group ((group transient-row))
   3729   (transient--maybe-pad-keys group)
   3730   (dolist (suffix (oref group suffixes))
   3731     (insert (transient-with-shadowed-buffer (transient-format suffix)))
   3732     (insert "   "))
   3733   (insert ?\n))
   3734 
   3735 (cl-defmethod transient--insert-group ((group transient-column))
   3736   (transient--maybe-pad-keys group)
   3737   (dolist (suffix (oref group suffixes))
   3738     (let ((str (transient-with-shadowed-buffer (transient-format suffix))))
   3739       (insert str)
   3740       (unless (string-match-p ".\n\\'" str)
   3741         (insert ?\n)))))
   3742 
   3743 (cl-defmethod transient--insert-group ((group transient-columns))
   3744   (let* ((columns
   3745           (mapcar
   3746            (lambda (column)
   3747              (transient--maybe-pad-keys column group)
   3748              (transient-with-shadowed-buffer
   3749                (let* ((transient--pending-group column)
   3750                       (rows (mapcar #'transient-format (oref column suffixes))))
   3751                  (when-let ((desc (transient-format-description column)))
   3752                    (push desc rows))
   3753                  (flatten-tree rows))))
   3754            (oref group suffixes)))
   3755          (vp (or (oref transient--prefix variable-pitch)
   3756                  transient-align-variable-pitch))
   3757          (rs (apply #'max (mapcar #'length columns)))
   3758          (cs (length columns))
   3759          (cw (mapcar (let ((widths (oref transient--prefix column-widths)))
   3760                        (lambda (col)
   3761                          (apply
   3762                           #'max
   3763                           (if-let ((min (pop widths)))
   3764                               (if vp (* min (transient--pixel-width " ")) min)
   3765                             0)
   3766                           (mapcar (if vp #'transient--pixel-width #'length)
   3767                                   col))))
   3768                      columns))
   3769          (cc (transient--seq-reductions-from
   3770               (apply-partially #'+ (* 3 (if vp (transient--pixel-width " ") 1)))
   3771               cw 0)))
   3772     (if transient-force-single-column
   3773         (dotimes (c cs)
   3774           (dotimes (r rs)
   3775             (when-let ((cell (nth r (nth c columns))))
   3776               (unless (equal cell "")
   3777                 (insert cell ?\n))))
   3778           (unless (= c (1- cs))
   3779             (insert ?\n)))
   3780       (dotimes (r rs)
   3781         (dotimes (c cs)
   3782           (if vp
   3783               (progn
   3784                 (when-let ((cell (nth r (nth c columns))))
   3785                   (insert cell))
   3786                 (if (= c (1- cs))
   3787                     (insert ?\n)
   3788                   (insert (propertize " " 'display
   3789                                       `(space :align-to (,(nth (1+ c) cc)))))))
   3790             (when (> c 0)
   3791               (insert (make-string (max 1 (- (nth c cc) (current-column)))
   3792                                    ?\s)))
   3793             (when-let ((cell (nth r (nth c columns))))
   3794               (insert cell))
   3795             (when (= c (1- cs))
   3796               (insert ?\n))))))))
   3797 
   3798 (cl-defmethod transient--insert-group ((group transient-subgroups))
   3799   (let* ((subgroups (oref group suffixes))
   3800          (n (length subgroups)))
   3801     (dotimes (s n)
   3802       (let ((subgroup (nth s subgroups)))
   3803         (transient--maybe-pad-keys subgroup group)
   3804         (transient--insert-group subgroup)
   3805         (when (< s (1- n))
   3806           (insert ?\n))))))
   3807 
   3808 (cl-defgeneric transient-format (obj)
   3809   "Format and return OBJ for display.
   3810 
   3811 When this function is called, then the current buffer is some
   3812 temporary buffer.  If you need the buffer from which the prefix
   3813 command was invoked to be current, then do so by temporarily
   3814 making `transient--original-buffer' current.")
   3815 
   3816 (cl-defmethod transient-format ((arg string))
   3817   "Return the string ARG after applying the `transient-heading' face."
   3818   (propertize arg 'face 'transient-heading))
   3819 
   3820 (cl-defmethod transient-format ((_   null))
   3821   "Return a string containing just the newline character."
   3822   "\n")
   3823 
   3824 (cl-defmethod transient-format ((arg integer))
   3825   "Return a string containing just the ARG character."
   3826   (char-to-string arg))
   3827 
   3828 (cl-defmethod transient-format :around ((obj transient-suffix))
   3829   "Add additional formatting if appropriate.
   3830 When reading user input for this infix, then highlight it.
   3831 When edit-mode is enabled, then prepend the level information.
   3832 When `transient-enable-popup-navigation' is non-nil then format
   3833 as a button."
   3834   (let ((str (cl-call-next-method obj)))
   3835     (when (and (cl-typep obj 'transient-infix)
   3836                (eq (oref obj command) this-original-command)
   3837                (active-minibuffer-window))
   3838       (setq str (transient--add-face str 'transient-active-infix)))
   3839     (when transient--editp
   3840       (setq str (concat (let ((level (oref obj level)))
   3841                           (propertize (format " %s " level)
   3842                                       'face (if (transient--use-level-p level t)
   3843                                                 'transient-enabled-suffix
   3844                                               'transient-disabled-suffix)))
   3845                         str)))
   3846     (when (and transient-enable-popup-navigation
   3847                (slot-boundp obj 'command))
   3848       (setq str (make-text-button str nil
   3849                                   'type 'transient
   3850                                   'command (oref obj command))))
   3851     str))
   3852 
   3853 (cl-defmethod transient-format ((obj transient-infix))
   3854   "Return a string generated using OBJ's `format'.
   3855 %k is formatted using `transient-format-key'.
   3856 %d is formatted using `transient-format-description'.
   3857 %v is formatted using `transient-format-value'."
   3858   (format-spec (oref obj format)
   3859                `((?k . ,(transient-format-key obj))
   3860                  (?d . ,(transient-format-description obj))
   3861                  (?v . ,(transient-format-value obj)))))
   3862 
   3863 (cl-defmethod transient-format ((obj transient-suffix))
   3864   "Return a string generated using OBJ's `format'.
   3865 %k is formatted using `transient-format-key'.
   3866 %d is formatted using `transient-format-description'."
   3867   (format-spec (oref obj format)
   3868                `((?k . ,(transient-format-key obj))
   3869                  (?d . ,(transient-format-description obj)))))
   3870 
   3871 (cl-defgeneric transient-format-key (obj)
   3872   "Format OBJ's `key' for display and return the result.")
   3873 
   3874 (cl-defmethod transient-format-key :around ((obj transient-suffix))
   3875   "Add `transient-inapt-suffix' face if suffix is inapt."
   3876   (let ((str (cl-call-next-method)))
   3877     (if (oref obj inapt)
   3878         (transient--add-face str 'transient-inapt-suffix)
   3879       str)))
   3880 
   3881 (cl-defmethod transient-format-key ((obj transient-suffix))
   3882   "Format OBJ's `key' for display and return the result."
   3883   (let ((key (if (slot-boundp obj 'key) (oref obj key) ""))
   3884         (cmd (and (slot-boundp obj 'command) (oref obj command))))
   3885     (when-let ((width (oref transient--pending-group pad-keys)))
   3886       (setq key (truncate-string-to-width key width nil ?\s)))
   3887     (if transient--redisplay-key
   3888         (let ((len (length transient--redisplay-key))
   3889               (seq (cl-coerce (edmacro-parse-keys key t) 'list)))
   3890           (cond
   3891            ((member (seq-take seq len)
   3892                     (list transient--redisplay-key
   3893                           (thread-last transient--redisplay-key
   3894                             (cl-substitute ?- 'kp-subtract)
   3895                             (cl-substitute ?= 'kp-equal)
   3896                             (cl-substitute ?+ 'kp-add))))
   3897             (let ((pre (key-description (vconcat (seq-take seq len))))
   3898                   (suf (key-description (vconcat (seq-drop seq len)))))
   3899               (setq pre (string-replace "RET" "C-m" pre))
   3900               (setq pre (string-replace "TAB" "C-i" pre))
   3901               (setq suf (string-replace "RET" "C-m" suf))
   3902               (setq suf (string-replace "TAB" "C-i" suf))
   3903               ;; We use e.g., "-k" instead of the more correct "- k",
   3904               ;; because the former is prettier.  If we did that in
   3905               ;; the definition, then we want to drop the space that
   3906               ;; is reinserted above.  False-positives are possible
   3907               ;; for silly bindings like "-C-c C-c".
   3908               (unless (string-search " " key)
   3909                 (setq pre (string-replace " " "" pre))
   3910                 (setq suf (string-replace " " "" suf)))
   3911               (concat (propertize pre 'face 'transient-unreachable-key)
   3912                       (and (string-prefix-p (concat pre " ") key) " ")
   3913                       (propertize suf 'face (transient--key-face cmd))
   3914                       (save-excursion
   3915                         (and (string-match " +\\'" key)
   3916                              (propertize (match-string 0 key)
   3917                                          'face 'fixed-pitch))))))
   3918            ((transient--lookup-key transient-sticky-map (kbd key))
   3919             (propertize key 'face (transient--key-face cmd)))
   3920            (t
   3921             (propertize key 'face 'transient-unreachable-key))))
   3922       (propertize key 'face (transient--key-face cmd)))))
   3923 
   3924 (cl-defmethod transient-format-key :around ((obj transient-argument))
   3925   "Handle `transient-highlight-mismatched-keys'."
   3926   (let ((key (cl-call-next-method obj)))
   3927     (cond
   3928      ((not transient-highlight-mismatched-keys) key)
   3929      ((not (slot-boundp obj 'shortarg))
   3930       (transient--add-face key 'transient-nonstandard-key))
   3931      ((not (string-equal key (oref obj shortarg)))
   3932       (transient--add-face key 'transient-mismatched-key))
   3933      (key))))
   3934 
   3935 (cl-defgeneric transient-format-description (obj)
   3936   "Format OBJ's `description' for display and return the result.")
   3937 
   3938 (cl-defmethod transient-format-description ((obj transient-child))
   3939   "The `description' slot may be a function, in which case that is
   3940 called inside the correct buffer (see `transient--insert-group')
   3941 and its value is returned to the caller."
   3942   (and-let* ((desc (oref obj description))
   3943              (desc (if (functionp desc)
   3944                        (if (= (car (transient--func-arity desc)) 1)
   3945                            (funcall desc obj)
   3946                          (funcall desc))
   3947                      desc)))
   3948     (if-let* ((face (transient--get-face obj 'face)))
   3949         (transient--add-face desc face t)
   3950       desc)))
   3951 
   3952 (cl-defmethod transient-format-description ((obj transient-group))
   3953   "Format the description by calling the next method.  If the result
   3954 doesn't use the `face' property at all, then apply the face
   3955 `transient-heading' to the complete string."
   3956   (and-let* ((desc (cl-call-next-method obj)))
   3957     (cond ((oref obj inapt)
   3958            (propertize desc 'face 'transient-inapt-suffix))
   3959           ((text-property-not-all 0 (length desc) 'face nil desc)
   3960            desc)
   3961           ((propertize desc 'face 'transient-heading)))))
   3962 
   3963 (cl-defmethod transient-format-description :around ((obj transient-suffix))
   3964   "Format the description by calling the next method.  If the result
   3965 is nil, then use \"(BUG: no description)\" as the description.
   3966 If the OBJ's `key' is currently unreachable, then apply the face
   3967 `transient-unreachable' to the complete string."
   3968   (let ((desc (or (cl-call-next-method obj)
   3969                   (and (slot-boundp transient--prefix 'suffix-description)
   3970                        (funcall (oref transient--prefix suffix-description)
   3971                                 obj))
   3972                   (propertize "(BUG: no description)" 'face 'error))))
   3973     (when (if transient--all-levels-p
   3974               (> (oref obj level) transient--default-prefix-level)
   3975             (and transient-highlight-higher-levels
   3976                  (> (max (oref obj level) transient--max-group-level)
   3977                     transient--default-prefix-level)))
   3978       (setq desc (transient--add-face desc 'transient-higher-level)))
   3979     (when-let ((inapt-face (and (oref obj inapt)
   3980                                 (transient--get-face obj 'inapt-face))))
   3981       (setq desc (transient--add-face desc inapt-face)))
   3982     (when (and (slot-boundp obj 'key)
   3983                (transient--key-unreachable-p obj))
   3984       (setq desc (transient--add-face desc 'transient-unreachable)))
   3985     desc))
   3986 
   3987 (cl-defgeneric transient-format-value (obj)
   3988   "Format OBJ's value for display and return the result.")
   3989 
   3990 (cl-defmethod transient-format-value ((obj transient-suffix))
   3991   (propertize (oref obj argument)
   3992               'face (if (oref obj value)
   3993                         'transient-argument
   3994                       'transient-inactive-argument)))
   3995 
   3996 (cl-defmethod transient-format-value ((obj transient-option))
   3997   (let ((argument (oref obj argument)))
   3998     (if-let ((value (oref obj value)))
   3999         (pcase-exhaustive (oref obj multi-value)
   4000           ('nil
   4001            (concat (propertize argument 'face 'transient-argument)
   4002                    (propertize value    'face 'transient-value)))
   4003           ((or 't 'rest)
   4004            (concat (propertize (if (string-suffix-p " " argument)
   4005                                    argument
   4006                                  (concat argument " "))
   4007                                'face 'transient-argument)
   4008                    (propertize (mapconcat #'prin1-to-string value " ")
   4009                                'face 'transient-value)))
   4010           ('repeat
   4011            (mapconcat (lambda (value)
   4012                         (concat (propertize argument 'face 'transient-argument)
   4013                                 (propertize value    'face 'transient-value)))
   4014                       value " ")))
   4015       (propertize argument 'face 'transient-inactive-argument))))
   4016 
   4017 (cl-defmethod transient-format-value ((obj transient-switches))
   4018   (with-slots (value argument-format choices) obj
   4019     (format (propertize argument-format
   4020                         'face (if value
   4021                                   'transient-argument
   4022                                 'transient-inactive-argument))
   4023             (format
   4024              (propertize "[%s]" 'face 'transient-delimiter)
   4025              (mapconcat
   4026               (lambda (choice)
   4027                 (propertize choice 'face
   4028                             (if (equal (format argument-format choice) value)
   4029                                 'transient-value
   4030                               'transient-inactive-value)))
   4031               choices
   4032               (propertize "|" 'face 'transient-delimiter))))))
   4033 
   4034 (defun transient--add-face (string face &optional append beg end)
   4035   (let ((str (copy-sequence string)))
   4036     (add-face-text-property (or beg 0) (or end (length str)) face append str)
   4037     str))
   4038 
   4039 (defun transient--get-face (obj slot)
   4040   (and-let* (((slot-exists-p obj slot))
   4041              ((slot-boundp obj slot))
   4042              (face (slot-value obj slot)))
   4043     (if (and (not (facep face))
   4044              (functionp face))
   4045         (let ((transient--pending-suffix obj))
   4046           (if (= (car (transient--func-arity face)) 1)
   4047               (funcall face obj)
   4048             (funcall face)))
   4049       face)))
   4050 
   4051 (defun transient--key-face (&optional cmd enforce-type)
   4052   (or (and transient-semantic-coloring
   4053            (not transient--helpp)
   4054            (not transient--editp)
   4055            (or (and cmd (get cmd 'transient-face))
   4056                (get (transient--get-pre-command cmd enforce-type)
   4057                     'transient-face)))
   4058       (if cmd 'transient-key 'transient-key-noop)))
   4059 
   4060 (defun transient--key-unreachable-p (obj)
   4061   (and transient--redisplay-key
   4062        (let ((key (oref obj key)))
   4063          (not (or (equal (seq-take (cl-coerce (edmacro-parse-keys key t) 'list)
   4064                                    (length transient--redisplay-key))
   4065                          transient--redisplay-key)
   4066                   (transient--lookup-key transient-sticky-map (kbd key)))))))
   4067 
   4068 (defun transient--lookup-key (keymap key)
   4069   (let ((val (lookup-key keymap key)))
   4070     (and val (not (integerp val)) val)))
   4071 
   4072 (defun transient--maybe-pad-keys (group &optional parent)
   4073   (when-let ((pad (or (oref group pad-keys)
   4074                       (and parent (oref parent pad-keys)))))
   4075     (oset group pad-keys
   4076           (apply #'max (cons (if (integerp pad) pad 0)
   4077                              (seq-keep (lambda (suffix)
   4078                                          (and (eieio-object-p suffix)
   4079                                               (slot-boundp suffix 'key)
   4080                                               (length (oref suffix key))))
   4081                                        (oref group suffixes)))))))
   4082 
   4083 (defun transient--pixel-width (string)
   4084   (save-window-excursion
   4085     (with-temp-buffer
   4086       (insert string)
   4087       (set-window-dedicated-p nil nil)
   4088       (set-window-buffer nil (current-buffer))
   4089       (car (window-text-pixel-size
   4090             nil (line-beginning-position) (point))))))
   4091 
   4092 (defun transient-command-summary-or-name (obj)
   4093   "Return the summary or name of the command represented by OBJ.
   4094 
   4095 If the command has a doc-string, then return the first line of
   4096 that, else its name.
   4097 
   4098 Intended to be temporarily used as the `:suffix-description' of
   4099 a prefix command, while porting a regular keymap to a transient."
   4100   (let ((command (oref obj command)))
   4101     (if-let ((doc (documentation command)))
   4102         (propertize (car (split-string doc "\n")) 'face 'font-lock-doc-face)
   4103       (propertize (symbol-name command) 'face 'font-lock-function-name-face))))
   4104 
   4105 ;;; Help
   4106 
   4107 (cl-defgeneric transient-show-help (obj)
   4108   "Show documentation for the command represented by OBJ.")
   4109 
   4110 (cl-defmethod transient-show-help ((obj transient-prefix))
   4111   "Call `show-help' if non-nil, else show `info-manual',
   4112 if non-nil, else show the `man-page' if non-nil, else use
   4113 `describe-function'."
   4114   (with-slots (show-help info-manual man-page command) obj
   4115     (cond (show-help (funcall show-help obj))
   4116           (info-manual (transient--show-manual info-manual))
   4117           (man-page (transient--show-manpage man-page))
   4118           ((transient--describe-function command)))))
   4119 
   4120 (cl-defmethod transient-show-help ((obj transient-suffix))
   4121   "Call `show-help' if non-nil, else use `describe-function'.
   4122 Also used to dispatch showing documentation for the current
   4123 prefix.  If the suffix is a sub-prefix, then also call the
   4124 prefix method."
   4125   (cond
   4126    ((eq this-command 'transient-help)
   4127     (transient-show-help transient--prefix))
   4128    ((let ((prefix (get (oref obj command)
   4129                        'transient--prefix)))
   4130       (and prefix (not (eq (oref transient--prefix command) this-command))
   4131            (prog1 t (transient-show-help prefix)))))
   4132    ((if-let ((show-help (oref obj show-help)))
   4133         (funcall show-help obj)
   4134       (transient--describe-function this-command)))))
   4135 
   4136 (cl-defmethod transient-show-help ((obj transient-infix))
   4137   "Call `show-help' if non-nil, else show the `man-page'
   4138 if non-nil, else use `describe-function'.  When showing the
   4139 manpage, then try to jump to the correct location."
   4140   (if-let ((show-help (oref obj show-help)))
   4141       (funcall show-help obj)
   4142     (if-let ((man-page (oref transient--prefix man-page))
   4143              (argument (and (slot-boundp obj 'argument)
   4144                             (oref obj argument))))
   4145         (transient--show-manpage man-page argument)
   4146       (transient--describe-function this-command))))
   4147 
   4148 ;; `cl-generic-generalizers' doesn't support `command' et al.
   4149 (cl-defmethod transient-show-help (cmd)
   4150   "Show the command doc-string."
   4151   (transient--describe-function cmd))
   4152 
   4153 (defun transient--describe-function (fn)
   4154   (describe-function fn)
   4155   (unless (derived-mode-p 'help-mode)
   4156     (when-let* ((buf (get-buffer "*Help*"))
   4157                 (win (or (and buf (get-buffer-window buf))
   4158                          (cl-find-if (lambda (win)
   4159                                        (with-current-buffer (window-buffer win)
   4160                                          (derived-mode-p 'help-mode)))
   4161                                      (window-list)))))
   4162       (select-window win))))
   4163 
   4164 (defun transient--show-manual (manual)
   4165   (info manual))
   4166 
   4167 (defun transient--show-manpage (manpage &optional argument)
   4168   (require 'man)
   4169   (let* ((Man-notify-method 'meek)
   4170          (buf (Man-getpage-in-background manpage))
   4171          (proc (get-buffer-process buf)))
   4172     (while (and proc (eq (process-status proc) 'run))
   4173       (accept-process-output proc))
   4174     (switch-to-buffer buf)
   4175     (when argument
   4176       (transient--goto-argument-description argument))))
   4177 
   4178 (defun transient--goto-argument-description (arg)
   4179   (goto-char (point-min))
   4180   (let ((case-fold-search nil)
   4181         ;; This matches preceding/proceeding options.  Options
   4182         ;; such as "-a", "-S[<keyid>]", and "--grep=<pattern>"
   4183         ;; are matched by this regex without the shy group.
   4184         ;; The ". " in the shy group is for options such as
   4185         ;; "-m parent-number", and the "-[^[:space:]]+ " is
   4186         ;; for options such as "--mainline parent-number"
   4187         (others "-\\(?:. \\|-[^[:space:]]+ \\)?[^[:space:]]+"))
   4188     (when (re-search-forward
   4189            (if (equal arg "--")
   4190                ;; Special case.
   4191                "^[\t\s]+\\(--\\(?: \\|$\\)\\|\\[--\\]\\)"
   4192              ;; Should start with whitespace and may have
   4193              ;; any number of options before and/or after.
   4194              (format
   4195               "^[\t\s]+\\(?:%s, \\)*?\\(?1:%s\\)%s\\(?:, %s\\)*$"
   4196               others
   4197               ;; Options don't necessarily end in an "="
   4198               ;; (e.g., "--gpg-sign[=<keyid>]")
   4199               (string-remove-suffix "=" arg)
   4200               ;; Simple options don't end in an "=".  Splitting this
   4201               ;; into 2 cases should make getting false positives
   4202               ;; less likely.
   4203               (if (string-suffix-p "=" arg)
   4204                   ;; "[^[:space:]]*[^.[:space:]]" matches the option
   4205                   ;; value, which is usually after the option name
   4206                   ;; and either '=' or '[='.  The value can't end in
   4207                   ;; a period, as that means it's being used at the
   4208                   ;; end of a sentence.  The space is for options
   4209                   ;; such as '--mainline parent-number'.
   4210                   "\\(?: \\|\\[?=\\)[^[:space:]]*[^.[:space:]]"
   4211                 ;; Either this doesn't match anything (e.g., "-a"),
   4212                 ;; or the option is followed by a value delimited
   4213                 ;; by a "[", "<", or ":".  A space might appear
   4214                 ;; before this value, as in "-f <file>".  The
   4215                 ;; space alternative is for options such as
   4216                 ;; "-m parent-number".
   4217                 "\\(?:\\(?: \\| ?[\\[<:]\\)[^[:space:]]*[^.[:space:]]\\)?")
   4218               others))
   4219            nil t)
   4220       (goto-char (match-beginning 1)))))
   4221 
   4222 (defun transient--insert-help ()
   4223   (unless (looking-back "\n\n" 2)
   4224     (insert "\n"))
   4225   (when transient--helpp
   4226     (insert
   4227      (format (propertize "\
   4228 Type a %s to show help for that suffix command, or %s to show manual.
   4229 Type %s to exit help.\n"
   4230                          'face 'transient-heading)
   4231              (propertize "<KEY>" 'face 'transient-key)
   4232              (propertize "?"     'face 'transient-key)
   4233              (propertize "C-g"   'face 'transient-key))))
   4234   (when transient--editp
   4235     (unless transient--helpp
   4236       (insert
   4237        (format (propertize "\
   4238 Type a %s to set level for that suffix command.
   4239 Type %s to set what levels are available for this prefix command.\n"
   4240                            'face 'transient-heading)
   4241                (propertize "<KEY>"   'face 'transient-key)
   4242                (propertize "C-x l" 'face 'transient-key))))
   4243     (with-slots (level) transient--prefix
   4244       (insert
   4245        (format (propertize "
   4246 Suffixes on levels %s are available.
   4247 Suffixes on levels %s and %s are unavailable.\n"
   4248                            'face 'transient-heading)
   4249                (propertize (format "1-%s" level)
   4250                            'face 'transient-enabled-suffix)
   4251                (propertize " 0 "
   4252                            'face 'transient-disabled-suffix)
   4253                (propertize (format ">=%s" (1+ level))
   4254                            'face 'transient-disabled-suffix))))))
   4255 
   4256 ;;; Popup Navigation
   4257 
   4258 (defun transient-scroll-up (&optional arg)
   4259   "Scroll text of transient popup window upward ARG lines.
   4260 If ARG is nil scroll near full screen.  This is a wrapper
   4261 around `scroll-up-command' (which see)."
   4262   (interactive "^P")
   4263   (with-selected-window transient--window
   4264     (scroll-up-command arg)))
   4265 
   4266 (defun transient-scroll-down (&optional arg)
   4267   "Scroll text of transient popup window down ARG lines.
   4268 If ARG is nil scroll near full screen.  This is a wrapper
   4269 around `scroll-down-command' (which see)."
   4270   (interactive "^P")
   4271   (with-selected-window transient--window
   4272     (scroll-down-command arg)))
   4273 
   4274 (defun transient-backward-button (n)
   4275   "Move to the previous button in the transient popup buffer.
   4276 See `backward-button' for information about N."
   4277   (interactive "p")
   4278   (with-selected-window transient--window
   4279     (backward-button n t)))
   4280 
   4281 (defun transient-forward-button (n)
   4282   "Move to the next button in the transient popup buffer.
   4283 See `forward-button' for information about N."
   4284   (interactive "p")
   4285   (with-selected-window transient--window
   4286     (forward-button n t)))
   4287 
   4288 (define-button-type 'transient
   4289   'face nil
   4290   'keymap transient-button-map)
   4291 
   4292 (defun transient--goto-button (command)
   4293   (cond
   4294    ((stringp command)
   4295     (when (re-search-forward (concat "^" (regexp-quote command)) nil t)
   4296       (goto-char (match-beginning 0))))
   4297    (command
   4298     (while (and (ignore-errors (forward-button 1))
   4299                 (not (eq (button-get (button-at (point)) 'command) command))))
   4300     (unless (eq (button-get (button-at (point)) 'command) command)
   4301       (goto-char (point-min))
   4302       (forward-button 1)))))
   4303 
   4304 (defun transient--heading-at-point ()
   4305   (and (eq (get-text-property (point) 'face) 'transient-heading)
   4306        (let ((beg (line-beginning-position)))
   4307          (buffer-substring-no-properties
   4308           beg (next-single-property-change
   4309                beg 'face nil (line-end-position))))))
   4310 
   4311 ;;; Compatibility
   4312 ;;;; Popup Isearch
   4313 
   4314 (defvar-keymap transient--isearch-mode-map
   4315   :parent isearch-mode-map
   4316   "<remap> <isearch-exit>"   #'transient-isearch-exit
   4317   "<remap> <isearch-cancel>" #'transient-isearch-cancel
   4318   "<remap> <isearch-abort>"  #'transient-isearch-abort)
   4319 
   4320 (defun transient-isearch-backward (&optional regexp-p)
   4321   "Do incremental search backward.
   4322 With a prefix argument, do an incremental regular expression
   4323 search instead."
   4324   (interactive "P")
   4325   (transient--isearch-setup)
   4326   (let ((isearch-mode-map transient--isearch-mode-map))
   4327     (isearch-mode nil regexp-p)))
   4328 
   4329 (defun transient-isearch-forward (&optional regexp-p)
   4330   "Do incremental search forward.
   4331 With a prefix argument, do an incremental regular expression
   4332 search instead."
   4333   (interactive "P")
   4334   (transient--isearch-setup)
   4335   (let ((isearch-mode-map transient--isearch-mode-map))
   4336     (isearch-mode t regexp-p)))
   4337 
   4338 (defun transient-isearch-exit ()
   4339   "Like `isearch-exit' but adapted for `transient'."
   4340   (interactive)
   4341   (isearch-exit)
   4342   (transient--isearch-exit))
   4343 
   4344 (defun transient-isearch-cancel ()
   4345   "Like `isearch-cancel' but adapted for `transient'."
   4346   (interactive)
   4347   (condition-case nil (isearch-cancel) (quit))
   4348   (transient--isearch-exit))
   4349 
   4350 (defun transient-isearch-abort ()
   4351   "Like `isearch-abort' but adapted for `transient'."
   4352   (interactive)
   4353   (let ((around (lambda (fn)
   4354                   (condition-case nil (funcall fn) (quit))
   4355                   (transient--isearch-exit))))
   4356     (advice-add 'isearch-cancel :around around)
   4357     (unwind-protect
   4358         (isearch-abort)
   4359       (advice-remove 'isearch-cancel around))))
   4360 
   4361 (defun transient--isearch-setup ()
   4362   (select-window transient--window)
   4363   (transient--suspend-override t))
   4364 
   4365 (defun transient--isearch-exit ()
   4366   (select-window transient--original-window)
   4367   (transient--resume-override))
   4368 
   4369 ;;;; Edebug
   4370 
   4371 (defun transient--edebug-command-p ()
   4372   (and (bound-and-true-p edebug-active)
   4373        (or (memq this-command '(top-level abort-recursive-edit))
   4374            (string-prefix-p "edebug" (symbol-name this-command)))))
   4375 
   4376 ;;;; Miscellaneous
   4377 
   4378 (cl-pushnew (list nil (concat "^\\s-*("
   4379                               (eval-when-compile
   4380                                 (regexp-opt
   4381                                  '("transient-define-prefix"
   4382                                    "transient-define-suffix"
   4383                                    "transient-define-infix"
   4384                                    "transient-define-argument")
   4385                                  t))
   4386                               "\\s-+\\(" lisp-mode-symbol-regexp "\\)")
   4387                   2)
   4388             lisp-imenu-generic-expression :test #'equal)
   4389 
   4390 (declare-function which-key-mode "which-key" (&optional arg))
   4391 
   4392 (defun transient--suspend-which-key-mode ()
   4393   (when (bound-and-true-p which-key-mode)
   4394     (which-key-mode -1)
   4395     (add-hook 'transient-exit-hook #'transient--resume-which-key-mode)))
   4396 
   4397 (defun transient--resume-which-key-mode ()
   4398   (unless transient--prefix
   4399     (which-key-mode 1)
   4400     (remove-hook 'transient-exit-hook #'transient--resume-which-key-mode)))
   4401 
   4402 (defun transient-bind-q-to-quit ()
   4403   "Modify some keymaps to bind \"q\" to the appropriate quit command.
   4404 
   4405 \"C-g\" is the default binding for such commands now, but Transient's
   4406 predecessor Magit-Popup used \"q\" instead.  If you would like to get
   4407 that binding back, then call this function in your init file like so:
   4408 
   4409   (with-eval-after-load \\='transient
   4410     (transient-bind-q-to-quit))
   4411 
   4412 Individual transients may already bind \"q\" to something else
   4413 and such a binding would shadow the quit binding.  If that is the
   4414 case then \"Q\" is bound to whatever \"q\" would have been bound
   4415 to by setting `transient-substitute-key-function' to a function
   4416 that does that.  Of course \"Q\" may already be bound to something
   4417 else, so that function binds \"M-q\" to that command instead.
   4418 Of course \"M-q\" may already be bound to something else, but
   4419 we stop there."
   4420   (keymap-set transient-base-map   "q" #'transient-quit-one)
   4421   (keymap-set transient-sticky-map "q" #'transient-quit-seq)
   4422   (setq transient-substitute-key-function
   4423         #'transient-rebind-quit-commands))
   4424 
   4425 (defun transient-rebind-quit-commands (obj)
   4426   "See `transient-bind-q-to-quit'."
   4427   (let ((key (oref obj key)))
   4428     (cond ((string-equal key "q") "Q")
   4429           ((string-equal key "Q") "M-q")
   4430           (key))))
   4431 
   4432 (defun transient--force-fixed-pitch ()
   4433   (require 'face-remap)
   4434   (face-remap-reset-base 'default)
   4435   (face-remap-add-relative 'default 'fixed-pitch))
   4436 
   4437 (defun transient--func-arity (fn)
   4438   (func-arity (advice--cd*r (if (symbolp fn) (symbol-function fn) fn))))
   4439 
   4440 (defun transient--seq-reductions-from (function sequence initial-value)
   4441   (let ((acc (list initial-value)))
   4442     (seq-doseq (elt sequence)
   4443       (push (funcall function (car acc) elt) acc))
   4444     (nreverse acc)))
   4445 
   4446 ;;; Font-Lock
   4447 
   4448 (defconst transient-font-lock-keywords
   4449   (eval-when-compile
   4450     `((,(concat "("
   4451                 (regexp-opt (list "transient-define-prefix"
   4452                                   "transient-define-infix"
   4453                                   "transient-define-argument"
   4454                                   "transient-define-suffix")
   4455                             t)
   4456                 "\\_>[ \t'(]*"
   4457                 "\\(\\(?:\\sw\\|\\s_\\)+\\)?")
   4458        (1 'font-lock-keyword-face)
   4459        (2 'font-lock-function-name-face nil t)))))
   4460 
   4461 (font-lock-add-keywords 'emacs-lisp-mode transient-font-lock-keywords)
   4462 
   4463 ;;; Auxiliary Classes
   4464 ;;;; `transient-lisp-variable'
   4465 
   4466 (defclass transient-lisp-variable (transient-variable)
   4467   ((reader :initform #'transient-lisp-variable--reader)
   4468    (always-read :initform t)
   4469    (set-value :initarg :set-value :initform #'set))
   4470   "[Experimental] Class used for Lisp variables.")
   4471 
   4472 (cl-defmethod transient-init-value ((obj transient-lisp-variable))
   4473   (oset obj value (symbol-value (oref obj variable))))
   4474 
   4475 (cl-defmethod transient-infix-set ((obj transient-lisp-variable) value)
   4476   (funcall (oref obj set-value)
   4477            (oref obj variable)
   4478            (oset obj value value)))
   4479 
   4480 (cl-defmethod transient-format-description ((obj transient-lisp-variable))
   4481   (or (cl-call-next-method obj)
   4482       (symbol-name (oref obj variable))))
   4483 
   4484 (cl-defmethod transient-format-value ((obj transient-lisp-variable))
   4485   (propertize (prin1-to-string (oref obj value))
   4486               'face 'transient-value))
   4487 
   4488 (cl-defmethod transient-prompt ((obj transient-lisp-variable))
   4489   (if (and (slot-boundp obj 'prompt)
   4490            (oref obj prompt))
   4491       (cl-call-next-method obj)
   4492     (format "Set %s: " (oref obj variable))))
   4493 
   4494 (defun transient-lisp-variable--reader (prompt initial-input _history)
   4495   (read--expression prompt initial-input))
   4496 
   4497 ;;; _
   4498 (provide 'transient)
   4499 ;; Local Variables:
   4500 ;; indent-tabs-mode: nil
   4501 ;; checkdoc-symbol-words: ("command-line" "edit-mode" "help-mode")
   4502 ;; End:
   4503 ;;; transient.el ends here