stgit.el: Allow revert on index and work tree
[stgit] / contrib / stgit.el
1 ;; stgit.el: An emacs mode for StGit
2 ;;
3 ;; Copyright (C) 2007 David Kågedal <davidk@lysator.liu.se>
4 ;;
5 ;; To install: put this file on the load-path and place the following
6 ;; in your .emacs file:
7 ;;
8 ;; (require 'stgit)
9 ;;
10 ;; To start: `M-x stgit'
11
12 (when (< emacs-major-version 22)
13 (error "Emacs older than 22 is not supported by stgit.el"))
14
15 (require 'git nil t)
16 (require 'cl)
17 (require 'ewoc)
18
19 (defun stgit (dir)
20 "Manage StGit patches for the tree in DIR.
21
22 See `stgit-mode' for commands available."
23 (interactive "DDirectory: \n")
24 (switch-to-stgit-buffer (git-get-top-dir dir))
25 (stgit-reload))
26
27 (unless (fboundp 'git-get-top-dir)
28 (defun git-get-top-dir (dir)
29 "Retrieve the top-level directory of a git tree."
30 (let ((cdup (with-output-to-string
31 (with-current-buffer standard-output
32 (cd dir)
33 (unless (eq 0 (call-process "git" nil t nil
34 "rev-parse" "--show-cdup"))
35 (error "Cannot find top-level git tree for %s" dir))))))
36 (expand-file-name (concat (file-name-as-directory dir)
37 (car (split-string cdup "\n")))))))
38
39 (defun stgit-refresh-git-status (&optional dir)
40 "If it exists, refresh the `git-status' buffer belonging to
41 directory DIR or `default-directory'"
42 (when (and (fboundp 'git-find-status-buffer)
43 (fboundp 'git-refresh-status))
44 (let* ((top-dir (git-get-top-dir (or dir default-directory)))
45 (git-status-buffer (and top-dir (git-find-status-buffer top-dir))))
46 (when git-status-buffer
47 (with-current-buffer git-status-buffer
48 (git-refresh-status))))))
49
50 (defun stgit-find-buffer (dir)
51 "Return the buffer displaying StGit patches for DIR, or nil if none."
52 (setq dir (file-name-as-directory dir))
53 (let ((buffers (buffer-list)))
54 (while (and buffers
55 (not (with-current-buffer (car buffers)
56 (and (eq major-mode 'stgit-mode)
57 (string= default-directory dir)))))
58 (setq buffers (cdr buffers)))
59 (and buffers (car buffers))))
60
61 (defun switch-to-stgit-buffer (dir)
62 "Switch to a (possibly new) buffer displaying StGit patches for DIR."
63 (setq dir (file-name-as-directory dir))
64 (let ((buffer (stgit-find-buffer dir)))
65 (switch-to-buffer (or buffer
66 (create-stgit-buffer dir)))))
67
68 (defstruct (stgit-patch)
69 status name desc empty files-ewoc)
70
71 (defun stgit-patch-pp (patch)
72 (let* ((status (stgit-patch-status patch))
73 (start (point))
74 (name (stgit-patch-name patch))
75 (face (cdr (assq status stgit-patch-status-face-alist))))
76 (insert (case status
77 ('applied "+")
78 ('top ">")
79 ('unapplied "-")
80 (t " "))
81 (if (memq name stgit-marked-patches)
82 "*" " "))
83 (if (memq status '(index work))
84 (insert (propertize (if (eq status 'index) "Index" "Work tree")
85 'face face))
86 (insert (format "%-30s"
87 (propertize (symbol-name name)
88 'face face
89 'syntax-table (string-to-syntax "w")))
90 " "
91 (if (stgit-patch-empty patch) "(empty) " "")
92 (propertize (or (stgit-patch-desc patch) "")
93 'face 'stgit-description-face)))
94 (insert "\n")
95 (put-text-property start (point) 'entry-type 'patch)
96 (when (memq name stgit-expanded-patches)
97 (stgit-insert-patch-files patch))
98 (put-text-property start (point) 'patch-data patch)))
99
100 (defun create-stgit-buffer (dir)
101 "Create a buffer for showing StGit patches.
102 Argument DIR is the repository path."
103 (let ((buf (create-file-buffer (concat dir "*stgit*")))
104 (inhibit-read-only t))
105 (with-current-buffer buf
106 (setq default-directory dir)
107 (stgit-mode)
108 (set (make-local-variable 'stgit-ewoc)
109 (ewoc-create #'stgit-patch-pp "Branch:\n\n" "--\n" t))
110 (setq buffer-read-only t))
111 buf))
112
113 (defmacro stgit-capture-output (name &rest body)
114 "Capture StGit output and, if there was any output, show it in a window
115 at the end.
116 Returns nil if there was no output."
117 (declare (debug ([&or stringp null] body))
118 (indent 1))
119 `(let ((output-buf (get-buffer-create ,(or name "*StGit output*")))
120 (stgit-dir default-directory)
121 (inhibit-read-only t))
122 (with-current-buffer output-buf
123 (erase-buffer)
124 (setq default-directory stgit-dir)
125 (setq buffer-read-only t))
126 (let ((standard-output output-buf))
127 ,@body)
128 (with-current-buffer output-buf
129 (set-buffer-modified-p nil)
130 (setq buffer-read-only t)
131 (if (< (point-min) (point-max))
132 (display-buffer output-buf t)))))
133
134 (defun stgit-make-run-args (args)
135 "Return a copy of ARGS with its elements converted to strings."
136 (mapcar (lambda (x)
137 ;; don't use (format "%s" ...) to limit type errors
138 (cond ((stringp x) x)
139 ((integerp x) (number-to-string x))
140 ((symbolp x) (symbol-name x))
141 (t
142 (error "Bad element in stgit-make-run-args args: %S" x))))
143 args))
144
145 (defun stgit-run-silent (&rest args)
146 (setq args (stgit-make-run-args args))
147 (apply 'call-process "stg" nil standard-output nil args))
148
149 (defun stgit-run (&rest args)
150 (setq args (stgit-make-run-args args))
151 (let ((msgcmd (mapconcat #'identity args " ")))
152 (message "Running stg %s..." msgcmd)
153 (apply 'call-process "stg" nil standard-output nil args)
154 (message "Running stg %s...done" msgcmd)))
155
156 (defun stgit-run-git (&rest args)
157 (setq args (stgit-make-run-args args))
158 (let ((msgcmd (mapconcat #'identity args " ")))
159 (message "Running git %s..." msgcmd)
160 (apply 'call-process "git" nil standard-output nil args)
161 (message "Running git %s...done" msgcmd)))
162
163 (defun stgit-run-git-silent (&rest args)
164 (setq args (stgit-make-run-args args))
165 (apply 'call-process "git" nil standard-output nil args))
166
167 (defun stgit-index-empty-p ()
168 "Returns non-nil if the index contains no changes from HEAD."
169 (zerop (stgit-run-git-silent "diff-index" "--cached" "--quiet" "HEAD")))
170
171 (defun stgit-work-tree-empty-p ()
172 "Returns non-nil if the work tree contains no changes from index."
173 (zerop (stgit-run-git-silent "diff-files" "--quiet")))
174
175 (defvar stgit-index-node)
176 (defvar stgit-worktree-node)
177
178 (defun stgit-refresh-index ()
179 (when stgit-index-node
180 (ewoc-invalidate (car stgit-index-node) (cdr stgit-index-node))))
181
182 (defun stgit-refresh-worktree ()
183 (when stgit-worktree-node
184 (ewoc-invalidate (car stgit-worktree-node) (cdr stgit-worktree-node))))
185
186 (defun stgit-run-series-insert-index (ewoc)
187 (setq index-node (cons ewoc (ewoc-enter-last ewoc
188 (make-stgit-patch
189 :status 'index
190 :name :index
191 :desc nil
192 :empty nil)))
193 worktree-node (cons ewoc (ewoc-enter-last ewoc
194 (make-stgit-patch
195 :status 'work
196 :name :work
197 :desc nil
198 :empty nil)))))
199
200 (defun stgit-run-series (ewoc)
201 (setq stgit-index-node nil
202 stgit-worktree-node nil)
203 (let ((inserted-index (not stgit-show-worktree))
204 index-node
205 worktree-node
206 all-patchsyms)
207 (with-temp-buffer
208 (let* ((standard-output (current-buffer))
209 (exit-status (stgit-run-silent "series"
210 "--description" "--empty")))
211 (goto-char (point-min))
212 (if (not (zerop exit-status))
213 (cond ((looking-at "stg series: \\(.*\\)")
214 (setq inserted-index t)
215 (ewoc-set-hf ewoc (car (ewoc-get-hf ewoc))
216 (substitute-command-keys
217 "-- not initialized; run \\[stgit-init]")))
218 ((looking-at ".*")
219 (error "Error running stg: %s"
220 (match-string 0))))
221 (while (not (eobp))
222 (unless (looking-at
223 "\\([0 ]\\)\\([>+-]\\)\\( \\)\\([^ ]+\\) *[|#] \\(.*\\)")
224 (error "Syntax error in output from stg series"))
225 (let* ((state-str (match-string 2))
226 (state (cond ((string= state-str ">") 'top)
227 ((string= state-str "+") 'applied)
228 ((string= state-str "-") 'unapplied)))
229 (name (intern (match-string 4)))
230 (desc (match-string 5))
231 (empty (string= (match-string 1) "0")))
232 (unless inserted-index
233 (when (or (eq stgit-show-worktree-mode 'top)
234 (and (eq stgit-show-worktree-mode 'center)
235 (eq state 'unapplied)))
236 (setq inserted-index t)
237 (stgit-run-series-insert-index ewoc)))
238 (setq all-patchsyms (cons name all-patchsyms))
239 (ewoc-enter-last ewoc
240 (make-stgit-patch
241 :status state
242 :name name
243 :desc desc
244 :empty empty)))
245 (forward-line 1))))
246 (unless inserted-index
247 (stgit-run-series-insert-index ewoc)))
248 (setq stgit-index-node index-node
249 stgit-worktree-node worktree-node
250 stgit-marked-patches (intersection stgit-marked-patches
251 all-patchsyms))))
252
253 (defun stgit-reload ()
254 "Update the contents of the StGit buffer."
255 (interactive)
256 (let ((inhibit-read-only t)
257 (curline (line-number-at-pos))
258 (curpatch (stgit-patch-name-at-point))
259 (curfile (stgit-patched-file-at-point)))
260 (ewoc-filter stgit-ewoc #'(lambda (x) nil))
261 (ewoc-set-hf stgit-ewoc
262 (concat "Branch: "
263 (propertize
264 (substring (with-output-to-string
265 (stgit-run-silent "branch"))
266 0 -1)
267 'face 'stgit-branch-name-face)
268 "\n\n")
269 (if stgit-show-worktree
270 "--"
271 (propertize
272 (substitute-command-keys "--\n\"\\[stgit-toggle-worktree]\"\
273 shows the working tree\n")
274 'face 'stgit-description-face)))
275 (stgit-run-series stgit-ewoc)
276 (if curpatch
277 (stgit-goto-patch curpatch (and curfile (stgit-file-file curfile)))
278 (goto-line curline)))
279 (stgit-refresh-git-status))
280
281 (defun stgit-set-default (symbol value)
282 "Set default value of SYMBOL to VALUE using `set-default' and
283 reload all StGit buffers."
284 (set-default symbol value)
285 (dolist (buf (buffer-list))
286 (with-current-buffer buf
287 (when (eq major-mode 'stgit-mode)
288 (stgit-reload)))))
289
290 (defgroup stgit nil
291 "A user interface for the StGit patch maintenance tool."
292 :group 'tools
293 :link '(function-link stgit)
294 :link '(url-link "http://www.procode.org/stgit/"))
295
296 (defcustom stgit-abbreviate-copies-and-renames t
297 "If non-nil, abbreviate copies and renames as \"dir/{old -> new}/file\"
298 instead of \"dir/old/file -> dir/new/file\"."
299 :type 'boolean
300 :group 'stgit
301 :set 'stgit-set-default)
302
303 (defcustom stgit-default-show-worktree t
304 "Set to non-nil to by default show the working tree in a new stgit buffer.
305
306 Use \\<stgit-mode-map>\\[stgit-toggle-worktree] to toggle the this setting in an already-started StGit buffer."
307 :type 'boolean
308 :group 'stgit
309 :link '(variable-link stgit-show-worktree))
310
311 (defcustom stgit-find-copies-harder nil
312 "Try harder to find copied files when listing patches.
313
314 When not nil, runs git diff-tree with the --find-copies-harder
315 flag, which reduces performance."
316 :type 'boolean
317 :group 'stgit
318 :set 'stgit-set-default)
319
320 (defcustom stgit-show-worktree-mode 'center
321 "This variable controls where the \"Index\" and \"Work tree\"
322 will be shown on in the buffer.
323
324 It can be set to 'top (above all patches), 'center (show between
325 applied and unapplied patches), and 'bottom (below all patches)."
326 :type '(radio (const :tag "above all patches (top)" top)
327 (const :tag "between applied and unapplied patches (center)"
328 center)
329 (const :tag "below all patches (bottom)" bottom))
330 :group 'stgit
331 :link '(variable-link stgit-show-worktree)
332 :set 'stgit-set-default)
333
334 (defface stgit-branch-name-face
335 '((t :inherit bold))
336 "The face used for the StGit branch name"
337 :group 'stgit)
338
339 (defface stgit-top-patch-face
340 '((((background dark)) (:weight bold :foreground "yellow"))
341 (((background light)) (:weight bold :foreground "purple"))
342 (t (:weight bold)))
343 "The face used for the top patch names"
344 :group 'stgit)
345
346 (defface stgit-applied-patch-face
347 '((((background dark)) (:foreground "light yellow"))
348 (((background light)) (:foreground "purple"))
349 (t ()))
350 "The face used for applied patch names"
351 :group 'stgit)
352
353 (defface stgit-unapplied-patch-face
354 '((((background dark)) (:foreground "gray80"))
355 (((background light)) (:foreground "orchid"))
356 (t ()))
357 "The face used for unapplied patch names"
358 :group 'stgit)
359
360 (defface stgit-description-face
361 '((((background dark)) (:foreground "tan"))
362 (((background light)) (:foreground "dark red")))
363 "The face used for StGit descriptions"
364 :group 'stgit)
365
366 (defface stgit-index-work-tree-title-face
367 '((((supports :slant italic)) :slant italic)
368 (t :inherit bold))
369 "StGit mode face used for the \"Index\" and \"Work tree\" titles"
370 :group 'stgit)
371
372 (defface stgit-unmerged-file-face
373 '((((class color) (background light)) (:foreground "red" :bold t))
374 (((class color) (background dark)) (:foreground "red" :bold t)))
375 "StGit mode face used for unmerged file status"
376 :group 'stgit)
377
378 (defface stgit-unknown-file-face
379 '((((class color) (background light)) (:foreground "goldenrod" :bold t))
380 (((class color) (background dark)) (:foreground "goldenrod" :bold t)))
381 "StGit mode face used for unknown file status"
382 :group 'stgit)
383
384 (defface stgit-ignored-file-face
385 '((((class color) (background light)) (:foreground "grey60"))
386 (((class color) (background dark)) (:foreground "grey40")))
387 "StGit mode face used for ignored files")
388
389 (defface stgit-file-permission-face
390 '((((class color) (background light)) (:foreground "green" :bold t))
391 (((class color) (background dark)) (:foreground "green" :bold t)))
392 "StGit mode face used for permission changes."
393 :group 'stgit)
394
395 (defface stgit-modified-file-face
396 '((((class color) (background light)) (:foreground "purple"))
397 (((class color) (background dark)) (:foreground "salmon")))
398 "StGit mode face used for modified file status"
399 :group 'stgit)
400
401 (defconst stgit-file-status-code-strings
402 (mapcar (lambda (arg)
403 (cons (car arg)
404 (propertize (cadr arg) 'face (car (cddr arg)))))
405 '((add "Added" stgit-modified-file-face)
406 (copy "Copied" stgit-modified-file-face)
407 (delete "Deleted" stgit-modified-file-face)
408 (modify "Modified" stgit-modified-file-face)
409 (rename "Renamed" stgit-modified-file-face)
410 (mode-change "Mode change" stgit-modified-file-face)
411 (unmerged "Unmerged" stgit-unmerged-file-face)
412 (unknown "Unknown" stgit-unknown-file-face)
413 (ignore "Ignored" stgit-ignored-file-face)))
414 "Alist of code symbols to description strings")
415
416 (defconst stgit-patch-status-face-alist
417 '((applied . stgit-applied-patch-face)
418 (top . stgit-top-patch-face)
419 (unapplied . stgit-unapplied-patch-face)
420 (index . stgit-index-work-tree-title-face)
421 (work . stgit-index-work-tree-title-face))
422 "Alist of face to use for a given patch status")
423
424 (defun stgit-file-status-code-as-string (file)
425 "Return stgit status code for FILE as a string"
426 (let* ((code (assq (stgit-file-status file)
427 stgit-file-status-code-strings))
428 (score (stgit-file-cr-score file)))
429 (when code
430 (format "%-11s "
431 (if (and score (/= score 100))
432 (format "%s %s" (cdr code)
433 (propertize (format "%d%%" score)
434 'face 'stgit-description-face))
435 (cdr code))))))
436
437 (defun stgit-file-status-code (str &optional score)
438 "Return stgit status code from git status string"
439 (let ((code (assoc str '(("A" . add)
440 ("C" . copy)
441 ("D" . delete)
442 ("I" . ignore)
443 ("M" . modify)
444 ("R" . rename)
445 ("T" . mode-change)
446 ("U" . unmerged)
447 ("X" . unknown)))))
448 (setq code (if code (cdr code) 'unknown))
449 (when (stringp score)
450 (if (> (length score) 0)
451 (setq score (string-to-number score))
452 (setq score nil)))
453 (if score (cons code score) code)))
454
455 (defconst stgit-file-type-strings
456 '((#o100 . "file")
457 (#o120 . "symlink")
458 (#o160 . "subproject"))
459 "Alist of names of file types")
460
461 (defun stgit-file-type-string (type)
462 "Return string describing file type TYPE (the high bits of file permission).
463 Cf. `stgit-file-type-strings' and `stgit-file-type-change-string'."
464 (let ((type-str (assoc type stgit-file-type-strings)))
465 (or (and type-str (cdr type-str))
466 (format "unknown type %o" type))))
467
468 (defun stgit-file-type-change-string (old-perm new-perm)
469 "Return string describing file type change from OLD-PERM to NEW-PERM.
470 Cf. `stgit-file-type-string'."
471 (let ((old-type (lsh old-perm -9))
472 (new-type (lsh new-perm -9)))
473 (cond ((= old-type new-type) "")
474 ((zerop new-type) "")
475 ((zerop old-type)
476 (if (= new-type #o100)
477 ""
478 (format " (%s)" (stgit-file-type-string new-type))))
479 (t (format " (%s -> %s)"
480 (stgit-file-type-string old-type)
481 (stgit-file-type-string new-type))))))
482
483 (defun stgit-file-mode-change-string (old-perm new-perm)
484 "Return string describing file mode change from OLD-PERM to NEW-PERM.
485 Cf. `stgit-file-type-change-string'."
486 (setq old-perm (logand old-perm #o777)
487 new-perm (logand new-perm #o777))
488 (if (or (= old-perm new-perm)
489 (zerop old-perm)
490 (zerop new-perm))
491 ""
492 (let* ((modified (logxor old-perm new-perm))
493 (not-x-modified (logand (logxor old-perm new-perm) #o666)))
494 (cond ((zerop modified) "")
495 ((and (zerop not-x-modified)
496 (or (and (eq #o111 (logand old-perm #o111))
497 (propertize "-x" 'face 'stgit-file-permission-face))
498 (and (eq #o111 (logand new-perm #o111))
499 (propertize "+x" 'face
500 'stgit-file-permission-face)))))
501 (t (concat (propertize (format "%o" old-perm)
502 'face 'stgit-file-permission-face)
503 (propertize " -> "
504 'face 'stgit-description-face)
505 (propertize (format "%o" new-perm)
506 'face 'stgit-file-permission-face)))))))
507
508 (defstruct (stgit-file)
509 old-perm new-perm copy-or-rename cr-score cr-from cr-to status file)
510
511 (defun stgit-describe-copy-or-rename (file)
512 (let ((arrow (concat " " (propertize "->" 'face 'stgit-description-face) " "))
513 from to common-head common-tail)
514
515 (when stgit-abbreviate-copies-and-renames
516 (setq from (split-string (stgit-file-cr-from file) "/")
517 to (split-string (stgit-file-cr-to file) "/"))
518
519 (while (and from to (cdr from) (cdr to)
520 (string-equal (car from) (car to)))
521 (setq common-head (cons (car from) common-head)
522 from (cdr from)
523 to (cdr to)))
524 (setq common-head (nreverse common-head)
525 from (nreverse from)
526 to (nreverse to))
527 (while (and from to (cdr from) (cdr to)
528 (string-equal (car from) (car to)))
529 (setq common-tail (cons (car from) common-tail)
530 from (cdr from)
531 to (cdr to)))
532 (setq from (nreverse from)
533 to (nreverse to)))
534
535 (if (or common-head common-tail)
536 (concat (if common-head
537 (mapconcat #'identity common-head "/")
538 "")
539 (if common-head "/" "")
540 (propertize "{" 'face 'stgit-description-face)
541 (mapconcat #'identity from "/")
542 arrow
543 (mapconcat #'identity to "/")
544 (propertize "}" 'face 'stgit-description-face)
545 (if common-tail "/" "")
546 (if common-tail
547 (mapconcat #'identity common-tail "/")
548 ""))
549 (concat (stgit-file-cr-from file) arrow (stgit-file-cr-to file)))))
550
551 (defun stgit-file-pp (file)
552 (let ((status (stgit-file-status file))
553 (name (if (stgit-file-copy-or-rename file)
554 (stgit-describe-copy-or-rename file)
555 (stgit-file-file file)))
556 (mode-change (stgit-file-mode-change-string
557 (stgit-file-old-perm file)
558 (stgit-file-new-perm file)))
559 (start (point)))
560 (insert (format " %-12s%s%s%s%s\n"
561 (stgit-file-status-code-as-string file)
562 mode-change
563 (if (zerop (length mode-change)) "" " ")
564 name
565 (propertize (stgit-file-type-change-string
566 (stgit-file-old-perm file)
567 (stgit-file-new-perm file))
568 'face 'stgit-description-face)))
569 (add-text-properties start (point)
570 (list 'entry-type 'file
571 'file-data file))))
572
573 (defun stgit-find-copies-harder-diff-arg ()
574 "Return the flag to use with `git-diff' depending on the
575 `stgit-find-copies-harder' flag."
576 (if stgit-find-copies-harder "--find-copies-harder" "-C"))
577
578 (defun stgit-insert-ls-files (args file-flag)
579 (let ((start (point)))
580 (apply 'stgit-run-git
581 (append '("ls-files" "--exclude-standard" "-z") args))
582 (goto-char start)
583 (while (looking-at "\\([^\0]*\\)\0")
584 (let ((name-len (- (match-end 0) (match-beginning 0))))
585 (insert ":0 0 0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 " file-flag "\0")
586 (forward-char name-len)))))
587
588 (defun stgit-insert-patch-files (patch)
589 "Expand (show modification of) the patch PATCH after the line
590 at point."
591 (let* ((patchsym (stgit-patch-name patch))
592 (end (point-marker))
593 (args (list "-z" (stgit-find-copies-harder-diff-arg)))
594 (ewoc (ewoc-create #'stgit-file-pp nil nil t)))
595 (set-marker-insertion-type end t)
596 (setf (stgit-patch-files-ewoc patch) ewoc)
597 (with-temp-buffer
598 (let ((standard-output (current-buffer)))
599 (apply 'stgit-run-git
600 (cond ((eq patchsym :work)
601 `("diff-files" "-0" ,@args))
602 ((eq patchsym :index)
603 `("diff-index" ,@args "--cached" "HEAD"))
604 (t
605 `("diff-tree" ,@args "-r" ,(stgit-id patchsym)))))
606
607 (when (and (eq patchsym :work))
608 (when stgit-show-ignored
609 (stgit-insert-ls-files '("--ignored" "--others") "I"))
610 (when stgit-show-unknown
611 (stgit-insert-ls-files '("--others") "X"))
612 (sort-regexp-fields nil ":[^\0]*\0\\([^\0]*\\)\0" "\\1"
613 (point-min) (point-max)))
614
615 (goto-char (point-min))
616 (unless (or (eobp) (memq patchsym '(:work :index)))
617 (forward-char 41))
618 (while (looking-at ":\\([0-7]+\\) \\([0-7]+\\) [0-9A-Fa-f]\\{40\\} [0-9A-Fa-f]\\{40\\} ")
619 (let ((old-perm (string-to-number (match-string 1) 8))
620 (new-perm (string-to-number (match-string 2) 8)))
621 (goto-char (match-end 0))
622 (let ((file
623 (cond ((looking-at
624 "\\([CR]\\)\\([0-9]*\\)\0\\([^\0]*\\)\0\\([^\0]*\\)\0")
625 (let* ((patch-status (stgit-patch-status patch))
626 (file-subexp (if (eq patch-status 'unapplied)
627 3
628 4))
629 (file (match-string file-subexp)))
630 (make-stgit-file
631 :old-perm old-perm
632 :new-perm new-perm
633 :copy-or-rename t
634 :cr-score (string-to-number (match-string 2))
635 :cr-from (match-string 3)
636 :cr-to (match-string 4)
637 :status (stgit-file-status-code
638 (match-string 1))
639 :file file)))
640 ((looking-at "\\([ABD-QS-Z]\\)\0\\([^\0]*\\)\0")
641 (make-stgit-file
642 :old-perm old-perm
643 :new-perm new-perm
644 :copy-or-rename nil
645 :cr-score nil
646 :cr-from nil
647 :cr-to nil
648 :status (stgit-file-status-code
649 (match-string 1))
650 :file (match-string 2))))))
651 (goto-char (match-end 0))
652 (ewoc-enter-last ewoc file))))
653
654 (unless (ewoc-nth ewoc 0)
655 (ewoc-set-hf ewoc ""
656 (concat " "
657 (propertize "<no files>"
658 'face 'stgit-description-face)
659 "\n")))))
660 (goto-char end)))
661
662 (defun stgit-find-file (&optional other-window)
663 (let* ((file (or (stgit-patched-file-at-point)
664 (error "No file at point")))
665 (filename (expand-file-name (stgit-file-file file))))
666 (unless (file-exists-p filename)
667 (error "File does not exist"))
668 (funcall (if other-window 'find-file-other-window 'find-file)
669 filename)
670 (when (eq (stgit-file-status file) 'unmerged)
671 (smerge-mode 1))))
672
673 (defun stgit-expand (&optional patches collapse)
674 "Show the contents selected patches, or the patch at point.
675
676 See also `stgit-collapse'.
677
678 Non-interactively, operate on PATCHES, and collapse instead of
679 expand if COLLAPSE is not nil."
680 (interactive (list (stgit-patches-marked-or-at-point)))
681 (let ((patches-diff (funcall (if collapse #'intersection #'set-difference)
682 patches stgit-expanded-patches)))
683 (setq stgit-expanded-patches
684 (if collapse
685 (set-difference stgit-expanded-patches patches-diff)
686 (append stgit-expanded-patches patches-diff)))
687 (ewoc-map #'(lambda (patch)
688 (memq (stgit-patch-name patch) patches-diff))
689 stgit-ewoc))
690 (move-to-column (stgit-goal-column)))
691
692 (defun stgit-collapse (&optional patches)
693 "Hide the contents selected patches, or the patch at point.
694
695 See also `stgit-expand'."
696 (interactive (list (stgit-patches-marked-or-at-point)))
697 (stgit-expand patches t))
698
699 (defun stgit-select-patch ()
700 (let ((patchname (stgit-patch-name-at-point)))
701 (stgit-expand (list patchname)
702 (memq patchname stgit-expanded-patches))))
703
704 (defun stgit-select ()
705 "With point on a patch, toggle showing files in the patch.
706
707 With point on a file, open the associated file. Opens the target
708 file for (applied) copies and renames."
709 (interactive)
710 (case (get-text-property (point) 'entry-type)
711 ('patch
712 (stgit-select-patch))
713 ('file
714 (stgit-find-file))
715 (t
716 (error "No patch or file on line"))))
717
718 (defun stgit-find-file-other-window ()
719 "Open file at point in other window"
720 (interactive)
721 (stgit-find-file t))
722
723 (defun stgit-find-file-merge ()
724 "Open file at point and merge it using `smerge-ediff'."
725 (interactive)
726 (stgit-find-file t)
727 (smerge-ediff))
728
729 (defun stgit-quit ()
730 "Hide the stgit buffer."
731 (interactive)
732 (bury-buffer))
733
734 (defun stgit-git-status ()
735 "Show status using `git-status'."
736 (interactive)
737 (unless (fboundp 'git-status)
738 (error "The stgit-git-status command requires git-status"))
739 (let ((dir default-directory))
740 (save-selected-window
741 (pop-to-buffer nil)
742 (git-status dir))))
743
744 (defun stgit-goal-column ()
745 "Return goal column for the current line"
746 (case (get-text-property (point) 'entry-type)
747 ('patch 2)
748 ('file 4)
749 (t 0)))
750
751 (defun stgit-next-line (&optional arg)
752 "Move cursor vertically down ARG lines"
753 (interactive "p")
754 (next-line arg)
755 (move-to-column (stgit-goal-column)))
756
757 (defun stgit-previous-line (&optional arg)
758 "Move cursor vertically up ARG lines"
759 (interactive "p")
760 (previous-line arg)
761 (move-to-column (stgit-goal-column)))
762
763 (defun stgit-next-patch (&optional arg)
764 "Move cursor down ARG patches."
765 (interactive "p")
766 (ewoc-goto-next stgit-ewoc (or arg 1))
767 (move-to-column goal-column))
768
769 (defun stgit-previous-patch (&optional arg)
770 "Move cursor up ARG patches."
771 (interactive "p")
772 (ewoc-goto-prev stgit-ewoc (or arg 1))
773 (move-to-column goal-column))
774
775 (defvar stgit-mode-hook nil
776 "Run after `stgit-mode' is setup.")
777
778 (defvar stgit-mode-map nil
779 "Keymap for StGit major mode.")
780
781 (unless stgit-mode-map
782 (let ((diff-map (make-keymap))
783 (toggle-map (make-keymap)))
784 (suppress-keymap diff-map)
785 (mapc (lambda (arg) (define-key diff-map (car arg) (cdr arg)))
786 '(("b" . stgit-diff-base)
787 ("c" . stgit-diff-combined)
788 ("m" . stgit-find-file-merge)
789 ("o" . stgit-diff-ours)
790 ("t" . stgit-diff-theirs)))
791 (suppress-keymap toggle-map)
792 (mapc (lambda (arg) (define-key toggle-map (car arg) (cdr arg)))
793 '(("t" . stgit-toggle-worktree)
794 ("i" . stgit-toggle-ignored)
795 ("u" . stgit-toggle-unknown)))
796 (setq stgit-mode-map (make-keymap))
797 (suppress-keymap stgit-mode-map)
798 (mapc (lambda (arg) (define-key stgit-mode-map (car arg) (cdr arg)))
799 `((" " . stgit-mark)
800 ("m" . stgit-mark)
801 ("\d" . stgit-unmark-up)
802 ("u" . stgit-unmark-down)
803 ("?" . stgit-help)
804 ("h" . stgit-help)
805 ("\C-p" . stgit-previous-line)
806 ("\C-n" . stgit-next-line)
807 ([up] . stgit-previous-line)
808 ([down] . stgit-next-line)
809 ("p" . stgit-previous-patch)
810 ("n" . stgit-next-patch)
811 ("\M-{" . stgit-previous-patch)
812 ("\M-}" . stgit-next-patch)
813 ("s" . stgit-git-status)
814 ("g" . stgit-reload-or-repair)
815 ("r" . stgit-refresh)
816 ("\C-c\C-r" . stgit-rename)
817 ("e" . stgit-edit)
818 ("M" . stgit-move-patches)
819 ("S" . stgit-squash)
820 ("N" . stgit-new)
821 ("c" . stgit-new-and-refresh)
822 ("\C-c\C-c" . stgit-commit)
823 ("\C-c\C-u" . stgit-uncommit)
824 ("U" . stgit-revert)
825 ("R" . stgit-resolve-file)
826 ("\r" . stgit-select)
827 ("+" . stgit-expand)
828 ("-" . stgit-collapse)
829 ("o" . stgit-find-file-other-window)
830 ("i" . stgit-file-toggle-index)
831 (">" . stgit-push-next)
832 ("<" . stgit-pop-next)
833 ("P" . stgit-push-or-pop)
834 ("G" . stgit-goto)
835 ("=" . stgit-diff)
836 ("D" . stgit-delete)
837 ([?\C-/] . stgit-undo)
838 ("\C-_" . stgit-undo)
839 ([?\C-c ?\C-/] . stgit-redo)
840 ("\C-c\C-_" . stgit-redo)
841 ("B" . stgit-branch)
842 ("\C-c\C-b" . stgit-rebase)
843 ("t" . ,toggle-map)
844 ("d" . ,diff-map)
845 ("q" . stgit-quit)))))
846
847 (defun stgit-mode ()
848 "Major mode for interacting with StGit.
849
850 Start StGit using \\[stgit].
851
852 Basic commands:
853 \\<stgit-mode-map>\
854 \\[stgit-help] Show this help text
855 \\[stgit-quit] Hide the StGit buffer
856 \\[describe-bindings] Show all key bindings
857
858 \\[stgit-reload-or-repair] Reload the StGit buffer
859 \\[universal-argument] \\[stgit-reload-or-repair] Repair StGit metadata
860
861 \\[stgit-undo] Undo most recent StGit operation
862 \\[stgit-redo] Undo recent undo
863
864 \\[stgit-git-status] Run `git-status' (if available)
865
866 Movement commands:
867 \\[stgit-previous-line] Move to previous line
868 \\[stgit-next-line] Move to next line
869 \\[stgit-previous-patch] Move to previous patch
870 \\[stgit-next-patch] Move to next patch
871
872 \\[stgit-mark] Mark patch
873 \\[stgit-unmark-up] Unmark patch and move up
874 \\[stgit-unmark-down] Unmark patch and move down
875
876 Commands for patches:
877 \\[stgit-select] Toggle showing changed files in patch
878 \\[stgit-refresh] Refresh patch with changes in index or work tree
879 \\[stgit-diff] Show the patch log and diff
880
881 \\[stgit-expand] Show changes in selected patches
882 \\[stgit-collapse] Hide changes in selected patches
883
884 \\[stgit-new] Create a new, empty patch
885 \\[stgit-new-and-refresh] Create a new patch from index or work tree
886 \\[stgit-rename] Rename patch
887 \\[stgit-edit] Edit patch description
888 \\[stgit-delete] Delete patch(es)
889
890 \\[stgit-revert] Revert all changes in index or work tree
891
892 \\[stgit-push-next] Push next patch onto stack
893 \\[stgit-pop-next] Pop current patch from stack
894 \\[stgit-push-or-pop] Push or pop patch at point
895 \\[stgit-goto] Make current patch current by popping or pushing
896
897 \\[stgit-squash] Squash (meld together) patches
898 \\[stgit-move-patches] Move patch(es) to point
899
900 \\[stgit-commit] Commit patch(es)
901 \\[stgit-uncommit] Uncommit patch(es)
902
903 Commands for files:
904 \\[stgit-select] Open the file in this window
905 \\[stgit-find-file-other-window] Open the file in another window
906 \\[stgit-diff] Show the file's diff
907
908 \\[stgit-file-toggle-index] Toggle change between index and work tree
909 \\[stgit-revert] Revert changes to file
910
911 Display commands:
912 \\[stgit-toggle-worktree] Toggle showing index and work tree
913 \\[stgit-toggle-unknown] Toggle showing unknown files
914 \\[stgit-toggle-ignored] Toggle showing ignored files
915
916 Commands for diffs:
917 \\[stgit-diff] Show diff of patch or file
918 \\[stgit-diff-base] Show diff against the merge base
919 \\[stgit-diff-ours] Show diff against our branch
920 \\[stgit-diff-theirs] Show diff against their branch
921
922 With one prefix argument (e.g., \\[universal-argument] \\[stgit-diff]), \
923 ignore space changes.
924 With two prefix arguments (e.g., \\[universal-argument] \
925 \\[universal-argument] \\[stgit-diff]), ignore all space changes.
926
927 Commands for merge conflicts:
928 \\[stgit-find-file-merge] Resolve conflicts using `smerge-ediff'
929 \\[stgit-resolve-file] Mark unmerged file as resolved
930
931 Commands for branches:
932 \\[stgit-branch] Switch to another branch
933 \\[stgit-rebase] Rebase the current branch
934
935 Customization variables:
936 `stgit-abbreviate-copies-and-renames'
937 `stgit-default-show-worktree'
938 `stgit-find-copies-harder'
939 `stgit-show-worktree-mode'
940
941 See also \\[customize-group] for the \"stgit\" group."
942 (kill-all-local-variables)
943 (buffer-disable-undo)
944 (setq mode-name "StGit"
945 major-mode 'stgit-mode
946 goal-column 2)
947 (use-local-map stgit-mode-map)
948 (set (make-local-variable 'list-buffers-directory) default-directory)
949 (set (make-local-variable 'stgit-marked-patches) nil)
950 (set (make-local-variable 'stgit-expanded-patches) (list :work :index))
951 (set (make-local-variable 'stgit-show-worktree) stgit-default-show-worktree)
952 (set (make-local-variable 'stgit-index-node) nil)
953 (set (make-local-variable 'stgit-worktree-node) nil)
954 (set (make-local-variable 'parse-sexp-lookup-properties) t)
955 (set-variable 'truncate-lines 't)
956 (add-hook 'after-save-hook 'stgit-update-saved-file)
957 (run-hooks 'stgit-mode-hook))
958
959 (defun stgit-update-saved-file ()
960 (let* ((file (expand-file-name buffer-file-name))
961 (dir (file-name-directory file))
962 (gitdir (condition-case nil (git-get-top-dir dir)
963 (error nil)))
964 (buffer (and gitdir (stgit-find-buffer gitdir))))
965 (when buffer
966 (with-current-buffer buffer
967 (stgit-refresh-worktree)))))
968
969 (defun stgit-add-mark (patchsym)
970 "Mark the patch PATCHSYM."
971 (setq stgit-marked-patches (cons patchsym stgit-marked-patches)))
972
973 (defun stgit-remove-mark (patchsym)
974 "Unmark the patch PATCHSYM."
975 (setq stgit-marked-patches (delq patchsym stgit-marked-patches)))
976
977 (defun stgit-clear-marks ()
978 "Unmark all patches."
979 (setq stgit-marked-patches '()))
980
981 (defun stgit-patch-at-point (&optional cause-error)
982 (get-text-property (point) 'patch-data))
983
984 (defun stgit-patch-name-at-point (&optional cause-error only-patches)
985 "Return the patch name on the current line as a symbol.
986 If CAUSE-ERROR is not nil, signal an error if none found.
987 If ONLY-PATCHES is not nil, only allow real patches, and not
988 index or work tree."
989 (let ((patch (stgit-patch-at-point)))
990 (and patch
991 only-patches
992 (memq (stgit-patch-status patch) '(work index))
993 (setq patch nil))
994 (cond (patch
995 (stgit-patch-name patch))
996 (cause-error
997 (error "No patch on this line")))))
998
999 (defun stgit-patched-file-at-point ()
1000 (get-text-property (point) 'file-data))
1001
1002 (defun stgit-patches-marked-or-at-point ()
1003 "Return the symbols of the marked patches, or the patch on the current line."
1004 (if stgit-marked-patches
1005 stgit-marked-patches
1006 (let ((patch (stgit-patch-name-at-point)))
1007 (if patch
1008 (list patch)
1009 '()))))
1010
1011 (defun stgit-goto-patch (patchsym &optional file)
1012 "Move point to the line containing patch PATCHSYM.
1013 If that patch cannot be found, do nothing.
1014
1015 If the patch was found and FILE is not nil, instead move to that
1016 file's line. If FILE cannot be found, stay on the line of
1017 PATCHSYM."
1018 (let ((node (ewoc-nth stgit-ewoc 0)))
1019 (while (and node (not (eq (stgit-patch-name (ewoc-data node))
1020 patchsym)))
1021 (setq node (ewoc-next stgit-ewoc node)))
1022 (when (and node file)
1023 (let* ((file-ewoc (stgit-patch-files-ewoc (ewoc-data node)))
1024 (file-node (ewoc-nth file-ewoc 0)))
1025 (while (and file-node (not (equal (stgit-file-file (ewoc-data file-node)) file)))
1026 (setq file-node (ewoc-next file-ewoc file-node)))
1027 (when file-node
1028 (ewoc-goto-node file-ewoc file-node)
1029 (move-to-column (stgit-goal-column))
1030 (setq node nil))))
1031 (when node
1032 (ewoc-goto-node stgit-ewoc node)
1033 (move-to-column goal-column))))
1034
1035 (defun stgit-init ()
1036 "Run stg init."
1037 (interactive)
1038 (stgit-capture-output nil
1039 (stgit-run "init"))
1040 (stgit-reload))
1041
1042 (defun stgit-mark ()
1043 "Mark the patch under point."
1044 (interactive)
1045 (let* ((node (ewoc-locate stgit-ewoc))
1046 (patch (ewoc-data node))
1047 (name (stgit-patch-name patch)))
1048 (when (eq name :work)
1049 (error "Cannot mark the work tree"))
1050 (when (eq name :index)
1051 (error "Cannot mark the index"))
1052 (stgit-add-mark (stgit-patch-name patch))
1053 (ewoc-invalidate stgit-ewoc node))
1054 (stgit-next-patch))
1055
1056 (defun stgit-unmark-up ()
1057 "Remove mark from the patch on the previous line."
1058 (interactive)
1059 (stgit-previous-patch)
1060 (let* ((node (ewoc-locate stgit-ewoc))
1061 (patch (ewoc-data node)))
1062 (stgit-remove-mark (stgit-patch-name patch))
1063 (ewoc-invalidate stgit-ewoc node))
1064 (move-to-column (stgit-goal-column)))
1065
1066 (defun stgit-unmark-down ()
1067 "Remove mark from the patch on the current line."
1068 (interactive)
1069 (let* ((node (ewoc-locate stgit-ewoc))
1070 (patch (ewoc-data node)))
1071 (stgit-remove-mark (stgit-patch-name patch))
1072 (ewoc-invalidate stgit-ewoc node))
1073 (stgit-next-patch))
1074
1075 (defun stgit-rename (name)
1076 "Rename the patch under point to NAME."
1077 (interactive (list
1078 (read-string "Patch name: "
1079 (symbol-name (stgit-patch-name-at-point t t)))))
1080 (let ((old-patchsym (stgit-patch-name-at-point t t)))
1081 (stgit-capture-output nil
1082 (stgit-run "rename" old-patchsym name))
1083 (let ((name-sym (intern name)))
1084 (when (memq old-patchsym stgit-expanded-patches)
1085 (setq stgit-expanded-patches
1086 (cons name-sym (delq old-patchsym stgit-expanded-patches))))
1087 (when (memq old-patchsym stgit-marked-patches)
1088 (setq stgit-marked-patches
1089 (cons name-sym (delq old-patchsym stgit-marked-patches))))
1090 (stgit-reload)
1091 (stgit-goto-patch name-sym))))
1092
1093 (defun stgit-reload-or-repair (repair)
1094 "Update the contents of the StGit buffer (`stgit-reload').
1095
1096 With a prefix argument, repair the StGit metadata if the branch
1097 was modified with git commands (`stgit-repair')."
1098 (interactive "P")
1099 (if repair
1100 (stgit-repair)
1101 (stgit-reload)))
1102
1103 (defun stgit-repair ()
1104 "Run stg repair."
1105 (interactive)
1106 (stgit-capture-output nil
1107 (stgit-run "repair"))
1108 (stgit-reload))
1109
1110 (defun stgit-available-branches ()
1111 "Returns a list of the available stg branches"
1112 (let ((output (with-output-to-string
1113 (stgit-run "branch" "--list")))
1114 (start 0)
1115 result)
1116 (while (string-match "^>?\\s-+s\\s-+\\(\\S-+\\)" output start)
1117 (setq result (cons (match-string 1 output) result))
1118 (setq start (match-end 0)))
1119 result))
1120
1121 (defun stgit-branch (branch)
1122 "Switch to branch BRANCH."
1123 (interactive (list (completing-read "Switch to branch: "
1124 (stgit-available-branches))))
1125 (stgit-capture-output nil (stgit-run "branch" "--" branch))
1126 (stgit-reload))
1127
1128 (defun stgit-available-refs (&optional omit-stgit)
1129 "Returns a list of the available git refs.
1130 If OMIT-STGIT is not nil, filter out \"resf/heads/*.stgit\"."
1131 (let* ((output (with-output-to-string
1132 (stgit-run-git-silent "for-each-ref" "--format=%(refname)"
1133 "refs/tags" "refs/heads"
1134 "refs/remotes")))
1135 (result (split-string output "\n" t)))
1136 (mapcar (lambda (s)
1137 (if (string-match "^refs/\\(heads\\|tags\\|remotes\\)/" s)
1138 (substring s (match-end 0))
1139 s))
1140 (if omit-stgit
1141 (delete-if (lambda (s)
1142 (string-match "^refs/heads/.*\\.stgit$" s))
1143 result)
1144 result))))
1145
1146 (defun stgit-rebase (new-base)
1147 "Rebase to NEW-BASE."
1148 (interactive (list (completing-read "Rebase to: "
1149 (stgit-available-refs t))))
1150 (stgit-capture-output nil (stgit-run "rebase" new-base))
1151 (stgit-reload))
1152
1153 (defun stgit-commit (count)
1154 "Run stg commit on COUNT commits.
1155 Interactively, the prefix argument is used as COUNT.
1156 A negative COUNT will uncommit instead."
1157 (interactive "p")
1158 (if (< count 0)
1159 (stgit-uncommit (- count))
1160 (stgit-capture-output nil (stgit-run "commit" "-n" count))
1161 (stgit-reload)))
1162
1163 (defun stgit-uncommit (count)
1164 "Run stg uncommit on COUNT commits.
1165 Interactively, the prefix argument is used as COUNT.
1166 A negative COUNT will commit instead."
1167 (interactive "p")
1168 (if (< count 0)
1169 (stgit-commit (- count))
1170 (stgit-capture-output nil (stgit-run "uncommit" "-n" count))
1171 (stgit-reload)))
1172
1173 (defun stgit-neighbour-file ()
1174 "Return the file name of the next file after point, or the
1175 previous file if point is at the last file within a patch."
1176 (let ((old-point (point))
1177 neighbour-file)
1178 (and (zerop (forward-line 1))
1179 (let ((f (stgit-patched-file-at-point)))
1180 (and f (setq neighbour-file (stgit-file-file f)))))
1181 (goto-char old-point)
1182 (unless neighbour-file
1183 (and (zerop (forward-line -1))
1184 (let ((f (stgit-patched-file-at-point)))
1185 (and f (setq neighbour-file (stgit-file-file f)))))
1186 (goto-char old-point))
1187 neighbour-file))
1188
1189 (defun stgit-revert-file ()
1190 "Revert the file at point, which must be in the index or the
1191 working tree."
1192 (interactive)
1193 (let* ((patched-file (or (stgit-patched-file-at-point)
1194 (error "No file on the current line")))
1195 (patch-name (stgit-patch-name-at-point))
1196 (file-status (stgit-file-status patched-file))
1197 (rm-file (cond ((stgit-file-copy-or-rename patched-file)
1198 (stgit-file-cr-to patched-file))
1199 ((eq file-status 'add)
1200 (stgit-file-file patched-file))))
1201 (co-file (cond ((eq file-status 'rename)
1202 (stgit-file-cr-from patched-file))
1203 ((not (memq file-status '(copy add)))
1204 (stgit-file-file patched-file))))
1205 (next-file (stgit-neighbour-file)))
1206
1207 (unless (memq patch-name '(:work :index))
1208 (error "No index or working tree file on this line"))
1209
1210 (when (eq file-status 'ignore)
1211 (error "Cannot revert ignored files"))
1212
1213 (when (eq file-status 'unknown)
1214 (error "Cannot revert unknown files"))
1215
1216 (let ((nfiles (+ (if rm-file 1 0) (if co-file 1 0))))
1217 (when (yes-or-no-p (format "Revert %d file%s? "
1218 nfiles
1219 (if (= nfiles 1) "" "s")))
1220 (stgit-capture-output nil
1221 (when rm-file
1222 (stgit-run-git "rm" "-f" "-q" "--" rm-file))
1223 (when co-file
1224 (stgit-run-git "checkout" "HEAD" co-file)))
1225 (stgit-reload)
1226 (stgit-goto-patch patch-name next-file)))))
1227
1228 (defun stgit-revert ()
1229 "Revert the change at point, which must be the index, the work
1230 tree, or a single change in either."
1231 (interactive)
1232 (let ((patched-file (stgit-patched-file-at-point)))
1233 (if patched-file
1234 (stgit-revert-file)
1235 (let* ((patch-name (or (stgit-patch-name-at-point)
1236 (error "No patch or file at point")))
1237 (patch-desc (case patch-name
1238 (:index "index")
1239 (:work "work tree")
1240 (t (error (substitute-command-keys
1241 "Use \\[stgit-delete] to delete a patch"))))))
1242 (when (if (eq patch-name :work)
1243 (stgit-work-tree-empty-p)
1244 (stgit-index-empty-p))
1245 (error (format "There are no changes in the %s to revert"
1246 patch-desc)))
1247 (and (eq patch-name :index)
1248 (not (stgit-work-tree-empty-p))
1249 (error "Cannot revert index as work tree contains unstaged changes"))
1250
1251 (when (yes-or-no-p (format "Revert all changes in the %s? "
1252 patch-desc))
1253 (if (eq patch-name :index)
1254 (stgit-run-git-silent "reset" "--hard" "-q")
1255 (stgit-run-git-silent "checkout" "--" "."))
1256 (stgit-refresh-index)
1257 (stgit-refresh-worktree)
1258 (stgit-goto-patch patch-name))))))
1259
1260 (defun stgit-resolve-file ()
1261 "Resolve conflict in the file at point."
1262 (interactive)
1263 (let* ((patched-file (stgit-patched-file-at-point))
1264 (patch (stgit-patch-at-point))
1265 (patch-name (and patch (stgit-patch-name patch)))
1266 (status (and patched-file (stgit-file-status patched-file))))
1267
1268 (unless (memq patch-name '(:work :index))
1269 (error "No index or working tree file on this line"))
1270
1271 (unless (eq status 'unmerged)
1272 (error "No conflict to resolve at the current line"))
1273
1274 (stgit-capture-output nil
1275 (stgit-move-change-to-index (stgit-file-file patched-file)))
1276
1277 (stgit-reload)))
1278
1279 (defun stgit-push-next (npatches)
1280 "Push the first unapplied patch.
1281 With numeric prefix argument, push that many patches."
1282 (interactive "p")
1283 (stgit-capture-output nil (stgit-run "push" "-n" npatches))
1284 (stgit-reload)
1285 (stgit-refresh-git-status))
1286
1287 (defun stgit-pop-next (npatches)
1288 "Pop the topmost applied patch.
1289 With numeric prefix argument, pop that many patches."
1290 (interactive "p")
1291 (stgit-capture-output nil (stgit-run "pop" "-n" npatches))
1292 (stgit-reload)
1293 (stgit-refresh-git-status))
1294
1295 (defun stgit-applied-at-point-p ()
1296 "Return non-nil if the patch at point is applied."
1297 (let ((patch (stgit-patch-at-point t)))
1298 (not (eq (stgit-patch-status patch) 'unapplied))))
1299
1300 (defun stgit-push-or-pop ()
1301 "Push or pop the patch on the current line."
1302 (interactive)
1303 (let ((patchsym (stgit-patch-name-at-point t t))
1304 (applied (stgit-applied-at-point-p)))
1305 (stgit-capture-output nil
1306 (stgit-run (if applied "pop" "push") patchsym))
1307 (stgit-reload)))
1308
1309 (defun stgit-goto ()
1310 "Go to the patch on the current line."
1311 (interactive)
1312 (let ((patchsym (stgit-patch-name-at-point t)))
1313 (stgit-capture-output nil
1314 (stgit-run "goto" patchsym))
1315 (stgit-reload)))
1316
1317 (defun stgit-id (patchsym)
1318 "Return the git commit id for PATCHSYM.
1319 If PATCHSYM is a keyword, returns PATCHSYM unmodified."
1320 (if (keywordp patchsym)
1321 patchsym
1322 (let ((result (with-output-to-string
1323 (stgit-run-silent "id" patchsym))))
1324 (unless (string-match "^\\([0-9A-Fa-f]\\{40\\}\\)$" result)
1325 (error "Cannot find commit id for %s" patchsym))
1326 (match-string 1 result))))
1327
1328 (defun stgit-show-patch (unmerged-stage ignore-whitespace)
1329 "Show the patch on the current line.
1330
1331 UNMERGED-STAGE is the argument to `git-diff' that that selects
1332 which stage to diff against in the case of unmerged files."
1333 (let ((space-arg (when (numberp ignore-whitespace)
1334 (cond ((> ignore-whitespace 4)
1335 "--ignore-all-space")
1336 ((> ignore-whitespace 1)
1337 "--ignore-space-change"))))
1338 (patch-name (stgit-patch-name-at-point t)))
1339 (stgit-capture-output "*StGit patch*"
1340 (case (get-text-property (point) 'entry-type)
1341 ('file
1342 (let* ((patched-file (stgit-patched-file-at-point))
1343 (patch-id (let ((id (stgit-id patch-name)))
1344 (if (and (eq id :index)
1345 (eq (stgit-file-status patched-file)
1346 'unmerged))
1347 :work
1348 id)))
1349 (args (append (and space-arg (list space-arg))
1350 (and (stgit-file-cr-from patched-file)
1351 (list (stgit-find-copies-harder-diff-arg)))
1352 (cond ((eq patch-id :index)
1353 '("--cached"))
1354 ((eq patch-id :work)
1355 (list unmerged-stage))
1356 (t
1357 (list (concat patch-id "^") patch-id)))
1358 '("--")
1359 (if (stgit-file-copy-or-rename patched-file)
1360 (list (stgit-file-cr-from patched-file)
1361 (stgit-file-cr-to patched-file))
1362 (list (stgit-file-file patched-file))))))
1363 (apply 'stgit-run-git "diff" args)))
1364 ('patch
1365 (let* ((patch-id (stgit-id patch-name)))
1366 (if (or (eq patch-id :index) (eq patch-id :work))
1367 (apply 'stgit-run-git "diff"
1368 (stgit-find-copies-harder-diff-arg)
1369 (append (and space-arg (list space-arg))
1370 (if (eq patch-id :index)
1371 '("--cached")
1372 (list unmerged-stage))))
1373 (let ((args (append '("show" "-O" "--patch-with-stat" "-O" "-M")
1374 (and space-arg (list "-O" space-arg))
1375 (list (stgit-patch-name-at-point)))))
1376 (apply 'stgit-run args)))))
1377 (t
1378 (error "No patch or file at point")))
1379 (with-current-buffer standard-output
1380 (goto-char (point-min))
1381 (diff-mode)))))
1382
1383 (defmacro stgit-define-diff (name diff-arg &optional unmerged-action)
1384 `(defun ,name (&optional ignore-whitespace)
1385 ,(format "Show the patch on the current line.
1386
1387 %sWith a prefix argument, ignore whitespace. With a prefix argument
1388 greater than four (e.g., \\[universal-argument] \
1389 \\[universal-argument] \\[%s]), ignore all whitespace."
1390 (if unmerged-action
1391 (format "For unmerged files, %s.\n\n" unmerged-action)
1392 "")
1393 name)
1394 (interactive "p")
1395 (stgit-show-patch ,diff-arg ignore-whitespace)))
1396
1397 (stgit-define-diff stgit-diff
1398 "--ours" nil)
1399 (stgit-define-diff stgit-diff-ours
1400 "--ours"
1401 "diff against our branch")
1402 (stgit-define-diff stgit-diff-theirs
1403 "--theirs"
1404 "diff against their branch")
1405 (stgit-define-diff stgit-diff-base
1406 "--base"
1407 "diff against the merge base")
1408 (stgit-define-diff stgit-diff-combined
1409 "--cc"
1410 "show a combined diff")
1411
1412 (defun stgit-move-change-to-index (file &optional force)
1413 "Copies the work tree state of FILE to index, using git add or git rm.
1414
1415 If FORCE is not nil, use --force."
1416 (let ((op (if (or (file-exists-p file) (file-symlink-p file))
1417 '("add") '("rm" "-q"))))
1418 (stgit-capture-output "*git output*"
1419 (apply 'stgit-run-git (append op (and force '("--force"))
1420 '("--") (list file))))))
1421
1422 (defun stgit-remove-change-from-index (file)
1423 "Unstages the change in FILE from the index"
1424 (stgit-capture-output "*git output*"
1425 (stgit-run-git "reset" "-q" "--" file)))
1426
1427 (defun stgit-file-toggle-index ()
1428 "Move modified file in or out of the index.
1429
1430 Leaves the point where it is, but moves the mark to where the
1431 file ended up. You can then jump to the file with \
1432 \\[exchange-point-and-mark]."
1433 (interactive)
1434 (let* ((patched-file (or (stgit-patched-file-at-point)
1435 (error "No file on the current line")))
1436 (patched-status (stgit-file-status patched-file)))
1437 (when (eq patched-status 'unmerged)
1438 (error (substitute-command-keys "Use \\[stgit-resolve-file] to move an unmerged file to the index")))
1439 (let* ((patch (stgit-patch-at-point))
1440 (patch-name (stgit-patch-name patch))
1441 (mark-file (if (eq patched-status 'rename)
1442 (stgit-file-cr-to patched-file)
1443 (stgit-file-file patched-file)))
1444 (point-file (if (eq patched-status 'rename)
1445 (stgit-file-cr-from patched-file)
1446 (stgit-neighbour-file))))
1447
1448 (cond ((eq patch-name :work)
1449 (stgit-move-change-to-index (stgit-file-file patched-file)
1450 (eq patched-status 'ignore)))
1451 ((eq patch-name :index)
1452 (stgit-remove-change-from-index (stgit-file-file patched-file)))
1453 (t
1454 (error "Can only move files between working tree and index")))
1455 (stgit-refresh-worktree)
1456 (stgit-refresh-index)
1457 (stgit-goto-patch (if (eq patch-name :index) :work :index) mark-file)
1458 (push-mark nil t t)
1459 (stgit-goto-patch patch-name point-file))))
1460
1461 (defun stgit-edit ()
1462 "Edit the patch on the current line."
1463 (interactive)
1464 (let ((patchsym (stgit-patch-name-at-point t t))
1465 (edit-buf (get-buffer-create "*StGit edit*"))
1466 (dir default-directory))
1467 (log-edit 'stgit-confirm-edit t nil edit-buf)
1468 (set (make-local-variable 'stgit-edit-patchsym) patchsym)
1469 (setq default-directory dir)
1470 (let ((standard-output edit-buf))
1471 (stgit-run-silent "edit" "--save-template=-" patchsym))))
1472
1473 (defun stgit-confirm-edit ()
1474 (interactive)
1475 (let ((file (make-temp-file "stgit-edit-")))
1476 (write-region (point-min) (point-max) file)
1477 (stgit-capture-output nil
1478 (stgit-run "edit" "-f" file stgit-edit-patchsym))
1479 (with-current-buffer log-edit-parent-buffer
1480 (stgit-reload))))
1481
1482 (defun stgit-new (add-sign &optional refresh)
1483 "Create a new patch.
1484 With a prefix argument, include a \"Signed-off-by:\" line at the
1485 end of the patch."
1486 (interactive "P")
1487 (let ((edit-buf (get-buffer-create "*StGit edit*"))
1488 (dir default-directory))
1489 (log-edit 'stgit-confirm-new t nil edit-buf)
1490 (setq default-directory dir)
1491 (set (make-local-variable 'stgit-refresh-after-new) refresh)
1492 (when add-sign
1493 (save-excursion
1494 (let ((standard-output (current-buffer)))
1495 (stgit-run-silent "new" "--sign" "--save-template=-"))))))
1496
1497 (defun stgit-confirm-new ()
1498 (interactive)
1499 (let ((file (make-temp-file "stgit-edit-"))
1500 (refresh stgit-refresh-after-new))
1501 (write-region (point-min) (point-max) file)
1502 (stgit-capture-output nil
1503 (stgit-run "new" "-f" file))
1504 (with-current-buffer log-edit-parent-buffer
1505 (if refresh
1506 (stgit-refresh)
1507 (stgit-reload)))))
1508
1509 (defun stgit-new-and-refresh (add-sign)
1510 "Create a new patch and refresh it with the current changes.
1511
1512 With a prefix argument, include a \"Signed-off-by:\" line at the
1513 end of the patch.
1514
1515 This works just like running `stgit-new' followed by `stgit-refresh'."
1516 (interactive "P")
1517 (stgit-new add-sign t))
1518
1519 (defun stgit-create-patch-name (description)
1520 "Create a patch name from a long description"
1521 (let ((patch ""))
1522 (while (> (length description) 0)
1523 (cond ((string-match "\\`[a-zA-Z_-]+" description)
1524 (setq patch (downcase (concat patch
1525 (match-string 0 description))))
1526 (setq description (substring description (match-end 0))))
1527 ((string-match "\\` +" description)
1528 (setq patch (concat patch "-"))
1529 (setq description (substring description (match-end 0))))
1530 ((string-match "\\`[^a-zA-Z_-]+" description)
1531 (setq description (substring description (match-end 0))))))
1532 (cond ((= (length patch) 0)
1533 "patch")
1534 ((> (length patch) 20)
1535 (substring patch 0 20))
1536 (t patch))))
1537
1538 (defun stgit-delete (patchsyms &optional spill-p)
1539 "Delete the patches in PATCHSYMS.
1540 Interactively, delete the marked patches, or the patch at point.
1541
1542 With a prefix argument, or SPILL-P, spill the patch contents to
1543 the work tree and index."
1544 (interactive (list (stgit-patches-marked-or-at-point)
1545 current-prefix-arg))
1546 (unless patchsyms
1547 (error "No patches to delete"))
1548 (when (memq :index patchsyms)
1549 (error "Cannot delete the index"))
1550 (when (memq :work patchsyms)
1551 (error "Cannot delete the work tree"))
1552
1553 (let ((npatches (length patchsyms)))
1554 (when (yes-or-no-p (format "Really delete %d patch%s%s? "
1555 npatches
1556 (if (= 1 npatches) "" "es")
1557 (if spill-p
1558 " (spilling contents to index)"
1559 "")))
1560 (let ((args (if spill-p
1561 (cons "--spill" patchsyms)
1562 patchsyms)))
1563 (stgit-capture-output nil
1564 (apply 'stgit-run "delete" args))
1565 (stgit-reload)))))
1566
1567 (defun stgit-move-patches-target ()
1568 "Return the patchsym indicating a target patch for
1569 `stgit-move-patches'.
1570
1571 This is either the patch at point, or one of :top and :bottom, if
1572 the point is after or before the applied patches."
1573
1574 (let ((patchsym (stgit-patch-name-at-point nil t)))
1575 (cond (patchsym patchsym)
1576 ((save-excursion (re-search-backward "^>" nil t)) :top)
1577 (t :bottom))))
1578
1579 (defun stgit-sort-patches (patchsyms)
1580 "Returns the list of patches in PATCHSYMS sorted according to
1581 their position in the patch series, bottommost first.
1582
1583 PATCHSYMS must not contain duplicate entries."
1584 (let (sorted-patchsyms
1585 (series (with-output-to-string
1586 (with-current-buffer standard-output
1587 (stgit-run-silent "series" "--noprefix"))))
1588 start)
1589 (while (string-match "^\\(.+\\)" series start)
1590 (let ((patchsym (intern (match-string 1 series))))
1591 (when (memq patchsym patchsyms)
1592 (setq sorted-patchsyms (cons patchsym sorted-patchsyms))))
1593 (setq start (match-end 0)))
1594 (setq sorted-patchsyms (nreverse sorted-patchsyms))
1595
1596 (unless (= (length patchsyms) (length sorted-patchsyms))
1597 (error "Internal error"))
1598
1599 sorted-patchsyms))
1600
1601 (defun stgit-move-patches (patchsyms target-patch)
1602 "Move the patches in PATCHSYMS to below TARGET-PATCH.
1603 If TARGET-PATCH is :bottom or :top, move the patches to the
1604 bottom or top of the stack, respectively.
1605
1606 Interactively, move the marked patches to where the point is."
1607 (interactive (list stgit-marked-patches
1608 (stgit-move-patches-target)))
1609 (unless patchsyms
1610 (error "Need at least one patch to move"))
1611
1612 (unless target-patch
1613 (error "Point not at a patch"))
1614
1615 (if (eq target-patch :top)
1616 (stgit-capture-output nil
1617 (apply 'stgit-run "float" patchsyms))
1618
1619 ;; need to have patchsyms sorted by position in the stack
1620 (let ((sorted-patchsyms (stgit-sort-patches patchsyms)))
1621 (while sorted-patchsyms
1622 (setq sorted-patchsyms
1623 (and (stgit-capture-output nil
1624 (if (eq target-patch :bottom)
1625 (stgit-run "sink" "--" (car sorted-patchsyms))
1626 (stgit-run "sink" "--to" target-patch "--"
1627 (car sorted-patchsyms))))
1628 (cdr sorted-patchsyms))))))
1629 (stgit-reload))
1630
1631 (defun stgit-squash (patchsyms)
1632 "Squash the patches in PATCHSYMS.
1633 Interactively, squash the marked patches.
1634
1635 Unless there are any conflicts, the patches will be merged into
1636 one patch, which will occupy the same spot in the series as the
1637 deepest patch had before the squash."
1638 (interactive (list stgit-marked-patches))
1639 (when (< (length patchsyms) 2)
1640 (error "Need at least two patches to squash"))
1641 (let ((stgit-buffer (current-buffer))
1642 (edit-buf (get-buffer-create "*StGit edit*"))
1643 (dir default-directory)
1644 (sorted-patchsyms (stgit-sort-patches patchsyms)))
1645 (log-edit 'stgit-confirm-squash t nil edit-buf)
1646 (set (make-local-variable 'stgit-patchsyms) sorted-patchsyms)
1647 (setq default-directory dir)
1648 (let ((result (let ((standard-output edit-buf))
1649 (apply 'stgit-run-silent "squash"
1650 "--save-template=-" sorted-patchsyms))))
1651
1652 ;; stg squash may have reordered the patches or caused conflicts
1653 (with-current-buffer stgit-buffer
1654 (stgit-reload))
1655
1656 (unless (eq 0 result)
1657 (fundamental-mode)
1658 (rename-buffer "*StGit error*")
1659 (resize-temp-buffer-window)
1660 (switch-to-buffer-other-window stgit-buffer)
1661 (error "stg squash failed")))))
1662
1663 (defun stgit-confirm-squash ()
1664 (interactive)
1665 (let ((file (make-temp-file "stgit-edit-")))
1666 (write-region (point-min) (point-max) file)
1667 (stgit-capture-output nil
1668 (apply 'stgit-run "squash" "-f" file stgit-patchsyms))
1669 (with-current-buffer log-edit-parent-buffer
1670 (stgit-clear-marks)
1671 ;; Go to first marked patch and stay there
1672 (goto-char (point-min))
1673 (re-search-forward (concat "^[>+-]\\*") nil t)
1674 (move-to-column goal-column)
1675 (let ((pos (point)))
1676 (stgit-reload)
1677 (goto-char pos)))))
1678
1679 (defun stgit-help ()
1680 "Display help for the StGit mode."
1681 (interactive)
1682 (describe-function 'stgit-mode))
1683
1684 (defun stgit-undo (&optional arg)
1685 "Run stg undo.
1686 With prefix argument, run it with the --hard flag.
1687
1688 See also `stgit-redo'."
1689 (interactive "P")
1690 (stgit-capture-output nil
1691 (if arg
1692 (stgit-run "undo" "--hard")
1693 (stgit-run "undo")))
1694 (stgit-reload))
1695
1696 (defun stgit-redo (&optional arg)
1697 "Run stg redo.
1698 With prefix argument, run it with the --hard flag.
1699
1700 See also `stgit-undo'."
1701 (interactive "P")
1702 (stgit-capture-output nil
1703 (if arg
1704 (stgit-run "redo" "--hard")
1705 (stgit-run "redo")))
1706 (stgit-reload))
1707
1708 (defun stgit-refresh (&optional arg)
1709 "Run stg refresh.
1710 If the index contains any changes, only refresh from index.
1711
1712 With prefix argument, refresh the marked patch or the patch under point."
1713 (interactive "P")
1714 (let ((patchargs (if arg
1715 (let ((patches (stgit-patches-marked-or-at-point)))
1716 (cond ((null patches)
1717 (error "No patch to update"))
1718 ((> (length patches) 1)
1719 (error "Too many patches selected"))
1720 (t
1721 (cons "-p" patches))))
1722 nil)))
1723 (unless (stgit-index-empty-p)
1724 (setq patchargs (cons "--index" patchargs)))
1725 (stgit-capture-output nil
1726 (apply 'stgit-run "refresh" patchargs))
1727 (stgit-refresh-git-status))
1728 (stgit-reload))
1729
1730 (defvar stgit-show-worktree nil
1731 "If nil, inhibit showing work tree and index in the stgit buffer.
1732
1733 See also `stgit-show-worktree-mode'.")
1734
1735 (defvar stgit-show-ignored nil
1736 "If nil, inhibit showing files ignored by git.")
1737
1738 (defvar stgit-show-unknown nil
1739 "If nil, inhibit showing files not registered with git.")
1740
1741 (defun stgit-toggle-worktree (&optional arg)
1742 "Toggle the visibility of the work tree.
1743 With ARG, show the work tree if ARG is positive.
1744
1745 Its initial setting is controlled by `stgit-default-show-worktree'.
1746
1747 `stgit-show-worktree-mode' controls where on screen the index and
1748 work tree will show up."
1749 (interactive)
1750 (setq stgit-show-worktree
1751 (if (numberp arg)
1752 (> arg 0)
1753 (not stgit-show-worktree)))
1754 (stgit-reload))
1755
1756 (defun stgit-toggle-ignored (&optional arg)
1757 "Toggle the visibility of files ignored by git in the work
1758 tree. With ARG, show these files if ARG is positive.
1759
1760 Use \\[stgit-toggle-worktree] to show the work tree."
1761 (interactive)
1762 (setq stgit-show-ignored
1763 (if (numberp arg)
1764 (> arg 0)
1765 (not stgit-show-ignored)))
1766 (stgit-reload))
1767
1768 (defun stgit-toggle-unknown (&optional arg)
1769 "Toggle the visibility of files not registered with git in the
1770 work tree. With ARG, show these files if ARG is positive.
1771
1772 Use \\[stgit-toggle-worktree] to show the work tree."
1773 (interactive)
1774 (setq stgit-show-unknown
1775 (if (numberp arg)
1776 (> arg 0)
1777 (not stgit-show-unknown)))
1778 (stgit-reload))
1779
1780 (provide 'stgit)