0b24b4d4749d9976149877e2b78c318fe7a09044
[git.git] / contrib / emacs / git.el
1 ;;; git.el --- A user interface for git
2
3 ;; Copyright (C) 2005, 2006 Alexandre Julliard <julliard@winehq.org>
4
5 ;; Version: 1.0
6
7 ;; This program is free software; you can redistribute it and/or
8 ;; modify it under the terms of the GNU General Public License as
9 ;; published by the Free Software Foundation; either version 2 of
10 ;; the License, or (at your option) any later version.
11 ;;
12 ;; This program is distributed in the hope that it will be
13 ;; useful, but WITHOUT ANY WARRANTY; without even the implied
14 ;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 ;; PURPOSE.  See the GNU General Public License for more details.
16 ;;
17 ;; You should have received a copy of the GNU General Public
18 ;; License along with this program; if not, write to the Free
19 ;; Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
20 ;; MA 02111-1307 USA
21
22 ;;; Commentary:
23
24 ;; This file contains an interface for the git version control
25 ;; system. It provides easy access to the most frequently used git
26 ;; commands. The user interface is as far as possible identical to
27 ;; that of the PCL-CVS mode.
28 ;;
29 ;; To install: put this file on the load-path and place the following
30 ;; in your .emacs file:
31 ;;
32 ;;    (require 'git)
33 ;;
34 ;; To start: `M-x git-status'
35 ;;
36 ;; TODO
37 ;;  - portability to XEmacs
38 ;;  - better handling of subprocess errors
39 ;;  - hook into file save (after-save-hook)
40 ;;  - diff against other branch
41 ;;  - renaming files from the status buffer
42 ;;  - creating tags
43 ;;  - fetch/pull
44 ;;  - switching branches
45 ;;  - revlist browser
46 ;;  - git-show-branch browser
47 ;;  - customize support
48 ;;  - menus
49 ;;
50
51 (eval-when-compile (require 'cl))
52 (require 'ewoc)
53
54
55 ;;;; Faces
56 ;;;; ------------------------------------------------------------
57
58 (defface git-status-face
59   '((((class color) (background light)) (:foreground "purple")))
60   "Git mode face used to highlight added and modified files.")
61
62 (defface git-unmerged-face
63   '((((class color) (background light)) (:foreground "red" :bold t)))
64   "Git mode face used to highlight unmerged files.")
65
66 (defface git-unknown-face
67   '((((class color) (background light)) (:foreground "goldenrod" :bold t)))
68   "Git mode face used to highlight unknown files.")
69
70 (defface git-uptodate-face
71   '((((class color) (background light)) (:foreground "grey60")))
72   "Git mode face used to highlight up-to-date files.")
73
74 (defface git-ignored-face
75   '((((class color) (background light)) (:foreground "grey60")))
76   "Git mode face used to highlight ignored files.")
77
78 (defface git-mark-face
79   '((((class color) (background light)) (:foreground "red" :bold t)))
80   "Git mode face used for the file marks.")
81
82 (defface git-header-face
83   '((((class color) (background light)) (:foreground "blue")))
84   "Git mode face used for commit headers.")
85
86 (defface git-separator-face
87   '((((class color) (background light)) (:foreground "brown")))
88   "Git mode face used for commit separator.")
89
90 (defface git-permission-face
91   '((((class color) (background light)) (:foreground "green" :bold t)))
92   "Git mode face used for permission changes.")
93
94 (defvar git-committer-name nil
95   "*User name to use for commits.
96 If not set, fall back to `add-log-full-name' and then `user-full-name'.")
97
98 (defvar git-committer-email nil
99   "*Email address to use for commits.
100 If not set, fall back to `add-log-mailing-address' and then `user-mail-address'.")
101
102 (defvar git-commits-coding-system 'utf-8
103   "Default coding system for git commits.")
104
105 (defvar git-append-signed-off-by nil
106   "Whether to append a Signed-off-by line to the commit message.")
107
108 (defconst git-log-msg-separator "--- log message follows this line ---")
109
110 (defconst git-per-dir-ignore-file ".gitignore"
111   "Name of the per-directory ignore file.")
112
113
114 ;;;; Utilities
115 ;;;; ------------------------------------------------------------
116
117 (defun git-get-env-strings (env)
118   "Build a list of NAME=VALUE strings from a list of environment strings."
119   (mapcar (lambda (entry) (concat (car entry) "=" (cdr entry))) env))
120
121 (defun git-call-process-env (buffer env &rest args)
122   "Wrapper for call-process that sets environment strings."
123   (if env
124       (apply #'call-process "env" nil buffer nil
125              (append (git-get-env-strings env) (list "git") args))
126     (apply #'call-process "git" nil buffer nil args)))
127
128 (defun git-run-process-region (buffer start end program args)
129   "Run a git process with a buffer region as input."
130   (let ((output-buffer (current-buffer))
131         (dir default-directory))
132     (with-current-buffer buffer
133       (cd dir)
134       (apply #'call-process-region start end program
135              nil (list output-buffer nil) nil args))))
136
137 (defun git-run-command-buffer (buffer-name &rest args)
138   "Run a git command, sending the output to a buffer named BUFFER-NAME."
139   (let ((dir default-directory)
140         (buffer (get-buffer-create buffer-name)))
141     (message "Running git %s..." (car args))
142     (with-current-buffer buffer
143       (let ((default-directory dir)
144             (buffer-read-only nil))
145         (erase-buffer)
146         (apply #'git-call-process-env buffer nil args)))
147     (message "Running git %s...done" (car args))
148     buffer))
149
150 (defun git-run-command (buffer env &rest args)
151   (message "Running git %s..." (car args))
152   (apply #'git-call-process-env buffer env args)
153   (message "Running git %s...done" (car args)))
154
155 (defun git-run-command-region (buffer start end env &rest args)
156   "Run a git command with specified buffer region as input."
157   (message "Running git %s..." (car args))
158   (unless (eq 0 (if env
159                     (git-run-process-region
160                      buffer start end "env"
161                      (append (git-get-env-strings env) (list "git") args))
162                   (git-run-process-region
163                    buffer start end "git" args)))
164     (error "Failed to run \"git %s\":\n%s" (mapconcat (lambda (x) x) args " ") (buffer-string)))
165   (message "Running git %s...done" (car args)))
166
167 (defun git-get-string-sha1 (string)
168   "Read a SHA1 from the specified string."
169   (let ((pos (string-match "[0-9a-f]\\{40\\}" string)))
170     (and pos (substring string pos (match-end 0)))))
171
172 (defun git-get-committer-name ()
173   "Return the name to use as GIT_COMMITTER_NAME."
174   ; copied from log-edit
175   (or git-committer-name
176       (and (boundp 'add-log-full-name) add-log-full-name)
177       (and (fboundp 'user-full-name) (user-full-name))
178       (and (boundp 'user-full-name) user-full-name)))
179
180 (defun git-get-committer-email ()
181   "Return the email address to use as GIT_COMMITTER_EMAIL."
182   ; copied from log-edit
183   (or git-committer-email
184       (and (boundp 'add-log-mailing-address) add-log-mailing-address)
185       (and (fboundp 'user-mail-address) (user-mail-address))
186       (and (boundp 'user-mail-address) user-mail-address)))
187
188 (defun git-escape-file-name (name)
189   "Escape a file name if necessary."
190   (if (string-match "[\n\t\"\\]" name)
191       (concat "\""
192               (mapconcat (lambda (c)
193                    (case c
194                      (?\n "\\n")
195                      (?\t "\\t")
196                      (?\\ "\\\\")
197                      (?\" "\\\"")
198                      (t (char-to-string c))))
199                  name "")
200               "\"")
201     name))
202
203 (defun git-get-top-dir (dir)
204   "Retrieve the top-level directory of a git tree."
205   (let ((cdup (with-output-to-string
206                 (with-current-buffer standard-output
207                   (cd dir)
208                   (unless (eq 0 (call-process "git" nil t nil "rev-parse" "--show-cdup"))
209                     (error "cannot find top-level git tree for %s." dir))))))
210     (expand-file-name (concat (file-name-as-directory dir)
211                               (car (split-string cdup "\n"))))))
212
213 ;stolen from pcl-cvs
214 (defun git-append-to-ignore (file)
215   "Add a file name to the ignore file in its directory."
216   (let* ((fullname (expand-file-name file))
217          (dir (file-name-directory fullname))
218          (name (file-name-nondirectory fullname))
219          (ignore-name (expand-file-name git-per-dir-ignore-file dir))
220          (created (not (file-exists-p ignore-name))))
221   (save-window-excursion
222     (set-buffer (find-file-noselect ignore-name))
223     (goto-char (point-max))
224     (unless (zerop (current-column)) (insert "\n"))
225     (insert name "\n")
226     (sort-lines nil (point-min) (point-max))
227     (save-buffer))
228   (when created
229     (git-run-command nil nil "update-index" "--info-only" "--add" "--" (file-relative-name ignore-name)))
230   (git-add-status-file (if created 'added 'modified) (file-relative-name ignore-name))))
231
232
233 ;;;; Wrappers for basic git commands
234 ;;;; ------------------------------------------------------------
235
236 (defun git-rev-parse (rev)
237   "Parse a revision name and return its SHA1."
238   (git-get-string-sha1
239    (with-output-to-string
240      (with-current-buffer standard-output
241        (git-call-process-env t nil "rev-parse" rev)))))
242
243 (defun git-symbolic-ref (ref)
244   "Wrapper for the git-symbolic-ref command."
245   (car
246    (split-string
247     (with-output-to-string
248       (with-current-buffer standard-output
249         (git-call-process-env t nil "symbolic-ref" ref)))
250     "\n")))
251
252 (defun git-update-ref (ref val &optional oldval)
253   "Update a reference by calling git-update-ref."
254   (apply #'git-call-process-env nil nil "update-ref" ref val (if oldval (list oldval))))
255
256 (defun git-read-tree (tree &optional index-file)
257   "Read a tree into the index file."
258   (apply #'git-call-process-env nil
259          (if index-file `(("GIT_INDEX_FILE" . ,index-file)) nil)
260          "read-tree" (if tree (list tree))))
261
262 (defun git-write-tree (&optional index-file)
263   "Call git-write-tree and return the resulting tree SHA1 as a string."
264   (git-get-string-sha1
265    (with-output-to-string
266      (with-current-buffer standard-output
267        (git-call-process-env t
268         (if index-file `(("GIT_INDEX_FILE" . ,index-file)) nil)
269         "write-tree")))))
270
271 (defun git-commit-tree (buffer tree head)
272   "Call git-commit-tree with buffer as input and return the resulting commit SHA1."
273   (let ((author-name (git-get-committer-name))
274         (author-email (git-get-committer-email))
275         author-date log-start log-end args)
276     (when head
277       (push "-p" args)
278       (push head args))
279     (with-current-buffer buffer
280       (goto-char (point-min))
281       (if
282           (setq log-start (re-search-forward (concat "^" git-log-msg-separator "\n") nil t))
283           (save-restriction
284             (narrow-to-region (point-min) log-start)
285             (goto-char (point-min))
286             (when (re-search-forward "^Author: +\\(.*?\\) *<\\(.*\\)> *$" nil t)
287               (setq author-name (match-string 1)
288                     author-email (match-string 2)))
289             (goto-char (point-min))
290             (when (re-search-forward "^Date: +\\(.*\\)$" nil t)
291               (setq author-date (match-string 1)))
292             (goto-char (point-min))
293             (while (re-search-forward "^Parent: +\\([0-9a-f]+\\)" nil t)
294               (unless (string-equal head (match-string 1))
295                 (push "-p" args)
296                 (push (match-string 1) args))))
297         (setq log-start (point-min)))
298       (setq log-end (point-max)))
299     (git-get-string-sha1
300      (with-output-to-string
301        (with-current-buffer standard-output
302          (let ((coding-system-for-write git-commits-coding-system)
303                (env `(("GIT_AUTHOR_NAME" . ,author-name)
304                       ("GIT_AUTHOR_EMAIL" . ,author-email)
305                       ("GIT_COMMITTER_NAME" . ,(git-get-committer-name))
306                       ("GIT_COMMITTER_EMAIL" . ,(git-get-committer-email)))))
307            (when author-date (push `("GIT_AUTHOR_DATE" . ,author-date) env))
308            (apply #'git-run-command-region
309                   buffer log-start log-end env
310                   "commit-tree" tree (nreverse args))))))))
311
312 (defun git-empty-db-p ()
313   "Check if the git db is empty (no commit done yet)."
314   (not (eq 0 (call-process "git" nil nil nil "rev-parse" "--verify" "HEAD"))))
315
316 (defun git-get-merge-heads ()
317   "Retrieve the merge heads from the MERGE_HEAD file if present."
318   (let (heads)
319     (when (file-readable-p ".git/MERGE_HEAD")
320       (with-temp-buffer
321         (insert-file-contents ".git/MERGE_HEAD" nil nil nil t)
322         (goto-char (point-min))
323         (while (re-search-forward "[0-9a-f]\\{40\\}" nil t)
324           (push (match-string 0) heads))))
325     (nreverse heads)))
326
327 ;;;; File info structure
328 ;;;; ------------------------------------------------------------
329
330 ; fileinfo structure stolen from pcl-cvs
331 (defstruct (git-fileinfo
332             (:copier nil)
333             (:constructor git-create-fileinfo (state name &optional old-perm new-perm rename-state orig-name marked))
334             (:conc-name git-fileinfo->))
335   marked              ;; t/nil
336   state               ;; current state
337   name                ;; file name
338   old-perm new-perm   ;; permission flags
339   rename-state        ;; rename or copy state
340   orig-name           ;; original name for renames or copies
341   needs-refresh)      ;; whether file needs to be refreshed
342
343 (defvar git-status nil)
344
345 (defun git-clear-status (status)
346   "Remove everything from the status list."
347   (ewoc-filter status (lambda (info) nil)))
348
349 (defun git-set-files-state (files state)
350   "Set the state of a list of files."
351   (dolist (info files)
352     (unless (eq (git-fileinfo->state info) state)
353       (setf (git-fileinfo->state info) state)
354       (setf (git-fileinfo->rename-state info) nil)
355       (setf (git-fileinfo->orig-name info) nil)
356       (setf (git-fileinfo->needs-refresh info) t))))
357
358 (defun git-state-code (code)
359   "Convert from a string to a added/deleted/modified state."
360   (case (string-to-char code)
361     (?M 'modified)
362     (?? 'unknown)
363     (?A 'added)
364     (?D 'deleted)
365     (?U 'unmerged)
366     (t nil)))
367
368 (defun git-status-code-as-string (code)
369   "Format a git status code as string."
370   (case code
371     ('modified (propertize "Modified" 'face 'git-status-face))
372     ('unknown  (propertize "Unknown " 'face 'git-unknown-face))
373     ('added    (propertize "Added   " 'face 'git-status-face))
374     ('deleted  (propertize "Deleted " 'face 'git-status-face))
375     ('unmerged (propertize "Unmerged" 'face 'git-unmerged-face))
376     ('uptodate (propertize "Uptodate" 'face 'git-uptodate-face))
377     ('ignored  (propertize "Ignored " 'face 'git-ignored-face))
378     (t "?       ")))
379
380 (defun git-rename-as-string (info)
381   "Return a string describing the copy or rename associated with INFO, or an empty string if none."
382   (let ((state (git-fileinfo->rename-state info)))
383     (if state
384         (propertize
385          (concat "   ("
386                  (if (eq state 'copy) "copied from "
387                    (if (eq (git-fileinfo->state info) 'added) "renamed to "
388                      "renamed from "))
389                  (git-escape-file-name (git-fileinfo->orig-name info))
390                  ")") 'face 'git-status-face)
391       "")))
392
393 (defun git-permissions-as-string (old-perm new-perm)
394   "Format a permission change as string."
395   (propertize
396    (if (or (not old-perm)
397            (not new-perm)
398            (eq 0 (logand ?\111 (logxor old-perm new-perm))))
399        "  "
400      (if (eq 0 (logand ?\111 old-perm)) "+x" "-x"))
401   'face 'git-permission-face))
402
403 (defun git-fileinfo-prettyprint (info)
404   "Pretty-printer for the git-fileinfo structure."
405   (insert (format "   %s %s %s  %s%s"
406                   (if (git-fileinfo->marked info) (propertize "*" 'face 'git-mark-face) " ")
407                   (git-status-code-as-string (git-fileinfo->state info))
408                   (git-permissions-as-string (git-fileinfo->old-perm info) (git-fileinfo->new-perm info))
409                   (git-escape-file-name (git-fileinfo->name info))
410                   (git-rename-as-string info))))
411
412 (defun git-parse-status (status)
413   "Parse the output of git-diff-index in the current buffer."
414   (goto-char (point-min))
415   (while (re-search-forward
416           ":\\([0-7]\\{6\\}\\) \\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\(\\([ADMU]\\)\0\\([^\0]+\\)\\|\\([CR]\\)[0-9]*\0\\([^\0]+\\)\0\\([^\0]+\\)\\)\0"
417           nil t 1)
418     (let ((old-perm (string-to-number (match-string 1) 8))
419           (new-perm (string-to-number (match-string 2) 8))
420           (state (or (match-string 4) (match-string 6)))
421           (name (or (match-string 5) (match-string 7)))
422           (new-name (match-string 8)))
423       (if new-name  ; copy or rename
424           (if (eq ?C (string-to-char state))
425               (ewoc-enter-last status (git-create-fileinfo 'added new-name old-perm new-perm 'copy name))
426             (ewoc-enter-last status (git-create-fileinfo 'deleted name 0 0 'rename new-name))
427             (ewoc-enter-last status (git-create-fileinfo 'added new-name old-perm new-perm 'rename name)))
428         (ewoc-enter-last status (git-create-fileinfo (git-state-code state) name old-perm new-perm))))))
429
430 (defun git-find-status-file (status file)
431   "Find a given file in the status ewoc and return its node."
432   (let ((node (ewoc-nth status 0)))
433     (while (and node (not (string= file (git-fileinfo->name (ewoc-data node)))))
434       (setq node (ewoc-next status node)))
435     node))
436
437 (defun git-parse-ls-files (status default-state &optional skip-existing)
438   "Parse the output of git-ls-files in the current buffer."
439   (goto-char (point-min))
440   (let (infolist)
441     (while (re-search-forward "\\([HMRCK?]\\) \\([^\0]*\\)\0" nil t 1)
442       (let ((state (match-string 1))
443             (name (match-string 2)))
444         (unless (and skip-existing (git-find-status-file status name))
445           (push (git-create-fileinfo (or (git-state-code state) default-state) name) infolist))))
446     (dolist (info (nreverse infolist))
447       (ewoc-enter-last status info))))
448
449 (defun git-parse-ls-unmerged (status)
450   "Parse the output of git-ls-files -u in the current buffer."
451   (goto-char (point-min))
452   (let (files)
453     (while (re-search-forward "[0-7]\\{6\\} [0-9a-f]\\{40\\} [123]\t\\([^\0]+\\)\0" nil t)
454       (let ((node (git-find-status-file status (match-string 1))))
455         (when node (push (ewoc-data node) files))))
456     (git-set-files-state files 'unmerged)))
457
458 (defun git-add-status-file (state name)
459   "Add a new file to the status list (if not existing already) and return its node."
460   (unless git-status (error "Not in git-status buffer."))
461   (or (git-find-status-file git-status name)
462       (ewoc-enter-last git-status (git-create-fileinfo state name))))
463
464 (defun git-marked-files ()
465   "Return a list of all marked files, or if none a list containing just the file at cursor position."
466   (unless git-status (error "Not in git-status buffer."))
467   (or (ewoc-collect git-status (lambda (info) (git-fileinfo->marked info)))
468       (list (ewoc-data (ewoc-locate git-status)))))
469
470 (defun git-marked-files-state (&rest states)
471   "Return marked files that are in the specified states."
472   (let ((files (git-marked-files))
473         result)
474     (dolist (info files)
475       (when (memq (git-fileinfo->state info) states)
476         (push info result)))
477     result))
478
479 (defun git-refresh-files ()
480   "Refresh all files that need it and clear the needs-refresh flag."
481   (unless git-status (error "Not in git-status buffer."))
482   (ewoc-map
483    (lambda (info)
484      (let ((refresh (git-fileinfo->needs-refresh info)))
485        (setf (git-fileinfo->needs-refresh info) nil)
486        refresh))
487    git-status)
488   ; move back to goal column
489   (when goal-column (move-to-column goal-column)))
490
491 (defun git-refresh-ewoc-hf (status)
492   "Refresh the ewoc header and footer."
493   (let ((branch (git-symbolic-ref "HEAD"))
494         (head (if (git-empty-db-p) "Nothing committed yet"
495                 (substring (git-rev-parse "HEAD") 0 10)))
496         (merge-heads (git-get-merge-heads)))
497     (ewoc-set-hf status
498                  (format "Directory:  %s\nBranch:     %s\nHead:       %s%s\n"
499                          default-directory
500                          (if (string-match "^refs/heads/" branch)
501                              (substring branch (match-end 0))
502                            branch)
503                          head
504                          (if merge-heads
505                              (concat "\nMerging:    "
506                                      (mapconcat (lambda (str) (substring str 0 10)) merge-heads " "))
507                            ""))
508                  (if (ewoc-nth status 0) "" "    No changes."))))
509
510 (defun git-get-filenames (files)
511   (mapcar (lambda (info) (git-fileinfo->name info)) files))
512
513 (defun git-update-index (index-file files)
514   "Run git-update-index on a list of files."
515   (let ((env (and index-file `(("GIT_INDEX_FILE" . ,index-file))))
516         added deleted modified)
517     (dolist (info files)
518       (case (git-fileinfo->state info)
519         ('added (push info added))
520         ('deleted (push info deleted))
521         ('modified (push info modified))))
522     (when added
523       (apply #'git-run-command nil env "update-index" "--add" "--" (git-get-filenames added)))
524     (when deleted
525       (apply #'git-run-command nil env "update-index" "--remove" "--" (git-get-filenames deleted)))
526     (when modified
527       (apply #'git-run-command nil env "update-index" "--" (git-get-filenames modified)))))
528
529 (defun git-do-commit ()
530   "Perform the actual commit using the current buffer as log message."
531   (interactive)
532   (let ((buffer (current-buffer))
533         (index-file (make-temp-file "gitidx")))
534     (with-current-buffer log-edit-parent-buffer
535       (if (git-marked-files-state 'unmerged)
536           (message "You cannot commit unmerged files, resolve them first.")
537         (unwind-protect
538             (let ((files (git-marked-files-state 'added 'deleted 'modified))
539                   head head-tree)
540               (unless (git-empty-db-p)
541                 (setq head (git-rev-parse "HEAD")
542                       head-tree (git-rev-parse "HEAD^{tree}")))
543               (if files
544                   (progn
545                     (git-read-tree head-tree index-file)
546                     (git-update-index nil files)         ;update both the default index
547                     (git-update-index index-file files)  ;and the temporary one
548                     (let ((tree (git-write-tree index-file)))
549                       (if (or (not (string-equal tree head-tree))
550                               (yes-or-no-p "The tree was not modified, do you really want to perform an empty commit? "))
551                           (let ((commit (git-commit-tree buffer tree head)))
552                             (git-update-ref "HEAD" commit head)
553                             (condition-case nil (delete-file ".git/MERGE_HEAD") (error nil))
554                             (with-current-buffer buffer (erase-buffer))
555                             (git-set-files-state files 'uptodate)
556                             (git-refresh-files)
557                             (git-refresh-ewoc-hf git-status)
558                             (message "Committed %s." commit))
559                         (message "Commit aborted."))))
560                 (message "No files to commit.")))
561           (delete-file index-file))))))
562
563
564 ;;;; Interactive functions
565 ;;;; ------------------------------------------------------------
566
567 (defun git-mark-file ()
568   "Mark the file that the cursor is on and move to the next one."
569   (interactive)
570   (unless git-status (error "Not in git-status buffer."))
571   (let* ((pos (ewoc-locate git-status))
572          (info (ewoc-data pos)))
573     (setf (git-fileinfo->marked info) t)
574     (ewoc-invalidate git-status pos)
575     (ewoc-goto-next git-status 1)))
576
577 (defun git-unmark-file ()
578   "Unmark the file that the cursor is on and move to the next one."
579   (interactive)
580   (unless git-status (error "Not in git-status buffer."))
581   (let* ((pos (ewoc-locate git-status))
582          (info (ewoc-data pos)))
583     (setf (git-fileinfo->marked info) nil)
584     (ewoc-invalidate git-status pos)
585     (ewoc-goto-next git-status 1)))
586
587 (defun git-unmark-file-up ()
588   "Unmark the file that the cursor is on and move to the previous one."
589   (interactive)
590   (unless git-status (error "Not in git-status buffer."))
591   (let* ((pos (ewoc-locate git-status))
592          (info (ewoc-data pos)))
593     (setf (git-fileinfo->marked info) nil)
594     (ewoc-invalidate git-status pos)
595     (ewoc-goto-prev git-status 1)))
596
597 (defun git-mark-all ()
598   "Mark all files."
599   (interactive)
600   (unless git-status (error "Not in git-status buffer."))
601   (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) t) t) git-status)
602   ; move back to goal column after invalidate
603   (when goal-column (move-to-column goal-column)))
604
605 (defun git-unmark-all ()
606   "Unmark all files."
607   (interactive)
608   (unless git-status (error "Not in git-status buffer."))
609   (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) nil) t) git-status)
610   ; move back to goal column after invalidate
611   (when goal-column (move-to-column goal-column)))
612
613 (defun git-toggle-all-marks ()
614   "Toggle all file marks."
615   (interactive)
616   (unless git-status (error "Not in git-status buffer."))
617   (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) (not (git-fileinfo->marked info))) t) git-status)
618   ; move back to goal column after invalidate
619   (when goal-column (move-to-column goal-column)))
620
621 (defun git-next-file (&optional n)
622   "Move the selection down N files."
623   (interactive "p")
624   (unless git-status (error "Not in git-status buffer."))
625   (ewoc-goto-next git-status n))
626
627 (defun git-prev-file (&optional n)
628   "Move the selection up N files."
629   (interactive "p")
630   (unless git-status (error "Not in git-status buffer."))
631   (ewoc-goto-prev git-status n))
632
633 (defun git-add-file ()
634   "Add marked file(s) to the index cache."
635   (interactive)
636   (let ((files (git-marked-files-state 'unknown)))
637     (unless files
638       (push (ewoc-data
639              (git-add-status-file 'added (file-relative-name
640                                           (read-file-name "File to add: " nil nil t))))
641             files))
642     (apply #'git-run-command nil nil "update-index" "--info-only" "--add" "--" (git-get-filenames files))
643     (git-set-files-state files 'added)
644     (git-refresh-files)))
645
646 (defun git-ignore-file ()
647   "Add marked file(s) to the ignore list."
648   (interactive)
649   (let ((files (git-marked-files-state 'unknown)))
650     (unless files
651       (push (ewoc-data
652              (git-add-status-file 'unknown (file-relative-name
653                                             (read-file-name "File to ignore: " nil nil t))))
654             files))
655     (dolist (info files) (git-append-to-ignore (git-fileinfo->name info)))
656     (git-set-files-state files 'ignored)
657     (git-refresh-files)))
658
659 (defun git-remove-file ()
660   "Remove the marked file(s)."
661   (interactive)
662   (let ((files (git-marked-files-state 'added 'modified 'unknown 'uptodate)))
663     (unless files
664       (push (ewoc-data
665              (git-add-status-file 'unknown (file-relative-name
666                                             (read-file-name "File to remove: " nil nil t))))
667             files))
668     (if (yes-or-no-p
669          (format "Remove %d file%s? " (length files) (if (> (length files) 1) "s" "")))
670         (progn
671           (dolist (info files)
672             (let ((name (git-fileinfo->name info)))
673               (when (file-exists-p name) (delete-file name))))
674           (apply #'git-run-command nil nil "update-index" "--info-only" "--remove" "--" (git-get-filenames files))
675           ; remove unknown files from the list, set the others to deleted
676           (ewoc-filter git-status
677                        (lambda (info files)
678                          (not (and (memq info files) (eq (git-fileinfo->state info) 'unknown))))
679                        files)
680           (git-set-files-state files 'deleted)
681           (git-refresh-files)
682           (unless (ewoc-nth git-status 0)  ; refresh header if list is empty
683             (git-refresh-ewoc-hf git-status)))
684       (message "Aborting"))))
685
686 (defun git-revert-file ()
687   "Revert changes to the marked file(s)."
688   (interactive)
689   (let ((files (git-marked-files))
690         added modified)
691     (when (and files
692                (yes-or-no-p
693                 (format "Revert %d file%s? " (length files) (if (> (length files) 1) "s" ""))))
694       (dolist (info files)
695         (case (git-fileinfo->state info)
696           ('added (push info added))
697           ('deleted (push info modified))
698           ('unmerged (push info modified))
699           ('modified (push info modified))))
700       (when added
701           (apply #'git-run-command nil nil "update-index" "--force-remove" "--" (git-get-filenames added))
702           (git-set-files-state added 'unknown))
703       (when modified
704           (apply #'git-run-command nil nil "checkout" "HEAD" (git-get-filenames modified))
705           (git-set-files-state modified 'uptodate))
706       (git-refresh-files))))
707
708 (defun git-resolve-file ()
709   "Resolve conflicts in marked file(s)."
710   (interactive)
711   (let ((files (git-marked-files-state 'unmerged)))
712     (when files
713       (apply #'git-run-command nil nil "update-index" "--info-only" "--" (git-get-filenames files))
714       (git-set-files-state files 'modified)
715       (git-refresh-files))))
716
717 (defun git-remove-handled ()
718   "Remove handled files from the status list."
719   (interactive)
720   (ewoc-filter git-status
721                (lambda (info)
722                  (not (or (eq (git-fileinfo->state info) 'ignored)
723                           (eq (git-fileinfo->state info) 'uptodate)))))
724   (unless (ewoc-nth git-status 0)  ; refresh header if list is empty
725     (git-refresh-ewoc-hf git-status)))
726
727 (defun git-setup-diff-buffer (buffer)
728   "Setup a buffer for displaying a diff."
729   (with-current-buffer buffer
730     (diff-mode)
731     (goto-char (point-min))
732     (setq buffer-read-only t))
733   (display-buffer buffer)
734   (shrink-window-if-larger-than-buffer))
735
736 (defun git-diff-file ()
737   "Diff the marked file(s) against HEAD."
738   (interactive)
739   (let ((files (git-marked-files)))
740     (git-setup-diff-buffer
741      (apply #'git-run-command-buffer "*git-diff*" "diff-index" "-p" "-M" "HEAD" "--" (git-get-filenames files)))))
742
743 (defun git-diff-unmerged-file (stage)
744   "Diff the marked unmerged file(s) against the specified stage."
745   (let ((files (git-marked-files)))
746     (git-setup-diff-buffer
747      (apply #'git-run-command-buffer "*git-diff*" "diff-files" "-p" stage "--" (git-get-filenames files)))))
748
749 (defun git-diff-file-base ()
750   "Diff the marked unmerged file(s) against the common base file."
751   (interactive)
752   (git-diff-unmerged-file "-1"))
753
754 (defun git-diff-file-mine ()
755   "Diff the marked unmerged file(s) against my pre-merge version."
756   (interactive)
757   (git-diff-unmerged-file "-2"))
758
759 (defun git-diff-file-other ()
760   "Diff the marked unmerged file(s) against the other's pre-merge version."
761   (interactive)
762   (git-diff-unmerged-file "-3"))
763
764 (defun git-diff-file-combined ()
765   "Do a combined diff of the marked unmerged file(s)."
766   (interactive)
767   (git-diff-unmerged-file "-c"))
768
769 (defun git-diff-file-idiff ()
770   "Perform an interactive diff on the current file."
771   (interactive)
772   (error "Interactive diffs not implemented yet."))
773
774 (defun git-log-file ()
775   "Display a log of changes to the marked file(s)."
776   (interactive)
777   (let* ((files (git-marked-files))
778          (coding-system-for-read git-commits-coding-system)
779          (buffer (apply #'git-run-command-buffer "*git-log*" "rev-list" "--pretty" "HEAD" "--" (git-get-filenames files))))
780     (with-current-buffer buffer
781       ; (git-log-mode)  FIXME: implement log mode
782       (goto-char (point-min))
783       (setq buffer-read-only t))
784     (display-buffer buffer)))
785
786 (defun git-log-edit-files ()
787   "Return a list of marked files for use in the log-edit buffer."
788   (with-current-buffer log-edit-parent-buffer
789     (git-get-filenames (git-marked-files-state 'added 'deleted 'modified))))
790
791 (defun git-commit-file ()
792   "Commit the marked file(s), asking for a commit message."
793   (interactive)
794   (unless git-status (error "Not in git-status buffer."))
795   (let ((buffer (get-buffer-create "*git-commit*"))
796         (merge-heads (git-get-merge-heads))
797         (dir default-directory)
798         (sign-off git-append-signed-off-by))
799     (with-current-buffer buffer
800       (when (eq 0 (buffer-size))
801         (cd dir)
802         (erase-buffer)
803         (insert
804          (propertize
805           (format "Author: %s <%s>\n%s"
806                   (git-get-committer-name) (git-get-committer-email)
807                   (if merge-heads
808                       (format "Parent: %s\n%s\n"
809                               (git-rev-parse "HEAD")
810                               (mapconcat (lambda (str) (concat "Parent: " str)) merge-heads "\n"))
811                     ""))
812           'face 'git-header-face)
813          (propertize git-log-msg-separator 'face 'git-separator-face)
814          "\n")
815         (cond ((and merge-heads (file-readable-p ".git/MERGE_MSG"))
816                (insert-file-contents ".git/MERGE_MSG"))
817               (sign-off
818                (insert (format "\n\nSigned-off-by: %s <%s>\n"
819                                (git-get-committer-name) (git-get-committer-email)))))))
820     (let ((log-edit-font-lock-keywords
821            `(("^\\(Author:\\|Date:\\|Parent:\\|Signed-off-by:\\)\\(.*\\)"
822               (1 font-lock-keyword-face)
823               (2 font-lock-function-name-face))
824              (,(concat "^\\(" (regexp-quote git-log-msg-separator) "\\)$")
825               (1 font-lock-comment-face)))))
826       (log-edit #'git-do-commit nil #'git-log-edit-files buffer))))
827
828 (defun git-find-file ()
829   "Visit the current file in its own buffer."
830   (interactive)
831   (unless git-status (error "Not in git-status buffer."))
832   (let ((info (ewoc-data (ewoc-locate git-status))))
833     (find-file (git-fileinfo->name info))
834     (when (eq 'unmerged (git-fileinfo->state info))
835       (smerge-mode))))
836
837 (defun git-find-file-imerge ()
838   "Visit the current file in interactive merge mode."
839   (interactive)
840   (unless git-status (error "Not in git-status buffer."))
841   (let ((info (ewoc-data (ewoc-locate git-status))))
842     (find-file (git-fileinfo->name info))
843     (smerge-ediff)))
844
845 (defun git-view-file ()
846   "View the current file in its own buffer."
847   (interactive)
848   (unless git-status (error "Not in git-status buffer."))
849   (let ((info (ewoc-data (ewoc-locate git-status))))
850     (view-file (git-fileinfo->name info))))
851
852 (defun git-refresh-status ()
853   "Refresh the git status buffer."
854   (interactive)
855   (let* ((status git-status)
856          (pos (ewoc-locate status))
857          (cur-name (and pos (git-fileinfo->name (ewoc-data pos)))))
858     (unless status (error "Not in git-status buffer."))
859     (git-clear-status status)
860     (git-run-command nil nil "update-index" "--info-only" "--refresh")
861     (if (git-empty-db-p)
862         ; we need some special handling for an empty db
863         (with-temp-buffer
864           (git-run-command t nil "ls-files" "-z" "-t" "-c")
865           (git-parse-ls-files status 'added))
866       (with-temp-buffer
867         (git-run-command t nil "diff-index" "-z" "-M" "HEAD")
868         (git-parse-status status)))
869       (with-temp-buffer
870         (git-run-command t nil "ls-files" "-z" "-u")
871         (git-parse-ls-unmerged status))
872       (when (file-readable-p ".git/info/exclude")
873         (with-temp-buffer
874           (git-run-command t nil "ls-files" "-z" "-t" "-o"
875                            "--exclude-from=.git/info/exclude"
876                            (concat "--exclude-per-directory=" git-per-dir-ignore-file))
877           (git-parse-ls-files status 'unknown)))
878     (git-refresh-files)
879     (git-refresh-ewoc-hf status)
880     ; move point to the current file name if any
881     (let ((node (and cur-name (git-find-status-file status cur-name))))
882       (when node (ewoc-goto-node status node)))))
883
884 (defun git-status-quit ()
885   "Quit git-status mode."
886   (interactive)
887   (bury-buffer))
888
889 ;;;; Major Mode
890 ;;;; ------------------------------------------------------------
891
892 (defvar git-status-mode-hook nil
893   "Run after `git-status-mode' is setup.")
894
895 (defvar git-status-mode-map nil
896   "Keymap for git major mode.")
897
898 (defvar git-status nil
899   "List of all files managed by the git-status mode.")
900
901 (unless git-status-mode-map
902   (let ((map (make-keymap))
903         (diff-map (make-sparse-keymap)))
904     (suppress-keymap map)
905     (define-key map " "   'git-next-file)
906     (define-key map "a"   'git-add-file)
907     (define-key map "c"   'git-commit-file)
908     (define-key map "d"    diff-map)
909     (define-key map "="   'git-diff-file)
910     (define-key map "f"   'git-find-file)
911     (define-key map "\r"  'git-find-file)
912     (define-key map "g"   'git-refresh-status)
913     (define-key map "i"   'git-ignore-file)
914     (define-key map "l"   'git-log-file)
915     (define-key map "m"   'git-mark-file)
916     (define-key map "M"   'git-mark-all)
917     (define-key map "n"   'git-next-file)
918     (define-key map "p"   'git-prev-file)
919     (define-key map "q"   'git-status-quit)
920     (define-key map "r"   'git-remove-file)
921     (define-key map "R"   'git-resolve-file)
922     (define-key map "T"   'git-toggle-all-marks)
923     (define-key map "u"   'git-unmark-file)
924     (define-key map "U"   'git-revert-file)
925     (define-key map "v"   'git-view-file)
926     (define-key map "x"   'git-remove-handled)
927     (define-key map "\C-?" 'git-unmark-file-up)
928     (define-key map "\M-\C-?" 'git-unmark-all)
929     ; the diff submap
930     (define-key diff-map "b" 'git-diff-file-base)
931     (define-key diff-map "c" 'git-diff-file-combined)
932     (define-key diff-map "=" 'git-diff-file)
933     (define-key diff-map "e" 'git-diff-file-idiff)
934     (define-key diff-map "E" 'git-find-file-imerge)
935     (define-key diff-map "m" 'git-diff-file-mine)
936     (define-key diff-map "o" 'git-diff-file-other)
937     (setq git-status-mode-map map)))
938
939 ;; git mode should only run in the *git status* buffer
940 (put 'git-status-mode 'mode-class 'special)
941
942 (defun git-status-mode ()
943   "Major mode for interacting with Git.
944 Commands:
945 \\{git-status-mode-map}"
946   (kill-all-local-variables)
947   (buffer-disable-undo)
948   (setq mode-name "git status"
949         major-mode 'git-status-mode
950         goal-column 17
951         buffer-read-only t)
952   (use-local-map git-status-mode-map)
953   (let ((buffer-read-only nil))
954     (erase-buffer)
955   (let ((status (ewoc-create 'git-fileinfo-prettyprint "" "")))
956     (set (make-local-variable 'git-status) status))
957   (set (make-local-variable 'list-buffers-directory) default-directory)
958   (run-hooks 'git-status-mode-hook)))
959
960 (defun git-status (dir)
961   "Entry point into git-status mode."
962   (interactive "DSelect directory: ")
963   (setq dir (git-get-top-dir dir))
964   (if (file-directory-p (concat (file-name-as-directory dir) ".git"))
965       (let ((buffer (create-file-buffer (expand-file-name "*git-status*" dir))))
966         (switch-to-buffer buffer)
967         (cd dir)
968         (git-status-mode)
969         (git-refresh-status)
970         (goto-char (point-min)))
971     (message "%s is not a git working tree." dir)))
972
973 (provide 'git)
974 ;;; git.el ends here