config

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

magit-base.el (52603B)


      1 ;;; magit-base.el --- Early birds  -*- lexical-binding:t; coding:utf-8 -*-
      2 
      3 ;; Copyright (C) 2008-2024 The Magit Project Contributors
      4 
      5 ;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev>
      6 ;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev>
      7 
      8 ;; SPDX-License-Identifier: GPL-3.0-or-later
      9 
     10 ;; Magit is free software: you can redistribute it and/or modify it
     11 ;; under the terms of the GNU General Public License as published by
     12 ;; the Free Software Foundation, either version 3 of the License, or
     13 ;; (at your option) any later version.
     14 ;;
     15 ;; Magit is distributed in the hope that it will be useful, but WITHOUT
     16 ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
     17 ;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
     18 ;; License for more details.
     19 ;;
     20 ;; You should have received a copy of the GNU General Public License
     21 ;; along with Magit.  If not, see <https://www.gnu.org/licenses/>.
     22 
     23 ;; This file contains code taken from GNU Emacs, which is
     24 ;; Copyright (C) 1976-2023 Free Software Foundation, Inc.
     25 
     26 ;;; Commentary:
     27 
     28 ;; This library defines utility functions, options and other things that
     29 ;; have to be available early on because they are used by several other
     30 ;; libraries, which cannot depend on one another, because that would lead
     31 ;; to circular dependencies.
     32 
     33 ;;; Code:
     34 
     35 (defconst magit--minimal-git "2.2.0")
     36 (defconst magit--minimal-emacs "25.1")
     37 
     38 (require 'cl-lib)
     39 (require 'compat)
     40 (require 'dash)
     41 (require 'eieio)
     42 (require 'subr-x)
     43 
     44 ;; For older Emacs releases we depend on an updated `seq' release from
     45 ;; GNU ELPA, for `seq-keep'.  Unfortunately something else may already
     46 ;; have required `seq', before `package' had a chance to put the more
     47 ;; recent version earlier on the `load-path'.
     48 (when (and (featurep' seq)
     49            (not (fboundp 'seq-keep)))
     50   (unload-feature 'seq 'force))
     51 (require 'seq)
     52 
     53 (require 'crm)
     54 
     55 (require 'magit-section)
     56 
     57 (eval-when-compile (require 'info))
     58 (declare-function Info-get-token "info" (pos start all &optional errorstring))
     59 
     60 (eval-when-compile (require 'vc-git))
     61 (declare-function vc-git--run-command-string "vc-git" (file &rest args))
     62 
     63 (eval-when-compile (require 'which-func))
     64 (declare-function which-function "which-func" ())
     65 
     66 ;;; Options
     67 
     68 (defcustom magit-completing-read-function #'magit-builtin-completing-read
     69   "Function to be called when requesting input from the user.
     70 
     71 If you have enabled `ivy-mode' or `helm-mode', then you don't
     72 have to customize this option; `magit-builtin-completing-read'
     73 will work just fine.  However, if you use Ido completion, then
     74 you do have to use `magit-ido-completing-read', because Ido is
     75 less well behaved than the former, more modern alternatives.
     76 
     77 If you would like to use Ivy or Helm completion with Magit but
     78 not enable the respective modes globally, then customize this
     79 option to use `ivy-completing-read' or
     80 `helm--completing-read-default'.  If you choose to use
     81 `ivy-completing-read', note that the items may always be shown in
     82 alphabetical order, depending on your version of Ivy."
     83   :group 'magit-essentials
     84   :type '(radio (function-item magit-builtin-completing-read)
     85                 (function-item magit-ido-completing-read)
     86                 (function-item ivy-completing-read)
     87                 (function-item helm--completing-read-default)
     88                 (function :tag "Other function")))
     89 
     90 (defcustom magit-dwim-selection
     91   '((magit-stash-apply        nil t)
     92     (magit-ediff-resolve-all  nil t)
     93     (magit-ediff-resolve-rest nil t)
     94     (magit-stash-branch       nil t)
     95     (magit-stash-branch-here  nil t)
     96     (magit-stash-format-patch nil t)
     97     (magit-stash-drop         nil ask)
     98     (magit-stash-pop          nil ask))
     99   "When not to offer alternatives and ask for confirmation.
    100 
    101 Many commands by default ask the user to select from a list of
    102 possible candidates.  They do so even when there is a thing at
    103 point that they can act on, which is then offered as the default.
    104 
    105 This option can be used to tell certain commands to use the thing
    106 at point instead of asking the user to select a candidate to act
    107 on, with or without confirmation.
    108 
    109 The value has the form ((COMMAND nil|PROMPT DEFAULT)...).
    110 
    111 - COMMAND is the command that should not prompt for a choice.
    112   To have an effect, the command has to use the function
    113   `magit-completing-read' or a utility function which in turn uses
    114   that function.
    115 
    116 - If the command uses `magit-completing-read' multiple times, then
    117   PROMPT can be used to only affect one of these uses.  PROMPT, if
    118   non-nil, is a regular expression that is used to match against
    119   the PROMPT argument passed to `magit-completing-read'.
    120 
    121 - DEFAULT specifies how to use the default.  If it is t, then
    122   the DEFAULT argument passed to `magit-completing-read' is used
    123   without confirmation.  If it is `ask', then the user is given
    124   a chance to abort.  DEFAULT can also be nil, in which case the
    125   entry has no effect."
    126   :package-version '(magit . "2.12.0")
    127   :group 'magit-commands
    128   :type '(repeat
    129           (list (symbol :tag "Command") ; It might not be fboundp yet.
    130                 (choice (const  :tag "for all prompts" nil)
    131                         (regexp :tag "for prompts matching regexp"))
    132                 (choice (const  :tag "offer other choices" nil)
    133                         (const  :tag "require confirmation" ask)
    134                         (const  :tag "use default without confirmation" t)))))
    135 
    136 (defconst magit--confirm-actions
    137   '((const discard)
    138     (const reverse)
    139     (const stage-all-changes)
    140     (const unstage-all-changes)
    141     (const delete)
    142     (const trash)
    143     (const resurrect)
    144     (const untrack)
    145     (const rename)
    146     (const reset-bisect)
    147     (const abort-cherry-pick)
    148     (const abort-revert)
    149     (const abort-rebase)
    150     (const abort-merge)
    151     (const merge-dirty)
    152     (const delete-unmerged-branch)
    153     (const delete-branch-on-remote)
    154     (const delete-pr-remote)
    155     (const drop-stashes)
    156     (const set-and-push)
    157     (const amend-published)
    158     (const rebase-published)
    159     (const edit-published)
    160     (const remove-modules)
    161     (const remove-dirty-modules)
    162     (const trash-module-gitdirs)
    163     (const stash-apply-3way)
    164     (const kill-process)
    165     (const safe-with-wip)))
    166 
    167 (defcustom magit-no-confirm '(set-and-push)
    168   "A list of symbols for actions Magit should not confirm, or t.
    169 
    170 Many potentially dangerous commands by default ask the user for
    171 confirmation.  Each of the below symbols stands for an action
    172 which, when invoked unintentionally or without being fully aware
    173 of the consequences, could lead to tears.  In many cases there
    174 are several commands that perform variations of a certain action,
    175 so we don't use the command names but more generic symbols.
    176 
    177 Applying changes:
    178 
    179   `discard' Discarding one or more changes (i.e., hunks or the
    180   complete diff for a file) loses that change, obviously.
    181 
    182   `reverse' Reverting one or more changes can usually be undone
    183   by reverting the reversion.
    184 
    185   `stage-all-changes', `unstage-all-changes' When there are both
    186   staged and unstaged changes, then un-/staging everything would
    187   destroy that distinction.  Of course that also applies when
    188   un-/staging a single change, but then less is lost and one does
    189   that so often that having to confirm every time would be
    190   unacceptable.
    191 
    192 Files:
    193 
    194   `delete' When a file that isn't yet tracked by Git is deleted
    195   then it is completely lost, not just the last changes.  Very
    196   dangerous.
    197 
    198   `trash' Instead of deleting a file it can also be move to the
    199   system trash.  Obviously much less dangerous than deleting it.
    200 
    201   Also see option `magit-delete-by-moving-to-trash'.
    202 
    203   `resurrect' A deleted file can easily be resurrected by
    204   \"deleting\" the deletion, which is done using the same command
    205   that was used to delete the same file in the first place.
    206 
    207   `untrack' Untracking a file can be undone by tracking it again.
    208 
    209   `rename' Renaming a file can easily be undone.
    210 
    211 Sequences:
    212 
    213   `reset-bisect' Aborting (known to Git as \"resetting\") a
    214   bisect operation loses all information collected so far.
    215 
    216   `abort-cherry-pick' Aborting a cherry-pick throws away all
    217   conflict resolutions which has already been carried out by the
    218   user.
    219 
    220   `abort-revert' Aborting a revert throws away all conflict
    221   resolutions which has already been carried out by the user.
    222 
    223   `abort-rebase' Aborting a rebase throws away all already
    224   modified commits, but it's possible to restore those from the
    225   reflog.
    226 
    227   `abort-merge' Aborting a merge throws away all conflict
    228   resolutions which has already been carried out by the user.
    229 
    230   `merge-dirty' Merging with a dirty worktree can make it hard to
    231   go back to the state before the merge was initiated.
    232 
    233 References:
    234 
    235   `delete-unmerged-branch' Once a branch has been deleted it can
    236   only be restored using low-level recovery tools provided by
    237   Git.  And even then the reflog is gone.  The user always has
    238   to confirm the deletion of a branch by accepting the default
    239   choice (or selecting another branch), but when a branch has
    240   not been merged yet, also make sure the user is aware of that.
    241 
    242   `delete-branch-on-remote' Deleting a \"remote branch\" may mean
    243   deleting the (local) \"remote-tracking\" branch only, or also
    244   removing it from the remote itself.  The latter often makes more
    245   sense because otherwise simply fetching from the remote would
    246   restore the remote-tracking branch, but doing that can be
    247   surprising and hard to recover from, so we ask.
    248 
    249   `delete-pr-remote' When deleting a branch that was created from
    250   a pull-request and if no other branches still exist on that
    251   remote, then `magit-branch-delete' offers to delete the remote
    252   as well.  This should be safe because it only happens if no
    253   other refs exist in the remotes namespace, and you can recreate
    254   the remote if necessary.
    255 
    256   `drop-stashes' Dropping a stash is dangerous because Git stores
    257   stashes in the reflog.  Once a stash is removed, there is no
    258   going back without using low-level recovery tools provided by
    259   Git.  When a single stash is dropped, then the user always has
    260   to confirm by accepting the default (or selecting another).
    261   This action only concerns the deletion of multiple stashes at
    262   once.
    263 
    264 Publishing:
    265 
    266   `set-and-push' When pushing to the upstream or the push-remote
    267   and that isn't actually configured yet, then the user can first
    268   set the target.  If s/he confirms the default too quickly, then
    269   s/he might end up pushing to the wrong branch and if the remote
    270   repository is configured to disallow fixing such mistakes, then
    271   that can be quite embarrassing and annoying.
    272 
    273 Edit published history:
    274 
    275   Without adding these symbols here, you will be warned before
    276   editing commits that have already been pushed to one of the
    277   branches listed in `magit-published-branches'.
    278 
    279   `amend-published' Affects most commands that amend to `HEAD'.
    280 
    281   `rebase-published' Affects commands that perform interactive
    282   rebases.  This includes commands from the commit popup that
    283   modify a commit other than `HEAD', namely the various fixup
    284   and squash variants.
    285 
    286   `edit-published' Affects the commands `magit-edit-line-commit'
    287   and `magit-diff-edit-hunk-commit'.  These two commands make
    288   it quite easy to accidentally edit a published commit, so you
    289   should think twice before configuring them not to ask for
    290   confirmation.
    291 
    292   To disable confirmation completely, add all three symbols here
    293   or set `magit-published-branches' to nil.
    294 
    295 Removing modules:
    296 
    297   `remove-modules' When you remove the working directory of a
    298   module that does not contain uncommitted changes, then that is
    299   safer than doing so when there are uncommitted changes and/or
    300   when you also remove the gitdir.  Still, you don't want to do
    301   that by accident.
    302 
    303   `remove-dirty-modules' When you remove the working directory of
    304   a module that contains uncommitted changes, then those changes
    305   are gone for good.  It is better to go to the module, inspect
    306   these changes and only if appropriate discard them manually.
    307 
    308   `trash-module-gitdirs' When you remove the gitdir of a module,
    309   then all unpushed changes are gone for good.  It is very easy
    310   to forget that you have some unfinished work on an unpublished
    311   feature branch or even in a stash.
    312 
    313   Actually there are some safety precautions in place, that might
    314   help you out if you make an unwise choice here, but don't count
    315   on it.  In case of emergency, stay calm and check the stash and
    316   the `trash-directory' for traces of lost work.
    317 
    318 Various:
    319 
    320   `stash-apply-3way' When a stash cannot be applied using \"git
    321   stash apply\", then Magit uses \"git apply\" instead, possibly
    322   using the \"--3way\" argument, which isn't always perfectly
    323   safe.  See also `magit-stash-apply'.
    324 
    325   `kill-process' There seldom is a reason to kill a process.
    326 
    327 Global settings:
    328 
    329   Instead of adding all of the above symbols to the value of this
    330   option you can also set it to the atom `t', which has the same
    331   effect as adding all of the above symbols.  Doing that most
    332   certainly is a bad idea, especially because other symbols might
    333   be added in the future.  So even if you don't want to be asked
    334   for confirmation for any of these actions, you are still better
    335   of adding all of the respective symbols individually.
    336 
    337   When `magit-wip-before-change-mode' is enabled then these actions
    338   can fairly easily be undone: `discard', `reverse',
    339   `stage-all-changes', and `unstage-all-changes'.  If and only if
    340   this mode is enabled, then `safe-with-wip' has the same effect
    341   as adding all of these symbols individually."
    342   :package-version '(magit . "2.1.0")
    343   :group 'magit-essentials
    344   :group 'magit-commands
    345   :type `(choice (const :tag "Always require confirmation" nil)
    346                  (const :tag "Never require confirmation" t)
    347                  (set   :tag "Require confirmation except for"
    348                         ;; `remove-dirty-modules' and
    349                         ;; `trash-module-gitdirs' intentionally
    350                         ;; omitted.
    351                         ,@magit--confirm-actions)))
    352 
    353 (defcustom magit-slow-confirm '(drop-stashes)
    354   "Whether to ask user \"y or n\" or \"yes or no\" questions.
    355 
    356 When this is nil, then `y-or-n-p' is used when the user has to
    357 confirm a potentially destructive action.  When this is t, then
    358 `yes-or-no-p' is used instead.  If this is a list of symbols
    359 identifying actions, then `yes-or-no-p' is used for those,
    360 `y-or-no-p' for all others.  The list of actions is the same as
    361 for `magit-no-confirm' (which see)."
    362   :package-version '(magit . "2.9.0")
    363   :group 'magit-miscellaneous
    364   :type `(choice (const :tag "Always ask \"yes or no\" questions" t)
    365                  (const :tag "Always ask \"y or n\" questions" nil)
    366                  (set   :tag "Ask \"yes or no\" questions only for"
    367                         ,@magit--confirm-actions)))
    368 
    369 (defcustom magit-no-message nil
    370   "A list of messages Magit should not display.
    371 
    372 Magit displays most echo area messages using `message', but a few
    373 are displayed using `magit-message' instead, which takes the same
    374 arguments as the former, FORMAT-STRING and ARGS.  `magit-message'
    375 forgoes printing a message if any member of this list is a prefix
    376 of the respective FORMAT-STRING.
    377 
    378 If Magit prints a message which causes you grief, then please
    379 first investigate whether there is another option which can be
    380 used to suppress it.  If that is not the case, then ask the Magit
    381 maintainers to start using `magit-message' instead of `message'
    382 in that case.  We are not proactively replacing all uses of
    383 `message' with `magit-message', just in case someone *might* find
    384 some of these messages useless.
    385 
    386 Messages which can currently be suppressed using this option are:
    387 * \"Turning on magit-auto-revert-mode...\""
    388   :package-version '(magit . "2.8.0")
    389   :group 'magit-miscellaneous
    390   :type '(repeat string))
    391 
    392 (defcustom magit-verbose-messages nil
    393   "Whether to make certain prompts and messages more verbose.
    394 
    395 Occasionally a user suggests that a certain prompt or message
    396 should be more verbose, but I would prefer to keep it as-is
    397 because I don't think that the fact that that one user did not
    398 understand the existing prompt/message means that a large number
    399 of users would have the same difficulty, and that making it more
    400 verbose would actually do a disservice to users who understand
    401 the shorter prompt well enough.
    402 
    403 Going forward I will start offering both messages when I feel the
    404 suggested longer message is reasonable enough, and the value of
    405 this option decides which will be used.  Note that changing the
    406 value of this option affects all such messages and that I do not
    407 intend to add an option per prompt."
    408   :package-version '(magit . "4.0.0")
    409   :group 'magit-miscellaneous
    410   :type 'boolean)
    411 
    412 (defcustom magit-ellipsis
    413   '((margin (?… . ">"))
    414     (t      (?… . "...")))
    415   "Characters or strings used to abbreviate text in some buffers.
    416 
    417 Each element has the form (WHERE (FANCY . UNIVERSAL)).
    418 
    419 FANCY is a single character or nil whereas UNIVERSAL is a string
    420 of any length.  The ellipsis produced by `magit--ellipsis' will
    421 be FANCY if it's a non-nil character that can be displayed with
    422 the available fonts, otherwise UNIVERSAL will be used.  FANCY is
    423 meant to be a rich character like a horizontal ellipsis symbol or
    424 an emoji whereas UNIVERSAL something simpler available in a less
    425 rich environment like the CLI.  WHERE determines the use-case for
    426 the ellipsis definition.  Currently the only acceptable values
    427 for WHERE are `margin' or t (representing the default).
    428 
    429 Whether collapsed sections are indicated using ellipsis is
    430 controlled by `magit-section-visibility-indicator'."
    431   :package-version '(magit . "4.0.0")
    432   :group 'magit-miscellaneous
    433   :type '(repeat (list (symbol :tag "Where")
    434                        (cons (choice :tag "Fancy" character (const nil))
    435                              (string :tag "Universal")))))
    436 
    437 (defcustom magit-update-other-window-delay 0.2
    438   "Delay before automatically updating the other window.
    439 
    440 When moving around in certain buffers, then certain other
    441 buffers, which are being displayed in another window, may
    442 optionally be updated to display information about the
    443 section at point.
    444 
    445 When holding down a key to move by more than just one section,
    446 then that would update that buffer for each section on the way.
    447 To prevent that, updating the revision buffer is delayed, and
    448 this option controls for how long.  For optimal experience you
    449 might have to adjust this delay and/or the keyboard repeat rate
    450 and delay of your graphical environment or operating system."
    451   :package-version '(magit . "2.3.0")
    452   :group 'magit-miscellaneous
    453   :type 'number)
    454 
    455 (defcustom magit-view-git-manual-method 'info
    456   "How links to Git documentation are followed from Magit's Info manuals.
    457 
    458 `info'  Follow the link to the node in the `gitman' Info manual
    459         as usual.  Unfortunately that manual is not installed by
    460         default on some platforms, and when it is then the nodes
    461         look worse than the actual manpages.
    462 
    463 `man'   View the respective man-page using the `man' package.
    464 
    465 `woman' View the respective man-page using the `woman' package."
    466   :package-version '(magit . "2.9.0")
    467   :group 'magit-miscellaneous
    468   :type '(choice (const :tag "view info manual" info)
    469                  (const :tag "view manpage using `man'" man)
    470                  (const :tag "view manpage using `woman'" woman)))
    471 
    472 ;;; Section Classes
    473 
    474 (defclass magit-commit-section (magit-section) ())
    475 
    476 (setf (alist-get 'commit magit--section-type-alist) 'magit-commit-section)
    477 
    478 (defclass magit-diff-section (magit-section) () :abstract t)
    479 
    480 (defclass magit-file-section (magit-diff-section)
    481   ((keymap :initform 'magit-file-section-map)
    482    (source :initform nil)
    483    (header :initform nil)
    484    (binary :initform nil)))
    485 
    486 (defclass magit-module-section (magit-file-section)
    487   ((keymap :initform 'magit-module-section-map)
    488    (range  :initform nil)))
    489 
    490 (defclass magit-hunk-section (magit-diff-section)
    491   ((keymap      :initform 'magit-hunk-section-map)
    492    (refined     :initform nil)
    493    (combined    :initform nil)
    494    (from-range  :initform nil)
    495    (from-ranges :initform nil)
    496    (to-range    :initform nil)
    497    (about       :initform nil)))
    498 
    499 (setf (alist-get 'file   magit--section-type-alist) 'magit-file-section)
    500 (setf (alist-get 'module magit--section-type-alist) 'magit-module-section)
    501 (setf (alist-get 'hunk   magit--section-type-alist) 'magit-hunk-section)
    502 
    503 (defclass magit-log-section (magit-section) () :abstract t)
    504 (defclass magit-unpulled-section (magit-log-section) ())
    505 (defclass magit-unpushed-section (magit-log-section) ())
    506 (defclass magit-unmerged-section (magit-log-section) ())
    507 
    508 (setf (alist-get 'unpulled magit--section-type-alist) 'magit-unpulled-section)
    509 (setf (alist-get 'unpushed magit--section-type-alist) 'magit-unpushed-section)
    510 (setf (alist-get 'unmerged magit--section-type-alist) 'magit-unmerged-section)
    511 
    512 ;;; User Input
    513 
    514 (defvar helm-completion-in-region-default-sort-fn)
    515 (defvar helm-crm-default-separator)
    516 (defvar ivy-sort-functions-alist)
    517 (defvar ivy-sort-matches-functions-alist)
    518 (defvar vertico-sort-function)
    519 
    520 (defvar magit-completing-read--silent-default nil)
    521 
    522 (defun magit-completing-read ( prompt collection &optional
    523                                predicate require-match initial-input
    524                                hist def fallback)
    525   "Read a choice in the minibuffer, or use the default choice.
    526 
    527 This is the function that Magit commands use when they need the
    528 user to select a single thing to act on.  The arguments have the
    529 same meaning as for `completing-read', except for FALLBACK, which
    530 is unique to this function and is described below.
    531 
    532 Instead of asking the user to choose from a list of possible
    533 candidates, this function may instead just return the default
    534 specified by DEF, with or without requiring user confirmation.
    535 Whether that is the case depends on PROMPT, `this-command' and
    536 `magit-dwim-selection'.  See the documentation of the latter for
    537 more information.
    538 
    539 If it does use the default without the user even having to
    540 confirm that, then `magit-completing-read--silent-default' is set
    541 to t, otherwise nil.
    542 
    543 If it does read a value in the minibuffer, then this function
    544 acts similarly to `completing-read', except for the following:
    545 
    546 - COLLECTION must be a list of choices.  A function is not
    547   supported.
    548 
    549 - If REQUIRE-MATCH is nil and the user exits without a choice,
    550   then nil is returned instead of an empty string.
    551 
    552 - If REQUIRE-MATCH is non-nil and the user exits without a
    553   choice, `user-error' is raised.
    554 
    555 - FALLBACK specifies a secondary default that is only used if
    556   the primary default DEF is nil.  The secondary default is not
    557   subject to `magit-dwim-selection' — if DEF is nil but FALLBACK
    558   is not, then this function always asks the user to choose a
    559   candidate, just as if both defaults were nil.
    560 
    561 - \": \" is appended to PROMPT.
    562 
    563 - PROMPT is modified to end with \" (default DEF|FALLBACK): \"
    564   provided that DEF or FALLBACK is non-nil, that neither
    565   `ivy-mode' nor `helm-mode' is enabled, and that
    566   `magit-completing-read-function' is set to its default value of
    567   `magit-builtin-completing-read'."
    568   (setq magit-completing-read--silent-default nil)
    569   (if-let ((dwim (and def
    570                       (nth 2 (seq-find (pcase-lambda (`(,cmd ,re ,_))
    571                                          (and (eq this-command cmd)
    572                                               (or (not re)
    573                                                   (string-match-p re prompt))))
    574                                        magit-dwim-selection)))))
    575       (if (eq dwim 'ask)
    576           (if (y-or-n-p (format "%s %s? " prompt def))
    577               def
    578             (user-error "Abort"))
    579         (setq magit-completing-read--silent-default t)
    580         def)
    581     (unless def
    582       (setq def fallback))
    583     (let ((command this-command)
    584           (reply (funcall magit-completing-read-function
    585                           (concat prompt ": ")
    586                           (if (and (not (functionp collection))
    587                                    def
    588                                    (not (member def collection)))
    589                               (cons def collection)
    590                             collection)
    591                           predicate
    592                           require-match initial-input hist def)))
    593       (setq this-command command)
    594       ;; Note: Avoid `string=' to support `helm-comp-read-use-marked'.
    595       (if (equal reply "")
    596           (if require-match
    597               (user-error "Nothing selected")
    598             nil)
    599         reply))))
    600 
    601 (defun magit--completion-table (collection)
    602   (lambda (string pred action)
    603     (if (eq action 'metadata)
    604         '(metadata (display-sort-function . identity))
    605       (complete-with-action action collection string pred))))
    606 
    607 (defun magit-builtin-completing-read
    608     (prompt choices &optional predicate require-match initial-input hist def)
    609   "Magit wrapper for standard `completing-read' function."
    610   (unless (or (bound-and-true-p helm-mode)
    611               (bound-and-true-p ivy-mode)
    612               (bound-and-true-p vertico-mode)
    613               (bound-and-true-p selectrum-mode))
    614     (setq prompt (magit-prompt-with-default prompt def)))
    615   (unless (or (bound-and-true-p helm-mode)
    616               (bound-and-true-p ivy-mode))
    617     (setq choices (magit--completion-table choices)))
    618   (cl-letf (((symbol-function #'completion-pcm--all-completions)))
    619     (when (< emacs-major-version 26)
    620       (fset 'completion-pcm--all-completions
    621             'magit-completion-pcm--all-completions))
    622     (let ((ivy-sort-functions-alist nil)
    623           (vertico-sort-function nil))
    624       (completing-read prompt choices
    625                        predicate require-match
    626                        initial-input hist def))))
    627 
    628 (define-obsolete-function-alias 'magit-completing-read-multiple*
    629   'magit-completing-read-multiple "Magit-Section 4.0.0")
    630 
    631 (defun magit-completing-read-multiple
    632     ( prompt table &optional predicate require-match initial-input
    633       hist def inherit-input-method
    634       no-split)
    635   "Read multiple strings in the minibuffer, with completion.
    636 Like `completing-read-multiple' but don't mess with order of
    637 TABLE and take an additional argument NO-SPLIT, which causes
    638 the user input to be returned as a single unmodified string.
    639 Also work around various incompatible features of various
    640 third-party completion frameworks."
    641   (cl-letf*
    642       (;; To implement NO-SPLIT we have to manipulate the respective
    643        ;; `split-string' invocation.  We cannot simply advice it to
    644        ;; return the input string because `SELECTRUM' would choke on
    645        ;; that string.  Use a variable to pass along the raw user
    646        ;; input string. aa5f098ab
    647        (input nil)
    648        (split-string (symbol-function #'split-string))
    649        ((symbol-function #'split-string)
    650         (lambda (string &optional separators omit-nulls trim)
    651           (when (and no-split
    652                      (equal separators crm-separator)
    653                      (equal omit-nulls t))
    654             (setq input string))
    655           (funcall split-string string separators omit-nulls trim)))
    656        ;; In Emacs 25 this function has a bug, so we use a copy of the
    657        ;; version from Emacs 26. bef9c7aa3
    658        ((symbol-function #'completion-pcm--all-completions)
    659         (if (< emacs-major-version 26)
    660             'magit-completion-pcm--all-completions
    661           (symbol-function #'completion-pcm--all-completions)))
    662        ;; Prevent `BUILT-IN' completion from messing up our existing
    663        ;; order of the completion candidates. aa5f098ab
    664        (table (magit--completion-table table))
    665        ;; Prevent `IVY' from messing up our existing order. c7af78726
    666        (ivy-sort-matches-functions-alist nil)
    667        ;; Prevent `HELM' from messing up our existing order.  6fcf994bd
    668        (helm-completion-in-region-default-sort-fn nil)
    669        ;; Prevent `HELM' from automatically appending the separator,
    670        ;; which is counterproductive when NO-SPLIT is non-nil and/or
    671        ;; when reading commit ranges. 798aff564
    672        (helm-crm-default-separator
    673         (if no-split nil (bound-and-true-p helm-crm-default-separator)))
    674        ;; And now, the moment we have all been waiting for...
    675        (values (completing-read-multiple
    676                 prompt table predicate require-match initial-input
    677                 hist def inherit-input-method)))
    678     (if no-split input values)))
    679 
    680 (defun magit-ido-completing-read
    681     (prompt choices &optional predicate require-match initial-input hist def)
    682   "Ido-based `completing-read' almost-replacement.
    683 
    684 Unfortunately `ido-completing-read' is not suitable as a
    685 drop-in replacement for `completing-read', instead we use
    686 `ido-completing-read+' from the third-party package by the
    687 same name."
    688   (if (and (require 'ido-completing-read+ nil t)
    689            (fboundp 'ido-completing-read+))
    690       (ido-completing-read+ prompt choices predicate require-match
    691                             initial-input hist
    692                             (or def (and require-match (car choices))))
    693     (display-warning 'magit "ido-completing-read+ is not installed
    694 
    695 To use Ido completion with Magit you need to install the
    696 third-party `ido-completing-read+' packages.  Falling
    697 back to built-in `completing-read' for now." :error)
    698     (magit-builtin-completing-read prompt choices predicate require-match
    699                                    initial-input hist def)))
    700 
    701 (defun magit-prompt-with-default (prompt def)
    702   (if (and def (length> prompt 2)
    703            (string-equal ": " (substring prompt -2)))
    704       (format "%s (default %s): " (substring prompt 0 -2) def)
    705     prompt))
    706 
    707 (defvar-keymap magit-minibuffer-local-ns-map
    708   :parent minibuffer-local-map
    709   "SPC" #'magit-whitespace-disallowed
    710   "TAB" #'magit-whitespace-disallowed)
    711 
    712 (defun magit-whitespace-disallowed ()
    713   "Beep to tell the user that whitespace is not allowed."
    714   (interactive)
    715   (ding)
    716   (message "Whitespace isn't allowed here")
    717   (setq defining-kbd-macro nil)
    718   (force-mode-line-update))
    719 
    720 (defun magit-read-string ( prompt &optional initial-input history default-value
    721                            inherit-input-method no-whitespace)
    722   "Read a string from the minibuffer, prompting with string PROMPT.
    723 
    724 This is similar to `read-string', but
    725 * empty input is only allowed if DEFAULT-VALUE is non-nil in
    726   which case that is returned,
    727 * whitespace is not allowed and leading and trailing whitespace is
    728   removed automatically if NO-WHITESPACE is non-nil,
    729 * \": \" is appended to PROMPT, and
    730 * an invalid DEFAULT-VALUE is silently ignored."
    731   (when default-value
    732     (when (consp default-value)
    733       (setq default-value (car default-value)))
    734     (unless (stringp default-value)
    735       (setq default-value nil)))
    736   (let* ((minibuffer-completion-table nil)
    737          (val (read-from-minibuffer
    738                (magit-prompt-with-default (concat prompt ": ") default-value)
    739                initial-input (and no-whitespace magit-minibuffer-local-ns-map)
    740                nil history default-value inherit-input-method))
    741          (trim (lambda (regexp string)
    742                  (save-match-data
    743                    (if (string-match regexp string)
    744                        (replace-match "" t t string)
    745                      string)))))
    746     (when (and (string= val "") default-value)
    747       (setq val default-value))
    748     (when no-whitespace
    749       (setq val (funcall trim "\\`\\(?:[ \t\n\r]+\\)"
    750                          (funcall trim "\\(?:[ \t\n\r]+\\)\\'" val))))
    751     (cond ((string= val "")
    752            (user-error "Need non-empty input"))
    753           ((and no-whitespace (string-match-p "[\s\t\n]" val))
    754            (user-error "Input contains whitespace"))
    755           (t val))))
    756 
    757 (defun magit-read-string-ns ( prompt &optional initial-input history
    758                               default-value inherit-input-method)
    759   "Call `magit-read-string' with non-nil NO-WHITESPACE."
    760   (magit-read-string prompt initial-input history default-value
    761                      inherit-input-method t))
    762 
    763 (defmacro magit-read-char-case (prompt verbose &rest clauses)
    764   (declare (indent 2)
    765            (debug (form form &rest (characterp form body))))
    766   `(prog1 (pcase (read-char-choice
    767                   (let ((parts (nconc (list ,@(mapcar #'cadr clauses))
    768                                       ,(and verbose '(list "[C-g] to abort")))))
    769                     (concat ,prompt
    770                             (mapconcat #'identity (butlast parts) ", ")
    771                             ", or "  (car (last parts)) " "))
    772                   ',(mapcar #'car clauses))
    773             ,@(--map `(,(car it) ,@(cddr it)) clauses))
    774      (message "")))
    775 
    776 (defun magit-y-or-n-p (prompt &optional action)
    777   "Ask user a \"y or n\" or a \"yes or no\" question using PROMPT.
    778 Which kind of question is used depends on whether
    779 ACTION is a member of option `magit-slow-confirm'."
    780   (if (or (eq magit-slow-confirm t)
    781           (and action (member action magit-slow-confirm)))
    782       (yes-or-no-p prompt)
    783     (y-or-n-p prompt)))
    784 
    785 (defvar magit--no-confirm-alist
    786   '((safe-with-wip magit-wip-before-change-mode
    787                    discard reverse stage-all-changes unstage-all-changes)))
    788 
    789 (cl-defun magit-confirm ( action &optional prompt prompt-n noabort
    790                           (items nil sitems) prompt-suffix)
    791   (declare (indent defun))
    792   (setq prompt-n (format (concat (or prompt-n prompt) "? ") (length items)))
    793   (setq prompt   (format (concat (or prompt (magit-confirm-make-prompt action))
    794                                  "? ")
    795                          (car items)))
    796   (when prompt-suffix
    797     (setq prompt (concat prompt prompt-suffix)))
    798   (or (cond ((and (not (eq action t))
    799                   (or (eq magit-no-confirm t)
    800                       (memq action magit-no-confirm)
    801                       (cl-member-if (pcase-lambda (`(,key ,var . ,sub))
    802                                       (and (memq key magit-no-confirm)
    803                                            (memq action sub)
    804                                            (or (not var)
    805                                                (and (boundp var)
    806                                                     (symbol-value var)))))
    807                                     magit--no-confirm-alist)))
    808              (or (not sitems) items))
    809             ((not sitems)
    810              (magit-y-or-n-p prompt action))
    811             ((length= items 1)
    812              (and (magit-y-or-n-p prompt action) items))
    813             ((length> items 1)
    814              (and (magit-y-or-n-p (concat (mapconcat #'identity items "\n")
    815                                           "\n\n" prompt-n)
    816                                   action)
    817                   items)))
    818       (if noabort nil (user-error "Abort"))))
    819 
    820 (defun magit-confirm-files (action files &optional prompt prompt-suffix noabort)
    821   (when files
    822     (unless prompt
    823       (setq prompt (magit-confirm-make-prompt action)))
    824     (magit-confirm action
    825       (concat prompt " \"%s\"")
    826       (concat prompt " %d files")
    827       noabort files prompt-suffix)))
    828 
    829 (defun magit-confirm-make-prompt (action)
    830   (let ((prompt (symbol-name action)))
    831     (string-replace "-" " "
    832                     (concat (upcase (substring prompt 0 1))
    833                             (substring prompt 1)))))
    834 
    835 (defun magit-read-number-string (prompt &optional default _history)
    836   "Like `read-number' but return value is a string.
    837 DEFAULT may be a number or a numeric string."
    838   (number-to-string
    839    (read-number prompt (if (stringp default)
    840                            (string-to-number default)
    841                          default))))
    842 
    843 ;;; Debug Utilities
    844 
    845 ;;;###autoload
    846 (defun magit-emacs-Q-command ()
    847   "Show a shell command that runs an uncustomized Emacs with only Magit loaded.
    848 See info node `(magit)Debugging Tools' for more information."
    849   (interactive)
    850   (let ((cmd (mapconcat
    851               #'shell-quote-argument
    852               `(,(concat invocation-directory invocation-name)
    853                 "-Q" "--eval" "(setq debug-on-error t)"
    854                 ,@(cl-mapcan
    855                    (lambda (dir) (list "-L" dir))
    856                    (delete-dups
    857                     (cl-mapcan
    858                      (lambda (lib)
    859                        (let ((path (locate-library lib)))
    860                          (cond
    861                           (path
    862                            (list (file-name-directory path)))
    863                           ((not (equal lib "libgit"))
    864                            (error "Cannot find mandatory dependency %s" lib)))))
    865                      '(;; Like `LOAD_PATH' in `default.mk'.
    866                        "compat"
    867                        "dash"
    868                        "libgit"
    869                        "transient"
    870                        "with-editor"
    871                        ;; Obviously `magit' itself is needed too.
    872                        "magit"
    873                        ;; While these are part of the Magit repository,
    874                        ;; they are distributed as separate packages.
    875                        "magit-section"
    876                        "git-commit"
    877                        ))))
    878                 ;; Avoid Emacs bug#16406 by using full path.
    879                 "-l" ,(file-name-sans-extension (locate-library "magit")))
    880               " ")))
    881     (message "Uncustomized Magit command saved to kill-ring, %s"
    882              "please run it in a terminal.")
    883     (kill-new cmd)))
    884 
    885 ;;; Text Utilities
    886 
    887 (defmacro magit-bind-match-strings (varlist string &rest body)
    888   "Bind variables to submatches according to VARLIST then evaluate BODY.
    889 Bind the symbols in VARLIST to submatches of the current match
    890 data, starting with 1 and incrementing by 1 for each symbol.  If
    891 the last match was against a string, then that has to be provided
    892 as STRING."
    893   (declare (indent 2) (debug (listp form body)))
    894   (let ((s (cl-gensym "string"))
    895         (i 0))
    896     `(let ((,s ,string))
    897        (let ,(save-match-data
    898                (cl-mapcan (lambda (sym)
    899                             (cl-incf i)
    900                             (and (not (eq (aref (symbol-name sym) 0) ?_))
    901                                  (list (list sym (list 'match-string i s)))))
    902                           varlist))
    903          ,@body))))
    904 
    905 (defun magit-delete-line ()
    906   "Delete the rest of the current line."
    907   (delete-region (point) (1+ (line-end-position))))
    908 
    909 (defun magit-delete-match (&optional num)
    910   "Delete text matched by last search.
    911 If optional NUM is specified, only delete that subexpression."
    912   (delete-region (match-beginning (or num 0))
    913                  (match-end (or num 0))))
    914 
    915 (defun magit-file-line (file)
    916   "Return the first line of FILE as a string."
    917   (when (file-regular-p file)
    918     (with-temp-buffer
    919       (insert-file-contents file)
    920       (buffer-substring-no-properties (point-min)
    921                                       (line-end-position)))))
    922 
    923 (defun magit-file-lines (file &optional keep-empty-lines)
    924   "Return a list of strings containing one element per line in FILE.
    925 Unless optional argument KEEP-EMPTY-LINES is t, trim all empty lines."
    926   (when (file-regular-p file)
    927     (with-temp-buffer
    928       (insert-file-contents file)
    929       (split-string (buffer-string) "\n" (not keep-empty-lines)))))
    930 
    931 (defun magit-set-header-line-format (string)
    932   "Set `header-line-format' in the current buffer based on STRING.
    933 Pad the left side of STRING so that it aligns with the text area."
    934   (setq header-line-format
    935         (concat (propertize " " 'display '(space :align-to 0))
    936                 string)))
    937 
    938 (defun magit--format-spec (format specification)
    939   "Like `format-spec' but preserve text properties in SPECIFICATION."
    940   (with-temp-buffer
    941     (insert format)
    942     (goto-char (point-min))
    943     (while (search-forward "%" nil t)
    944       (cond
    945        ;; Quoted percent sign.
    946        ((eq (char-after) ?%)
    947         (delete-char 1))
    948        ;; Valid format spec.
    949        ((looking-at "\\([-0-9.]*\\)\\([a-zA-Z]\\)")
    950         (let* ((num (match-string 1))
    951                (spec (string-to-char (match-string 2)))
    952                (val (assq spec specification)))
    953           (unless val
    954             (error "Invalid format character: `%%%c'" spec))
    955           (setq val (cdr val))
    956           ;; Pad result to desired length.
    957           (let ((text (format (concat "%" num "s") val)))
    958             ;; Insert first, to preserve text properties.
    959             (if (next-property-change 0 (concat " " text))
    960                 ;; If the inserted text has properties, then preserve those.
    961                 (insert text)
    962               ;; Otherwise preserve FORMAT's properties, like `format-spec'.
    963               (insert-and-inherit text))
    964             ;; Delete the specifier body.
    965             (delete-region (+ (match-beginning 0) (length text))
    966                            (+ (match-end 0) (length text)))
    967             ;; Delete the percent sign.
    968             (delete-region (1- (match-beginning 0)) (match-beginning 0)))))
    969        ;; Signal an error on bogus format strings.
    970        (t
    971         (error "Invalid format string"))))
    972     (buffer-string)))
    973 
    974 ;;; Missing from Emacs
    975 
    976 (defun magit-kill-this-buffer ()
    977   "Kill the current buffer."
    978   (interactive)
    979   (kill-buffer (current-buffer)))
    980 
    981 (defun magit--buffer-string (&optional min max trim)
    982   "Like `buffer-substring-no-properties' but the arguments are optional.
    983 
    984 This combines the benefits of `buffer-string', `buffer-substring'
    985 and `buffer-substring-no-properties' into one function that is
    986 not as painful to use as the latter.  I.e., you can write
    987   (magit--buffer-string)
    988 instead of
    989   (buffer-substring-no-properties (point-min)
    990                                   (point-max))
    991 
    992 Optional MIN defaults to the value of `point-min'.
    993 Optional MAX defaults to the value of `point-max'.
    994 
    995 If optional TRIM is non-nil, then all leading and trailing
    996 whitespace is remove.  If it is the newline character, then
    997 one trailing newline is added."
    998   ;; Lets write that one last time and be done with it:
    999   (let ((str (buffer-substring-no-properties (or min (point-min))
   1000                                              (or max (point-max)))))
   1001     (if trim
   1002         (concat (string-trim str)
   1003                 (and (eq trim ?\n) "\n"))
   1004       str)))
   1005 
   1006 (defun magit--version> (v1 v2)
   1007   "Return t if version V1 is higher (younger) than V2.
   1008 This function should be named `version>' and be part of Emacs."
   1009   (version-list-< (version-to-list v2) (version-to-list v1)))
   1010 
   1011 (defun magit--version>= (v1 v2)
   1012   "Return t if version V1 is higher (younger) than or equal to V2.
   1013 This function should be named `version>=' and be part of Emacs."
   1014   (version-list-<= (version-to-list v2) (version-to-list v1)))
   1015 
   1016 ;;; Kludges for Emacs Bugs
   1017 
   1018 (when (< emacs-major-version 27)
   1019   ;; Work around https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559.
   1020   ;; Fixed by cb55ccae8be946f1562d74718086a4c8c8308ee5 in Emacs 27.1.
   1021   (with-eval-after-load 'vc-git
   1022     (defun vc-git-conflicted-files (directory)
   1023       "Return the list of files with conflicts in DIRECTORY."
   1024       (let* ((status
   1025               (vc-git--run-command-string directory "diff-files"
   1026                                           "--name-status"))
   1027              (lines (when status (split-string status "\n" 'omit-nulls)))
   1028              files)
   1029         (dolist (line lines files)
   1030           (when (string-match "\\([ MADRCU?!]\\)[ \t]+\\(.+\\)" line)
   1031             (let ((state (match-string 1 line))
   1032                   (file (match-string 2 line)))
   1033               (when (equal state "U")
   1034                 (push (expand-file-name file directory) files)))))))))
   1035 
   1036 (when (< emacs-major-version 27)
   1037   (defun vc-git--call@bug21559 (fn buffer command &rest args)
   1038     "Backport https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559."
   1039     (let ((process-environment process-environment))
   1040       (when revert-buffer-in-progress-p
   1041         (push "GIT_OPTIONAL_LOCKS=0" process-environment))
   1042       (apply fn buffer command args)))
   1043   (advice-add 'vc-git--call :around 'vc-git--call@bug21559)
   1044 
   1045   (defun vc-git-command@bug21559
   1046       (fn buffer okstatus file-or-list &rest flags)
   1047     "Backport https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559."
   1048     (let ((process-environment process-environment))
   1049       (when revert-buffer-in-progress-p
   1050         (push "GIT_OPTIONAL_LOCKS=0" process-environment))
   1051       (apply fn buffer okstatus file-or-list flags)))
   1052   (advice-add 'vc-git-command :around 'vc-git-command@bug21559)
   1053 
   1054   (defun auto-revert-handler@bug21559 (fn)
   1055     "Backport https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559."
   1056     (let ((revert-buffer-in-progress-p t))
   1057       (funcall fn)))
   1058   (advice-add 'auto-revert-handler :around 'auto-revert-handler@bug21559)
   1059   )
   1060 
   1061 (when (< emacs-major-version 26)
   1062   ;; In Emacs 25 `completion-pcm--all-completions' reverses the
   1063   ;; completion list.  This is the version from Emacs 26, which
   1064   ;; fixes that issue.  bug#24676
   1065   (defun magit-completion-pcm--all-completions (prefix pattern table pred)
   1066     (if (completion-pcm--pattern-trivial-p pattern)
   1067         (all-completions (concat prefix (car pattern)) table pred)
   1068       (let* ((regex (completion-pcm--pattern->regex pattern))
   1069              (case-fold-search completion-ignore-case)
   1070              (completion-regexp-list (cons regex completion-regexp-list))
   1071              (compl (all-completions
   1072                      (concat prefix
   1073                              (if (stringp (car pattern)) (car pattern) ""))
   1074                      table pred)))
   1075         (if (not (functionp table))
   1076             compl
   1077           (let ((poss ()))
   1078             (dolist (c compl)
   1079               (when (string-match-p regex c) (push c poss)))
   1080             (nreverse poss)))))))
   1081 
   1082 (defun magit-which-function ()
   1083   "Return current function name based on point.
   1084 
   1085 This is a simple wrapper around `which-function', that resets
   1086 Imenu's potentially outdated and therefore unreliable cache by
   1087 setting `imenu--index-alist' to nil before calling that function."
   1088   (setq imenu--index-alist nil)
   1089   (which-function))
   1090 
   1091 ;;; Kludges for Custom
   1092 
   1093 (defun magit-custom-initialize-reset (symbol exp)
   1094   "Initialize SYMBOL based on EXP.
   1095 Set the value of the variable SYMBOL, using `set-default'
   1096 \(unlike `custom-initialize-reset', which uses the `:set'
   1097 function if any).  The value is either the symbol's current
   1098 value (as obtained using the `:get' function), if any, or
   1099 the value in the symbol's `saved-value' property if any, or
   1100 \(last of all) the value of EXP."
   1101   (set-default-toplevel-value
   1102    symbol
   1103    (condition-case nil
   1104        (let ((def (default-toplevel-value symbol))
   1105              (getter (get symbol 'custom-get)))
   1106          (if getter (funcall getter symbol) def))
   1107      (error
   1108       (eval (let ((sv (get symbol 'saved-value)))
   1109               (if sv (car sv) exp)))))))
   1110 
   1111 (defun magit-hook-custom-get (symbol)
   1112   (if (symbol-file symbol 'defvar)
   1113       (default-toplevel-value symbol)
   1114     ;;
   1115     ;; Called by `custom-initialize-reset' on behalf of `symbol's
   1116     ;; `defcustom', which is being evaluated for the first time to
   1117     ;; set the initial value, but there's already a default value,
   1118     ;; which most likely was established by one or more `add-hook'
   1119     ;; calls.
   1120     ;;
   1121     ;; We combine the `standard-value' and the current value, while
   1122     ;; preserving the order established by `:options', and return
   1123     ;; the result of that to be used as the "initial" default value.
   1124     ;;
   1125     (let ((standard (eval (car (get symbol 'standard-value))))
   1126           (current (default-toplevel-value symbol))
   1127           (value nil))
   1128       (dolist (fn (get symbol 'custom-options))
   1129         (when (or (memq fn standard)
   1130                   (memq fn current))
   1131           (push fn value)))
   1132       (dolist (fn current)
   1133         (unless (memq fn value)
   1134           (push fn value)))
   1135       (nreverse value))))
   1136 
   1137 ;;; Kludges for Info Manuals
   1138 
   1139 ;;;###autoload
   1140 (defun Info-follow-nearest-node--magit-gitman (fn &optional fork)
   1141   (let ((node (Info-get-token
   1142                (point) "\\*note[ \n\t]+"
   1143                "\\*note[ \n\t]+\\([^:]*\\):\\(:\\|[ \n\t]*(\\)?")))
   1144     (if (and node (string-match "^(gitman)\\(.+\\)" node))
   1145         (pcase magit-view-git-manual-method
   1146           ('info  (funcall fn fork))
   1147           ('man   (require 'man)
   1148                   (man (match-string 1 node)))
   1149           ('woman (require 'woman)
   1150                   (woman (match-string 1 node)))
   1151           (_
   1152            (user-error "Invalid value for `magit-view-git-manual-method'")))
   1153       (funcall fn fork))))
   1154 
   1155 ;;;###autoload
   1156 (advice-add 'Info-follow-nearest-node :around
   1157             #'Info-follow-nearest-node--magit-gitman)
   1158 
   1159 ;; When making changes here, then also adjust the copy in docs/Makefile.
   1160 ;;;###autoload
   1161 (advice-add 'org-man-export :around #'org-man-export--magit-gitman)
   1162 ;;;###autoload
   1163 (defun org-man-export--magit-gitman (fn link description format)
   1164   (if (and (eq format 'texinfo)
   1165            (string-prefix-p "git" link))
   1166       (string-replace "%s" link "
   1167 @ifinfo
   1168 @ref{%s,,,gitman,}.
   1169 @end ifinfo
   1170 @ifhtml
   1171 @html
   1172 the <a href=\"http://git-scm.com/docs/%s\">%s(1)</a> manpage.
   1173 @end html
   1174 @end ifhtml
   1175 @iftex
   1176 the %s(1) manpage.
   1177 @end iftex
   1178 ")
   1179     (funcall fn link description format)))
   1180 
   1181 ;;; Kludges for Package Managers
   1182 
   1183 (defun magit--straight-chase-links (filename)
   1184   "Chase links in FILENAME until a name that is not a link.
   1185 
   1186 This is the same as `file-chase-links', except that it also
   1187 handles fake symlinks that are created by the package manager
   1188 straight.el on Windows.
   1189 
   1190 See <https://github.com/raxod502/straight.el/issues/520>."
   1191   (when (and (bound-and-true-p straight-symlink-emulation-mode)
   1192              (fboundp 'straight-chase-emulated-symlink))
   1193     (when-let ((target (straight-chase-emulated-symlink filename)))
   1194       (unless (eq target 'broken)
   1195         (setq filename target))))
   1196   (file-chase-links filename))
   1197 
   1198 ;;; Kludges for older Emacs versions
   1199 
   1200 (if (fboundp 'with-connection-local-variables)
   1201     (defalias 'magit--with-connection-local-variables
   1202       #'with-connection-local-variables)
   1203   (defmacro magit--with-connection-local-variables (&rest body)
   1204     "Abridged `with-connection-local-variables' for pre Emacs 27 compatibility.
   1205 Bind shell file name and switch for remote execution.
   1206 `with-connection-local-variables' isn't available until Emacs 27.
   1207 This kludge provides the minimal functionality required by
   1208 Magit."
   1209     `(if (file-remote-p default-directory)
   1210          (pcase-let ((`(,shell-file-name ,shell-command-switch)
   1211                       (with-no-warnings ; about unknown tramp functions
   1212                         (require 'tramp)
   1213                         (let ((vec (tramp-dissect-file-name
   1214                                     default-directory)))
   1215                           (list (tramp-get-method-parameter
   1216                                  vec 'tramp-remote-shell)
   1217                                 (mapconcat #'identity
   1218                                            (tramp-get-method-parameter
   1219                                             vec 'tramp-remote-shell-args)
   1220                                            " "))))))
   1221            ,@body)
   1222        ,@body)))
   1223 
   1224 (put 'magit--with-connection-local-variables 'lisp-indent-function 'defun)
   1225 
   1226 ;;; Miscellaneous
   1227 
   1228 (defun magit-message (format-string &rest args)
   1229   "Display a message at the bottom of the screen, or not.
   1230 Like `message', except that if the users configured option
   1231 `magit-no-message' to prevent the message corresponding to
   1232 FORMAT-STRING to be displayed, then don't."
   1233   (unless (--first (string-prefix-p it format-string) magit-no-message)
   1234     (apply #'message format-string args)))
   1235 
   1236 (defun magit-msg (format-string &rest args)
   1237   "Display a message at the bottom of the screen, but don't log it.
   1238 Like `message', except that `message-log-max' is bound to nil."
   1239   (let ((message-log-max nil))
   1240     (apply #'message format-string args)))
   1241 
   1242 (defmacro magit--with-temp-position (buf pos &rest body)
   1243   (declare (indent 2))
   1244   `(with-current-buffer ,buf
   1245      (save-excursion
   1246        (save-restriction
   1247          (widen)
   1248          (goto-char (or ,pos 1))
   1249          ,@body))))
   1250 
   1251 (defun magit--ellipsis (&optional where)
   1252   "Build an ellipsis always as string, depending on WHERE."
   1253   (if (stringp magit-ellipsis)
   1254       magit-ellipsis
   1255     (if-let ((pair (car (or
   1256                          (alist-get (or where t) magit-ellipsis)
   1257                          (alist-get t magit-ellipsis)))))
   1258         (pcase-let ((`(,fancy . ,universal) pair))
   1259           (let ((ellipsis (if (and fancy (char-displayable-p fancy))
   1260                               fancy
   1261                             universal)))
   1262             (if (characterp ellipsis)
   1263                 (char-to-string ellipsis)
   1264               ellipsis)))
   1265       (user-error "Variable magit-ellipsis is invalid"))))
   1266 
   1267 (defun magit--ext-regexp-quote (str)
   1268   "Like `reqexp-quote', but for Extended Regular Expressions."
   1269   (let ((special (string-to-list "[*.\\?+^$({"))
   1270         (quoted nil))
   1271     (mapc (lambda (c)
   1272             (when (memq c special)
   1273               (push ?\\ quoted))
   1274             (push c quoted))
   1275           str)
   1276     (concat (nreverse quoted))))
   1277 
   1278 ;;; _
   1279 (provide 'magit-base)
   1280 ;;; magit-base.el ends here