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