config

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

magit-section.el (102978B)


      1 ;;; magit-section.el --- Sections for read-only buffers  -*- 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 ;; Homepage: https://github.com/magit/magit
      9 ;; Keywords: tools
     10 
     11 ;; Package-Version: 3.3.0.50-git
     12 ;; Package-Requires: (
     13 ;;     (emacs "26.1")
     14 ;;     (compat "29.1.4.5")
     15 ;;     (dash "2.19.1")
     16 ;;     (seq "2.24"))
     17 
     18 ;; SPDX-License-Identifier: GPL-3.0-or-later
     19 
     20 ;; Magit is free software: you can redistribute it and/or modify
     21 ;; it under the terms of the GNU General Public License as published
     22 ;; by the Free Software Foundation, either version 3 of the License,
     23 ;; or (at your option) any later version.
     24 ;;
     25 ;; Magit is distributed in the hope that it will be useful,
     26 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     27 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     28 ;; GNU General Public License for more details.
     29 ;;
     30 ;; You should have received a copy of the GNU General Public License
     31 ;; along with Magit.  If not, see <https://www.gnu.org/licenses/>.
     32 
     33 ;; You should have received a copy of the AUTHORS.md file, which
     34 ;; lists all contributors.  If not, see https://magit.vc/authors.
     35 
     36 ;;; Commentary:
     37 
     38 ;; This package implements the main user interface of Magit — the
     39 ;; collapsible sections that make up its buffers.  This package used
     40 ;; to be distributed as part of Magit but now it can also be used by
     41 ;; other packages that have nothing to do with Magit or Git.
     42 
     43 ;;; Code:
     44 
     45 (require 'cl-lib)
     46 (require 'compat)
     47 (require 'dash)
     48 (require 'eieio)
     49 (require 'subr-x)
     50 
     51 ;; For older Emacs releases we depend on an updated `seq' release from GNU
     52 ;; ELPA, for `seq-keep'.  Unfortunately something else may require `seq'
     53 ;; before `package' had a chance to put this version on the `load-path'.
     54 (when (and (featurep 'seq)
     55            (not (fboundp 'seq-keep)))
     56   (unload-feature 'seq 'force))
     57 (require 'seq)
     58 ;; Furthermore, by default `package' just silently refuses to upgrade.
     59 (defconst magit--core-upgrade-instructions "\
     60 Magit requires `%s' >= %s,
     61 but due to bad defaults, Emacs' package manager, refuses to
     62 upgrade this and other built-in packages to higher releases
     63 from GNU Elpa.
     64 
     65 To fix this, you have to add this to your init file:
     66 
     67   (setq package-install-upgrade-built-in t)
     68 
     69 Then evaluate that expression by placing the cursor after it
     70 and typing \\[eval-last-sexp].
     71 
     72 Once you have done that, you have to explicitly upgrade `%s':
     73 
     74   \\[package-install] %s \\`RET'
     75 
     76 Then you also must make sure the updated version is loaded,
     77 by evaluating this form:
     78 
     79   (progn (unload-feature \\='%s t) (require \\='%s))
     80 
     81 If this does not work, then try uninstalling Magit and all of its
     82 dependencies.  After that exit and restart Emacs, and only then
     83 reinstalling Magit.
     84 
     85 If you don't use the `package' package manager but still get
     86 this warning, then your chosen package manager likely has a
     87 similar defect.")
     88 (unless (fboundp 'seq-keep)
     89   (display-warning 'magit (substitute-command-keys
     90                            (format magit--core-upgrade-instructions
     91                                    'seq "2.24" 'seq 'seq 'seq 'seq))
     92                    :emergency))
     93 
     94 (require 'cursor-sensor)
     95 (require 'format-spec)
     96 
     97 (eval-when-compile (require 'benchmark))
     98 
     99 ;; For `magit-section-get-relative-position'
    100 (declare-function magit-hunk-section-p "magit-diff" (section) t)
    101 
    102 ;;; Hooks
    103 
    104 (defvar magit-section-movement-hook nil
    105   "Hook run by `magit-section-goto'.
    106 That function in turn is used by all section movement commands.")
    107 
    108 (defvar magit-section-highlight-hook
    109   '(magit-section-highlight
    110     magit-section-highlight-selection)
    111   "Functions used to highlight the current section.
    112 Each function is run with the current section as only argument
    113 until one of them returns non-nil.")
    114 
    115 (defvar magit-section-unhighlight-hook nil
    116   "Functions used to unhighlight the previously current section.
    117 Each function is run with the current section as only argument
    118 until one of them returns non-nil.  Most sections are properly
    119 unhighlighted without requiring a specialized unhighlighter,
    120 diff-related sections being the only exception.")
    121 
    122 (defvar magit-section-set-visibility-hook
    123   '(magit-section-cached-visibility)
    124   "Hook used to set the initial visibility of a section.
    125 Stop at the first function that returns non-nil.  The returned
    126 value should be `show', `hide' or nil.  If no function returns
    127 non-nil, determine the visibility as usual, i.e., use the
    128 hardcoded section specific default (see `magit-insert-section').")
    129 
    130 ;;; Options
    131 
    132 (defgroup magit-section nil
    133   "Expandable sections."
    134   :link '(info-link "(magit)Sections")
    135   :group 'extensions)
    136 
    137 (defcustom magit-section-show-child-count t
    138   "Whether to append the number of children to section headings.
    139 This only applies to sections for which doing so makes sense."
    140   :package-version '(magit-section . "2.1.0")
    141   :group 'magit-section
    142   :type 'boolean)
    143 
    144 (defcustom magit-section-cache-visibility t
    145   "Whether to cache visibility of sections.
    146 
    147 Sections always retain their visibility state when they are being
    148 recreated during a refresh.  But if a section disappears and then
    149 later reappears again, then this option controls whether this is
    150 the case.
    151 
    152 If t, then cache the visibility of all sections.  If a list of
    153 section types, then only do so for matching sections.  If nil,
    154 then don't do so for any sections."
    155   :package-version '(magit-section . "2.12.0")
    156   :group 'magit-section
    157   :type '(choice (const  :tag "Don't cache visibility" nil)
    158                  (const  :tag "Cache visibility of all sections" t)
    159                  (repeat :tag "Cache visibility for section types" symbol)))
    160 
    161 (defcustom magit-section-initial-visibility-alist
    162   '((stashes . hide))
    163   "Alist controlling the initial visibility of sections.
    164 
    165 Each element maps a section type or lineage to the initial
    166 visibility state for such sections.  The state has to be one of
    167 `show' or `hide', or a function that returns one of these symbols.
    168 A function is called with the section as the only argument.
    169 
    170 Use the command `magit-describe-section' to determine a section's
    171 lineage or type.  The vector in the output is the section lineage
    172 and the type is the first element of that vector.  Wildcards can
    173 be used, see `magit-section-match'.
    174 
    175 Currently this option is only used to override hardcoded defaults,
    176 but in the future it will also be used set the defaults.
    177 
    178 An entry whose key is `magit-status-initial-section' specifies
    179 the visibility of the section `magit-status-goto-initial-section'
    180 jumps to.  This does not only override defaults, but also other
    181 entries of this alist."
    182   :package-version '(magit-section . "2.12.0")
    183   :group 'magit-section
    184   :type '(alist :key-type (sexp :tag "Section type/lineage")
    185                 :value-type (choice (const hide)
    186                                     (const show)
    187                                     function)))
    188 
    189 (defcustom magit-section-visibility-indicator
    190   (if (window-system)
    191       '(magit-fringe-bitmap> . magit-fringe-bitmapv)
    192     (cons (if (char-displayable-p ?…) "…" "...")
    193           t))
    194   "Whether and how to indicate that a section can be expanded/collapsed.
    195 
    196 If nil, then don't show any indicators.
    197 Otherwise the value has to have one of these two forms:
    198 
    199 \(EXPANDABLE-BITMAP . COLLAPSIBLE-BITMAP)
    200 
    201   Both values have to be variables whose values are fringe
    202   bitmaps.  In this case every section that can be expanded or
    203   collapsed gets an indicator in the left fringe.
    204 
    205   To provide extra padding around the indicator, set
    206   `left-fringe-width' in `magit-mode-hook'.
    207 
    208 \(STRING . BOOLEAN)
    209 
    210   In this case STRING (usually an ellipsis) is shown at the end
    211   of the heading of every collapsed section.  Expanded sections
    212   get no indicator.  The cdr controls whether the appearance of
    213   these ellipsis take section highlighting into account.  Doing
    214   so might potentially have an impact on performance, while not
    215   doing so is kinda ugly."
    216   :package-version '(magit-section . "3.0.0")
    217   :group 'magit-section
    218   :type '(choice (const :tag "No indicators" nil)
    219                  (cons  :tag "Use +- fringe indicators"
    220                         (const magit-fringe-bitmap+)
    221                         (const magit-fringe-bitmap-))
    222                  (cons  :tag "Use >v fringe indicators"
    223                         (const magit-fringe-bitmap>)
    224                         (const magit-fringe-bitmapv))
    225                  (cons  :tag "Use bold >v fringe indicators)"
    226                         (const magit-fringe-bitmap-bold>)
    227                         (const magit-fringe-bitmap-boldv))
    228                  (cons  :tag "Use custom fringe indicators"
    229                         (variable :tag "Expandable bitmap variable")
    230                         (variable :tag "Collapsible bitmap variable"))
    231                  (cons  :tag "Use ellipses at end of headings"
    232                         (string :tag "Ellipsis" "…")
    233                         (choice :tag "Use face kludge"
    234                                 (const :tag "Yes (potentially slow)" t)
    235                                 (const :tag "No (kinda ugly)" nil)))))
    236 
    237 (define-obsolete-variable-alias 'magit-keep-region-overlay
    238   'magit-section-keep-region-overlay "Magit-Section 4.0.0")
    239 
    240 (defcustom magit-section-keep-region-overlay nil
    241   "Whether to keep the region overlay when there is a valid selection.
    242 
    243 By default Magit removes the regular region overlay if, and only
    244 if, that region constitutes a valid selection as understood by
    245 Magit commands.  Otherwise it does not remove that overlay, and
    246 the region looks like it would in other buffers.
    247 
    248 There are two types of such valid selections: hunk-internal
    249 regions and regions that select two or more sibling sections.
    250 In such cases Magit removes the region overlay and instead
    251 highlights a slightly larger range.  All text (for hunk-internal
    252 regions) or the headings of all sections (for sibling selections)
    253 that are inside that range (not just inside the region) are acted
    254 on by commands such as the staging command.  This buffer range
    255 begins at the beginning of the line on which the region begins
    256 and ends at the end of the line on which the region ends.
    257 
    258 Because Magit acts on this larger range and not the region, it is
    259 actually quite important to visualize that larger range.  If we
    260 don't do that, then one might think that these commands act on
    261 the region instead.  If you want to *also* visualize the region,
    262 then set this option to t.  But please note that when the region
    263 does *not* constitute a valid selection, then the region is
    264 *always* visualized as usual, and that it is usually under such
    265 circumstances that you want to use a non-magit command to act on
    266 the region.
    267 
    268 Besides keeping the region overlay, setting this option to t also
    269 causes all face properties, except for `:foreground', to be
    270 ignored for the faces used to highlight headings of selected
    271 sections.  This avoids the worst conflicts that result from
    272 displaying the region and the selection overlays at the same
    273 time.  We are not interested in dealing with other conflicts.
    274 In fact we *already* provide a way to avoid all of these
    275 conflicts: *not* changing the value of this option.
    276 
    277 It should be clear by now that we consider it a mistake to set
    278 this to display the region when the Magit selection is also
    279 visualized, but since it has been requested a few times and
    280 because it doesn't cost much to offer this option we do so.
    281 However that might change.  If the existence of this option
    282 starts complicating other things, then it will be removed."
    283   :package-version '(magit-section . "2.3.0")
    284   :group 'magit-section
    285   :type 'boolean)
    286 
    287 (defcustom magit-section-disable-line-numbers t
    288   "In Magit buffers, whether to disable modes that display line numbers.
    289 
    290 Some users who turn on `global-display-line-numbers-mode' (or
    291 `global-nlinum-mode' or `global-linum-mode') expect line numbers
    292 to be displayed everywhere except in Magit buffers.  Other users
    293 do not expect Magit buffers to be treated differently.  At least
    294 in theory users in the first group should not use the global mode,
    295 but that ship has sailed, thus this option."
    296   :package-version '(magit-section . "3.0.0")
    297   :group 'magit-section
    298   :type 'boolean)
    299 
    300 (defcustom magit-section-show-context-menu-for-emacs<28 nil
    301   "Whether `mouse-3' shows a context menu for Emacs < 28.
    302 
    303 This has to be set before loading `magit-section' or it has
    304 no effect.  This also has no effect for Emacs >= 28, where
    305 `context-menu-mode' should be enabled instead."
    306   :package-version '(magit-section . "4.0.0")
    307   :group 'magit-section
    308   :type 'boolean)
    309 
    310 ;;; Variables
    311 
    312 (defvar-local magit-section-preserve-visibility t)
    313 
    314 (defvar-local magit-section-pre-command-region-p nil)
    315 (defvar-local magit-section-pre-command-section nil)
    316 (defvar-local magit-section-highlight-force-update nil)
    317 (defvar-local magit-section-highlight-overlays nil)
    318 (defvar-local magit-section-highlighted-sections nil)
    319 (defvar-local magit-section-unhighlight-sections nil)
    320 
    321 (defvar-local magit-section-inhibit-markers nil)
    322 (defvar-local magit-section-insert-in-reverse nil)
    323 
    324 ;;; Faces
    325 
    326 (defgroup magit-section-faces nil
    327   "Faces used by Magit-Section."
    328   :group 'magit-section
    329   :group 'faces)
    330 
    331 (defface magit-section-highlight
    332   `((((class color) (background light))
    333      ,@(and (>= emacs-major-version 27) '(:extend t))
    334      :background "grey95")
    335     (((class color) (background  dark))
    336      ,@(and (>= emacs-major-version 27) '(:extend t))
    337      :background "grey20"))
    338   "Face for highlighting the current section."
    339   :group 'magit-section-faces)
    340 
    341 (defface magit-section-heading
    342   `((((class color) (background light))
    343      ,@(and (>= emacs-major-version 27) '(:extend t))
    344      :foreground "DarkGoldenrod4"
    345      :weight bold)
    346     (((class color) (background  dark))
    347      ,@(and (>= emacs-major-version 27) '(:extend t))
    348      :foreground "LightGoldenrod2"
    349      :weight bold))
    350   "Face for section headings."
    351   :group 'magit-section-faces)
    352 
    353 (defface magit-section-secondary-heading
    354   `((t ,@(and (>= emacs-major-version 27) '(:extend t))
    355        :weight bold))
    356   "Face for section headings of some secondary headings."
    357   :group 'magit-section-faces)
    358 
    359 (defface magit-section-heading-selection
    360   `((((class color) (background light))
    361      ,@(and (>= emacs-major-version 27) '(:extend t))
    362      :foreground "salmon4")
    363     (((class color) (background  dark))
    364      ,@(and (>= emacs-major-version 27) '(:extend t))
    365      :foreground "LightSalmon3"))
    366   "Face for selected section headings."
    367   :group 'magit-section-faces)
    368 
    369 (defface magit-section-child-count '((t nil))
    370   "Face used for child counts at the end of some section headings."
    371   :group 'magit-section-faces)
    372 
    373 ;;; Classes
    374 
    375 (defvar magit--current-section-hook nil
    376   "Internal variable used for `magit-describe-section'.")
    377 
    378 (defvar magit--section-type-alist nil)
    379 
    380 (defclass magit-section ()
    381   ((type     :initform nil :initarg :type)
    382    (keymap   :initform nil)
    383    (value    :initform nil)
    384    (start    :initform nil)
    385    (content  :initform nil)
    386    (end      :initform nil)
    387    (hidden)
    388    (washer   :initform nil :initarg :washer)
    389    (inserter :initform (symbol-value 'magit--current-section-hook))
    390    (heading-highlight-face :initform nil :initarg :heading-highlight-face)
    391    (parent   :initform nil)
    392    (children :initform nil)))
    393 
    394 ;;; Mode
    395 
    396 (defvar symbol-overlay-inhibit-map)
    397 
    398 (defvar-keymap magit-section-heading-map
    399   :doc "Keymap used in the heading line of all expandable sections.
    400 This keymap is used in addition to the section-specific keymap,
    401 if any."
    402   "<double-down-mouse-1>" #'ignore
    403   "<double-mouse-1>" #'magit-mouse-toggle-section
    404   "<double-mouse-2>" #'magit-mouse-toggle-section)
    405 
    406 (defvar magit-section-mode-map
    407   (let ((map (make-keymap)))
    408     (suppress-keymap map t)
    409     (when (and magit-section-show-context-menu-for-emacs<28
    410                (< emacs-major-version 28))
    411       (keymap-set map "<mouse-3>" nil)
    412       (keymap-set
    413        map "<down-mouse-3>"
    414        `( menu-item "" ,(make-sparse-keymap)
    415           :filter ,(lambda (_)
    416                      (let ((menu (make-sparse-keymap)))
    417                        (if (fboundp 'context-menu-local)
    418                            (context-menu-local menu last-input-event)
    419                          (magit--context-menu-local menu last-input-event))
    420                        (magit-section-context-menu menu last-input-event)
    421                        menu)))))
    422     (keymap-set map "<left-fringe> <mouse-1>" #'magit-mouse-toggle-section)
    423     (keymap-set map "<left-fringe> <mouse-2>" #'magit-mouse-toggle-section)
    424     (keymap-set map "TAB"       #'magit-section-toggle)
    425     (keymap-set map "C-c TAB"   #'magit-section-cycle)
    426     (keymap-set map "C-<tab>"   #'magit-section-cycle)
    427     (keymap-set map "M-<tab>"   #'magit-section-cycle)
    428     ;; <backtab> is the most portable binding for Shift+Tab.
    429     (keymap-set map "<backtab>" #'magit-section-cycle-global)
    430     (keymap-set map   "^" #'magit-section-up)
    431     (keymap-set map   "p" #'magit-section-backward)
    432     (keymap-set map   "n" #'magit-section-forward)
    433     (keymap-set map "M-p" #'magit-section-backward-sibling)
    434     (keymap-set map "M-n" #'magit-section-forward-sibling)
    435     (keymap-set map   "1" #'magit-section-show-level-1)
    436     (keymap-set map   "2" #'magit-section-show-level-2)
    437     (keymap-set map   "3" #'magit-section-show-level-3)
    438     (keymap-set map   "4" #'magit-section-show-level-4)
    439     (keymap-set map "M-1" #'magit-section-show-level-1-all)
    440     (keymap-set map "M-2" #'magit-section-show-level-2-all)
    441     (keymap-set map "M-3" #'magit-section-show-level-3-all)
    442     (keymap-set map "M-4" #'magit-section-show-level-4-all)
    443     map)
    444   "Parent keymap for all keymaps of modes derived from `magit-section-mode'.")
    445 
    446 (define-derived-mode magit-section-mode special-mode "Magit-Sections"
    447   "Parent major mode from which major modes with Magit-like sections inherit.
    448 
    449 Magit-Section is documented in info node `(magit-section)'."
    450   :group 'magit-section
    451   (buffer-disable-undo)
    452   (setq truncate-lines t)
    453   (setq buffer-read-only t)
    454   (setq-local line-move-visual t) ; see #1771
    455   ;; Turn off syntactic font locking, but not by setting
    456   ;; `font-lock-defaults' because that would enable font locking, and
    457   ;; not all magit plugins may be ready for that (see #3950).
    458   (setq-local font-lock-syntactic-face-function #'ignore)
    459   (setq show-trailing-whitespace nil)
    460   (setq-local symbol-overlay-inhibit-map t)
    461   (setq list-buffers-directory (abbreviate-file-name default-directory))
    462   ;; (hack-dir-local-variables-non-file-buffer)
    463   (make-local-variable 'text-property-default-nonsticky)
    464   (push (cons 'keymap t) text-property-default-nonsticky)
    465   (add-hook 'pre-command-hook #'magit-section-pre-command-hook nil t)
    466   (add-hook 'post-command-hook #'magit-section-post-command-hook t t)
    467   (add-hook 'deactivate-mark-hook #'magit-section-deactivate-mark t t)
    468   (setq-local redisplay-highlight-region-function
    469               #'magit-section--highlight-region)
    470   (setq-local redisplay-unhighlight-region-function
    471               #'magit-section--unhighlight-region)
    472   (add-function :filter-return (local 'filter-buffer-substring-function)
    473                 #'magit-section--remove-text-properties)
    474   (when (fboundp 'magit-section-context-menu)
    475     (add-hook 'context-menu-functions #'magit-section-context-menu 10 t))
    476   (when magit-section-disable-line-numbers
    477     (when (and (fboundp 'linum-mode)
    478                (bound-and-true-p global-linum-mode))
    479       (linum-mode -1))
    480     (when (and (fboundp 'nlinum-mode)
    481                (bound-and-true-p global-nlinum-mode))
    482       (nlinum-mode -1))
    483     (when (and (fboundp 'display-line-numbers-mode)
    484                (bound-and-true-p global-display-line-numbers-mode))
    485       (display-line-numbers-mode -1)))
    486   (when (fboundp 'magit-preserve-section-visibility-cache)
    487     (add-hook 'kill-buffer-hook #'magit-preserve-section-visibility-cache)))
    488 
    489 (defun magit-section--remove-text-properties (string)
    490   "Remove all text-properties from STRING.
    491 Most importantly `magit-section'."
    492   (set-text-properties 0 (length string) nil string)
    493   string)
    494 
    495 ;;; Core
    496 
    497 (defvar-local magit-root-section nil
    498   "The root section in the current buffer.
    499 All other sections are descendants of this section.  The value
    500 of this variable is set by `magit-insert-section' and you should
    501 never modify it.")
    502 (put 'magit-root-section 'permanent-local t)
    503 
    504 (defvar-local magit--context-menu-section nil "For internal use only.")
    505 
    506 (defvar magit--context-menu-buffer nil "For internal use only.")
    507 
    508 (defun magit-point ()
    509   "Return point or the position where the context menu was invoked.
    510 When using the context menu, return the position the user clicked
    511 on, provided the current buffer is the buffer in which the click
    512 occurred.  Otherwise return the same value as `point'."
    513   (if magit--context-menu-section
    514       (magit-menu-position)
    515     (point)))
    516 
    517 (defun magit-thing-at-point (thing &optional no-properties)
    518   "Return the THING at point or where the context menu was invoked.
    519 When using the context menu, return the thing the user clicked
    520 on, provided the current buffer is the buffer in which the click
    521 occurred.  Otherwise return the same value as `thing-at-point'.
    522 For the meaning of THING and NO-PROPERTIES see that function."
    523   (if-let ((pos (magit-menu-position)))
    524       (save-excursion
    525         (goto-char pos)
    526         (thing-at-point thing no-properties))
    527     (thing-at-point thing no-properties)))
    528 
    529 (defun magit-current-section ()
    530   "Return the section at point or where the context menu was invoked.
    531 When using the context menu, return the section that the user
    532 clicked on, provided the current buffer is the buffer in which
    533 the click occurred.  Otherwise return the section at point."
    534   (or magit--context-menu-section
    535       (magit-section-at)
    536       magit-root-section))
    537 
    538 (defun magit-section-at (&optional position)
    539   "Return the section at POSITION, defaulting to point."
    540   (get-text-property (or position (point)) 'magit-section))
    541 
    542 (defun magit-section-ident (section)
    543   "Return an unique identifier for SECTION.
    544 The return value has the form ((TYPE . VALUE)...)."
    545   (cons (cons (oref section type)
    546               (magit-section-ident-value section))
    547         (and-let* ((parent (oref section parent)))
    548           (magit-section-ident parent))))
    549 
    550 (cl-defgeneric magit-section-ident-value (object)
    551   "Return OBJECT's value, making it constant and unique if necessary.
    552 
    553 This is used to correlate different incarnations of the same
    554 section, see `magit-section-ident' and `magit-get-section'.
    555 
    556 Sections whose values that are not constant and/or unique should
    557 implement a method that return a value that can be used for this
    558 purpose.")
    559 
    560 (cl-defmethod magit-section-ident-value ((section magit-section))
    561   "Return the value unless it is an object.
    562 
    563 Different object incarnations representing the same value tend to not be
    564 equal, so call this generic function on the object itself to determine a
    565 constant value."
    566   (let ((value (oref section value)))
    567     (if (eieio-object-p value)
    568         (magit-section-ident-value value)
    569       value)))
    570 
    571 (cl-defmethod magit-section-ident-value ((object eieio-default-superclass))
    572   "Simply return the object itself.  That likely isn't
    573 good enough, so you need to implement your own method."
    574   object)
    575 
    576 (defun magit-get-section (ident &optional root)
    577   "Return the section identified by IDENT.
    578 IDENT has to be a list as returned by `magit-section-ident'.
    579 If optional ROOT is non-nil, then search in that section tree
    580 instead of in the one whose root `magit-root-section' is."
    581   (setq ident (reverse ident))
    582   (let ((section (or root magit-root-section)))
    583     (when (eq (car (pop ident))
    584               (oref section type))
    585       (while (and ident
    586                   (pcase-let ((`(,type . ,value) (car ident)))
    587                     (setq section
    588                           (cl-find-if
    589                            (lambda (section)
    590                              (and (eq (oref section type) type)
    591                                   (equal (magit-section-ident-value section)
    592                                          value)))
    593                            (oref section children)))))
    594         (pop ident))
    595       section)))
    596 
    597 (defun magit-section-lineage (section &optional raw)
    598   "Return the lineage of SECTION.
    599 If optional RAW is non-nil, return a list of section objects, beginning
    600 with SECTION, otherwise return a list of section types."
    601   (cons (if raw section (oref section type))
    602         (and-let* ((parent (oref section parent)))
    603           (magit-section-lineage parent raw))))
    604 
    605 (defvar magit-insert-section--current nil "For internal use only.")
    606 (defvar magit-insert-section--parent  nil "For internal use only.")
    607 (defvar magit-insert-section--oldroot nil "For internal use only.")
    608 
    609 ;;; Menu
    610 
    611 (defvar magit-menu-common-value nil "See function `magit-menu-common-value'.")
    612 (defvar magit-menu--desc-values nil "For internal use only.")
    613 
    614 (defun magit-section-context-menu (menu click)
    615   "Populate MENU with Magit-Section commands at CLICK."
    616   (when-let ((section (save-excursion
    617                         (unless (region-active-p)
    618                           (mouse-set-point click))
    619                         (magit-section-at))))
    620     (unless (region-active-p)
    621       (setq magit--context-menu-buffer (current-buffer))
    622       (if-let ((alt (save-excursion
    623                       (mouse-set-point click)
    624                       (run-hook-with-args-until-success
    625                        'magit-menu-alternative-section-hook section))))
    626           (setq magit--context-menu-section (setq section alt))
    627         (setq magit--context-menu-section section)
    628         (magit-section-update-highlight t)))
    629     (when (magit-section-content-p section)
    630       (keymap-set-after menu "<magit-section-toggle>"
    631         `(menu-item
    632           ,(if (oref section hidden) "Expand section" "Collapse section")
    633           magit-section-toggle))
    634       (unless (oref section hidden)
    635         (when-let ((children (oref section children)))
    636           (when (seq-some #'magit-section-content-p children)
    637             (when (seq-some (lambda (c) (oref c hidden)) children)
    638               (keymap-set-after menu "<magit-section-show-children>"
    639                 `(menu-item "Expand children"
    640                             magit-section-show-children)))
    641             (when (seq-some (lambda (c) (not (oref c hidden))) children)
    642               (keymap-set-after menu "<magit-section-hide-children>"
    643                 `(menu-item "Collapse children"
    644                             magit-section-hide-children))))))
    645       (keymap-set-after menu "<separator-magit-1>" menu-bar-separator))
    646     (keymap-set-after menu "<magit-describe-section>"
    647       `(menu-item "Describe section" magit-describe-section))
    648     (when-let ((map (oref section keymap)))
    649       (keymap-set-after menu "<separator-magit-2>" menu-bar-separator)
    650       (when (symbolp map)
    651         (setq map (symbol-value map)))
    652       (setq magit-menu-common-value (magit-menu-common-value section))
    653       (setq magit-menu--desc-values (magit-menu--desc-values section))
    654       (map-keymap (lambda (key binding)
    655                     (when (consp binding)
    656                       (define-key-after menu (vector key)
    657                         (copy-sequence binding))))
    658                   (if (fboundp 'menu-bar-keymap)
    659                       (menu-bar-keymap map)
    660                     (magit--menu-bar-keymap map)))))
    661   menu)
    662 
    663 (defun magit-menu-item (desc def &optional props)
    664   "Return a menu item named DESC binding DEF and using PROPS.
    665 
    666 If DESC contains a supported %-spec, substitute the
    667 expression (magit-menu-format-desc DESC) for that.
    668 See `magit-menu-format-desc'."
    669   `(menu-item
    670     ,(if (and (stringp desc) (string-match-p "%[tTvsmMx]" desc))
    671          (list 'magit-menu-format-desc desc)
    672        desc)
    673     ,def
    674     ;; Without this, the keys for point would be shown instead
    675     ;; of the relevant ones from where the click occurred.
    676     :keys ,(apply-partially #'magit--menu-position-keys def)
    677     ,@props))
    678 
    679 (defun magit--menu-position-keys (def)
    680   (or (ignore-errors
    681         (save-excursion
    682           (goto-char (magit-menu-position))
    683           (and-let* ((key (cl-find-if-not
    684                            (lambda (key)
    685                              (string-match-p "\\`<[0-9]+>\\'"
    686                                              (key-description key)))
    687                            (where-is-internal def))))
    688             (key-description key))))
    689       ""))
    690 
    691 (defun magit-menu-position ()
    692   "Return the position where the context-menu was invoked.
    693 If the current command wasn't invoked using the context-menu,
    694 then return nil."
    695   (and magit--context-menu-section
    696        (ignore-errors
    697          (posn-point (event-start (aref (this-command-keys-vector) 0))))))
    698 
    699 (defun magit-menu-highlight-point-section ()
    700   (setq magit-section-highlight-force-update t)
    701   (if (eq (current-buffer) magit--context-menu-buffer)
    702       (setq magit--context-menu-section nil)
    703     (if-let ((window (get-buffer-window magit--context-menu-buffer)))
    704         (with-selected-window window
    705           (setq magit--context-menu-section nil)
    706           (magit-section-update-highlight))
    707       (with-current-buffer magit--context-menu-buffer
    708         (setq magit--context-menu-section nil))))
    709   (setq magit--context-menu-buffer nil))
    710 
    711 (defvar magit--plural-append-es '(branch))
    712 
    713 (cl-defgeneric magit-menu-common-value (_section)
    714   "Return some value to be used by multiple menu items.
    715 This function is called by `magit-section-context-menu', which
    716 stores the value in `magit-menu-common-value'.  Individual menu
    717 items can use it, e.g., in the expression used to set their
    718 description."
    719   nil)
    720 
    721 (defun magit-menu--desc-values (section)
    722   (let ((type (oref section type))
    723         (value (oref section value))
    724         (multiple (magit-region-sections nil t)))
    725     (list type
    726           value
    727           (format "%s %s" type value)
    728           (and multiple (length multiple))
    729           (if (memq type magit--plural-append-es) "es" "s"))))
    730 
    731 (defun magit-menu-format-desc (format)
    732   "Format a string based on FORMAT and menu section or selection.
    733 The following %-specs are allowed:
    734 %t means \"TYPE\".
    735 %T means \"TYPE\", or \"TYPEs\" if multiple sections are selected.
    736 %v means \"VALUE\".
    737 %s means \"TYPE VALUE\".
    738 %m means \"TYPE VALUE\", or \"COUNT TYPEs\" if multiple sections
    739    are selected.
    740 %M means \"VALUE\", or \"COUNT TYPEs\" if multiple sections are
    741    selected.
    742 %x means the value of `magit-menu-common-value'."
    743   (pcase-let* ((`(,type ,value ,single ,count ,suffix) magit-menu--desc-values)
    744                (multiple (and count (format "%s %s%s" count type suffix))))
    745     (format-spec format
    746                  `((?t . ,type)
    747                    (?T . ,(format "%s%s" type (if count suffix "")))
    748                    (?v . ,value)
    749                    (?s . ,single)
    750                    (?m . ,(or multiple single))
    751                    (?M . ,(or multiple value))
    752                    (?x . ,(format "%s" magit-menu-common-value))))))
    753 
    754 (defun magit--menu-bar-keymap (keymap)
    755   "Backport of `menu-bar-keymap' for Emacs < 28.
    756 Slight trimmed down."
    757   (let ((menu-bar nil))
    758     (map-keymap (lambda (key binding)
    759                   (push (cons key binding) menu-bar))
    760                 keymap)
    761     (cons 'keymap (nreverse menu-bar))))
    762 
    763 (defun magit--context-menu-local (menu _click)
    764   "Backport of `context-menu-local' for Emacs < 28."
    765   (run-hooks 'activate-menubar-hook 'menu-bar-update-hook)
    766   (keymap-set-after menu "<separator-local>" menu-bar-separator)
    767   (let ((keymap (local-key-binding [menu-bar])))
    768     (when keymap
    769       (map-keymap (lambda (key binding)
    770                     (when (consp binding)
    771                       (define-key-after menu (vector key)
    772                         (copy-sequence binding))))
    773                   (magit--menu-bar-keymap keymap))))
    774   menu)
    775 
    776 (define-advice context-menu-region (:around (fn menu click) magit-section-mode)
    777   "Disable in `magit-section-mode' buffers."
    778   (if (derived-mode-p 'magit-section-mode)
    779       menu
    780     (funcall fn menu click)))
    781 
    782 ;;; Commands
    783 ;;;; Movement
    784 
    785 (defun magit-section-forward ()
    786   "Move to the beginning of the next visible section."
    787   (interactive)
    788   (if (eobp)
    789       (user-error "No next section")
    790     (let ((section (magit-current-section)))
    791       (if (oref section parent)
    792           (let ((next (and (not (oref section hidden))
    793                            (not (= (oref section end)
    794                                    (1+ (point))))
    795                            (car (oref section children)))))
    796             (while (and section (not next))
    797               (unless (setq next (car (magit-section-siblings section 'next)))
    798                 (setq section (oref section parent))))
    799             (if next
    800                 (magit-section-goto next)
    801               (user-error "No next section")))
    802         (magit-section-goto 1)))))
    803 
    804 (defun magit-section-backward ()
    805   "Move to the beginning of the current or the previous visible section.
    806 When point is at the beginning of a section then move to the
    807 beginning of the previous visible section.  Otherwise move to
    808 the beginning of the current section."
    809   (interactive)
    810   (if (bobp)
    811       (user-error "No previous section")
    812     (let ((section (magit-current-section)) children)
    813       (cond
    814        ((and (= (point)
    815                 (1- (oref section end)))
    816              (setq children (oref section children)))
    817         (magit-section-goto (car (last children))))
    818        ((and (oref section parent)
    819              (not (= (point)
    820                      (oref section start))))
    821         (magit-section-goto section))
    822        (t
    823         (let ((prev (car (magit-section-siblings section 'prev))))
    824           (if prev
    825               (while (and (not (oref prev hidden))
    826                           (setq children (oref prev children)))
    827                 (setq prev (car (last children))))
    828             (setq prev (oref section parent)))
    829           (cond (prev
    830                  (magit-section-goto prev))
    831                 ((oref section parent)
    832                  (user-error "No previous section"))
    833                 ;; Eob special cases.
    834                 ((not (get-text-property (1- (point)) 'invisible))
    835                  (magit-section-goto -1))
    836                 (t
    837                  (goto-char (previous-single-property-change
    838                              (1- (point)) 'invisible))
    839                  (forward-line -1)
    840                  (magit-section-goto (magit-current-section))))))))))
    841 
    842 (defun magit-section-up ()
    843   "Move to the beginning of the parent section."
    844   (interactive)
    845   (if-let ((parent (oref (magit-current-section) parent)))
    846       (magit-section-goto parent)
    847     (user-error "No parent section")))
    848 
    849 (defun magit-section-forward-sibling ()
    850   "Move to the beginning of the next sibling section.
    851 If there is no next sibling section, then move to the parent."
    852   (interactive)
    853   (let ((current (magit-current-section)))
    854     (if (oref current parent)
    855         (if-let ((next (car (magit-section-siblings current 'next))))
    856             (magit-section-goto next)
    857           (magit-section-forward))
    858       (magit-section-goto 1))))
    859 
    860 (defun magit-section-backward-sibling ()
    861   "Move to the beginning of the previous sibling section.
    862 If there is no previous sibling section, then move to the parent."
    863   (interactive)
    864   (let ((current (magit-current-section)))
    865     (if (oref current parent)
    866         (if-let ((previous (car (magit-section-siblings current 'prev))))
    867             (magit-section-goto previous)
    868           (magit-section-backward))
    869       (magit-section-goto -1))))
    870 
    871 (defun magit-section-goto (arg)
    872   (if (integerp arg)
    873       (progn (forward-line arg)
    874              (setq arg (magit-current-section)))
    875     (goto-char (oref arg start)))
    876   (run-hook-with-args 'magit-section-movement-hook arg))
    877 
    878 (defun magit-section-set-window-start (section)
    879   "Ensure the beginning of SECTION is visible."
    880   (unless (pos-visible-in-window-p (oref section end))
    881     (set-window-start (selected-window) (oref section start))))
    882 
    883 (defmacro magit-define-section-jumper (name heading type &optional value)
    884   "Define an interactive function to go some section.
    885 Together TYPE and VALUE identify the section.
    886 HEADING is the displayed heading of the section."
    887   (declare (indent defun))
    888   `(defun ,name (&optional expand)
    889      ,(format "Jump to the section \"%s\".
    890 With a prefix argument also expand it." heading)
    891      (interactive "P")
    892      (if-let ((section (magit-get-section
    893                         (cons (cons ',type ,value)
    894                               (magit-section-ident magit-root-section)))))
    895          (progn (goto-char (oref section start))
    896                 (when expand
    897                   (with-local-quit (magit-section-show section))
    898                   (recenter 0)))
    899        (message ,(format "Section \"%s\" wasn't found" heading)))))
    900 
    901 ;;;; Visibility
    902 
    903 (defun magit-section-show (section)
    904   "Show the body of the current section."
    905   (interactive (list (magit-current-section)))
    906   (oset section hidden nil)
    907   (magit-section--maybe-wash section)
    908   (when-let ((beg (oref section content)))
    909     (remove-overlays beg (oref section end) 'invisible t))
    910   (magit-section-maybe-update-visibility-indicator section)
    911   (magit-section-maybe-cache-visibility section)
    912   (dolist (child (oref section children))
    913     (if (oref child hidden)
    914         (magit-section-hide child)
    915       (magit-section-show child))))
    916 
    917 (defun magit-section--maybe-wash (section)
    918   (when-let ((washer (oref section washer)))
    919     (oset section washer nil)
    920     (let ((inhibit-read-only t)
    921           (magit-insert-section--parent section)
    922           (magit-insert-section--current section)
    923           (content (oref section content)))
    924       (save-excursion
    925         (if (and content (< content (oref section end)))
    926             (funcall washer section) ; already partially washed (hunk)
    927           (goto-char (oref section end))
    928           (oset section content (point-marker))
    929           (funcall washer)
    930           (oset section end (point-marker)))))
    931     (setq magit-section-highlight-force-update t)))
    932 
    933 (defun magit-section-hide (section)
    934   "Hide the body of the current section."
    935   (interactive (list (magit-current-section)))
    936   (if (eq section magit-root-section)
    937       (user-error "Cannot hide root section")
    938     (oset section hidden t)
    939     (when-let ((beg (oref section content)))
    940       (let ((end (oref section end)))
    941         (when (< beg (point) end)
    942           (goto-char (oref section start)))
    943         (remove-overlays beg end 'invisible t)
    944         (let ((o (make-overlay beg end)))
    945           (overlay-put o 'evaporate t)
    946           (overlay-put o 'invisible t)
    947           (overlay-put o 'cursor-intangible t))))
    948     (magit-section-maybe-update-visibility-indicator section)
    949     (magit-section-maybe-cache-visibility section)))
    950 
    951 (defun magit-section-toggle (section)
    952   "Toggle visibility of the body of the current section."
    953   (interactive (list (magit-current-section)))
    954   (cond ((eq section magit-root-section)
    955          (user-error "Cannot hide root section"))
    956         ((oref section hidden)
    957          (magit-section-show section))
    958         ((magit-section-hide section))))
    959 
    960 (defun magit-section-toggle-children (section)
    961   "Toggle visibility of bodies of children of the current section."
    962   (interactive (list (magit-current-section)))
    963   (let* ((children (oref section children))
    964          (show (--any-p (oref it hidden) children)))
    965     (dolist (c children)
    966       (oset c hidden show)))
    967   (magit-section-show section))
    968 
    969 (defun magit-section-show-children (section &optional depth)
    970   "Recursively show the bodies of children of the current section.
    971 With a prefix argument show children that deep and hide deeper
    972 children."
    973   (interactive (list (magit-current-section)))
    974   (magit-section-show-children-1 section depth)
    975   (magit-section-show section))
    976 
    977 (defun magit-section-show-children-1 (section &optional depth)
    978   (dolist (child (oref section children))
    979     (oset child hidden nil)
    980     (if depth
    981         (if (> depth 0)
    982             (magit-section-show-children-1 child (1- depth))
    983           (magit-section-hide child))
    984       (magit-section-show-children-1 child))))
    985 
    986 (defun magit-section-hide-children (section)
    987   "Recursively hide the bodies of children of the current section."
    988   (interactive (list (magit-current-section)))
    989   (mapc #'magit-section-hide (oref section children)))
    990 
    991 (defun magit-section-show-headings (section)
    992   "Recursively show headings of children of the current section.
    993 Only show the headings, previously shown text-only bodies are
    994 hidden."
    995   (interactive (list (magit-current-section)))
    996   (magit-section-show-headings-1 section)
    997   (magit-section-show section))
    998 
    999 (defun magit-section-show-headings-1 (section)
   1000   (dolist (child (oref section children))
   1001     (oset child hidden nil)
   1002     (when (or (oref child children)
   1003               (not (oref child content)))
   1004       (magit-section-show-headings-1 child))))
   1005 
   1006 (defun magit-section-cycle (section)
   1007   "Cycle visibility of current section and its children.
   1008 
   1009 If this command is invoked using \\`C-<tab>' and that is globally bound
   1010 to `tab-next', then this command pivots to behave like that command, and
   1011 you must instead use \\`C-c TAB' to cycle section visibility.
   1012 
   1013 If you would like to keep using \\`C-<tab>' to cycle section visibility
   1014 but also want to use `tab-bar-mode', then you have to prevent that mode
   1015 from using this key and instead bind another key to `tab-next'.  Because
   1016 `tab-bar-mode' does not use a mode map but instead manipulates the
   1017 global map, this involves advising `tab-bar--define-keys'."
   1018   (interactive (list (magit-current-section)))
   1019   (cond
   1020    ((and (equal (this-command-keys) [C-tab])
   1021          (eq (global-key-binding [C-tab]) 'tab-next)
   1022          (fboundp 'tab-bar-switch-to-next-tab))
   1023     (tab-bar-switch-to-next-tab current-prefix-arg))
   1024    ((oref section hidden)
   1025     (magit-section-show section)
   1026     (magit-section-hide-children section))
   1027    ((let ((children (oref section children)))
   1028       (cond ((and (--any-p (oref it hidden)   children)
   1029                   (--any-p (oref it children) children))
   1030              (magit-section-show-headings section))
   1031             ((seq-some #'magit-section-hidden-body children)
   1032              (magit-section-show-children section))
   1033             ((magit-section-hide section)))))))
   1034 
   1035 (defun magit-section-cycle-global ()
   1036   "Cycle visibility of all sections in the current buffer."
   1037   (interactive)
   1038   (let ((children (oref magit-root-section children)))
   1039     (cond ((and (--any-p (oref it hidden)   children)
   1040                 (--any-p (oref it children) children))
   1041            (magit-section-show-headings magit-root-section))
   1042           ((seq-some #'magit-section-hidden-body children)
   1043            (magit-section-show-children magit-root-section))
   1044           (t
   1045            (mapc #'magit-section-hide children)))))
   1046 
   1047 (defun magit-section-hidden-body (section &optional pred)
   1048   (if-let ((children (oref section children)))
   1049       (funcall (or pred #'-any-p) #'magit-section-hidden-body children)
   1050     (and (oref section content)
   1051          (oref section hidden))))
   1052 
   1053 (defun magit-section-content-p (section)
   1054   "Return non-nil if SECTION has content or an unused washer function."
   1055   (with-slots (content end washer) section
   1056     (and content (or (not (= content end)) washer))))
   1057 
   1058 (defun magit-section-invisible-p (section)
   1059   "Return t if the SECTION's body is invisible.
   1060 When the body of an ancestor of SECTION is collapsed then
   1061 SECTION's body (and heading) obviously cannot be visible."
   1062   (or (oref section hidden)
   1063       (and-let* ((parent (oref section parent)))
   1064         (magit-section-invisible-p parent))))
   1065 
   1066 (defun magit-section-show-level (level)
   1067   "Show surrounding sections up to LEVEL.
   1068 If LEVEL is negative, show up to the absolute value.
   1069 Sections at higher levels are hidden."
   1070   (if (< level 0)
   1071       (let ((s (magit-current-section)))
   1072         (setq level (- level))
   1073         (while (> (1- (length (magit-section-ident s))) level)
   1074           (setq s (oref s parent))
   1075           (goto-char (oref s start)))
   1076         (magit-section-show-children magit-root-section (1- level)))
   1077     (cl-do* ((s (magit-current-section)
   1078                 (oref s parent))
   1079              (i (1- (length (magit-section-ident s)))
   1080                 (cl-decf i)))
   1081         ((cond ((< i level) (magit-section-show-children s (- level i 1)) t)
   1082                ((= i level) (magit-section-hide s) t))
   1083          (magit-section-goto s)))))
   1084 
   1085 (defun magit-section-show-level-1 ()
   1086   "Show surrounding sections on first level."
   1087   (interactive)
   1088   (magit-section-show-level 1))
   1089 
   1090 (defun magit-section-show-level-1-all ()
   1091   "Show all sections on first level."
   1092   (interactive)
   1093   (magit-section-show-level -1))
   1094 
   1095 (defun magit-section-show-level-2 ()
   1096   "Show surrounding sections up to second level."
   1097   (interactive)
   1098   (magit-section-show-level 2))
   1099 
   1100 (defun magit-section-show-level-2-all ()
   1101   "Show all sections up to second level."
   1102   (interactive)
   1103   (magit-section-show-level -2))
   1104 
   1105 (defun magit-section-show-level-3 ()
   1106   "Show surrounding sections up to third level."
   1107   (interactive)
   1108   (magit-section-show-level 3))
   1109 
   1110 (defun magit-section-show-level-3-all ()
   1111   "Show all sections up to third level."
   1112   (interactive)
   1113   (magit-section-show-level -3))
   1114 
   1115 (defun magit-section-show-level-4 ()
   1116   "Show surrounding sections up to fourth level."
   1117   (interactive)
   1118   (magit-section-show-level 4))
   1119 
   1120 (defun magit-section-show-level-4-all ()
   1121   "Show all sections up to fourth level."
   1122   (interactive)
   1123   (magit-section-show-level -4))
   1124 
   1125 (defun magit-mouse-toggle-section (event)
   1126   "Toggle visibility of the clicked section.
   1127 Clicks outside either the section heading or the left fringe are
   1128 silently ignored."
   1129   (interactive "e")
   1130   (let* ((pos (event-start event))
   1131          (section (magit-section-at (posn-point pos))))
   1132     (if (eq (posn-area pos) 'left-fringe)
   1133         (when section
   1134           (while (not (magit-section-content-p section))
   1135             (setq section (oref section parent)))
   1136           (unless (eq section magit-root-section)
   1137             (goto-char (oref section start))
   1138             (magit-section-toggle section)))
   1139       (magit-section-toggle section))))
   1140 
   1141 ;;;; Auxiliary
   1142 
   1143 (defun magit-describe-section-briefly (section &optional ident interactive)
   1144   "Show information about the section at point.
   1145 With a prefix argument show the section identity instead of the
   1146 section lineage.  This command is intended for debugging purposes.
   1147 \n(fn SECTION &optional IDENT)"
   1148   (interactive (list (magit-current-section) current-prefix-arg t))
   1149   (let ((str (format "#<%s %S %S %s-%s%s>"
   1150                      (eieio-object-class section)
   1151                      (let ((val (oref section value)))
   1152                        (cond ((stringp val)
   1153                               (substring-no-properties val))
   1154                              ((and (eieio-object-p val)
   1155                                    (fboundp 'cl-prin1-to-string))
   1156                               (cl-prin1-to-string val))
   1157                              (t
   1158                               val)))
   1159                      (if ident
   1160                          (magit-section-ident section)
   1161                        (apply #'vector (magit-section-lineage section)))
   1162                      (and-let* ((m (oref section start)))
   1163                        (if (markerp m) (marker-position m) m))
   1164                      (if-let ((m (oref section content)))
   1165                          (format "[%s-]"
   1166                                  (if (markerp m) (marker-position m) m))
   1167                        "")
   1168                      (and-let* ((m (oref section end)))
   1169                        (if (markerp m) (marker-position m) m)))))
   1170     (when interactive
   1171       (message "%s" str))
   1172     str))
   1173 
   1174 (cl-defmethod cl-print-object ((section magit-section) stream)
   1175   "Print `magit-describe-section' result of SECTION."
   1176   ;; Used by debug and edebug as of Emacs 26.
   1177   (princ (magit-describe-section-briefly section) stream))
   1178 
   1179 (defun magit-describe-section (section &optional interactive-p)
   1180   "Show information about the section at point."
   1181   (interactive (list (magit-current-section) t))
   1182   (let ((inserter-section section))
   1183     (while (and inserter-section (not (oref inserter-section inserter)))
   1184       (setq inserter-section (oref inserter-section parent)))
   1185     (when (and inserter-section (oref inserter-section inserter))
   1186       (setq section inserter-section)))
   1187   (pcase (oref section inserter)
   1188     (`((,hook ,fun) . ,src-src)
   1189      (help-setup-xref `(magit-describe-section ,section) interactive-p)
   1190      (with-help-window (help-buffer)
   1191        (with-current-buffer standard-output
   1192          (insert (format-message
   1193                   "%s\n  is inserted by `%s'\n  from `%s'"
   1194                   (magit-describe-section-briefly section)
   1195                   (make-text-button (symbol-name fun) nil
   1196                                     :type 'help-function
   1197                                     'help-args (list fun))
   1198                   (make-text-button (symbol-name hook) nil
   1199                                     :type 'help-variable
   1200                                     'help-args (list hook))))
   1201          (pcase-dolist (`(,hook ,fun) src-src)
   1202            (insert (format-message
   1203                     ",\n  called by `%s'\n  from `%s'"
   1204                     (make-text-button (symbol-name fun) nil
   1205                                       :type 'help-function
   1206                                       'help-args (list fun))
   1207                     (make-text-button (symbol-name hook) nil
   1208                                       :type 'help-variable
   1209                                       'help-args (list hook)))))
   1210          (insert ".\n\n")
   1211          (insert
   1212           (format-message
   1213            "`%s' is "
   1214            (make-text-button (symbol-name fun) nil
   1215                              :type 'help-function 'help-args (list fun))))
   1216          (describe-function-1 fun))))
   1217     (_ (message "%s, inserter unknown"
   1218                 (magit-describe-section-briefly section)))))
   1219 
   1220 ;;; Match
   1221 
   1222 (cl-defun magit-section-match
   1223     (condition &optional (section (magit-current-section)))
   1224   "Return t if SECTION matches CONDITION.
   1225 
   1226 SECTION defaults to the section at point.  If SECTION is not
   1227 specified and there also is no section at point, then return
   1228 nil.
   1229 
   1230 CONDITION can take the following forms:
   1231   (CONDITION...)  matches if any of the CONDITIONs matches.
   1232   [CLASS...]      matches if the section's class is the same
   1233                   as the first CLASS or a subclass of that;
   1234                   the section's parent class matches the
   1235                   second CLASS; and so on.
   1236   [* CLASS...]    matches sections that match [CLASS...] and
   1237                   also recursively all their child sections.
   1238   CLASS           matches if the section's class is the same
   1239                   as CLASS or a subclass of that; regardless
   1240                   of the classes of the parent sections.
   1241 
   1242 Each CLASS should be a class symbol, identifying a class that
   1243 derives from `magit-section'.  For backward compatibility CLASS
   1244 can also be a \"type symbol\".  A section matches such a symbol
   1245 if the value of its `type' slot is `eq'.  If a type symbol has
   1246 an entry in `magit--section-type-alist', then a section also
   1247 matches that type if its class is a subclass of the class that
   1248 corresponds to the type as per that alist.
   1249 
   1250 Note that it is not necessary to specify the complete section
   1251 lineage as printed by `magit-describe-section-briefly', unless
   1252 of course you want to be that precise."
   1253   (and section (magit-section-match-1 condition section)))
   1254 
   1255 (defun magit-section-match-1 (condition section)
   1256   (cl-assert condition)
   1257   (and section
   1258        (if (listp condition)
   1259            (--first (magit-section-match-1 it section) condition)
   1260          (magit-section-match-2 (if (symbolp condition)
   1261                                     (list condition)
   1262                                   (cl-coerce condition 'list))
   1263                                 section))))
   1264 
   1265 (defun magit-section-match-2 (condition section)
   1266   (if (eq (car condition) '*)
   1267       (or (magit-section-match-2 (cdr condition) section)
   1268           (and-let* ((parent (oref section parent)))
   1269             (magit-section-match-2 condition parent)))
   1270     (and (let ((c (car condition)))
   1271            (if (class-p c)
   1272                (cl-typep section c)
   1273              (if-let ((class (cdr (assq c magit--section-type-alist))))
   1274                  (cl-typep section class)
   1275                (eq (oref section type) c))))
   1276          (or (not (setq condition (cdr condition)))
   1277              (and-let* ((parent (oref section parent)))
   1278                (magit-section-match-2 condition parent))))))
   1279 
   1280 (defun magit-section-value-if (condition &optional section)
   1281   "If the section at point matches CONDITION, then return its value.
   1282 
   1283 If optional SECTION is non-nil then test whether that matches
   1284 instead.  If there is no section at point and SECTION is nil,
   1285 then return nil.  If the section does not match, then return
   1286 nil.
   1287 
   1288 See `magit-section-match' for the forms CONDITION can take."
   1289   (and-let* ((section (or section (magit-current-section))))
   1290     (and (magit-section-match condition section)
   1291          (oref section value))))
   1292 
   1293 (defmacro magit-section-case (&rest clauses)
   1294   "Choose among clauses on the type of the section at point.
   1295 
   1296 Each clause looks like (CONDITION BODY...).  The type of the
   1297 section is compared against each CONDITION; the BODY forms of the
   1298 first match are evaluated sequentially and the value of the last
   1299 form is returned.  Inside BODY the symbol `it' is bound to the
   1300 section at point.  If no clause succeeds or if there is no
   1301 section at point, return nil.
   1302 
   1303 See `magit-section-match' for the forms CONDITION can take.
   1304 Additionally a CONDITION of t is allowed in the final clause, and
   1305 matches if no other CONDITION match, even if there is no section
   1306 at point."
   1307   (declare (indent 0)
   1308            (debug (&rest (sexp body))))
   1309   `(let* ((it (magit-current-section)))
   1310      (cond ,@(mapcar (lambda (clause)
   1311                        `(,(or (eq (car clause) t)
   1312                               `(and it
   1313                                     (magit-section-match-1 ',(car clause) it)))
   1314                          ,@(cdr clause)))
   1315                      clauses))))
   1316 
   1317 (defun magit-section-match-assoc (section alist)
   1318   "Return the value associated with SECTION's type or lineage in ALIST."
   1319   (seq-some (pcase-lambda (`(,key . ,val))
   1320               (and (magit-section-match-1 key section) val))
   1321             alist))
   1322 
   1323 ;;; Create
   1324 
   1325 (defvar magit-insert-section-hook nil
   1326   "Hook run after `magit-insert-section's BODY.
   1327 Avoid using this hook and only ever do so if you know
   1328 what you are doing and are sure there is no other way.")
   1329 
   1330 (defmacro magit-insert-section (&rest args)
   1331   "Insert a section at point.
   1332 
   1333 Create a section object of type CLASS, storing VALUE in its
   1334 `value' slot, and insert the section at point.  CLASS is a
   1335 subclass of `magit-section' or has the form `(eval FORM)', in
   1336 which case FORM is evaluated at runtime and should return a
   1337 subclass.  In other places a sections class is often referred
   1338 to as its \"type\".
   1339 
   1340 Many commands behave differently depending on the class of the
   1341 current section and sections of a certain class can have their
   1342 own keymap, which is specified using the `keymap' class slot.
   1343 The value of that slot should be a variable whose value is a
   1344 keymap.
   1345 
   1346 For historic reasons Magit and Forge in most cases use symbols
   1347 as CLASS that don't actually identify a class and that lack the
   1348 appropriate package prefix.  This works due to some undocumented
   1349 kludges, which are not available to other packages.
   1350 
   1351 When optional HIDE is non-nil collapse the section body by
   1352 default, i.e., when first creating the section, but not when
   1353 refreshing the buffer.  Else expand it by default.  This can be
   1354 overwritten using `magit-section-set-visibility-hook'.  When a
   1355 section is recreated during a refresh, then the visibility of
   1356 predecessor is inherited and HIDE is ignored (but the hook is
   1357 still honored).
   1358 
   1359 BODY is any number of forms that actually insert the section's
   1360 heading and body.  Optional NAME, if specified, has to be a
   1361 symbol, which is then bound to the object of the section being
   1362 inserted.
   1363 
   1364 Before BODY is evaluated the `start' of the section object is set
   1365 to the value of `point' and after BODY was evaluated its `end' is
   1366 set to the new value of `point'; BODY is responsible for moving
   1367 `point' forward.
   1368 
   1369 If it turns out inside BODY that the section is empty, then
   1370 `magit-cancel-section' can be used to abort and remove all traces
   1371 of the partially inserted section.  This can happen when creating
   1372 a section by washing Git's output and Git didn't actually output
   1373 anything this time around.
   1374 
   1375 \(fn [NAME] (CLASS &optional VALUE HIDE) &rest BODY)"
   1376   (declare (indent 1)
   1377            (debug ([&optional symbolp]
   1378                    (&or [("eval" form) &optional form form &rest form]
   1379                         [symbolp &optional form form &rest form])
   1380                    body)))
   1381   (pcase-let* ((bind (and (symbolp (car args))
   1382                           (pop args)))
   1383                (`((,class ,value ,hide . ,args) . ,body) args)
   1384                (obj (cl-gensym "section")))
   1385     `(let* ((,obj (magit-insert-section--create
   1386                    ,(if (eq (car-safe class) 'eval) (cadr class) `',class)
   1387                    ,value ,hide ,@args))
   1388             (magit-insert-section--current ,obj)
   1389             (magit-insert-section--oldroot
   1390              (or magit-insert-section--oldroot
   1391                  (and (not magit-insert-section--parent)
   1392                       (prog1 magit-root-section
   1393                         (setq magit-root-section ,obj)))))
   1394             (magit-insert-section--parent ,obj))
   1395        (catch 'cancel-section
   1396          ,@(if bind `((let ((,bind ,obj)) ,@body)) body)
   1397          (magit-insert-section--finish ,obj))
   1398        ,obj)))
   1399 
   1400 (defun magit-insert-section--create (class value hide &rest args)
   1401   (let (type)
   1402     (if (class-p class)
   1403         (setq type (or (car (rassq class magit--section-type-alist))
   1404                        class))
   1405       (setq type class)
   1406       (setq class (or (cdr (assq class magit--section-type-alist))
   1407                       'magit-section)))
   1408     (let ((obj (apply class :type type args)))
   1409       (oset obj value value)
   1410       (oset obj parent magit-insert-section--parent)
   1411       (oset obj start (if magit-section-inhibit-markers (point) (point-marker)))
   1412       (unless (slot-boundp obj 'hidden)
   1413         (oset obj hidden
   1414               (let (set old)
   1415                 (cond
   1416                  ((setq set (run-hook-with-args-until-success
   1417                              'magit-section-set-visibility-hook obj))
   1418                   (eq set 'hide))
   1419                  ((setq old (and (not magit-section-preserve-visibility)
   1420                                  magit-insert-section--oldroot
   1421                                  (magit-get-section
   1422                                   (magit-section-ident obj)
   1423                                   magit-insert-section--oldroot)))
   1424                   (oref old hidden))
   1425                  ((setq set (magit-section-match-assoc
   1426                              obj magit-section-initial-visibility-alist))
   1427                   (eq (if (functionp set) (funcall set obj) set) 'hide))
   1428                  (hide)))))
   1429       (unless (oref obj keymap)
   1430         (let ((type (oref obj type)))
   1431           (oset obj keymap
   1432                 (or (let ((sym (intern (format "magit-%s-section-map" type))))
   1433                       (and (boundp sym) sym))
   1434                     (let ((sym (intern (format "forge-%s-section-map" type))))
   1435                       (and (boundp sym) sym))))))
   1436       obj)))
   1437 
   1438 (defun magit-insert-section--finish (obj)
   1439   (run-hooks 'magit-insert-section-hook)
   1440   (let ((beg (oref obj start))
   1441         (end (oset obj end
   1442                    (if magit-section-inhibit-markers
   1443                        (point)
   1444                      (point-marker))))
   1445         (props `( magit-section ,obj
   1446                   ,@(and-let* ((map (symbol-value (oref obj keymap))))
   1447                       (list 'keymap map)))))
   1448     (unless magit-section-inhibit-markers
   1449       (set-marker-insertion-type beg t))
   1450     (cond ((eq obj magit-root-section))
   1451           ((oref obj children)
   1452            (magit-insert-child-count obj)
   1453            (magit-section-maybe-add-heading-map obj)
   1454            (save-excursion
   1455              (goto-char beg)
   1456              (while (< (point) end)
   1457                (let ((next (or (next-single-property-change
   1458                                 (point) 'magit-section)
   1459                                end)))
   1460                  (unless (magit-section-at)
   1461                    (add-text-properties (point) next props))
   1462                  (goto-char next)))))
   1463           ((add-text-properties beg end props)))
   1464     (cond ((eq obj magit-root-section)
   1465            (when (eq magit-section-inhibit-markers 'delay)
   1466              (setq magit-section-inhibit-markers nil)
   1467              (magit-map-sections
   1468               (lambda (section)
   1469                 (oset section start (copy-marker (oref section start) t))
   1470                 (oset section end   (copy-marker (oref section end)   t)))))
   1471            (let ((magit-section-cache-visibility nil))
   1472              (magit-section-show obj)))
   1473           (magit-section-insert-in-reverse
   1474            (push obj (oref (oref obj parent) children)))
   1475           ((let ((parent (oref obj parent)))
   1476              (oset parent children
   1477                    (nconc (oref parent children)
   1478                           (list obj))))))
   1479     (when magit-section-insert-in-reverse
   1480       (oset obj children (nreverse (oref obj children))))))
   1481 
   1482 (defun magit-cancel-section (&optional if-empty)
   1483   "Cancel inserting the section that is currently being inserted.
   1484 
   1485 Canceling returns from the inner most use of `magit-insert-section' and
   1486 removes all text that was inserted by that.
   1487 
   1488 If optional IF-EMPTY is non-nil, then only cancel the section, if it is
   1489 empty.  If a section is split into a heading and a body (i.e., when its
   1490 `content' slot is non-nil), then only check if the body is empty."
   1491   (when (and magit-insert-section--current
   1492              (or (not if-empty)
   1493                  (= (point) (or (oref magit-insert-section--current content)
   1494                                 (oref magit-insert-section--current start)))))
   1495     (if (eq magit-insert-section--current magit-root-section)
   1496         (insert "(empty)\n")
   1497       (delete-region (oref magit-insert-section--current start)
   1498                      (point))
   1499       (setq magit-insert-section--current nil)
   1500       (throw 'cancel-section nil))))
   1501 
   1502 (defun magit-insert-heading (&rest args)
   1503   "Insert the heading for the section currently being inserted.
   1504 
   1505 This function should only be used inside `magit-insert-section'.
   1506 
   1507 When called without any arguments, then just set the `content'
   1508 slot of the object representing the section being inserted to
   1509 a marker at `point'.  The section should only contain a single
   1510 line when this function is used like this.
   1511 
   1512 When called with arguments ARGS, which have to be strings, or
   1513 nil, then insert those strings at point.  The section should not
   1514 contain any text before this happens and afterwards it should
   1515 again only contain a single line.  If the `face' property is set
   1516 anywhere inside any of these strings, then insert all of them
   1517 unchanged.  Otherwise use the `magit-section-heading' face for
   1518 all inserted text.
   1519 
   1520 The `content' property of the section object is the end of the
   1521 heading (which lasts from `start' to `content') and the beginning
   1522 of the the body (which lasts from `content' to `end').  If the
   1523 value of `content' is nil, then the section has no heading and
   1524 its body cannot be collapsed.  If a section does have a heading,
   1525 then its height must be exactly one line, including a trailing
   1526 newline character.  This isn't enforced, you are responsible for
   1527 getting it right.  The only exception is that this function does
   1528 insert a newline character if necessary."
   1529   (declare (indent defun))
   1530   (when args
   1531     (let ((heading (apply #'concat args)))
   1532       (insert (if (or (text-property-not-all 0 (length heading)
   1533                                              'font-lock-face nil heading)
   1534                       (text-property-not-all 0 (length heading)
   1535                                              'face nil heading))
   1536                   heading
   1537                 (propertize heading 'font-lock-face 'magit-section-heading)))))
   1538   (unless (bolp)
   1539     (insert ?\n))
   1540   (when (fboundp 'magit-maybe-make-margin-overlay)
   1541     (magit-maybe-make-margin-overlay))
   1542   (oset magit-insert-section--current content
   1543         (if magit-section-inhibit-markers (point) (point-marker))))
   1544 
   1545 (defmacro magit-insert-section-body (&rest body)
   1546   "Use BODY to insert the section body, once the section is expanded.
   1547 If the section is expanded when it is created, then this is
   1548 like `progn'.  Otherwise BODY isn't evaluated until the section
   1549 is explicitly expanded."
   1550   (declare (indent 0))
   1551   (let ((f (cl-gensym))
   1552         (s (cl-gensym))
   1553         (l (cl-gensym)))
   1554     `(let ((,f (lambda () ,@body)))
   1555        (if (oref magit-insert-section--current hidden)
   1556            (oset magit-insert-section--current washer
   1557                  (let ((,s magit-insert-section--current))
   1558                    (lambda ()
   1559                      (let ((,l (magit-section-lineage ,s t)))
   1560                        (dolist (s ,l)
   1561                          (set-marker-insertion-type (oref s end) t))
   1562                        (funcall ,f)
   1563                        (dolist (s ,l)
   1564                          (set-marker-insertion-type (oref s end) nil))
   1565                        (magit-section-maybe-remove-heading-map ,s)
   1566                        (magit-section-maybe-remove-visibility-indicator ,s)))))
   1567          (funcall ,f)))))
   1568 
   1569 (defun magit-insert-headers (hook)
   1570   (let* ((header-sections nil)
   1571          (magit-insert-section-hook
   1572           (cons (lambda ()
   1573                   (push magit-insert-section--current
   1574                         header-sections))
   1575                 (if (listp magit-insert-section-hook)
   1576                     magit-insert-section-hook
   1577                   (list magit-insert-section-hook)))))
   1578     (magit-run-section-hook hook)
   1579     (when header-sections
   1580       (insert "\n")
   1581       ;; Make the first header into the parent of the rest.
   1582       (when (cdr header-sections)
   1583         (cl-callf nreverse header-sections)
   1584         (let* ((1st-header (pop header-sections))
   1585                (header-parent (oref 1st-header parent)))
   1586           (oset header-parent children (list 1st-header))
   1587           (oset 1st-header children header-sections)
   1588           (oset 1st-header content (oref (car header-sections) start))
   1589           (oset 1st-header end (oref (car (last header-sections)) end))
   1590           (dolist (sub-header header-sections)
   1591             (oset sub-header parent 1st-header))
   1592           (magit-section-maybe-add-heading-map 1st-header))))))
   1593 
   1594 (defun magit-section-maybe-add-heading-map (section)
   1595   (when (magit-section-content-p section)
   1596     (let ((start (oref section start))
   1597           (map (oref section keymap)))
   1598       (when (symbolp map)
   1599         (setq map (symbol-value map)))
   1600       (put-text-property
   1601        start
   1602        (save-excursion
   1603          (goto-char start)
   1604          (line-end-position))
   1605        'keymap (if map
   1606                    (make-composed-keymap
   1607                     (list map magit-section-heading-map))
   1608                  magit-section-heading-map)))))
   1609 
   1610 (defun magit-section-maybe-remove-heading-map (section)
   1611   (with-slots (start content end keymap) section
   1612     (when (= content end)
   1613       (put-text-property start end 'keymap keymap))))
   1614 
   1615 (defun magit-insert-child-count (section)
   1616   "Modify SECTION's heading to contain number of child sections.
   1617 
   1618 If `magit-section-show-child-count' is non-nil and the SECTION
   1619 has children and its heading ends with \":\", then replace that
   1620 with \" (N)\", where N is the number of child sections.
   1621 
   1622 This function is called by `magit-insert-section' after that has
   1623 evaluated its BODY.  Admittedly that's a bit of a hack."
   1624   (let (content count)
   1625     (when (and magit-section-show-child-count
   1626                (setq content (oref section content))
   1627                (setq count (length (oref section children)))
   1628                (> count 0)
   1629                (eq (char-before (1- content)) ?:))
   1630       (save-excursion
   1631         (goto-char (- content 2))
   1632         (insert (magit--propertize-face (format " (%s)" count)
   1633                                         'magit-section-child-count))
   1634         (delete-char 1)))))
   1635 
   1636 ;;; Highlight
   1637 
   1638 (defun magit-section-pre-command-hook ()
   1639   (when (and (or magit--context-menu-buffer
   1640                  magit--context-menu-section)
   1641              (not (eq (ignore-errors
   1642                         (event-basic-type (aref (this-command-keys) 0)))
   1643                       'mouse-3)))
   1644     ;; This is the earliest opportunity to clean up after an aborted
   1645     ;; context-menu because that neither causes the command that created
   1646     ;; the menu to abort nor some abortion hook to be run.  It is not
   1647     ;; possible to update highlighting before the first command invoked
   1648     ;; after the menu is aborted.  Here we can only make sure it is
   1649     ;; updated afterwards.
   1650     (magit-menu-highlight-point-section))
   1651   (setq magit-section-pre-command-region-p (region-active-p))
   1652   (setq magit-section-pre-command-section (magit-current-section)))
   1653 
   1654 (defun magit-section-post-command-hook ()
   1655   (let ((window (selected-window)))
   1656     ;; The command may have used `set-window-buffer' to change
   1657     ;; the window's buffer without changing the current buffer.
   1658     (when (eq (current-buffer) (window-buffer window))
   1659       (cursor-sensor-move-to-tangible window)
   1660       (when (or magit--context-menu-buffer
   1661                 magit--context-menu-section)
   1662         (magit-menu-highlight-point-section))))
   1663   (unless (memq this-command '(magit-refresh magit-refresh-all))
   1664     (magit-section-update-highlight)))
   1665 
   1666 (defun magit-section-deactivate-mark ()
   1667   (setq magit-section-highlight-force-update t))
   1668 
   1669 (defun magit-section-update-highlight (&optional force)
   1670   (let ((section (magit-current-section)))
   1671     (when (or force
   1672               magit-section-highlight-force-update
   1673               (xor magit-section-pre-command-region-p (region-active-p))
   1674               (not (eq magit-section-pre-command-section section)))
   1675       (let ((inhibit-read-only t)
   1676             (deactivate-mark nil)
   1677             (selection (magit-region-sections)))
   1678         (mapc #'delete-overlay magit-section-highlight-overlays)
   1679         (setq magit-section-highlight-overlays nil)
   1680         (setq magit-section-unhighlight-sections
   1681               magit-section-highlighted-sections)
   1682         (setq magit-section-highlighted-sections nil)
   1683         (if (and (fboundp 'long-line-optimizations-p)
   1684                  (long-line-optimizations-p))
   1685             (magit-section--enable-long-lines-shortcuts)
   1686           (unless (eq section magit-root-section)
   1687             (run-hook-with-args-until-success
   1688              'magit-section-highlight-hook section selection))
   1689           (dolist (s magit-section-unhighlight-sections)
   1690             (run-hook-with-args-until-success
   1691              'magit-section-unhighlight-hook s selection)))
   1692         (restore-buffer-modified-p nil)))
   1693     (setq magit-section-highlight-force-update nil)
   1694     (magit-section-maybe-paint-visibility-ellipses)))
   1695 
   1696 (defun magit-section-highlight (section selection)
   1697   "Highlight SECTION and if non-nil all sections in SELECTION.
   1698 This function works for any section but produces undesirable
   1699 effects for diff related sections, which by default are
   1700 highlighted using `magit-diff-highlight'.  Return t."
   1701   (when-let ((face (oref section heading-highlight-face)))
   1702     (dolist (section (or selection (list section)))
   1703       (magit-section-make-overlay
   1704        (oref section start)
   1705        (or (oref section content)
   1706            (oref section end))
   1707        face)))
   1708   (cond (selection
   1709          (magit-section-make-overlay (oref (car selection) start)
   1710                                      (oref (car (last selection)) end)
   1711                                      'magit-section-highlight)
   1712          (magit-section-highlight-selection nil selection))
   1713         (t
   1714          (magit-section-make-overlay (oref section start)
   1715                                      (oref section end)
   1716                                      'magit-section-highlight)))
   1717   t)
   1718 
   1719 (defun magit-section-highlight-selection (_ selection)
   1720   "Highlight the section-selection region.
   1721 If SELECTION is non-nil, then it is a list of sections selected by
   1722 the region.  The headings of these sections are then highlighted.
   1723 
   1724 This is a fallback for people who don't want to highlight the
   1725 current section and therefore removed `magit-section-highlight'
   1726 from `magit-section-highlight-hook'.
   1727 
   1728 This function is necessary to ensure that a representation of
   1729 such a region is visible.  If neither of these functions were
   1730 part of the hook variable, then such a region would be
   1731 invisible."
   1732   (when (and selection
   1733              (not (and (eq this-command 'mouse-drag-region))))
   1734     (dolist (section selection)
   1735       (magit-section-make-overlay (oref section start)
   1736                                   (or (oref section content)
   1737                                       (oref section end))
   1738                                   'magit-section-heading-selection))
   1739     t))
   1740 
   1741 (defun magit-section-make-overlay (start end face)
   1742   ;; Yes, this doesn't belong here.  But the alternative of
   1743   ;; spreading this hack across the code base is even worse.
   1744   (when (and magit-section-keep-region-overlay
   1745              (memq face '(magit-section-heading-selection
   1746                           magit-diff-file-heading-selection
   1747                           magit-diff-hunk-heading-selection)))
   1748     (setq face (list :foreground (face-foreground face))))
   1749   (let ((ov (make-overlay start end nil t)))
   1750     (overlay-put ov 'font-lock-face face)
   1751     (overlay-put ov 'evaporate t)
   1752     (push ov magit-section-highlight-overlays)
   1753     ov))
   1754 
   1755 (defvar magit-show-long-lines-warning t)
   1756 
   1757 (defun magit-section--enable-long-lines-shortcuts ()
   1758   (message "Enabling long lines shortcuts in %S" (current-buffer))
   1759   (kill-local-variable 'redisplay-highlight-region-function)
   1760   (kill-local-variable 'redisplay-unhighlight-region-function)
   1761   (when magit-show-long-lines-warning
   1762     (setq magit-show-long-lines-warning nil)
   1763     (display-warning 'magit (format "\
   1764 Emacs has enabled redisplay shortcuts
   1765 in this buffer because there are lines whose length go beyond
   1766 `long-line-threshold' \(%s characters).  As a result, section
   1767 highlighting and the special appearance of the region has been
   1768 disabled.  Some existing highlighting might remain in effect.
   1769 
   1770 These shortcuts remain enabled, even once there no longer are
   1771 any long lines in this buffer.  To disable them again, kill
   1772 and recreate the buffer.
   1773 
   1774 This message won't be shown for this session again.  To disable
   1775 it for all future sessions, set `magit-show-long-lines-warning'
   1776 to nil." (bound-and-true-p long-line-threshold)) :warning)))
   1777 
   1778 (cl-defgeneric magit-section-get-relative-position (section))
   1779 
   1780 (cl-defmethod magit-section-get-relative-position ((section magit-section))
   1781   (let ((start (oref section start))
   1782         (point (magit-point)))
   1783     (list (- (line-number-at-pos point)
   1784              (line-number-at-pos start))
   1785           (- point (line-beginning-position)))))
   1786 
   1787 (cl-defgeneric magit-section-goto-successor ())
   1788 
   1789 (cl-defmethod magit-section-goto-successor ((section magit-section)
   1790                                             line char &optional _arg)
   1791   (or (magit-section-goto-successor--same section line char)
   1792       (magit-section-goto-successor--related section)))
   1793 
   1794 (defun magit-section-goto-successor--same (section line char)
   1795   (let ((ident (magit-section-ident section)))
   1796     (and-let* ((found (magit-get-section ident)))
   1797       (let ((start (oref found start)))
   1798         (goto-char start)
   1799         (unless (eq found magit-root-section)
   1800           (ignore-errors
   1801             (forward-line line)
   1802             (forward-char char))
   1803           (unless (eq (magit-current-section) found)
   1804             (goto-char start)))
   1805         t))))
   1806 
   1807 (defun magit-section-goto-successor--related (section)
   1808   (and-let* ((found (magit-section-goto-successor--related-1 section)))
   1809     (goto-char (if (eq (oref found type) 'button)
   1810                    (point-min)
   1811                  (oref found start)))))
   1812 
   1813 (defun magit-section-goto-successor--related-1 (section)
   1814   (or (and-let* ((alt (pcase (oref section type)
   1815                         ('staged 'unstaged)
   1816                         ('unstaged 'staged)
   1817                         ('unpushed 'unpulled)
   1818                         ('unpulled 'unpushed))))
   1819         (magit-get-section `((,alt) (status))))
   1820       (and-let* ((next (car (magit-section-siblings section 'next))))
   1821         (magit-get-section (magit-section-ident next)))
   1822       (and-let* ((prev (car (magit-section-siblings section 'prev))))
   1823         (magit-get-section (magit-section-ident prev)))
   1824       (and-let* ((parent (oref section parent)))
   1825         (or (magit-get-section (magit-section-ident parent))
   1826             (magit-section-goto-successor--related-1 parent)))))
   1827 
   1828 ;;; Region
   1829 
   1830 (defvar-local magit-section--region-overlays nil)
   1831 
   1832 (defun magit-section--delete-region-overlays ()
   1833   (mapc #'delete-overlay magit-section--region-overlays)
   1834   (setq magit-section--region-overlays nil))
   1835 
   1836 (defun magit-section--highlight-region (start end window rol)
   1837   (magit-section--delete-region-overlays)
   1838   (if (and (not magit-section-keep-region-overlay)
   1839            (or (magit-region-sections)
   1840                (run-hook-with-args-until-success 'magit-region-highlight-hook
   1841                                                  (magit-current-section)))
   1842            (not (= (line-number-at-pos start)
   1843                    (line-number-at-pos end)))
   1844            ;; (not (eq (car-safe last-command-event) 'mouse-movement))
   1845            )
   1846       (funcall (default-value 'redisplay-unhighlight-region-function) rol)
   1847     (funcall (default-value 'redisplay-highlight-region-function)
   1848              start end window rol)))
   1849 
   1850 (defun magit-section--unhighlight-region (rol)
   1851   (magit-section--delete-region-overlays)
   1852   (funcall (default-value 'redisplay-unhighlight-region-function) rol))
   1853 
   1854 ;;; Visibility
   1855 
   1856 (defvar-local magit-section-visibility-cache nil)
   1857 (put 'magit-section-visibility-cache 'permanent-local t)
   1858 
   1859 (defun magit-section-cached-visibility (section)
   1860   "Set SECTION's visibility to the cached value.
   1861 When `magit-section-preserve-visibility' is nil, do nothing."
   1862   (and magit-section-preserve-visibility
   1863        (cdr (assoc (magit-section-ident section)
   1864                    magit-section-visibility-cache))))
   1865 
   1866 (cl-defun magit-section-cache-visibility
   1867     (&optional (section magit-insert-section--current))
   1868   (setf (compat-call alist-get
   1869                      (magit-section-ident section)
   1870                      magit-section-visibility-cache
   1871                      nil nil #'equal)
   1872         (if (oref section hidden) 'hide 'show)))
   1873 
   1874 (cl-defun magit-section-maybe-cache-visibility
   1875     (&optional (section magit-insert-section--current))
   1876   (when (or (eq magit-section-cache-visibility t)
   1877             (memq (oref section type)
   1878                   magit-section-cache-visibility))
   1879     (magit-section-cache-visibility section)))
   1880 
   1881 (defun magit-section-maybe-update-visibility-indicator (section)
   1882   (when (and magit-section-visibility-indicator
   1883              (magit-section-content-p section))
   1884     (let* ((beg (oref section start))
   1885            (eoh (save-excursion
   1886                   (goto-char beg)
   1887                   (line-end-position))))
   1888       (cond
   1889        ((symbolp (car-safe magit-section-visibility-indicator))
   1890         (let ((ov (magit--overlay-at beg 'magit-vis-indicator 'fringe)))
   1891           (unless ov
   1892             (setq ov (make-overlay beg eoh nil t))
   1893             (overlay-put ov 'evaporate t)
   1894             (overlay-put ov 'magit-vis-indicator 'fringe))
   1895           (overlay-put
   1896            ov 'before-string
   1897            (propertize "fringe" 'display
   1898                        (list 'left-fringe
   1899                              (if (oref section hidden)
   1900                                  (car magit-section-visibility-indicator)
   1901                                (cdr magit-section-visibility-indicator))
   1902                              'fringe)))))
   1903        ((stringp (car-safe magit-section-visibility-indicator))
   1904         (let ((ov (magit--overlay-at (1- eoh) 'magit-vis-indicator 'eoh)))
   1905           (cond ((oref section hidden)
   1906                  (unless ov
   1907                    (setq ov (make-overlay (1- eoh) eoh))
   1908                    (overlay-put ov 'evaporate t)
   1909                    (overlay-put ov 'magit-vis-indicator 'eoh))
   1910                  (overlay-put ov 'after-string
   1911                               (car magit-section-visibility-indicator)))
   1912                 (ov
   1913                  (delete-overlay ov)))))))))
   1914 
   1915 (defvar-local magit--ellipses-sections nil)
   1916 
   1917 (defun magit-section-maybe-paint-visibility-ellipses ()
   1918   ;; This is needed because we hide the body instead of "the body
   1919   ;; except the final newline and additionally the newline before
   1920   ;; the body"; otherwise we could use `buffer-invisibility-spec'.
   1921   (when (stringp (car-safe magit-section-visibility-indicator))
   1922     (let* ((sections (append magit--ellipses-sections
   1923                              (setq magit--ellipses-sections
   1924                                    (or (magit-region-sections)
   1925                                        (list (magit-current-section))))))
   1926            (beg (--map (oref it start) sections))
   1927            (end (--map (oref it end)   sections)))
   1928       (when (region-active-p)
   1929         ;; This ensures that the region face is removed from ellipses
   1930         ;; when the region becomes inactive, but fails to ensure that
   1931         ;; all ellipses within the active region use the region face,
   1932         ;; because the respective overlay has not yet been updated at
   1933         ;; this time.  The magit-selection face is always applied.
   1934         (push (region-beginning) beg)
   1935         (push (region-end)       end))
   1936       (setq beg (apply #'min beg))
   1937       (setq end (apply #'max end))
   1938       (dolist (ov (overlays-in beg end))
   1939         (when (eq (overlay-get ov 'magit-vis-indicator) 'eoh)
   1940           (overlay-put
   1941            ov 'after-string
   1942            (propertize
   1943             (car magit-section-visibility-indicator) 'font-lock-face
   1944             (let ((pos (overlay-start ov)))
   1945               (delq nil (nconc (--map (overlay-get it 'font-lock-face)
   1946                                       (overlays-at pos))
   1947                                (list (get-char-property
   1948                                       pos 'font-lock-face))))))))))))
   1949 
   1950 (defun magit-section-maybe-remove-visibility-indicator (section)
   1951   (when (and magit-section-visibility-indicator
   1952              (= (oref section content)
   1953                 (oref section end)))
   1954     (dolist (o (overlays-in (oref section start)
   1955                             (save-excursion
   1956                               (goto-char (oref section start))
   1957                               (1+ (line-end-position)))))
   1958       (when (overlay-get o 'magit-vis-indicator)
   1959         (delete-overlay o)))))
   1960 
   1961 (defvar-local magit-section--opened-sections nil)
   1962 
   1963 (defun magit-section--open-temporarily (beg end)
   1964   (save-excursion
   1965     (goto-char beg)
   1966     (let ((section (magit-current-section)))
   1967       (while section
   1968         (let ((content (oref section content)))
   1969           (if (and (magit-section-invisible-p section)
   1970                    (<= (or content (oref section start))
   1971                        beg
   1972                        (oref section end)))
   1973               (progn
   1974                 (when content
   1975                   (magit-section-show section)
   1976                   (push section magit-section--opened-sections))
   1977                 (setq section (oref section parent)))
   1978             (setq section nil))))))
   1979   (or (eq search-invisible t)
   1980       (not (isearch-range-invisible beg end))))
   1981 
   1982 (define-advice isearch-clean-overlays (:around (fn) magit-mode)
   1983   (if (derived-mode-p 'magit-mode)
   1984       (let ((pos (point)))
   1985         (dolist (section magit-section--opened-sections)
   1986           (unless (<= (oref section content) pos (oref section end))
   1987             (magit-section-hide section)))
   1988         (setq magit-section--opened-sections nil))
   1989     (funcall fn)))
   1990 
   1991 ;;; Utilities
   1992 
   1993 (cl-defun magit-section-selected-p (section &optional (selection nil sselection))
   1994   (and (not (eq section magit-root-section))
   1995        (or  (eq section (magit-current-section))
   1996             (memq section (if sselection
   1997                               selection
   1998                             (setq selection (magit-region-sections))))
   1999             (and-let* ((parent (oref section parent)))
   2000               (magit-section-selected-p parent selection)))))
   2001 
   2002 (defun magit-section-parent-value (section)
   2003   (and-let* ((parent (oref section parent)))
   2004     (oref parent value)))
   2005 
   2006 (defun magit-section-siblings (section &optional direction)
   2007   "Return a list of the sibling sections of SECTION.
   2008 
   2009 If optional DIRECTION is `prev', then return siblings that come
   2010 before SECTION.  If it is `next', then return siblings that come
   2011 after SECTION.  For all other values, return all siblings
   2012 excluding SECTION itself."
   2013   (and-let* ((parent (oref section parent))
   2014              (siblings (oref parent children)))
   2015     (pcase direction
   2016       ('prev  (cdr (member section (reverse siblings))))
   2017       ('next  (cdr (member section siblings)))
   2018       (_      (remq section siblings)))))
   2019 
   2020 (defun magit-region-values (&optional condition multiple)
   2021   "Return a list of the values of the selected sections.
   2022 
   2023 Return the values that themselves would be returned by
   2024 `magit-region-sections' (which see)."
   2025   (--map (oref it value)
   2026          (magit-region-sections condition multiple)))
   2027 
   2028 (defun magit-region-sections (&optional condition multiple)
   2029   "Return a list of the selected sections.
   2030 
   2031 When the region is active and constitutes a valid section
   2032 selection, then return a list of all selected sections.  This is
   2033 the case when the region begins in the heading of a section and
   2034 ends in the heading of the same section or in that of a sibling
   2035 section.  If optional MULTIPLE is non-nil, then the region cannot
   2036 begin and end in the same section.
   2037 
   2038 When the selection is not valid, then return nil.  In this case,
   2039 most commands that can act on the selected sections will instead
   2040 act on the section at point.
   2041 
   2042 When the region looks like it would in any other buffer then
   2043 the selection is invalid.  When the selection is valid then the
   2044 region uses the `magit-section-highlight' face.  This does not
   2045 apply to diffs where things get a bit more complicated, but even
   2046 here if the region looks like it usually does, then that's not
   2047 a valid selection as far as this function is concerned.
   2048 
   2049 If optional CONDITION is non-nil, then the selection not only
   2050 has to be valid; all selected sections additionally have to match
   2051 CONDITION, or nil is returned.  See `magit-section-match' for the
   2052 forms CONDITION can take."
   2053   (and (region-active-p)
   2054        (let* ((rbeg (region-beginning))
   2055               (rend (region-end))
   2056               (sbeg (magit-section-at rbeg))
   2057               (send (magit-section-at rend)))
   2058          (and send
   2059               (not (eq send magit-root-section))
   2060               (not (and multiple (eq send sbeg)))
   2061               (let ((siblings (cons sbeg (magit-section-siblings sbeg 'next)))
   2062                     (sections ()))
   2063                 (and (memq send siblings)
   2064                      (magit-section-position-in-heading-p sbeg rbeg)
   2065                      (magit-section-position-in-heading-p send rend)
   2066                      (progn
   2067                        (while siblings
   2068                          (push (car siblings) sections)
   2069                          (when (eq (pop siblings) send)
   2070                            (setq siblings nil)))
   2071                        (setq sections (nreverse sections))
   2072                        (and (or (not condition)
   2073                                 (--all-p (magit-section-match condition it)
   2074                                          sections))
   2075                             sections))))))))
   2076 
   2077 (defun magit-map-sections (function &optional section)
   2078   "Apply FUNCTION to all sections for side effects only, depth first.
   2079 If optional SECTION is non-nil, only map over that section and
   2080 its descendants, otherwise map over all sections in the current
   2081 buffer, ending with `magit-root-section'."
   2082   (let ((section (or section magit-root-section)))
   2083     (mapc (lambda (child) (magit-map-sections function child))
   2084           (oref section children))
   2085     (funcall function section)))
   2086 
   2087 (defun magit-section-position-in-heading-p (&optional section pos)
   2088   "Return t if POSITION is inside the heading of SECTION.
   2089 POSITION defaults to point and SECTION defaults to the
   2090 current section."
   2091   (unless section
   2092     (setq section (magit-current-section)))
   2093   (unless pos
   2094     (setq pos (point)))
   2095   (ignore-errors ; Allow navigating broken sections.
   2096     (and section
   2097          (>= pos (oref section start))
   2098          (<  pos (or (oref section content)
   2099                      (oref section end)))
   2100          t)))
   2101 
   2102 (defun magit-section-internal-region-p (&optional section)
   2103   "Return t if the region is active and inside SECTION's body.
   2104 If optional SECTION is nil, use the current section."
   2105   (and (region-active-p)
   2106        (or section (setq section (magit-current-section)))
   2107        (let ((beg (magit-section-at (region-beginning))))
   2108          (and (eq beg (magit-section-at (region-end)))
   2109               (eq beg section)))
   2110        (not (or (magit-section-position-in-heading-p section (region-beginning))
   2111                 (magit-section-position-in-heading-p section (region-end))))
   2112        t))
   2113 
   2114 (defun magit-wash-sequence (function)
   2115   "Repeatedly call FUNCTION until it returns nil or eob is reached.
   2116 FUNCTION has to move point forward or return nil."
   2117   (while (and (not (eobp)) (funcall function))))
   2118 
   2119 (defun magit-add-section-hook (hook function &optional at append local)
   2120   "Add to the value of section hook HOOK the function FUNCTION.
   2121 
   2122 Add FUNCTION at the beginning of the hook list unless optional
   2123 APPEND is non-nil, in which case FUNCTION is added at the end.
   2124 If FUNCTION already is a member, then move it to the new location.
   2125 
   2126 If optional AT is non-nil and a member of the hook list, then
   2127 add FUNCTION next to that instead.  Add before or after AT, or
   2128 replace AT with FUNCTION depending on APPEND.  If APPEND is the
   2129 symbol `replace', then replace AT with FUNCTION.  For any other
   2130 non-nil value place FUNCTION right after AT.  If nil, then place
   2131 FUNCTION right before AT.  If FUNCTION already is a member of the
   2132 list but AT is not, then leave FUNCTION where ever it already is.
   2133 
   2134 If optional LOCAL is non-nil, then modify the hook's buffer-local
   2135 value rather than its global value.  This makes the hook local by
   2136 copying the default value.  That copy is then modified.
   2137 
   2138 HOOK should be a symbol.  If HOOK is void, it is first set to nil.
   2139 HOOK's value must not be a single hook function.  FUNCTION should
   2140 be a function that takes no arguments and inserts one or multiple
   2141 sections at point, moving point forward.  FUNCTION may choose not
   2142 to insert its section(s), when doing so would not make sense.  It
   2143 should not be abused for other side-effects.  To remove FUNCTION
   2144 again use `remove-hook'."
   2145   (unless (boundp hook)
   2146     (error "Cannot add function to undefined hook variable %s" hook))
   2147   (unless (default-boundp hook)
   2148     (set-default hook nil))
   2149   (let ((value (if local
   2150                    (if (local-variable-p hook)
   2151                        (symbol-value hook)
   2152                      (unless (local-variable-if-set-p hook)
   2153                        (make-local-variable hook))
   2154                      (copy-sequence (default-value hook)))
   2155                  (default-value hook))))
   2156     (if at
   2157         (when (setq at (member at value))
   2158           (setq value (delq function value))
   2159           (cond ((eq append 'replace)
   2160                  (setcar at function))
   2161                 (append
   2162                  (push function (cdr at)))
   2163                 (t
   2164                  (push (car at) (cdr at))
   2165                  (setcar at function))))
   2166       (setq value (delq function value)))
   2167     (unless (member function value)
   2168       (setq value (if append
   2169                       (append value (list function))
   2170                     (cons function value))))
   2171     (when (eq append 'replace)
   2172       (setq value (delq at value)))
   2173     (if local
   2174         (set hook value)
   2175       (set-default hook value))))
   2176 
   2177 (defvar-local magit-disabled-section-inserters nil)
   2178 
   2179 (defun magit-disable-section-inserter (fn)
   2180   "Disable the section inserter FN in the current repository.
   2181 It is only intended for use in \".dir-locals.el\" and
   2182 \".dir-locals-2.el\".  Also see info node `(magit)Per-Repository
   2183 Configuration'."
   2184   (cl-pushnew fn magit-disabled-section-inserters))
   2185 
   2186 (put 'magit-disable-section-inserter 'safe-local-eval-function t)
   2187 
   2188 (defun magit-run-section-hook (hook &rest args)
   2189   "Run HOOK with ARGS, warning about invalid entries."
   2190   (let ((entries (symbol-value hook)))
   2191     (unless (listp entries)
   2192       (setq entries (list entries)))
   2193     (when-let ((invalid (seq-remove #'functionp entries)))
   2194       (message "`%s' contains entries that are no longer valid.
   2195 %s\nUsing standard value instead.  Please re-configure hook variable."
   2196                hook
   2197                (mapconcat (lambda (sym) (format "  `%s'" sym)) invalid "\n"))
   2198       (sit-for 5)
   2199       (setq entries (eval (car (get hook 'standard-value)))))
   2200     (dolist (entry entries)
   2201       (let ((magit--current-section-hook (cons (list hook entry)
   2202                                                magit--current-section-hook)))
   2203         (unless (memq entry magit-disabled-section-inserters)
   2204           (if (bound-and-true-p magit-refresh-verbose)
   2205               (let ((time (benchmark-elapse (apply entry args))))
   2206                 (message "  %-50s %f %s" entry time
   2207                          (cond ((> time 0.03) "!!")
   2208                                ((> time 0.01) "!")
   2209                                (t ""))))
   2210             (apply entry args)))))))
   2211 
   2212 (cl-defun magit--overlay-at (pos prop &optional (val nil sval) testfn)
   2213   (cl-find-if (lambda (o)
   2214                 (let ((p (overlay-properties o)))
   2215                   (and (plist-member p prop)
   2216                        (or (not sval)
   2217                            (funcall (or testfn #'eql)
   2218                                     (plist-get p prop)
   2219                                     val)))))
   2220               (overlays-at pos t)))
   2221 
   2222 (defun magit-face-property-all (face string)
   2223   "Return non-nil if FACE is present in all of STRING."
   2224   (catch 'missing
   2225     (let ((pos 0))
   2226       (while (setq pos (next-single-property-change pos 'font-lock-face string))
   2227         (let ((val (get-text-property pos 'font-lock-face string)))
   2228           (unless (if (consp val)
   2229                       (memq face val)
   2230                     (eq face val))
   2231             (throw 'missing nil))))
   2232       (not pos))))
   2233 
   2234 (defun magit--add-face-text-property (beg end face &optional append object)
   2235   "Like `add-face-text-property' but for `font-lock-face'."
   2236   (while (< beg end)
   2237     (let* ((pos (next-single-property-change beg 'font-lock-face object end))
   2238            (val (get-text-property beg 'font-lock-face object))
   2239            (val (if (listp val) val (list val))))
   2240       (put-text-property beg pos 'font-lock-face
   2241                          (if append
   2242                              (append val (list face))
   2243                            (cons face val))
   2244                          object)
   2245       (setq beg pos))))
   2246 
   2247 (defun magit--propertize-face (string face)
   2248   (propertize string 'face face 'font-lock-face face))
   2249 
   2250 (defun magit--put-face (beg end face string)
   2251   (put-text-property beg end 'face face string)
   2252   (put-text-property beg end 'font-lock-face face string))
   2253 
   2254 ;;; Imenu Support
   2255 
   2256 (defvar-local magit--imenu-group-types nil)
   2257 (defvar-local magit--imenu-item-types nil)
   2258 
   2259 (defun magit--imenu-create-index ()
   2260   ;; If `which-function-mode' is active, then the create-index
   2261   ;; function is called at the time the major-mode is being enabled.
   2262   ;; Modes that derive from `magit-mode' have not populated the buffer
   2263   ;; at that time yet, so we have to abort.
   2264   (and magit-root-section
   2265        (or magit--imenu-group-types
   2266            magit--imenu-item-types)
   2267        (let ((index
   2268               (cl-mapcan
   2269                (lambda (section)
   2270                  (cond
   2271                   (magit--imenu-group-types
   2272                    (and (if (eq (car-safe magit--imenu-group-types) 'not)
   2273                             (not (magit-section-match
   2274                                   (cdr magit--imenu-group-types)
   2275                                   section))
   2276                           (magit-section-match magit--imenu-group-types section))
   2277                         (and-let* ((children (oref section children)))
   2278                           `((,(magit--imenu-index-name section)
   2279                              ,@(mapcar (lambda (s)
   2280                                          (cons (magit--imenu-index-name s)
   2281                                                (oref s start)))
   2282                                        children))))))
   2283                   (magit--imenu-item-types
   2284                    (and (magit-section-match magit--imenu-item-types section)
   2285                         `((,(magit--imenu-index-name section)
   2286                            . ,(oref section start)))))))
   2287                (oref magit-root-section children))))
   2288          (if (and magit--imenu-group-types (symbolp magit--imenu-group-types))
   2289              (cdar index)
   2290            index))))
   2291 
   2292 (defun magit--imenu-index-name (section)
   2293   (let ((heading (buffer-substring-no-properties
   2294                   (oref section start)
   2295                   (1- (or (oref section content)
   2296                           (oref section end))))))
   2297     (save-match-data
   2298       (cond
   2299        ((and (magit-section-match [commit logbuf] section)
   2300              (string-match "[^ ]+\\([ *|]*\\).+" heading))
   2301         (replace-match " " t t heading 1))
   2302        ((magit-section-match
   2303          '([branch local branchbuf] [tag tags branchbuf]) section)
   2304         (oref section value))
   2305        ((magit-section-match [branch remote branchbuf] section)
   2306         (concat (oref (oref section parent) value) "/"
   2307                 (oref section value)))
   2308        ((string-match " ([0-9]+)\\'" heading)
   2309         (substring heading 0 (match-beginning 0)))
   2310        (t heading)))))
   2311 
   2312 (defun magit--imenu-goto-function (_name position &rest _rest)
   2313   "Go to the section at POSITION.
   2314 Make sure it is visible, by showing its ancestors where
   2315 necessary.  For use as `imenu-default-goto-function' in
   2316 `magit-mode' buffers."
   2317   (goto-char position)
   2318   (let ((section (magit-current-section)))
   2319     (while (setq section (oref section parent))
   2320       (when (oref section hidden)
   2321         (magit-section-show section)))))
   2322 
   2323 ;;; Bookmark support
   2324 
   2325 (declare-function bookmark-get-filename "bookmark" (bookmark-name-or-record))
   2326 (declare-function bookmark-make-record-default "bookmark"
   2327                   (&optional no-file no-context posn))
   2328 (declare-function bookmark-prop-get "bookmark" (bookmark-name-or-record prop))
   2329 (declare-function bookmark-prop-set "bookmark" (bookmark-name-or-record prop val))
   2330 
   2331 (cl-defgeneric magit-bookmark-get-filename ()
   2332   (or (buffer-file-name) (buffer-name)))
   2333 
   2334 (cl-defgeneric magit-bookmark--get-child-value (section)
   2335   (oref section value))
   2336 
   2337 (cl-defgeneric magit-bookmark-get-buffer-create (bookmark mode))
   2338 
   2339 (defun magit--make-bookmark ()
   2340   "Create a bookmark for the current Magit buffer.
   2341 Input values are the major-mode's `magit-bookmark-name' method,
   2342 and the buffer-local values of the variables referenced in its
   2343 `magit-bookmark-variables' property."
   2344   (require 'bookmark)
   2345   (if (plist-member (symbol-plist major-mode) 'magit-bookmark-variables)
   2346       ;; `bookmark-make-record-default's return value does not match
   2347       ;; (NAME . ALIST), even though it is used as the default value
   2348       ;; of `bookmark-make-record-function', which states that such
   2349       ;; functions must do that.  See #4356.
   2350       (let ((bookmark (cons nil (bookmark-make-record-default 'no-file))))
   2351         (bookmark-prop-set bookmark 'handler  #'magit--handle-bookmark)
   2352         (bookmark-prop-set bookmark 'mode     major-mode)
   2353         (bookmark-prop-set bookmark 'filename (magit-bookmark-get-filename))
   2354         (bookmark-prop-set bookmark 'defaults (list (magit-bookmark-name)))
   2355         (dolist (var (get major-mode 'magit-bookmark-variables))
   2356           (bookmark-prop-set bookmark var (symbol-value var)))
   2357         (bookmark-prop-set
   2358          bookmark 'magit-hidden-sections
   2359          (--keep (and (oref it hidden)
   2360                       (cons (oref it type)
   2361                             (magit-bookmark--get-child-value it)))
   2362                  (oref magit-root-section children)))
   2363         bookmark)
   2364     (user-error "Bookmarking is not implemented for %s buffers" major-mode)))
   2365 
   2366 (defun magit--handle-bookmark (bookmark)
   2367   "Open a bookmark created by `magit--make-bookmark'.
   2368 
   2369 Call the generic function `magit-bookmark-get-buffer-create' to get
   2370 the appropriate buffer without displaying it.
   2371 
   2372 Then call the `magit-*-setup-buffer' function of the the major-mode
   2373 with the variables' values as arguments, which were recorded by
   2374 `magit--make-bookmark'."
   2375   (let ((buffer (magit-bookmark-get-buffer-create
   2376                  bookmark
   2377                  (bookmark-prop-get bookmark 'mode))))
   2378     (set-buffer buffer) ; That is the interface we have to adhere to.
   2379     (when-let ((hidden (bookmark-prop-get bookmark 'magit-hidden-sections)))
   2380       (with-current-buffer buffer
   2381         (dolist (child (oref magit-root-section children))
   2382           (if (member (cons (oref child type)
   2383                             (oref child value))
   2384                       hidden)
   2385               (magit-section-hide child)
   2386             (magit-section-show child)))))
   2387     ;; Compatibility with `bookmark+' package.  See #4356.
   2388     (when (bound-and-true-p bmkp-jump-display-function)
   2389       (funcall bmkp-jump-display-function (current-buffer)))
   2390     nil))
   2391 
   2392 (put 'magit--handle-bookmark 'bookmark-handler-type "Magit")
   2393 
   2394 (cl-defgeneric magit-bookmark-name ()
   2395   "Return name for bookmark to current buffer."
   2396   (format "%s%s"
   2397           (substring (symbol-name major-mode) 0 -5)
   2398           (if-let ((vars (get major-mode 'magit-bookmark-variables)))
   2399               (cl-mapcan (lambda (var)
   2400                            (let ((val (symbol-value var)))
   2401                              (if (and val (atom val))
   2402                                  (list val)
   2403                                val)))
   2404                          vars)
   2405             "")))
   2406 
   2407 ;;; Bitmaps
   2408 
   2409 (when (fboundp 'define-fringe-bitmap) ;for Emacs 26
   2410   (define-fringe-bitmap 'magit-fringe-bitmap+
   2411     [#b00000000
   2412      #b00011000
   2413      #b00011000
   2414      #b01111110
   2415      #b01111110
   2416      #b00011000
   2417      #b00011000
   2418      #b00000000])
   2419 
   2420   (define-fringe-bitmap 'magit-fringe-bitmap-
   2421     [#b00000000
   2422      #b00000000
   2423      #b00000000
   2424      #b01111110
   2425      #b01111110
   2426      #b00000000
   2427      #b00000000
   2428      #b00000000])
   2429 
   2430   (define-fringe-bitmap 'magit-fringe-bitmap>
   2431     [#b01100000
   2432      #b00110000
   2433      #b00011000
   2434      #b00001100
   2435      #b00011000
   2436      #b00110000
   2437      #b01100000
   2438      #b00000000])
   2439 
   2440   (define-fringe-bitmap 'magit-fringe-bitmapv
   2441     [#b00000000
   2442      #b10000010
   2443      #b11000110
   2444      #b01101100
   2445      #b00111000
   2446      #b00010000
   2447      #b00000000
   2448      #b00000000])
   2449 
   2450   (define-fringe-bitmap 'magit-fringe-bitmap-bold>
   2451     [#b11100000
   2452      #b01110000
   2453      #b00111000
   2454      #b00011100
   2455      #b00011100
   2456      #b00111000
   2457      #b01110000
   2458      #b11100000])
   2459 
   2460   (define-fringe-bitmap 'magit-fringe-bitmap-boldv
   2461     [#b10000001
   2462      #b11000011
   2463      #b11100111
   2464      #b01111110
   2465      #b00111100
   2466      #b00011000
   2467      #b00000000
   2468      #b00000000])
   2469   )
   2470 
   2471 ;;; _
   2472 (provide 'magit-section)
   2473 ;;; magit-section.el ends here