config

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

transient.el (180014B)


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