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