magit-mode.el 56.9 KB
Newer Older
1
;;; magit-mode.el --- create and refresh Magit buffers  -*- lexical-binding: t -*-
2

Jonas Bernoulli's avatar
Jonas Bernoulli committed
3
;; Copyright (C) 2010-2018  The Magit Project Contributors
4
;;
5 6
;; You should have received a copy of the AUTHORS.md file which
;; lists all contributors.  If not, see http://magit.vc/authors.
7

8
;; Author: Jonas Bernoulli <jonas@bernoul.li>
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>

;; Magit is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; Magit is distributed in the hope that it will be useful, but WITHOUT
;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
;; License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with Magit.  If not, see http://www.gnu.org/licenses.

24 25 26 27 28 29
;;; Commentary:

;; This library implements the abstract major-mode `magit-mode' from
;; which almost all other Magit major-modes derive.  The code in here
;; is mostly concerned with creating and refreshing Magit buffers.

30 31 32 33 34 35 36 37
;;; Code:

(require 'cl-lib)
(require 'dash)

(require 'magit-section)
(require 'magit-git)

Jonas Bernoulli's avatar
Jonas Bernoulli committed
38 39
;; For `magit-display-buffer-fullcolumn-most-v1' from `git-commit'
(defvar git-commit-mode)
40 41
;; For `magit-xref-insert-buttons' from `magit'
(defvar magit-diff-show-xref-buttons)
42
(defvar magit-revision-show-xref-buttons)
43
;; For `magit-refresh'
44
(defvar magit-post-commit-hook-commands)
45 46
(defvar magit-post-stage-hook-commands)
(defvar magit-post-unstage-hook-commands)
47
;; For `magit-refresh' and `magit-refresh-all'
48
(declare-function magit-auto-revert-buffers "magit-autorevert" ())
Jonas Bernoulli's avatar
Jonas Bernoulli committed
49
;; For `magit-refresh-buffer'
50
(declare-function magit-process-unset-mode-line-error-status "magit-process" ())
51 52
;; For `magit-mode-setup-internal'
(declare-function magit-status-goto-initial-section "magit-status" ())
53 54 55 56 57 58

(require 'format-spec)
(require 'help-mode)

;;; Options

59 60 61
(defcustom magit-mode-hook
  '(magit-load-config-extensions
    magit-xref-setup)
62 63 64
  "Hook run when entering a mode derived from Magit mode."
  :group 'magit-modes
  :type 'hook
65 66 67
  :options '(magit-load-config-extensions
             magit-xref-setup
             bug-reference-mode))
68

69 70
(defcustom magit-mode-setup-hook
  '(magit-maybe-save-repository-buffers
71
    magit-set-buffer-margin)
72 73 74 75 76 77 78
  "Hook run by `magit-mode-setup'.

This is run right after displaying the buffer and right before
generating or updating its content.  `magit-mode-hook' and other,
more specific, `magit-mode-*-hook's on the other hand are run
right before displaying the buffer.  Usually one of these hooks
should be used instead of this one."
79 80
  :package-version '(magit . "2.3.0")
  :group 'magit-modes
81 82
  :type 'hook
  :options '(magit-maybe-save-repository-buffers
83
             magit-set-buffer-margin))
84

85 86 87 88 89 90 91 92 93 94
(defcustom magit-pre-refresh-hook '(magit-maybe-save-repository-buffers)
  "Hook run before refreshing in `magit-refresh'.

This hook, or `magit-post-refresh-hook', should be used
for functions that are not tied to a particular buffer.

To run a function with a particular buffer current, use
`magit-refresh-buffer-hook' and use `derived-mode-p'
inside your function."
  :package-version '(magit . "2.4.0")
95
  :group 'magit-refresh
96 97 98
  :type 'hook
  :options '(magit-maybe-save-repository-buffers))

99 100 101 102 103 104 105 106 107 108
(defcustom magit-post-refresh-hook nil
  "Hook run after refreshing in `magit-refresh'.

This hook, or `magit-pre-refresh-hook', should be used
for functions that are not tied to a particular buffer.

To run a function with a particular buffer current, use
`magit-refresh-buffer-hook' and use `derived-mode-p'
inside your function."
  :package-version '(magit . "2.4.0")
109
  :group 'magit-refresh
110 111
  :type 'hook)

112 113 114 115 116
(defcustom magit-display-buffer-function 'magit-display-buffer-traditional
  "The function used display a Magit buffer.

All Magit buffers (buffers whose major-modes derive from
`magit-mode') are displayed using `magit-display-buffer',
117
which in turn uses the function specified here."
118
  :package-version '(magit . "2.3.0")
119
  :group 'magit-buffers
120
  :type '(radio (function-item magit-display-buffer-traditional)
121 122
                (function-item magit-display-buffer-same-window-except-diff-v1)
                (function-item magit-display-buffer-fullframe-status-v1)
123
                (function-item magit-display-buffer-fullframe-status-topleft-v1)
124
                (function-item magit-display-buffer-fullcolumn-most-v1)
125 126 127
                (function-item display-buffer)
                (function :tag "Function")))

128 129 130
(defcustom magit-pre-display-buffer-hook '(magit-save-window-configuration)
  "Hook run by `magit-display-buffer' before displaying the buffer."
  :package-version '(magit . "2.3.0")
131
  :group 'magit-buffers
132
  :type 'hook
133
  :get 'magit-hook-custom-get
134 135 136 137 138
  :options '(magit-save-window-configuration))

(defcustom magit-post-display-buffer-hook '(magit-maybe-set-dedicated)
  "Hook run by `magit-display-buffer' after displaying the buffer."
  :package-version '(magit . "2.3.0")
139
  :group 'magit-buffers
140
  :type 'hook
141
  :get 'magit-hook-custom-get
142 143
  :options '(magit-maybe-set-dedicated))

144 145 146 147
(defcustom magit-generate-buffer-name-function
  'magit-generate-buffer-name-default-function
  "The function used to generate the name for a Magit buffer."
  :package-version '(magit . "2.3.0")
148
  :group 'magit-buffers
149 150 151
  :type '(radio (function-item magit-generate-buffer-name-default-function)
                (function :tag "Function")))

152
(defcustom magit-buffer-name-format "%x%M%v: %t%x"
153 154 155 156 157 158 159 160 161
  "The format string used to name Magit buffers.

The following %-sequences are supported:

`%m' The name of the major-mode, but with the `-mode' suffix
     removed.

`%M' Like \"%m\" but abbreviate `magit-status-mode' as `magit'.

162 163
`%v' The value the buffer is locked to, in parentheses, or an
     empty string if the buffer is not locked to a value.
164

165 166
`%V' Like \"%v\", but the string is prefixed with a space, unless
     it is an empty string.
167

168
`%t' The top-level directory of the working tree of the
169
     repository, or if `magit-uniquify-buffer-names' is non-nil
170 171
     an abbreviation of that.

172 173 174
`%x' If `magit-uniquify-buffer-names' is nil \"*\", otherwise the
     empty string.  Due to limitations of the `uniquify' package,
     buffer names must end with the path.
175

176 177 178 179 180 181 182 183 184
`%T' Obsolete, use \"%t%x\" instead.  Like \"%t\", but append an
     asterisk if and only if `magit-uniquify-buffer-names' is nil.

The value should always contain \"%m\" or \"%M\", \"%v\" or
\"%V\", and \"%t\" (or the obsolete \"%T\").

If `magit-uniquify-buffer-names' is non-nil, then the value must
end with \"%t\" or \"%t%x\" (or the obsolete \"%T\").  See issue
#2841.
185 186 187

This is used by `magit-generate-buffer-name-default-function'.
If another `magit-generate-buffer-name-function' is used, then
188
it may not respect this option, or on the contrary it may
189
support additional %-sequences."
190
  :package-version '(magit . "2.12.0")
191
  :group 'magit-buffers
192 193
  :type 'string)

194 195 196
(defcustom magit-uniquify-buffer-names t
  "Whether to uniquify the names of Magit buffers."
  :package-version '(magit . "2.3.0")
197
  :group 'magit-buffers
198 199
  :type 'boolean)

200 201 202
(defcustom magit-bury-buffer-function 'magit-restore-window-configuration
  "The function used to bury or kill the current Magit buffer."
  :package-version '(magit . "2.3.0")
203
  :group 'magit-buffers
204 205 206 207 208
  :type '(radio (function-item quit-window)
                (function-item magit-mode-quit-window)
                (function-item magit-restore-window-configuration)
                (function :tag "Function")))

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
(defcustom magit-use-sticky-arguments t
  "How to reuse arguments from existing diff and log buffers.

nil       Always use the default value of the variable
          `magit-log-arguments' for log commands.  Likewise,
          always use the default value of the variable
          `magit-diff-arguments' for diff command calls.

current   If the mode of the current buffer is derived from
          `magit-log-mode' or `magit-diff-mode', reuse the
          arguments from that buffer instead of those given by
          the variable `magit-log-arguments' or
          `magit-diff-arguments', respectively.

t         Like `current', but if the mode of the current buffer
          is not derived from `magit-log-mode' or
          `magit-diff-mode', use the arguments from the current
          repository's active (i.e. non-locked) `magit-log-mode'
          or `magit-diff-mode' buffer, respectively, if it
          exists.

          Note that commands that generate a
          `magit-revision-mode' or `magit-stash-mode' buffer will
          also collect their diff arguments from the active
          `magit-diff-mode' buffer.

In general, there is a separation between the \"sticky\"
arguments for log and diff buffers, but there is one special
case: if the current buffer is a log buffer,
`magit-show-commit' (considered a diff command) uses the file
filter from the log buffer."
  :package-version '(magit . "2.11.0")
  :group 'magit-buffers
  :type '(choice (const :tag "disabled" nil)
                 (const :tag "sticky for current" current)
                 (const :tag "sticky" t)))

246 247 248
(defcustom magit-region-highlight-hook
  '(magit-section-update-region magit-diff-update-hunk-region)
  "Functions used to highlight the region.
249

250
Each function is run with the current section as only argument
251 252
until one of them returns non-nil.  If all functions return nil,
then fall back to regular region highlighting."
253
  :package-version '(magit . "2.1.0")
254
  :group 'magit-refresh
255 256 257
  :type 'hook
  :options '(magit-section-update-region magit-diff-update-hunk-region))

258
(defcustom magit-create-buffer-hook nil
259 260 261
  "Normal hook run after creating a new `magit-mode' buffer."
  :package-version '(magit . "2.90.0")
  :group 'magit-refresh
262
  :type 'hook)
263

264
(defcustom magit-refresh-buffer-hook nil
265
  "Normal hook for `magit-refresh-buffer' to run after refreshing."
266
  :package-version '(magit . "2.1.0")
267
  :group 'magit-refresh
268 269
  :type 'hook)

270 271 272 273 274 275 276 277 278 279
(defcustom magit-refresh-status-buffer t
  "Whether the status buffer is refreshed after running git.

When this is non-nil, then the status buffer is automatically
refreshed after running git for side-effects, in addition to the
current Magit buffer, which is always refreshed automatically.

Only set this to nil after exhausting all other options to
improve performance."
  :package-version '(magit . "2.4.0")
280
  :group 'magit-refresh
281 282 283
  :group 'magit-status
  :type 'boolean)

284 285 286 287 288 289
(defcustom magit-refresh-verbose nil
  "Whether to revert Magit buffers verbosely."
  :package-version '(magit . "2.1.0")
  :group 'magit-refresh
  :type 'boolean)

290
(defcustom magit-save-repository-buffers t
291 292
  "Whether to save file-visiting buffers when appropriate.

293
If non-nil, then all modified file-visiting buffers belonging
294 295
to the current repository may be saved before running Magit
commands and before creating or refreshing Magit buffers.
296
If `dontask', then this is done without user intervention, for
297 298 299 300
any other non-nil value the user has to confirm each save.

The default is t to avoid surprises, but `dontask' is the
recommended value."
301 302
  :group 'magit-essentials
  :group 'magit-buffers
303 304 305 306
  :type '(choice (const :tag "Never" nil)
                 (const :tag "Ask" t)
                 (const :tag "Save without asking" dontask)))

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
(defcustom magit-keep-region-overlay nil
  "Whether to keep the region overlay when there is a valid selection.

By default Magit removes the regular region overlay if, and only
if, that region constitutes a valid selection as understood by
Magit commands.  Otherwise it does not remove that overlay, and
the region looks like it would in other buffers.

There are two types of such valid selections: hunk-internal
regions and regions that select two or more sibling sections.
In such cases Magit removes the region overlay and instead
highlights a slightly larger range.  All text (for hunk-internal
regions) or the headings of all sections (for sibling selections)
that are inside that range (not just inside the region) are acted
on by commands such as the staging command.  This buffer range
begins at the beginning of the line on which the region begins
and ends at the end of the line on which the region ends.

Because Magit acts on this larger range and not the region, it is
actually quite important to visualize that larger range.  If we
don't do that, then one might think that these commands act on
the region instead.  If you want to *also* visualize the region,
then set this option to t.  But please note that when the region
does *not* constitute a valid selection, then the region is
*always* visualized as usual, and that it is usually under such
circumstances that you want to use a non-magit command to act on
the region.

Besides keeping the region overlay, setting this option to t also
causes all face properties, except for `:foreground', to be
ignored for the faces used to highlight headings of selected
sections.  This avoids the worst conflicts that result from
displaying the region and the selection overlays at the same
time.  We are not interested in dealing with other conflicts.
In fact we *already* provide a way to avoid all of these
conflicts: *not* changing the value of this option.

It should be clear by now that we consider it a mistake to set
this to display the region when the Magit selection is also
visualized, but since it has been requested a few times and
because it doesn't cost much to offer this option we do so.
Lele Gaifax's avatar
Lele Gaifax committed
348
However that might change.  If the existence of this option
349 350
starts complicating other things, then it will be removed."
  :package-version '(magit . "2.3.0")
351
  :group 'magit-miscellaneous
352 353
  :type 'boolean)

354 355 356 357 358
;;; Magit Mode

(defvar magit-mode-map
  (let ((map (make-keymap)))
    (suppress-keymap map t)
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    (cond ((featurep 'jkl)
           (define-key map   [return]  'magit-visit-thing)
           (define-key map [C-return]  'magit-dired-jump)
           (define-key map   [tab]     'magit-section-toggle)
           (define-key map [C-tab]     'magit-section-cycle)
           (define-key map [M-tab]     'magit-section-cycle-diffs)
           (define-key map [S-tab]     'magit-section-cycle-global)
           (define-key map (kbd "M-o") 'magit-section-up)
           (define-key map (kbd   "i") 'magit-section-backward)
           (define-key map (kbd   "k") 'magit-section-forward)
           (define-key map (kbd "M-i") 'magit-section-backward-sibling)
           (define-key map (kbd "M-k") 'magit-section-forward-sibling)
           (define-key map (kbd   "p") 'magit-push-popup)
           (define-key map (kbd   ",") 'magit-delete-thing)
           (define-key map (kbd   ";") 'magit-file-untrack)
374
           (define-key map (kbd "C-c C-i") 'magit-gitignore-popup))
375 376 377 378 379 380 381
          (t
           (define-key map [C-return]  'magit-visit-thing)
           (define-key map (kbd "C-m") 'magit-visit-thing)
           (define-key map (kbd "C-M-i") 'magit-dired-jump)
           (define-key map (kbd "C-i") 'magit-section-toggle)
           (define-key map [C-tab]     'magit-section-cycle)
           (define-key map [M-tab]     'magit-section-cycle-diffs)
382 383
           ;; [backtab] is the most portable binding for Shift+Tab.
           (define-key map [backtab]   'magit-section-cycle-global)
384 385 386 387 388 389 390 391
           (define-key map (kbd   "^") 'magit-section-up)
           (define-key map (kbd   "p") 'magit-section-backward)
           (define-key map (kbd   "n") 'magit-section-forward)
           (define-key map (kbd "M-p") 'magit-section-backward-sibling)
           (define-key map (kbd "M-n") 'magit-section-forward-sibling)
           (define-key map (kbd   "P") 'magit-push-popup)
           (define-key map (kbd   "k") 'magit-delete-thing)
           (define-key map (kbd   "K") 'magit-file-untrack)
392
           (define-key map (kbd   "i") 'magit-gitignore-popup)
393
           (define-key map (kbd   "I") 'magit-gitignore-popup)))
394 395
    (define-key map (kbd "SPC") 'magit-diff-show-or-scroll-up)
    (define-key map (kbd "DEL") 'magit-diff-show-or-scroll-down)
396 397 398 399 400 401 402 403 404 405 406
    (define-key map "+"         'magit-diff-more-context)
    (define-key map "-"         'magit-diff-less-context)
    (define-key map "0"         'magit-diff-default-context)
    (define-key map "1"         'magit-section-show-level-1)
    (define-key map "2"         'magit-section-show-level-2)
    (define-key map "3"         'magit-section-show-level-3)
    (define-key map "4"         'magit-section-show-level-4)
    (define-key map (kbd "M-1") 'magit-section-show-level-1-all)
    (define-key map (kbd "M-2") 'magit-section-show-level-2-all)
    (define-key map (kbd "M-3") 'magit-section-show-level-3-all)
    (define-key map (kbd "M-4") 'magit-section-show-level-4-all)
407
    (define-key map "$" 'magit-process-buffer)
408
    (define-key map "%" 'magit-worktree-popup)
409
    (define-key map "a" 'magit-cherry-apply)
410 411 412 413 414
    (define-key map "A" 'magit-cherry-pick-popup)
    (define-key map "b" 'magit-branch-popup)
    (define-key map "B" 'magit-bisect-popup)
    (define-key map "c" 'magit-commit-popup)
    (define-key map "d" 'magit-diff-popup)
415
    (define-key map "D" 'magit-diff-refresh-popup)
416 417
    (define-key map "e" 'magit-ediff-dwim)
    (define-key map "E" 'magit-ediff-popup)
418 419
    (define-key map "f" 'magit-fetch-popup)
    (define-key map "F" 'magit-pull-popup)
420 421 422 423
    (define-key map "g" 'magit-refresh)
    (define-key map "G" 'magit-refresh-all)
    (define-key map "h" 'magit-dispatch-popup)
    (define-key map "?" 'magit-dispatch-popup)
424
    (define-key map "l" 'magit-log-popup)
425
    (define-key map "L" 'magit-log-refresh-popup)
426 427 428
    (define-key map "m" 'magit-merge-popup)
    (define-key map "M" 'magit-remote-popup)
    (define-key map "o" 'magit-submodule-popup)
429
    (define-key map "O" 'magit-subtree-popup)
430
    (define-key map "q" 'magit-mode-bury-buffer)
431
    (define-key map "r" 'magit-rebase-popup)
432
    (define-key map "R" 'magit-file-rename)
433
    (define-key map "t" 'magit-tag-popup)
Jonas Bernoulli's avatar
Jonas Bernoulli committed
434
    (define-key map "T" 'magit-notes-popup)
435 436 437
    (define-key map "s" 'magit-stage-file)
    (define-key map "S" 'magit-stage-modified)
    (define-key map "u" 'magit-unstage-file)
438
    (define-key map "U" 'magit-unstage-all)
439
    (define-key map "v" 'magit-revert-no-commit)
440 441
    (define-key map "V" 'magit-revert-popup)
    (define-key map "w" 'magit-am-popup)
442
    (define-key map "W" 'magit-patch-popup)
443
    (define-key map "x" 'magit-reset-quickly)
444
    (define-key map "X" 'magit-reset-popup)
445
    (define-key map "y" 'magit-show-refs-popup)
446 447
    (define-key map "Y" 'magit-cherry)
    (define-key map "z" 'magit-stash-popup)
448
    (define-key map "Z" 'magit-stash-popup)
449 450
    (define-key map ":" 'magit-git-command)
    (define-key map "!" 'magit-run-popup)
451
    (define-key map (kbd "C-c C-b") 'magit-browse-thing)
452 453 454 455 456 457
    (define-key map (kbd "C-c C-c") 'magit-dispatch-popup)
    (define-key map (kbd "C-c C-e") 'magit-dispatch-popup)
    (define-key map (kbd "C-x a")   'magit-add-change-log-entry)
    (define-key map (kbd "C-x 4 a") 'magit-add-change-log-entry-other-window)
    (define-key map (kbd "C-w")     'magit-copy-section-value)
    (define-key map (kbd "M-w")     'magit-copy-buffer-revision)
458 459
    (define-key map [remap previous-line]      'magit-previous-line)
    (define-key map [remap next-line]          'magit-next-line)
460
    (define-key map [remap evil-previous-line] 'evil-previous-visual-line)
461
    (define-key map [remap evil-next-line]     'evil-next-visual-line)
462 463 464
    map)
  "Parent keymap for all keymaps of modes derived from `magit-mode'.")

465 466 467 468
(defun magit-delete-thing ()
  "This is a placeholder command.
Where applicable, section-specific keymaps bind another command
which deletes the thing at point."
469
  (interactive)
470 471 472 473 474 475
  (user-error "There is no thing at point that could be deleted"))

(defun magit-visit-thing ()
  "This is a placeholder command.
Where applicable, section-specific keymaps bind another command
which visits the thing at point."
476
  (interactive)
477 478 479 480 481 482 483 484 485 486
  (if (eq magit-current-popup 'magit-dispatch-popup)
      (progn (setq magit-current-popup nil)
             (call-interactively (key-binding (this-command-keys))))
    (user-error "There is no thing at point that could be visited")))

(defun magit-edit-thing ()
  "This is a placeholder command.
Where applicable, section-specific keymaps bind another command
which lets you edit the thing at point, likely in another buffer."
  (interactive)
487 488 489
  (if (eq magit-current-popup 'magit-dispatch-popup)
      (progn (setq magit-current-popup nil)
             (call-interactively (key-binding (this-command-keys))))
490
    (user-error "There is no thing at point that could be edited")))
491

492 493 494 495 496 497 498
(defun magit-browse-thing ()
  "This is a placeholder command.
Where applicable, section-specific keymaps bind another command
which visits the thing at point using `browse-url'."
  (interactive)
  (user-error "There is no thing at point that could be browsed"))

499 500 501 502 503 504 505 506 507 508 509 510
(easy-menu-define magit-mode-menu magit-mode-map
  "Magit menu"
  '("Magit"
    ["Refresh" magit-refresh t]
    ["Refresh all" magit-refresh-all t]
    "---"
    ["Stage" magit-stage t]
    ["Stage modified" magit-stage-modified t]
    ["Unstage" magit-unstage t]
    ["Reset index" magit-reset-index t]
    ["Commit" magit-commit-popup t]
    ["Add log entry" magit-commit-add-log t]
511
    ["Tag" magit-tag-create t]
512 513 514 515
    "---"
    ["Diff working tree" magit-diff-working-tree t]
    ["Diff" magit-diff t]
    ("Log"
516
     ["Log" magit-log-other t]
517
     ["Reflog" magit-reflog-other t]
518 519 520 521 522
     ["Extended..." magit-log-popup t])
    "---"
    ["Cherry pick" magit-cherry-pick t]
    ["Revert commit" magit-revert-popup t]
    "---"
523
    ["Ignore globally" magit-gitignore-globally t]
524 525
    ["Ignore locally" magit-gitignore-locally t]
    ["Discard" magit-discard t]
526
    ["Reset head and index" magit-reset-mixed t]
527 528
    ["Stash" magit-stash-both t]
    ["Snapshot" magit-snapshot-both t]
529 530 531 532 533 534 535
    "---"
    ["Branch..." magit-checkout t]
    ["Merge" magit-merge t]
    ["Ediff resolve" magit-ediff-resolve t]
    ["Rebase..." magit-rebase-popup t]
    "---"
    ["Push" magit-push t]
536
    ["Pull" magit-pull-branch t]
537
    ["Remote update" magit-fetch-all t]
538 539
    ("Submodule"
     ["Submodule update" magit-submodule-update t]
Kyle Meyer's avatar
Kyle Meyer committed
540
     ["Submodule update and init" magit-submodule-setup t]
541 542 543 544 545
     ["Submodule init" magit-submodule-init t]
     ["Submodule sync" magit-submodule-sync t])
    "---"
    ("Extensions")
    "---"
546
    ["Display Git output" magit-process-buffer t]
547
    ["Quit Magit" magit-mode-bury-buffer t]))
548 549 550 551 552

(defun magit-load-config-extensions ()
  "Load Magit extensions that are defined at the Git config layer."
  (dolist (ext (magit-get-all "magit.extension"))
    (let ((sym (intern (format "magit-%s-mode" ext))))
553
      (when (fboundp sym)
554 555 556 557
        (funcall sym 1)))))

(define-derived-mode magit-mode special-mode "Magit"
  "Parent major mode from which Magit major modes inherit.
558

559 560 561 562
Magit is documented in info node `(magit)'."
  :group 'magit-modes
  (buffer-disable-undo)
  (setq truncate-lines t)
563 564
  (setq buffer-read-only t)
  (setq-local line-move-visual t) ; see #1771
565
  (setq show-trailing-whitespace nil)
566
  (setq list-buffers-directory (abbreviate-file-name default-directory))
567
  (hack-dir-local-variables-non-file-buffer)
568
  (make-local-variable 'text-property-default-nonsticky)
569
  (push (cons 'keymap t) text-property-default-nonsticky)
570
  (add-hook 'post-command-hook #'magit-section-update-highlight t t)
571
  (add-hook 'deactivate-mark-hook #'magit-section-update-highlight t t)
572
  (setq-local redisplay-highlight-region-function 'magit-highlight-region)
573
  (setq-local redisplay-unhighlight-region-function 'magit-unhighlight-region)
574
  (setq mode-line-process (magit-repository-local-get 'mode-line-process))
575 576
  (when (bound-and-true-p global-linum-mode)
    (linum-mode -1))
577 578
  (when (and (fboundp 'nlinum-mode)
             (bound-and-true-p global-nlinum-mode))
579
    (nlinum-mode -1))
580 581 582
  (when (and (fboundp 'display-line-numbers-mode)
             (bound-and-true-p global-display-line-numbers-mode))
    (display-line-numbers-mode -1))
583
  (add-hook 'kill-buffer-hook 'magit-preserve-section-visibility-cache))
584

585 586
(defvar-local magit-region-overlays nil)

587
(defun magit-delete-region-overlays ()
588
  (mapc #'delete-overlay magit-region-overlays)
589 590 591 592
  (setq magit-region-overlays nil))

(defun magit-highlight-region (start end window rol)
  (magit-delete-region-overlays)
593 594
  (if (and (run-hook-with-args-until-success 'magit-region-highlight-hook
                                             (magit-current-section))
Jonas Bernoulli's avatar
Jonas Bernoulli committed
595 596 597 598 599
           (not magit-keep-region-overlay)
           (not (= (line-number-at-pos start)
                   (line-number-at-pos end)))
           ;; (not (eq (car-safe last-command-event) 'mouse-movement))
           )
600 601 602 603 604
      (funcall (default-value 'redisplay-unhighlight-region-function) rol)
    (funcall (default-value 'redisplay-highlight-region-function)
             start end window rol)))

(defun magit-unhighlight-region (rol)
605
  (setq magit-section-highlighted-section nil)
606
  (magit-delete-region-overlays)
607 608
  (funcall (default-value 'redisplay-unhighlight-region-function) rol))

609
(defvar-local magit-refresh-args nil
610
  "The arguments used to refresh the current buffer.")
611 612
(put 'magit-refresh-args 'permanent-local t)

613 614 615 616
(defvar-local magit-previous-section nil)
(put 'magit-previous-section 'permanent-local t)

(defun magit-mode-setup (mode &rest args)
617 618 619
  "Setup up a MODE buffer using ARGS to generate its content."
  (magit-mode-setup-internal mode args))

620 621 622 623
(defun magit-mode-setup-internal (mode args &optional locked)
  "Setup up a MODE buffer using ARGS to generate its content.
When optional LOCKED is non-nil, then create a buffer that is
locked to its value, which is derived from MODE and ARGS."
624 625 626 627 628 629 630
  (let* ((value   (and locked (magit-buffer-lock-value mode args)))
         (buffer  (magit-mode-get-buffer mode nil nil value))
         (section (and buffer (magit-current-section)))
         (created (not buffer)))
    (unless buffer
      (setq buffer (magit-with-toplevel
                     (magit-generate-new-buffer mode value))))
631
    (with-current-buffer buffer
632 633
      (setq magit-previous-section section)
      (setq magit-refresh-args args)
634 635
      (funcall mode)
      (when created
636
        (magit-status-goto-initial-section)
637
        (run-hooks 'magit-create-buffer-hook)))
638
    (magit-display-buffer buffer)
639 640 641
    (with-current-buffer buffer
      (run-hooks 'magit-mode-setup-hook)
      (magit-refresh-buffer))))
642

643 644
(defvar magit-display-buffer-noselect nil
  "If non-nil, then `magit-display-buffer' doesn't call `select-window'.")
645

646 647 648 649 650 651 652 653 654 655 656 657 658
(defun magit-display-buffer (buffer)
  "Display BUFFER in some window and maybe select it.

Display the buffer using `magit-display-buffer-function' and
then, unless `magit-display-buffer-noselect' is non-nil, select
the window which was used to display the buffer.

Also run the hooks `magit-pre-display-buffer-hook'
and `magit-post-display-buffer-hook'."
  (with-current-buffer buffer
    (run-hooks 'magit-pre-display-buffer-hook))
  (let ((window (funcall magit-display-buffer-function buffer)))
    (unless magit-display-buffer-noselect
659 660 661 662 663
      (let* ((old-frame (selected-frame))
             (new-frame (window-frame window)))
        (select-window window)
        (unless (eq old-frame new-frame)
          (select-frame-set-input-focus new-frame)))))
664 665 666
  (with-current-buffer buffer
    (run-hooks 'magit-post-display-buffer-hook)))

667 668 669
(defun magit-display-buffer-traditional (buffer)
  "Display BUFFER the way this has traditionally been done."
  (display-buffer
670 671 672 673 674 675 676 677 678
   buffer (if (and (derived-mode-p 'magit-mode)
                   (not (memq (with-current-buffer buffer major-mode)
                              '(magit-process-mode
                                magit-revision-mode
                                magit-diff-mode
                                magit-stash-mode
                                magit-status-mode))))
              '(display-buffer-same-window)
            nil))) ; display in another window
679

680 681 682 683 684 685 686
(defun magit-display-buffer-same-window-except-diff-v1 (buffer)
  "Display BUFFER in the selected window except for some modes.
If a buffer's `major-mode' derives from `magit-diff-mode' or
`magit-process-mode', display it in another window.  Display all
other buffers in the selected window."
  (display-buffer
   buffer (if (with-current-buffer buffer
687
                (derived-mode-p 'magit-diff-mode 'magit-process-mode))
688 689 690 691
              nil  ; display in another window
            '(display-buffer-same-window))))

(defun magit--display-buffer-fullframe (buffer alist)
692 693 694 695
  (when-let ((window (or (display-buffer-reuse-window buffer alist)
                         (display-buffer-same-window buffer alist)
                         (display-buffer-pop-up-window buffer alist)
                         (display-buffer-use-some-window buffer alist))))
696 697 698 699 700 701 702 703 704 705 706
    (delete-other-windows window)
    window))

(defun magit-display-buffer-fullframe-status-v1 (buffer)
  "Display BUFFER, filling entire frame if BUFFER is a status buffer.
Otherwise, behave like `magit-display-buffer-traditional'."
  (if (eq (with-current-buffer buffer major-mode)
          'magit-status-mode)
      (display-buffer buffer '(magit--display-buffer-fullframe))
    (magit-display-buffer-traditional buffer)))

707 708
(defun magit--display-buffer-topleft (buffer alist)
  (or (display-buffer-reuse-window buffer alist)
709
      (when-let ((window2 (display-buffer-pop-up-window buffer alist)))
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        (let ((window1 (get-buffer-window))
              (buffer1 (current-buffer))
              (buffer2 (window-buffer window2))
              (w2-quit-restore (window-parameter window2 'quit-restore)))
          (set-window-buffer window1 buffer2)
          (set-window-buffer window2 buffer1)
          (select-window window2)
          ;; Swap some window state that `magit-mode-quit-window' and
          ;; `quit-restore-window' inspect.
          (set-window-prev-buffers window2 (cdr (window-prev-buffers window1)))
          (set-window-prev-buffers window1 nil)
          (set-window-parameter window2 'magit-dedicated
                                (window-parameter window1 'magit-dedicated))
          (set-window-parameter window1 'magit-dedicated t)
          (set-window-parameter window1 'quit-restore
                                (list 'window 'window
                                      (nth 2 w2-quit-restore)
                                      (nth 3 w2-quit-restore)))
          (set-window-parameter window2 'quit-restore nil)
          window1))))

(defun magit-display-buffer-fullframe-status-topleft-v1 (buffer)
  "Display BUFFER, filling entire frame if BUFFER is a status buffer.
When BUFFER derives from `magit-diff-mode' or
`magit-process-mode', try to display BUFFER to the top or left of
the current buffer rather than to the bottom or right, as
`magit-display-buffer-fullframe-status-v1' would.  Whether the
split is made vertically or horizontally is determined by
`split-window-preferred-function'."
  (display-buffer
   buffer
   (cond ((eq (with-current-buffer buffer major-mode)
              'magit-status-mode)
          '(magit--display-buffer-fullframe))
         ((with-current-buffer buffer
            (derived-mode-p 'magit-diff-mode 'magit-process-mode))
          '(magit--display-buffer-topleft))
         (t
          '(display-buffer-same-window)))))

750
(defun magit--display-buffer-fullcolumn (buffer alist)
751 752 753
  (when-let ((window (or (display-buffer-reuse-window buffer alist)
                         (display-buffer-same-window buffer alist)
                         (display-buffer-below-selected buffer alist))))
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    (delete-other-windows-vertically window)
    window))

(defun magit-display-buffer-fullcolumn-most-v1 (buffer)
  "Display BUFFER using the full column except in some cases.
For most cases where BUFFER's `major-mode' derives from
`magit-mode', display it in the selected window and grow that
window to the full height of the frame, deleting other windows in
that column as necessary.  However, display BUFFER in another
window if 1) BUFFER's mode derives from `magit-process-mode', or
2) BUFFER's mode derives from `magit-diff-mode', provided that
the mode of the current buffer derives from `magit-log-mode' or
`magit-cherry-mode'."
  (display-buffer
   buffer
769 770
   (cond ((and (or git-commit-mode
                   (derived-mode-p 'magit-log-mode 'magit-cherry-mode))
771 772 773 774 775 776 777 778 779
               (with-current-buffer buffer
                 (derived-mode-p 'magit-diff-mode)))
          nil)
         ((with-current-buffer buffer
            (derived-mode-p 'magit-process-mode))
          nil)
         (t
          '(magit--display-buffer-fullcolumn)))))

780 781 782 783 784 785 786 787 788 789 790
(defun magit-maybe-set-dedicated ()
  "Mark the selected window as dedicated if appropriate.

If a new window was created to display the buffer, then remember
that fact.  That information is used by `magit-mode-quit-window',
to determine whether the window should be deleted when its last
Magit buffer is buried."
  (let ((window (get-buffer-window (current-buffer))))
    (when (and (window-live-p window)
               (not (window-prev-buffers window)))
      (set-window-parameter window 'magit-dedicated t))))
791

792 793 794 795 796 797 798
(defvar-local magit--default-directory nil
  "Value of `default-directory' when buffer is generated.
This exists to prevent a let-bound `default-directory' from
tricking `magit-mode-get-buffer' or `magit-mode-get-buffers' into
thinking a buffer belongs to a repo that it doesn't.")
(put 'magit--default-directory 'permanent-local t)

799 800 801 802
(defun magit-mode-get-buffers ()
  (let ((topdir (magit-toplevel)))
    (--filter (with-current-buffer it
                (and (derived-mode-p 'magit-mode)
803
                     (equal magit--default-directory topdir)))
804
              (buffer-list))))
805

806 807 808
(defvar-local magit-buffer-locked-p nil)
(put 'magit-buffer-locked-p 'permanent-local t)

809
(defun magit-mode-get-buffer (mode &optional create frame value)
810 811
  (when create
    (error "`magit-mode-get-buffer's CREATE argument is obsolete"))
812
  (if-let ((topdir (magit-toplevel)))
813 814 815 816 817 818 819 820 821 822 823
      (--first (with-current-buffer it
                 (and (eq major-mode mode)
                      (equal magit--default-directory topdir)
                      (if value
                          (and magit-buffer-locked-p
                               (equal (magit-buffer-lock-value) value))
                        (not magit-buffer-locked-p))))
               (if frame
                   (mapcar #'window-buffer
                           (window-list (unless (eq frame t) frame)))
                 (buffer-list)))
824
    (magit--not-inside-repository-error)))
825

826 827
(defun magit-generate-new-buffer (mode &optional value)
  (let* ((name (funcall magit-generate-buffer-name-function mode value))
828
         (buffer (generate-new-buffer name)))
829
    (with-current-buffer buffer
830
      (setq magit--default-directory default-directory)
831 832
      (setq magit-buffer-locked-p (and value t))
      (magit-restore-section-visibility-cache mode))
833 834 835
    (when magit-uniquify-buffer-names
      (add-to-list 'uniquify-list-buffers-directory-modes mode)
      (with-current-buffer buffer
836
        (setq list-buffers-directory (abbreviate-file-name default-directory)))
837
      (let ((uniquify-buffer-name-style
838
             (if (memq uniquify-buffer-name-style '(nil forward))
839 840 841 842 843
                 'post-forward-angle-brackets
               uniquify-buffer-name-style)))
        (uniquify-rationalize-file-buffer-names
         name (file-name-directory (directory-file-name default-directory))
         buffer)))
844 845 846
    buffer))

(defun magit-generate-buffer-name-default-function (mode &optional value)
847 848 849 850
  "Generate buffer name for a MODE buffer in the current repository.
The returned name is based on `magit-buffer-name-format' and
takes `magit-uniquify-buffer-names' and VALUE, if non-nil, into
account."
851
  (let ((m (substring (symbol-name mode) 0 -5))
852 853 854 855 856
        (v (and value (format "%s" (if (listp value) value (list value)))))
        (n (if magit-uniquify-buffer-names
               (file-name-nondirectory
                (directory-file-name default-directory))
             (abbreviate-file-name default-directory))))
857 858 859 860
    (format-spec
     magit-buffer-name-format
     `((?m . ,m)
       (?M . ,(if (eq mode 'magit-status-mode) "magit" m))
861 862
       (?v . ,(or v ""))
       (?V . ,(if v (concat " " v) ""))
863
       (?t . ,n)
864
       (?x . ,(if magit-uniquify-buffer-names "" "*"))
865
       (?T . ,(if magit-uniquify-buffer-names n (concat n "*")))))))
866

867 868 869
(defun magit-toggle-buffer-lock ()
  "Lock the current buffer to its value or unlock it.

870
Locking a buffer to its value prevents it from being reused to
871 872 873 874 875 876 877 878 879 880 881 882 883 884
display another value.  The name of a locked buffer contains its
value, which allows telling it apart from other locked buffers
and the unlocked buffer.

Not all Magit buffers can be locked to their values, for example
it wouldn't make sense to lock a status buffer.

There can only be a single unlocked buffer using a certain
major-mode per repository.  So when a buffer is being unlocked
and another unlocked buffer already exists for that mode and
repository, then the former buffer is instead deleted and the
latter is displayed in its place."
  (interactive)
  (if magit-buffer-locked-p
885
      (if-let ((unlocked (magit-mode-get-buffer major-mode)))
886
          (let ((locked (current-buffer)))
887
            (switch-to-buffer unlocked nil t)
888 889 890 891
            (kill-buffer locked))
        (setq magit-buffer-locked-p nil)
        (rename-buffer (funcall magit-generate-buffer-name-function
                                major-mode)))
892 893
    (if-let ((value (magit-buffer-lock-value)))
        (if-let ((locked (magit-mode-get-buffer major-mode nil nil value)))
894 895 896 897 898 899
            (let ((unlocked (current-buffer)))
              (switch-to-buffer locked nil t)
              (kill-buffer unlocked))
          (setq magit-buffer-locked-p t)
          (rename-buffer (funcall magit-generate-buffer-name-function
                                  major-mode value)))
900 901
      (user-error "Buffer has no value it could be locked to"))))

902 903 904 905 906 907
(defvar magit-buffer-lock-functions nil
  "Provide buffer-locking support for third-party modes.
An alist of symbols to functions.

The symbol must be the major-mode the locked buffer will have.

908 909 910 911
The function must take a single argument, a list of refresh
arguments (the value of `magit-refresh-args') and return a
value that identifies the buffer (i.e., its 'lock value').
If the third-party mode is invoked as
912 913 914 915 916

    (magit-mode-setup-internal #\\='my-mode \\='(1 2 3) t)

the function will be invoked as

917
    (funcall lock-func \\='(1 2 3))
918 919 920 921 922 923 924 925

if the cons (my-mode . lock-func) is in this list.

This variable is intended for third-party extensions;
`magit-buffer-lock-value' implements all built-in behavior.

See also `magit-toggle-buffer-lock'.")

926 927 928
(cl-defun magit-buffer-lock-value
    (&optional (mode major-mode)
               (args magit-refresh-args))
929 930
  "Find an appropriate buffer lock value for MODE under ARGS.
See also `magit-buffer-lock-functions'."
931
  (cl-case mode
932
    (magit-cherry-mode
933
     (pcase-let ((`(,upstream ,head) args))
934
       (concat head ".." upstream)))
935
    (magit-diff-mode
936
     (pcase-let ((`(,rev-or-range ,const ,_args ,files) args))
937 938 939 940 941 942 943 944
       (nconc (cons (or rev-or-range
                        (if (member "--cached" const)
                            (progn (setq const (delete "--cached" const))
                                   'staged)
                          'unstaged))
                    const)
              (and files (cons "--" files)))))
    (magit-log-mode
945
     (pcase-let ((`(,revs ,_args ,files) args))
946 947 948 949
       (if (and revs files)
           (append revs (cons "--" files))
         (append revs files))))
    (magit-refs-mode
950
     (pcase-let ((`(,ref ,args) args))
951 952
       (cons (or ref "HEAD") args)))
    (magit-revision-mode
953
     (pcase-let ((`(,rev ,_const ,_args ,files) args))
954 955 956 957
       (if files (cons rev files) (list rev))))
    ((magit-reflog-mode   ; (ref ~args)
      magit-stash-mode    ; (stash _const _args _files)
      magit-stashes-mode) ; (ref)
958 959
     (car args))
    (t
960
     (--when-let (cdr (assq mode magit-buffer-lock-functions))
961
       (funcall it args)))))
962

963 964
(defun magit-mode-bury-buffer (&optional kill-buffer)
  "Bury the current buffer.
965
With a prefix argument, kill the buffer instead.
966
This is done using `magit-bury-buffer-function'."
967
  (interactive "P")
968
  (funcall magit-bury-buffer-function kill-buffer))
969

970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
(defun magit-mode-quit-window (kill-buffer)
  "Quit the selected window and bury its buffer.

This behaves similar to `quit-window', but when the window
was originally created to display a Magit buffer and the
current buffer is the last remaining Magit buffer that was
ever displayed in the selected window, then delete that
window."
  (if (or (one-window-p)
          (--first (let ((buffer (car it)))
                     (and (not (eq buffer (current-buffer)))
                          (buffer-live-p buffer)
                          (or (not (window-parameter nil 'magit-dedicated))
                              (with-current-buffer buffer
                                (derived-mode-p 'magit-mode
                                                'magit-process-mode)))))
                   (window-prev-buffers)))
      (quit-window kill-buffer)
    (let ((window (selected-window)))
      (quit-window kill-buffer)
      (when (window-live-p window)
        (delete-window window)))))

993
;;; Refresh Magit Buffers
994 995 996 997 998 999 1000

(defvar inhibit-magit-refresh nil)

(defun magit-refresh ()
  "Refresh some buffers belonging to the current repository.

Refresh the current buffer if its major mode derives from
1001 1002 1003
`magit-mode', and refresh the corresponding status buffer.

Run hooks `magit-pre-refresh-hook' and `magit-post-refresh-hook'."
1004 1005
  (interactive)
  (unless inhibit-magit-refresh
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    (unwind-protect
        (let ((start (current-time))
              (magit--refresh-cache (or magit--refresh-cache
                                        (list (cons 0 0)))))
          (when magit-refresh-verbose
            (message "Refreshing magit..."))
          (magit-run-hook-with-benchmark 'magit-pre-refresh-hook)
          (when (derived-mode-p 'magit-mode)
            (magit-refresh-buffer))
          (--when-let (and magit-refresh-status-buffer
                           (not (derived-mode-p 'magit-status-mode))
                           (magit-mode-get-buffer 'magit-status-mode))
            (with-current-buffer it
              (magit-refresh-buffer)))
          (magit-auto-revert-buffers)
1021
          (cond
1022 1023
           ((and (not this-command)
                 (memq last-command magit-post-commit-hook-commands))
1024 1025 1026 1027 1028
            (magit-run-hook-with-benchmark 'magit-post-commit-hook))
           ((memq this-command magit-post-stage-hook-commands)
            (magit-run-hook-with-benchmark 'magit-post-stage-hook))
           ((memq this-command magit-post-unstage-hook-commands)
            (magit-run-hook-with-benchmark 'magit-post-unstage-hook)))
1029 1030 1031 1032 1033 1034 1035 1036
          (magit-run-hook-with-benchmark 'magit-post-refresh-hook)
          (when magit-refresh-verbose
            (message "Refreshing magit...done (%.3fs, cached %s/%s)"
                     (float-time (time-subtract (current-time) start))
                     (caar magit--refresh-cache)
                     (+ (caar magit--refresh-cache)
                        (cdar magit--refresh-cache)))))
      (run-hooks 'magit-unwind-refresh-hook))))
1037 1038 1039 1040

(defun magit-refresh-all ()
  "Refresh all buffers belonging to the current repository.

1041 1042 1043
Refresh all Magit buffers belonging to the current repository,
and revert buffers that visit files located inside the current
repository.
1044

1045
Run hooks `magit-pre-refresh-hook' and `magit-post-refresh-hook'."
1046
  (interactive)
1047
  (magit-run-hook-with-benchmark 'magit-pre-refresh-hook)
1048 1049
  (dolist (buffer (magit-mode-get-buffers))
    (with-current-buffer buffer (magit-refresh-buffer)))
1050 1051
  (magit-auto-revert-buffers)
  (magit-run-hook-with-benchmark 'magit-post-refresh-hook))
1052

1053 1054
(defvar-local magit-refresh-start-time nil)

1055
(defun magit-refresh-buffer ()
1056
  "Refresh the current Magit buffer."
1057
  (setq magit-refresh-start-time (current-time))
1058
  (let ((refresh (intern (format "%s-refresh-buffer"
1059 1060
                                 (substring (symbol-name major-mode) 0 -5))))
        (magit--refresh-cache (or magit--refresh-cache (list (cons 0 0)))))
1061 1062 1063 1064 1065 1066 1067
    (when (functionp refresh)
      (when magit-refresh-verbose
        (message "Refreshing buffer `%s'..." (buffer-name)))
      (let* ((buffer (current-buffer))
             (windows
              (--mapcat (with-selected-window it
                          (with-current-buffer buffer
1068
                            (when-let ((section (magit-current-section)))
1069 1070 1071 1072 1073 1074
                              (list
                               (nconc (list it section)
                                      (magit-refresh-get-relative-position))))))
                        (or (get-buffer-window-list buffer nil t)
                            (list (selected-window))))))
        (deactivate-mark)
1075 1076 1077 1078
        (setq magit-section-highlight-overlays nil)
        (setq magit-section-highlighted-section nil)
        (setq magit-section-highlighted-sections nil)
        (setq magit-section-unhighlight-sections nil)
1079
        (magit-process-unset-mode-line-error-status)
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
        (let ((inhibit-read-only t))
          (erase-buffer)
          (save-excursion
            (apply refresh magit-refresh-args)))
        (dolist (window windows)
          (with-selected-window (car window)
            (with-current-buffer buffer
              (apply #'magit-section-goto-successor (cdr window)))))
        (run-hooks 'magit-refresh-buffer-hook)
        (magit-section-update-highlight)
        (set-buffer-modified-p nil))
      (when magit-refresh-verbose
        (message "Refreshing buffer `%s'...done (%.3fs)" (buffer-name)
                 (float-time (time-subtract (current-time)
                                            magit-refresh-start-time)))))))
1095

1096
(defun magit-refresh-get-relative-position ()
1097
  (when-let ((section (magit-current-section)))
1098
    (let ((start (oref section start)))
1099 1100
      (list (count-lines start (point))
            (- (point) (line-beginning-position))
1101
            (and (magit-hunk-section-p section)
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
                 (region-active-p)
                 (progn (goto-char (line-beginning-position))
                        (when  (looking-at "^[-+]") (forward-line))
                        (while (looking-at "^[ @]") (forward-line))
                        (let ((beg (point)))
                          (cond ((looking-at "^[-+]")
                                 (forward-line)
                                 (while (looking-at "^[-+]") (forward-line))
                                 (while (looking-at "^ ")    (forward-line))
                                 (forward-line -1)
                                 (regexp-quote (buffer-substring-no-properties
                                                beg (line-end-position))))
                                (t t)))))))))

1116
;;; Save File-Visiting Buffers
1117 1118 1119 1120 1121 1122 1123

(defvar disable-magit-save-buffers nil)

(defun magit-pre-command-hook ()
  (setq disable-magit-save-buffers nil))
(add-hook 'pre-command-hook #'magit-pre-command-hook)

1124 1125 1126 1127
(defvar magit-after-save-refresh-buffers nil)

(defun magit-after-save-refresh-buffers ()
  (dolist (buffer magit-after-save-refresh-buffers)
1128 1129 1130
    (when (buffer-live-p buffer)
      (with-current-buffer buffer
        (magit-refresh-buffer))))
1131 1132 1133 1134 1135 1136 1137 1138 1139
  (setq magit-after-save-refresh-buffers nil)
  (remove-hook 'post-command-hook 'magit-after-save-refresh-buffers))

(defun magit-after-save-refresh-status ()
  "Refresh the status buffer of the current repository.

This function is intended to be added to `after-save-hook'.

If the status buffer does not exist or the file being visited in
1140 1141
the current buffer isn't inside the working tree of a repository,
then do nothing.
1142 1143 1144 1145 1146

Note that refreshing a Magit buffer is done by re-creating its
contents from scratch, which can be slow in large repositories.
If you are not satisfied with Magit's performance, then you
should obviously not add this function to that hook."
1147
  (when (and (not disable-magit-save-buffers)
1148
             (magit-inside-worktree-p t))
1149 1150 1151 1152
    (--when-let (ignore-errors (magit-mode-get-buffer 'magit-status-mode))
      (add-to-list 'magit-after-save-refresh-buffers it)
      (add-hook 'post-command-hook 'magit-after-save-refresh-buffers))))

1153
(defun magit-maybe-save-repository-buffers ()
1154
  "Maybe save file-visiting buffers belonging to the current repository.
1155 1156 1157
Do so if `magit-save-repository-buffers' is non-nil.  You should
not remove this from any hooks, instead set that variable to nil
if you so desire."
1158 1159 1160
  (when (and magit-save-repository-buffers
             (not disable-magit-save-buffers))
    (setq disable-magit-save-buffers t)
1161 1162 1163
    (let ((msg (current-message)))
      (magit-save-repository-buffers
       (eq magit-save-repository-buffers 'dontask))
1164 1165 1166
      (when (and msg
                 (current-message)
                 (not (equal msg (current-message))))
1167
        (message "%s" msg)))))
1168 1169 1170 1171 1172

(add-hook 'magit-pre-refresh-hook #'magit-maybe-save-repository-buffers)
(add-hook 'magit-pre-call-git-hook #'magit-maybe-save-repository-buffers)
(add-hook 'magit-pre-start-git-hook #'magit-maybe-save-repository-buffers)

1173 1174
(defvar-local magit-inhibit-refresh-save nil)

1175 1176 1177 1178 1179 1180 1181
(defun magit-save-repository-buffers (&optional arg)
  "Save file-visiting buffers belonging to the current repository.
After any buffer where `buffer-save-without-query' is non-nil
is saved without asking, the user is asked about each modified
buffer which visits a file in the current repository.  Optional
argument (the prefix) non-nil means save all with no questions."
  (interactive "P")
1182
  (when-let ((topdir (magit-rev-parse-safe "--show-toplevel")))
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    (let ((remote (file-remote-p topdir))
          (save-some-buffers-action-alist
           `((?Y (lambda (buffer)
                   (with-current-buffer buffer
                     (setq buffer-save-without-query t)
                     (save-buffer)))
                 "to save the current buffer and remember choice")
             (?N (lambda (buffer)
                   (with-current-buffer buffer
                     (setq magit-inhibit-refresh-save t)))
                 "to skip the current buffer and remember choice")
             ,@save-some-buffers-action-alist)))
1195 1196
      (save-some-buffers
       arg (lambda ()
1197 1198
             (and (not magit-inhibit-refresh-save)
                  buffer-file-name
1199
                  (file-exists-p (file-name-directory buffer-file-name))
1200 1201 1202 1203 1204 1205
                  ;; Avoid needlessly connecting to unrelated remotes.
                  (equal (file-remote-p buffer-file-name)
                         remote)
                  (string-prefix-p topdir (file-truename buffer-file-name))
                  (equal (magit-rev-parse-safe "--show-toplevel")
                         topdir)))))))
1206

1207 1208 1209 1210 1211 1212 1213 1214
;;; Restore Window Configuration

(defvar magit-inhibit-save-previous-winconf nil)

(defvar-local magit-previous-window-configuration nil)
(put 'magit-previous-window-configuration 'permanent-local t)

(defun magit-save-window-configuration ()
1215 1216 1217 1218
  "Save the current window configuration.

Later, when the buffer is buried, it may be restored by
`magit-restore-window-configuration'."
1219 1220 1221 1222 1223 1224 1225 1226
  (if magit-inhibit-save-previous-winconf
      (when (eq magit-inhibit-save-previous-winconf 'unset)
        (setq magit-previous-window-configuration nil))
    (unless (get-buffer-window (current-buffer) (selected-frame))
      (setq magit-previous-window-configuration
            (current-window-configuration)))))

(defun magit-restore-window-configuration (&optional kill-buffer)
1227
  "Bury or kill the current buffer and restore previous window configuration."
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
  (let ((winconf magit-previous-window-configuration)
        (buffer (current-buffer))
        (frame (selected-frame)))
    (quit-window kill-buffer (selected-window))
    (when (and winconf (equal frame (window-configuration-frame winconf)))
      (set-window-configuration winconf)
      (when (buffer-live-p buffer)
        (with-current-buffer buffer
          (setq magit-previous-window-configuration nil))))))

1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
;;; Buffer History

(defun magit-go-backward ()
  "Move backward in current buffer's history."
  (interactive)
  (if help-xref-stack
      (help-xref-go-back (current-buffer))
    (user-error "No previous entry in buffer's history")))

(defun magit-go-forward ()
  "Move forward in current buffer's history."
  (interactive)
  (if help-xref-forward-stack
      (help-xref-go-forward (current-buffer))
    (user-error "No next entry in buffer's history")))

1254 1255 1256
(defun magit-insert-xref-buttons (&optional _)
  "Insert xref buttons."
  (when (or help-xref-stack help-xref-forward-stack)
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
    (when help-xref-stack
      (magit-xref-insert-button help-back-label 'magit-xref-backward))
    (when help-xref-forward-stack
      (when help-xref-stack
        (insert " "))
      (magit-xref-insert-button help-forward-label 'magit-xref-forward))))

(defun magit-xref-insert-button (label type)
  (magit-insert-section (button label)
    (insert-text-button label 'type type
                        'help-args (list (current-buffer)))))

(define-button-type 'magit-xref-backward
  :supertype 'help-back
  'mouse-face 'magit-section-highlight
  'help-echo (purecopy "mouse-2, RET: go back to previous history entry"))

(define-button-type 'magit-xref-forward
  :supertype 'help-forward
  'mouse-face 'magit-section-highlight
  'help-echo (purecopy "mouse-2, RET: go back to next history entry"))

1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
(defun magit-xref-setup ()
  "Insert backward/forward buttons if the major-mode supports it.
Currently `magit-log-mode', `magit-reflog-mode',
`magit-diff-mode', and `magit-revision-mode' support it"
  (when (memq major-mode '(magit-log-mode
                           magit-reflog-mode
                           magit-diff-mode
                           magit-revision-mode))
    (when help-xref-stack-item
      (push (cons (point) help-xref-stack-item) help-xref-stack)
      (setq help-xref-forward-stack nil))
    (when (called-interactively-p 'interactive)
      (--when-let (nthcdr 10 help-xref-stack)
        (setcdr it nil)))
    (setq help-xref-stack-item
          `(magit-xref-restore ,default-directory ,@magit-refresh-args))))
1295 1296

(defun magit-xref-restore (&rest args)
1297
  (magit-xref-setup)
1298 1299 1300 1301
  (setq default-directory  (car args))
  (setq magit-refresh-args (cdr args))
  (magit-refresh-buffer))

1302
;;; Repository-Local Cache
1303

1304 1305 1306 1307 1308 1309
(defvar magit-repository-local-cache nil
  "Alist mapping `magit-toplevel' paths to alists of key/value pairs.")

(defun magit-repository-local-repository ()
  "Return the key for the current repository."
  (or (bound-and-true-p magit--default-directory)
1310
      (magit-toplevel)))
1311 1312 1313 1314

(defun magit-repository-local-set (key value &optional repository)
  "Set the repository-local VALUE for KEY.

1315 1316 1317 1318
Unless specified, REPOSITORY is the current buffer's repository.

If REPOSITORY is nil (meaning there is no current repository),
then the value is not cached, and we return nil."
1319 1320
  (let* ((repokey (or repository (magit-repository-local-repository)))
         (cache (assoc repokey magit-repository-local-cache)))
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
    ;; Don't cache values for a nil REPOSITORY, as the 'set' and 'get'
    ;; calls for some KEY may happen in unrelated contexts.
    (when repokey
      (if cache
          (let ((keyvalue (assoc key (cdr cache))))
            (if keyvalue
                ;; Update pre-existing value for key.
                (setcdr keyvalue value)
              ;; No such key in repository-local cache.
              (push (cons key value) (cdr cache))))
        ;; No cache for this repository.
        (push (cons repokey (list (cons key value)))
              magit-repository-local-cache)))))
1334 1335 1336 1337

(defun magit-repository-local-exists-p (key &optional repository)
  "Non-nil when a repository-local value exists for KEY.

1338 1339 1340 1341
Returns a (KEY . value) cons cell.

The KEY is matched using `equal'.

1342 1343 1344 1345
Unless specified, REPOSITORY is the current buffer's repository."
  (let* ((repokey (or repository (magit-repository-local-repository)))
         (cache (assoc repokey magit-repository-local-cache)))
    (and cache
1346
         (assoc key (cdr cache)))))
1347 1348 1349 1350 1351 1352

(defun magit-repository-local-get (key &optional default repository)
  "Return the repository-local value for KEY.

Return DEFAULT if no value for KEY exists.

1353 1354
The KEY is matched using `equal'.

1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
Unless specified, REPOSITORY is the current buffer's repository."
  (let ((keyvalue (magit-repository-local-exists-p key repository)))
    (if keyvalue
        (cdr keyvalue)
      default)))

(defun magit-repository-local-delete (key &optional repository)
  "Delete the repository-local value for KEY.

Unless specified, REPOSITORY is the current buffer's repository."
  (let* ((repokey (or repository (magit-repository-local-repository)))
         (cache (assoc repokey magit-repository-local-cache)))
    (when cache
1368 1369 1370
      ;; There is no `assoc-delete-all'.
      (setf (cdr cache)
            (cl-delete key (cdr cache) :key #'car :test #'equal)))))
1371

1372 1373
(defun magit-zap-caches ()
  "Zap caches for the current repository.
1374
Remove the repository's entry from `magit-repository-local-cache'
1375
and set `magit-section-visibility-cache' to nil in all of the
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
repository's Magit buffers."
  (interactive)
  (magit-with-toplevel
    (setq magit-repository-local-cache
          (cl-delete default-directory
                     magit-repository-local-cache
                     :key #'car :test #'equal)))
  (dolist (buffer (magit-mode-get-buffers))
    (with-current-buffer buffer
      (setq magit-section-visibility-cache nil))))

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
;;; Utilities

(defun magit-run-hook-with-benchmark (hook)
  (when hook
    (if magit-refresh-verbose
        (let ((start (current-time)))
          (message "Running %s..." hook)
          (run-hooks hook)
          (message "Running %s...done (%.3fs)" hook
                   (float-time (time-subtract (current-time) start))))
      (run-hooks hook))))

1399
;;; _
1400 1401
(provide 'magit-mode)
;;; magit-mode.el ends here