stgit.el: Allow toggle-index 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-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 \\[stgit-toggle-index] Toggle all changes between index and work tree
892
893 \\[stgit-push-next] Push next patch onto stack
894 \\[stgit-pop-next] Pop current patch from stack
895 \\[stgit-push-or-pop] Push or pop patch at point
896 \\[stgit-goto] Make current patch current by popping or pushing
897
898 \\[stgit-squash] Squash (meld together) patches
899 \\[stgit-move-patches] Move patch(es) to point
900
901 \\[stgit-commit] Commit patch(es)
902 \\[stgit-uncommit] Uncommit patch(es)
903
904 Commands for files:
905 \\[stgit-select] Open the file in this window
906 \\[stgit-find-file-other-window] Open the file in another window
907 \\[stgit-diff] Show the file's diff
908
909 \\[stgit-toggle-index] Toggle change between index and work tree
910 \\[stgit-revert] Revert changes to file
911
912 Display commands:
913 \\[stgit-toggle-worktree] Toggle showing index and work tree
914 \\[stgit-toggle-unknown] Toggle showing unknown files
915 \\[stgit-toggle-ignored] Toggle showing ignored files
916
917 Commands for diffs:
918 \\[stgit-diff] Show diff of patch or file
919 \\[stgit-diff-base] Show diff against the merge base
920 \\[stgit-diff-ours] Show diff against our branch
921 \\[stgit-diff-theirs] Show diff against their branch
922
923 With one prefix argument (e.g., \\[universal-argument] \\[stgit-diff]), \
924 ignore space changes.
925 With two prefix arguments (e.g., \\[universal-argument] \
926 \\[universal-argument] \\[stgit-diff]), ignore all space changes.
927
928 Commands for merge conflicts:
929 \\[stgit-find-file-merge] Resolve conflicts using `smerge-ediff'
930 \\[stgit-resolve-file] Mark unmerged file as resolved
931
932 Commands for branches:
933 \\[stgit-branch] Switch to another branch
934 \\[stgit-rebase] Rebase the current branch
935
936 Customization variables:
937 `stgit-abbreviate-copies-and-renames'
938 `stgit-default-show-worktree'
939 `stgit-find-copies-harder'
940 `stgit-show-worktree-mode'
941
942 See also \\[customize-group] for the \"stgit\" group."
943 (kill-all-local-variables)
944 (buffer-disable-undo)
945 (setq mode-name "StGit"
946 major-mode 'stgit-mode
947 goal-column 2)
948 (use-local-map stgit-mode-map)
949 (set (make-local-variable 'list-buffers-directory) default-directory)
950 (set (make-local-variable 'stgit-marked-patches) nil)
951 (set (make-local-variable 'stgit-expanded-patches) (list :work :index))
952 (set (make-local-variable 'stgit-show-worktree) stgit-default-show-worktree)
953 (set (make-local-variable 'stgit-index-node) nil)
954 (set (make-local-variable 'stgit-worktree-node) nil)
955 (set (make-local-variable 'parse-sexp-lookup-properties) t)
956 (set-variable 'truncate-lines 't)
957 (add-hook 'after-save-hook 'stgit-update-saved-file)
958 (run-hooks 'stgit-mode-hook))
959
960 (defun stgit-update-saved-file ()
961 (let* ((file (expand-file-name buffer-file-name))
962 (dir (file-name-directory file))
963 (gitdir (condition-case nil (git-get-top-dir dir)
964 (error nil)))
965 (buffer (and gitdir (stgit-find-buffer gitdir))))
966 (when buffer
967 (with-current-buffer buffer
968 (stgit-refresh-worktree)))))
969
970 (defun stgit-add-mark (patchsym)
971 "Mark the patch PATCHSYM."
972 (setq stgit-marked-patches (cons patchsym stgit-marked-patches)))
973
974 (defun stgit-remove-mark (patchsym)
975 "Unmark the patch PATCHSYM."
976 (setq stgit-marked-patches (delq patchsym stgit-marked-patches)))
977
978 (defun stgit-clear-marks ()
979 "Unmark all patches."
980 (setq stgit-marked-patches '()))
981
982 (defun stgit-patch-at-point (&optional cause-error)
983 (get-text-property (point) 'patch-data))
984
985 (defun stgit-patch-name-at-point (&optional cause-error only-patches)
986 "Return the patch name on the current line as a symbol.
987 If CAUSE-ERROR is not nil, signal an error if none found.
988 If ONLY-PATCHES is not nil, only allow real patches, and not
989 index or work tree."
990 (let ((patch (stgit-patch-at-point)))
991 (and patch
992 only-patches
993 (memq (stgit-patch-status patch) '(work index))
994 (setq patch nil))
995 (cond (patch
996 (stgit-patch-name patch))
997 (cause-error
998 (error "No patch on this line")))))
999
1000 (defun stgit-patched-file-at-point ()
1001 (get-text-property (point) 'file-data))
1002
1003 (defun stgit-patches-marked-or-at-point ()
1004 "Return the symbols of the marked patches, or the patch on the current line."
1005 (if stgit-marked-patches
1006 stgit-marked-patches
1007 (let ((patch (stgit-patch-name-at-point)))
1008 (if patch
1009 (list patch)
1010 '()))))
1011
1012 (defun stgit-goto-patch (patchsym &optional file)
1013 "Move point to the line containing patch PATCHSYM.
1014 If that patch cannot be found, do nothing.
1015
1016 If the patch was found and FILE is not nil, instead move to that
1017 file's line. If FILE cannot be found, stay on the line of
1018 PATCHSYM."
1019 (let ((node (ewoc-nth stgit-ewoc 0)))
1020 (while (and node (not (eq (stgit-patch-name (ewoc-data node))
1021 patchsym)))
1022 (setq node (ewoc-next stgit-ewoc node)))
1023 (when (and node file)
1024 (let* ((file-ewoc (stgit-patch-files-ewoc (ewoc-data node)))
1025 (file-node (ewoc-nth file-ewoc 0)))
1026 (while (and file-node (not (equal (stgit-file-file (ewoc-data file-node)) file)))
1027 (setq file-node (ewoc-next file-ewoc file-node)))
1028 (when file-node
1029 (ewoc-goto-node file-ewoc file-node)
1030 (move-to-column (stgit-goal-column))
1031 (setq node nil))))
1032 (when node
1033 (ewoc-goto-node stgit-ewoc node)
1034 (move-to-column goal-column))))
1035
1036 (defun stgit-init ()
1037 "Run stg init."
1038 (interactive)
1039 (stgit-capture-output nil
1040 (stgit-run "init"))
1041 (stgit-reload))
1042
1043 (defun stgit-mark ()
1044 "Mark the patch under point."
1045 (interactive)
1046 (let* ((node (ewoc-locate stgit-ewoc))
1047 (patch (ewoc-data node))
1048 (name (stgit-patch-name patch)))
1049 (when (eq name :work)
1050 (error "Cannot mark the work tree"))
1051 (when (eq name :index)
1052 (error "Cannot mark the index"))
1053 (stgit-add-mark (stgit-patch-name patch))
1054 (ewoc-invalidate stgit-ewoc node))
1055 (stgit-next-patch))
1056
1057 (defun stgit-unmark-up ()
1058 "Remove mark from the patch on the previous line."
1059 (interactive)
1060 (stgit-previous-patch)
1061 (let* ((node (ewoc-locate stgit-ewoc))
1062 (patch (ewoc-data node)))
1063 (stgit-remove-mark (stgit-patch-name patch))
1064 (ewoc-invalidate stgit-ewoc node))
1065 (move-to-column (stgit-goal-column)))
1066
1067 (defun stgit-unmark-down ()
1068 "Remove mark from the patch on the current line."
1069 (interactive)
1070 (let* ((node (ewoc-locate stgit-ewoc))
1071 (patch (ewoc-data node)))
1072 (stgit-remove-mark (stgit-patch-name patch))
1073 (ewoc-invalidate stgit-ewoc node))
1074 (stgit-next-patch))
1075
1076 (defun stgit-rename (name)
1077 "Rename the patch under point to NAME."
1078 (interactive (list
1079 (read-string "Patch name: "
1080 (symbol-name (stgit-patch-name-at-point t t)))))
1081 (let ((old-patchsym (stgit-patch-name-at-point t t)))
1082 (stgit-capture-output nil
1083 (stgit-run "rename" old-patchsym name))
1084 (let ((name-sym (intern name)))
1085 (when (memq old-patchsym stgit-expanded-patches)
1086 (setq stgit-expanded-patches
1087 (cons name-sym (delq old-patchsym stgit-expanded-patches))))
1088 (when (memq old-patchsym stgit-marked-patches)
1089 (setq stgit-marked-patches
1090 (cons name-sym (delq old-patchsym stgit-marked-patches))))
1091 (stgit-reload)
1092 (stgit-goto-patch name-sym))))
1093
1094 (defun stgit-reload-or-repair (repair)
1095 "Update the contents of the StGit buffer (`stgit-reload').
1096
1097 With a prefix argument, repair the StGit metadata if the branch
1098 was modified with git commands (`stgit-repair')."
1099 (interactive "P")
1100 (if repair
1101 (stgit-repair)
1102 (stgit-reload)))
1103
1104 (defun stgit-repair ()
1105 "Run stg repair."
1106 (interactive)
1107 (stgit-capture-output nil
1108 (stgit-run "repair"))
1109 (stgit-reload))
1110
1111 (defun stgit-available-branches ()
1112 "Returns a list of the available stg branches"
1113 (let ((output (with-output-to-string
1114 (stgit-run "branch" "--list")))
1115 (start 0)
1116 result)
1117 (while (string-match "^>?\\s-+s\\s-+\\(\\S-+\\)" output start)
1118 (setq result (cons (match-string 1 output) result))
1119 (setq start (match-end 0)))
1120 result))
1121
1122 (defun stgit-branch (branch)
1123 "Switch to branch BRANCH."
1124 (interactive (list (completing-read "Switch to branch: "
1125 (stgit-available-branches))))
1126 (stgit-capture-output nil (stgit-run "branch" "--" branch))
1127 (stgit-reload))
1128
1129 (defun stgit-available-refs (&optional omit-stgit)
1130 "Returns a list of the available git refs.
1131 If OMIT-STGIT is not nil, filter out \"resf/heads/*.stgit\"."
1132 (let* ((output (with-output-to-string
1133 (stgit-run-git-silent "for-each-ref" "--format=%(refname)"
1134 "refs/tags" "refs/heads"
1135 "refs/remotes")))
1136 (result (split-string output "\n" t)))
1137 (mapcar (lambda (s)
1138 (if (string-match "^refs/\\(heads\\|tags\\|remotes\\)/" s)
1139 (substring s (match-end 0))
1140 s))
1141 (if omit-stgit
1142 (delete-if (lambda (s)
1143 (string-match "^refs/heads/.*\\.stgit$" s))
1144 result)
1145 result))))
1146
1147 (defun stgit-rebase (new-base)
1148 "Rebase to NEW-BASE."
1149 (interactive (list (completing-read "Rebase to: "
1150 (stgit-available-refs t))))
1151 (stgit-capture-output nil (stgit-run "rebase" new-base))
1152 (stgit-reload))
1153
1154 (defun stgit-commit (count)
1155 "Run stg commit on COUNT commits.
1156 Interactively, the prefix argument is used as COUNT.
1157 A negative COUNT will uncommit instead."
1158 (interactive "p")
1159 (if (< count 0)
1160 (stgit-uncommit (- count))
1161 (stgit-capture-output nil (stgit-run "commit" "-n" count))
1162 (stgit-reload)))
1163
1164 (defun stgit-uncommit (count)
1165 "Run stg uncommit on COUNT commits.
1166 Interactively, the prefix argument is used as COUNT.
1167 A negative COUNT will commit instead."
1168 (interactive "p")
1169 (if (< count 0)
1170 (stgit-commit (- count))
1171 (stgit-capture-output nil (stgit-run "uncommit" "-n" count))
1172 (stgit-reload)))
1173
1174 (defun stgit-neighbour-file ()
1175 "Return the file name of the next file after point, or the
1176 previous file if point is at the last file within a patch."
1177 (let ((old-point (point))
1178 neighbour-file)
1179 (and (zerop (forward-line 1))
1180 (let ((f (stgit-patched-file-at-point)))
1181 (and f (setq neighbour-file (stgit-file-file f)))))
1182 (goto-char old-point)
1183 (unless neighbour-file
1184 (and (zerop (forward-line -1))
1185 (let ((f (stgit-patched-file-at-point)))
1186 (and f (setq neighbour-file (stgit-file-file f)))))
1187 (goto-char old-point))
1188 neighbour-file))
1189
1190 (defun stgit-revert-file ()
1191 "Revert the file at point, which must be in the index or the
1192 working tree."
1193 (interactive)
1194 (let* ((patched-file (or (stgit-patched-file-at-point)
1195 (error "No file on the current line")))
1196 (patch-name (stgit-patch-name-at-point))
1197 (file-status (stgit-file-status patched-file))
1198 (rm-file (cond ((stgit-file-copy-or-rename patched-file)
1199 (stgit-file-cr-to patched-file))
1200 ((eq file-status 'add)
1201 (stgit-file-file patched-file))))
1202 (co-file (cond ((eq file-status 'rename)
1203 (stgit-file-cr-from patched-file))
1204 ((not (memq file-status '(copy add)))
1205 (stgit-file-file patched-file))))
1206 (next-file (stgit-neighbour-file)))
1207
1208 (unless (memq patch-name '(:work :index))
1209 (error "No index or working tree file on this line"))
1210
1211 (when (eq file-status 'ignore)
1212 (error "Cannot revert ignored files"))
1213
1214 (when (eq file-status 'unknown)
1215 (error "Cannot revert unknown files"))
1216
1217 (let ((nfiles (+ (if rm-file 1 0) (if co-file 1 0))))
1218 (when (yes-or-no-p (format "Revert %d file%s? "
1219 nfiles
1220 (if (= nfiles 1) "" "s")))
1221 (stgit-capture-output nil
1222 (when rm-file
1223 (stgit-run-git "rm" "-f" "-q" "--" rm-file))
1224 (when co-file
1225 (stgit-run-git "checkout" "HEAD" co-file)))
1226 (stgit-reload)
1227 (stgit-goto-patch patch-name next-file)))))
1228
1229 (defun stgit-revert ()
1230 "Revert the change at point, which must be the index, the work
1231 tree, or a single change in either."
1232 (interactive)
1233 (let ((patched-file (stgit-patched-file-at-point)))
1234 (if patched-file
1235 (stgit-revert-file)
1236 (let* ((patch-name (or (stgit-patch-name-at-point)
1237 (error "No patch or file at point")))
1238 (patch-desc (case patch-name
1239 (:index "index")
1240 (:work "work tree")
1241 (t (error (substitute-command-keys
1242 "Use \\[stgit-delete] to delete a patch"))))))
1243 (when (if (eq patch-name :work)
1244 (stgit-work-tree-empty-p)
1245 (stgit-index-empty-p))
1246 (error (format "There are no changes in the %s to revert"
1247 patch-desc)))
1248 (and (eq patch-name :index)
1249 (not (stgit-work-tree-empty-p))
1250 (error "Cannot revert index as work tree contains unstaged changes"))
1251
1252 (when (yes-or-no-p (format "Revert all changes in the %s? "
1253 patch-desc))
1254 (if (eq patch-name :index)
1255 (stgit-run-git-silent "reset" "--hard" "-q")
1256 (stgit-run-git-silent "checkout" "--" "."))
1257 (stgit-refresh-index)
1258 (stgit-refresh-worktree)
1259 (stgit-goto-patch patch-name))))))
1260
1261 (defun stgit-resolve-file ()
1262 "Resolve conflict in the file at point."
1263 (interactive)
1264 (let* ((patched-file (stgit-patched-file-at-point))
1265 (patch (stgit-patch-at-point))
1266 (patch-name (and patch (stgit-patch-name patch)))
1267 (status (and patched-file (stgit-file-status patched-file))))
1268
1269 (unless (memq patch-name '(:work :index))
1270 (error "No index or working tree file on this line"))
1271
1272 (unless (eq status 'unmerged)
1273 (error "No conflict to resolve at the current line"))
1274
1275 (stgit-capture-output nil
1276 (stgit-move-change-to-index (stgit-file-file patched-file)))
1277
1278 (stgit-reload)))
1279
1280 (defun stgit-push-next (npatches)
1281 "Push the first unapplied patch.
1282 With numeric prefix argument, push that many patches."
1283 (interactive "p")
1284 (stgit-capture-output nil (stgit-run "push" "-n" npatches))
1285 (stgit-reload)
1286 (stgit-refresh-git-status))
1287
1288 (defun stgit-pop-next (npatches)
1289 "Pop the topmost applied patch.
1290 With numeric prefix argument, pop that many patches."
1291 (interactive "p")
1292 (stgit-capture-output nil (stgit-run "pop" "-n" npatches))
1293 (stgit-reload)
1294 (stgit-refresh-git-status))
1295
1296 (defun stgit-applied-at-point-p ()
1297 "Return non-nil if the patch at point is applied."
1298 (let ((patch (stgit-patch-at-point t)))
1299 (not (eq (stgit-patch-status patch) 'unapplied))))
1300
1301 (defun stgit-push-or-pop ()
1302 "Push or pop the patch on the current line."
1303 (interactive)
1304 (let ((patchsym (stgit-patch-name-at-point t t))
1305 (applied (stgit-applied-at-point-p)))
1306 (stgit-capture-output nil
1307 (stgit-run (if applied "pop" "push") patchsym))
1308 (stgit-reload)))
1309
1310 (defun stgit-goto ()
1311 "Go to the patch on the current line."
1312 (interactive)
1313 (let ((patchsym (stgit-patch-name-at-point t)))
1314 (stgit-capture-output nil
1315 (stgit-run "goto" patchsym))
1316 (stgit-reload)))
1317
1318 (defun stgit-id (patchsym)
1319 "Return the git commit id for PATCHSYM.
1320 If PATCHSYM is a keyword, returns PATCHSYM unmodified."
1321 (if (keywordp patchsym)
1322 patchsym
1323 (let ((result (with-output-to-string
1324 (stgit-run-silent "id" patchsym))))
1325 (unless (string-match "^\\([0-9A-Fa-f]\\{40\\}\\)$" result)
1326 (error "Cannot find commit id for %s" patchsym))
1327 (match-string 1 result))))
1328
1329 (defun stgit-show-patch (unmerged-stage ignore-whitespace)
1330 "Show the patch on the current line.
1331
1332 UNMERGED-STAGE is the argument to `git-diff' that that selects
1333 which stage to diff against in the case of unmerged files."
1334 (let ((space-arg (when (numberp ignore-whitespace)
1335 (cond ((> ignore-whitespace 4)
1336 "--ignore-all-space")
1337 ((> ignore-whitespace 1)
1338 "--ignore-space-change"))))
1339 (patch-name (stgit-patch-name-at-point t)))
1340 (stgit-capture-output "*StGit patch*"
1341 (case (get-text-property (point) 'entry-type)
1342 ('file
1343 (let* ((patched-file (stgit-patched-file-at-point))
1344 (patch-id (let ((id (stgit-id patch-name)))
1345 (if (and (eq id :index)
1346 (eq (stgit-file-status patched-file)
1347 'unmerged))
1348 :work
1349 id)))
1350 (args (append (and space-arg (list space-arg))
1351 (and (stgit-file-cr-from patched-file)
1352 (list (stgit-find-copies-harder-diff-arg)))
1353 (cond ((eq patch-id :index)
1354 '("--cached"))
1355 ((eq patch-id :work)
1356 (list unmerged-stage))
1357 (t
1358 (list (concat patch-id "^") patch-id)))
1359 '("--")
1360 (if (stgit-file-copy-or-rename patched-file)
1361 (list (stgit-file-cr-from patched-file)
1362 (stgit-file-cr-to patched-file))
1363 (list (stgit-file-file patched-file))))))
1364 (apply 'stgit-run-git "diff" args)))
1365 ('patch
1366 (let* ((patch-id (stgit-id patch-name)))
1367 (if (or (eq patch-id :index) (eq patch-id :work))
1368 (apply 'stgit-run-git "diff"
1369 (stgit-find-copies-harder-diff-arg)
1370 (append (and space-arg (list space-arg))
1371 (if (eq patch-id :index)
1372 '("--cached")
1373 (list unmerged-stage))))
1374 (let ((args (append '("show" "-O" "--patch-with-stat" "-O" "-M")
1375 (and space-arg (list "-O" space-arg))
1376 (list (stgit-patch-name-at-point)))))
1377 (apply 'stgit-run args)))))
1378 (t
1379 (error "No patch or file at point")))
1380 (with-current-buffer standard-output
1381 (goto-char (point-min))
1382 (diff-mode)))))
1383
1384 (defmacro stgit-define-diff (name diff-arg &optional unmerged-action)
1385 `(defun ,name (&optional ignore-whitespace)
1386 ,(format "Show the patch on the current line.
1387
1388 %sWith a prefix argument, ignore whitespace. With a prefix argument
1389 greater than four (e.g., \\[universal-argument] \
1390 \\[universal-argument] \\[%s]), ignore all whitespace."
1391 (if unmerged-action
1392 (format "For unmerged files, %s.\n\n" unmerged-action)
1393 "")
1394 name)
1395 (interactive "p")
1396 (stgit-show-patch ,diff-arg ignore-whitespace)))
1397
1398 (stgit-define-diff stgit-diff
1399 "--ours" nil)
1400 (stgit-define-diff stgit-diff-ours
1401 "--ours"
1402 "diff against our branch")
1403 (stgit-define-diff stgit-diff-theirs
1404 "--theirs"
1405 "diff against their branch")
1406 (stgit-define-diff stgit-diff-base
1407 "--base"
1408 "diff against the merge base")
1409 (stgit-define-diff stgit-diff-combined
1410 "--cc"
1411 "show a combined diff")
1412
1413 (defun stgit-move-change-to-index (file &optional force)
1414 "Copies the work tree state of FILE to index, using git add or git rm.
1415
1416 If FORCE is not nil, use --force."
1417 (let ((op (if (or (file-exists-p file) (file-symlink-p file))
1418 '("add") '("rm" "-q"))))
1419 (stgit-capture-output "*git output*"
1420 (apply 'stgit-run-git (append op (and force '("--force"))
1421 '("--") (list file))))))
1422
1423 (defun stgit-remove-change-from-index (file)
1424 "Unstages the change in FILE from the index"
1425 (stgit-capture-output "*git output*"
1426 (stgit-run-git "reset" "-q" "--" file)))
1427
1428 (defun stgit-git-index-unmerged-p ()
1429 (let (result)
1430 (with-output-to-string
1431 (setq result (not (zerop (stgit-run-git-silent "diff-index" "--cached"
1432 "--diff-filter=U"
1433 "--quiet" "HEAD")))))
1434 result))
1435
1436 (defun stgit-file-toggle-index ()
1437 "Move modified file in or out of the index.
1438
1439 Leaves the point where it is, but moves the mark to where the
1440 file ended up. You can then jump to the file with \
1441 \\[exchange-point-and-mark]."
1442 (interactive)
1443 (let* ((patched-file (or (stgit-patched-file-at-point)
1444 (error "No file on the current line")))
1445 (patched-status (stgit-file-status patched-file)))
1446 (when (eq patched-status 'unmerged)
1447 (error (substitute-command-keys "Use \\[stgit-resolve-file] to move an unmerged file to the index")))
1448 (let* ((patch (stgit-patch-at-point))
1449 (patch-name (stgit-patch-name patch))
1450 (mark-file (if (eq patched-status 'rename)
1451 (stgit-file-cr-to patched-file)
1452 (stgit-file-file patched-file)))
1453 (point-file (if (eq patched-status 'rename)
1454 (stgit-file-cr-from patched-file)
1455 (stgit-neighbour-file))))
1456
1457 (cond ((eq patch-name :work)
1458 (stgit-move-change-to-index (stgit-file-file patched-file)
1459 (eq patched-status 'ignore)))
1460 ((eq patch-name :index)
1461 (stgit-remove-change-from-index (stgit-file-file patched-file)))
1462 (t
1463 (error "Can only move files between working tree and index")))
1464 (stgit-refresh-worktree)
1465 (stgit-refresh-index)
1466 (stgit-goto-patch (if (eq patch-name :index) :work :index) mark-file)
1467 (push-mark nil t t)
1468 (stgit-goto-patch patch-name point-file))))
1469
1470 (defun stgit-toggle-index ()
1471 "Move change in or out of the index.
1472
1473 Works on index and work tree, as well as files in either.
1474
1475 Leaves the point where it is, but moves the mark to where the
1476 file ended up. You can then jump to the file with \
1477 \\[exchange-point-and-mark]."
1478 (interactive)
1479 (if (stgit-patched-file-at-point)
1480 (stgit-file-toggle-index)
1481 (let ((patch-name (stgit-patch-name-at-point)))
1482 (unless (memq patch-name '(:index :work))
1483 (error "Can only move changes between working tree and index"))
1484 (when (stgit-git-index-unmerged-p)
1485 (error "Resolve unmerged changes with \\[stgit-resolve-file] first"))
1486 (if (if (eq patch-name :index)
1487 (stgit-index-empty-p)
1488 (stgit-work-tree-empty-p))
1489 (message "No changes to be moved")
1490 (stgit-capture-output nil
1491 (if (eq patch-name :work)
1492 (stgit-run-git "add" "--update")
1493 (stgit-run-git "reset" "--mixed" "-q")))
1494 (stgit-refresh-worktree)
1495 (stgit-refresh-index))
1496 (stgit-goto-patch (if (eq patch-name :index) :work :index)))))
1497
1498 (defun stgit-edit ()
1499 "Edit the patch on the current line."
1500 (interactive)
1501 (let ((patchsym (stgit-patch-name-at-point t t))
1502 (edit-buf (get-buffer-create "*StGit edit*"))
1503 (dir default-directory))
1504 (log-edit 'stgit-confirm-edit t nil edit-buf)
1505 (set (make-local-variable 'stgit-edit-patchsym) patchsym)
1506 (setq default-directory dir)
1507 (let ((standard-output edit-buf))
1508 (stgit-run-silent "edit" "--save-template=-" patchsym))))
1509
1510 (defun stgit-confirm-edit ()
1511 (interactive)
1512 (let ((file (make-temp-file "stgit-edit-")))
1513 (write-region (point-min) (point-max) file)
1514 (stgit-capture-output nil
1515 (stgit-run "edit" "-f" file stgit-edit-patchsym))
1516 (with-current-buffer log-edit-parent-buffer
1517 (stgit-reload))))
1518
1519 (defun stgit-new (add-sign &optional refresh)
1520 "Create a new patch.
1521 With a prefix argument, include a \"Signed-off-by:\" line at the
1522 end of the patch."
1523 (interactive "P")
1524 (let ((edit-buf (get-buffer-create "*StGit edit*"))
1525 (dir default-directory))
1526 (log-edit 'stgit-confirm-new t nil edit-buf)
1527 (setq default-directory dir)
1528 (set (make-local-variable 'stgit-refresh-after-new) refresh)
1529 (when add-sign
1530 (save-excursion
1531 (let ((standard-output (current-buffer)))
1532 (stgit-run-silent "new" "--sign" "--save-template=-"))))))
1533
1534 (defun stgit-confirm-new ()
1535 (interactive)
1536 (let ((file (make-temp-file "stgit-edit-"))
1537 (refresh stgit-refresh-after-new))
1538 (write-region (point-min) (point-max) file)
1539 (stgit-capture-output nil
1540 (stgit-run "new" "-f" file))
1541 (with-current-buffer log-edit-parent-buffer
1542 (if refresh
1543 (stgit-refresh)
1544 (stgit-reload)))))
1545
1546 (defun stgit-new-and-refresh (add-sign)
1547 "Create a new patch and refresh it with the current changes.
1548
1549 With a prefix argument, include a \"Signed-off-by:\" line at the
1550 end of the patch.
1551
1552 This works just like running `stgit-new' followed by `stgit-refresh'."
1553 (interactive "P")
1554 (stgit-new add-sign t))
1555
1556 (defun stgit-create-patch-name (description)
1557 "Create a patch name from a long description"
1558 (let ((patch ""))
1559 (while (> (length description) 0)
1560 (cond ((string-match "\\`[a-zA-Z_-]+" description)
1561 (setq patch (downcase (concat patch
1562 (match-string 0 description))))
1563 (setq description (substring description (match-end 0))))
1564 ((string-match "\\` +" description)
1565 (setq patch (concat patch "-"))
1566 (setq description (substring description (match-end 0))))
1567 ((string-match "\\`[^a-zA-Z_-]+" description)
1568 (setq description (substring description (match-end 0))))))
1569 (cond ((= (length patch) 0)
1570 "patch")
1571 ((> (length patch) 20)
1572 (substring patch 0 20))
1573 (t patch))))
1574
1575 (defun stgit-delete (patchsyms &optional spill-p)
1576 "Delete the patches in PATCHSYMS.
1577 Interactively, delete the marked patches, or the patch at point.
1578
1579 With a prefix argument, or SPILL-P, spill the patch contents to
1580 the work tree and index."
1581 (interactive (list (stgit-patches-marked-or-at-point)
1582 current-prefix-arg))
1583 (unless patchsyms
1584 (error "No patches to delete"))
1585 (when (memq :index patchsyms)
1586 (error "Cannot delete the index"))
1587 (when (memq :work patchsyms)
1588 (error "Cannot delete the work tree"))
1589
1590 (let ((npatches (length patchsyms)))
1591 (when (yes-or-no-p (format "Really delete %d patch%s%s? "
1592 npatches
1593 (if (= 1 npatches) "" "es")
1594 (if spill-p
1595 " (spilling contents to index)"
1596 "")))
1597 (let ((args (if spill-p
1598 (cons "--spill" patchsyms)
1599 patchsyms)))
1600 (stgit-capture-output nil
1601 (apply 'stgit-run "delete" args))
1602 (stgit-reload)))))
1603
1604 (defun stgit-move-patches-target ()
1605 "Return the patchsym indicating a target patch for
1606 `stgit-move-patches'.
1607
1608 This is either the patch at point, or one of :top and :bottom, if
1609 the point is after or before the applied patches."
1610
1611 (let ((patchsym (stgit-patch-name-at-point nil t)))
1612 (cond (patchsym patchsym)
1613 ((save-excursion (re-search-backward "^>" nil t)) :top)
1614 (t :bottom))))
1615
1616 (defun stgit-sort-patches (patchsyms)
1617 "Returns the list of patches in PATCHSYMS sorted according to
1618 their position in the patch series, bottommost first.
1619
1620 PATCHSYMS must not contain duplicate entries."
1621 (let (sorted-patchsyms
1622 (series (with-output-to-string
1623 (with-current-buffer standard-output
1624 (stgit-run-silent "series" "--noprefix"))))
1625 start)
1626 (while (string-match "^\\(.+\\)" series start)
1627 (let ((patchsym (intern (match-string 1 series))))
1628 (when (memq patchsym patchsyms)
1629 (setq sorted-patchsyms (cons patchsym sorted-patchsyms))))
1630 (setq start (match-end 0)))
1631 (setq sorted-patchsyms (nreverse sorted-patchsyms))
1632
1633 (unless (= (length patchsyms) (length sorted-patchsyms))
1634 (error "Internal error"))
1635
1636 sorted-patchsyms))
1637
1638 (defun stgit-move-patches (patchsyms target-patch)
1639 "Move the patches in PATCHSYMS to below TARGET-PATCH.
1640 If TARGET-PATCH is :bottom or :top, move the patches to the
1641 bottom or top of the stack, respectively.
1642
1643 Interactively, move the marked patches to where the point is."
1644 (interactive (list stgit-marked-patches
1645 (stgit-move-patches-target)))
1646 (unless patchsyms
1647 (error "Need at least one patch to move"))
1648
1649 (unless target-patch
1650 (error "Point not at a patch"))
1651
1652 (if (eq target-patch :top)
1653 (stgit-capture-output nil
1654 (apply 'stgit-run "float" patchsyms))
1655
1656 ;; need to have patchsyms sorted by position in the stack
1657 (let ((sorted-patchsyms (stgit-sort-patches patchsyms)))
1658 (while sorted-patchsyms
1659 (setq sorted-patchsyms
1660 (and (stgit-capture-output nil
1661 (if (eq target-patch :bottom)
1662 (stgit-run "sink" "--" (car sorted-patchsyms))
1663 (stgit-run "sink" "--to" target-patch "--"
1664 (car sorted-patchsyms))))
1665 (cdr sorted-patchsyms))))))
1666 (stgit-reload))
1667
1668 (defun stgit-squash (patchsyms)
1669 "Squash the patches in PATCHSYMS.
1670 Interactively, squash the marked patches.
1671
1672 Unless there are any conflicts, the patches will be merged into
1673 one patch, which will occupy the same spot in the series as the
1674 deepest patch had before the squash."
1675 (interactive (list stgit-marked-patches))
1676 (when (< (length patchsyms) 2)
1677 (error "Need at least two patches to squash"))
1678 (let ((stgit-buffer (current-buffer))
1679 (edit-buf (get-buffer-create "*StGit edit*"))
1680 (dir default-directory)
1681 (sorted-patchsyms (stgit-sort-patches patchsyms)))
1682 (log-edit 'stgit-confirm-squash t nil edit-buf)
1683 (set (make-local-variable 'stgit-patchsyms) sorted-patchsyms)
1684 (setq default-directory dir)
1685 (let ((result (let ((standard-output edit-buf))
1686 (apply 'stgit-run-silent "squash"
1687 "--save-template=-" sorted-patchsyms))))
1688
1689 ;; stg squash may have reordered the patches or caused conflicts
1690 (with-current-buffer stgit-buffer
1691 (stgit-reload))
1692
1693 (unless (eq 0 result)
1694 (fundamental-mode)
1695 (rename-buffer "*StGit error*")
1696 (resize-temp-buffer-window)
1697 (switch-to-buffer-other-window stgit-buffer)
1698 (error "stg squash failed")))))
1699
1700 (defun stgit-confirm-squash ()
1701 (interactive)
1702 (let ((file (make-temp-file "stgit-edit-")))
1703 (write-region (point-min) (point-max) file)
1704 (stgit-capture-output nil
1705 (apply 'stgit-run "squash" "-f" file stgit-patchsyms))
1706 (with-current-buffer log-edit-parent-buffer
1707 (stgit-clear-marks)
1708 ;; Go to first marked patch and stay there
1709 (goto-char (point-min))
1710 (re-search-forward (concat "^[>+-]\\*") nil t)
1711 (move-to-column goal-column)
1712 (let ((pos (point)))
1713 (stgit-reload)
1714 (goto-char pos)))))
1715
1716 (defun stgit-help ()
1717 "Display help for the StGit mode."
1718 (interactive)
1719 (describe-function 'stgit-mode))
1720
1721 (defun stgit-undo (&optional arg)
1722 "Run stg undo.
1723 With prefix argument, run it with the --hard flag.
1724
1725 See also `stgit-redo'."
1726 (interactive "P")
1727 (stgit-capture-output nil
1728 (if arg
1729 (stgit-run "undo" "--hard")
1730 (stgit-run "undo")))
1731 (stgit-reload))
1732
1733 (defun stgit-redo (&optional arg)
1734 "Run stg redo.
1735 With prefix argument, run it with the --hard flag.
1736
1737 See also `stgit-undo'."
1738 (interactive "P")
1739 (stgit-capture-output nil
1740 (if arg
1741 (stgit-run "redo" "--hard")
1742 (stgit-run "redo")))
1743 (stgit-reload))
1744
1745 (defun stgit-refresh (&optional arg)
1746 "Run stg refresh.
1747 If the index contains any changes, only refresh from index.
1748
1749 With prefix argument, refresh the marked patch or the patch under point."
1750 (interactive "P")
1751 (let ((patchargs (if arg
1752 (let ((patches (stgit-patches-marked-or-at-point)))
1753 (cond ((null patches)
1754 (error "No patch to update"))
1755 ((> (length patches) 1)
1756 (error "Too many patches selected"))
1757 (t
1758 (cons "-p" patches))))
1759 nil)))
1760 (unless (stgit-index-empty-p)
1761 (setq patchargs (cons "--index" patchargs)))
1762 (stgit-capture-output nil
1763 (apply 'stgit-run "refresh" patchargs))
1764 (stgit-refresh-git-status))
1765 (stgit-reload))
1766
1767 (defvar stgit-show-worktree nil
1768 "If nil, inhibit showing work tree and index in the stgit buffer.
1769
1770 See also `stgit-show-worktree-mode'.")
1771
1772 (defvar stgit-show-ignored nil
1773 "If nil, inhibit showing files ignored by git.")
1774
1775 (defvar stgit-show-unknown nil
1776 "If nil, inhibit showing files not registered with git.")
1777
1778 (defun stgit-toggle-worktree (&optional arg)
1779 "Toggle the visibility of the work tree.
1780 With ARG, show the work tree if ARG is positive.
1781
1782 Its initial setting is controlled by `stgit-default-show-worktree'.
1783
1784 `stgit-show-worktree-mode' controls where on screen the index and
1785 work tree will show up."
1786 (interactive)
1787 (setq stgit-show-worktree
1788 (if (numberp arg)
1789 (> arg 0)
1790 (not stgit-show-worktree)))
1791 (stgit-reload))
1792
1793 (defun stgit-toggle-ignored (&optional arg)
1794 "Toggle the visibility of files ignored by git in the work
1795 tree. With ARG, show these files if ARG is positive.
1796
1797 Use \\[stgit-toggle-worktree] to show the work tree."
1798 (interactive)
1799 (setq stgit-show-ignored
1800 (if (numberp arg)
1801 (> arg 0)
1802 (not stgit-show-ignored)))
1803 (stgit-reload))
1804
1805 (defun stgit-toggle-unknown (&optional arg)
1806 "Toggle the visibility of files not registered with git in the
1807 work tree. With ARG, show these files if ARG is positive.
1808
1809 Use \\[stgit-toggle-worktree] to show the work tree."
1810 (interactive)
1811 (setq stgit-show-unknown
1812 (if (numberp arg)
1813 (> arg 0)
1814 (not stgit-show-unknown)))
1815 (stgit-reload))
1816
1817 (provide 'stgit)