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