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