git.el: Preserve file marks when doing a full refresh.
[git] / contrib / emacs / git.el
1 ;;; git.el --- A user interface for git
2
3 ;; Copyright (C) 2005, 2006, 2007 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 ;;  - menus
48 ;;
49
50 (eval-when-compile (require 'cl))
51 (require 'ewoc)
52 (require 'log-edit)
53
54
55 ;;;; Customizations
56 ;;;; ------------------------------------------------------------
57
58 (defgroup git nil
59   "A user interface for the git versioning system."
60   :group 'tools)
61
62 (defcustom git-committer-name nil
63   "User name to use for commits.
64 The default is to fall back to the repository config,
65 then to `add-log-full-name' and then to `user-full-name'."
66   :group 'git
67   :type '(choice (const :tag "Default" nil)
68                  (string :tag "Name")))
69
70 (defcustom git-committer-email nil
71   "Email address to use for commits.
72 The default is to fall back to the git repository config,
73 then to `add-log-mailing-address' and then to `user-mail-address'."
74   :group 'git
75   :type '(choice (const :tag "Default" nil)
76                  (string :tag "Email")))
77
78 (defcustom git-commits-coding-system nil
79   "Default coding system for the log message of git commits."
80   :group 'git
81   :type '(choice (const :tag "From repository config" nil)
82                  (coding-system)))
83
84 (defcustom git-append-signed-off-by nil
85   "Whether to append a Signed-off-by line to the commit message before editing."
86   :group 'git
87   :type 'boolean)
88
89 (defcustom git-reuse-status-buffer t
90   "Whether `git-status' should try to reuse an existing buffer
91 if there is already one that displays the same directory."
92   :group 'git
93   :type 'boolean)
94
95 (defcustom git-per-dir-ignore-file ".gitignore"
96   "Name of the per-directory ignore file."
97   :group 'git
98   :type 'string)
99
100 (defcustom git-show-uptodate nil
101   "Whether to display up-to-date files."
102   :group 'git
103   :type 'boolean)
104
105 (defcustom git-show-ignored nil
106   "Whether to display ignored files."
107   :group 'git
108   :type 'boolean)
109
110 (defcustom git-show-unknown t
111   "Whether to display unknown files."
112   :group 'git
113   :type 'boolean)
114
115
116 (defface git-status-face
117   '((((class color) (background light)) (:foreground "purple"))
118     (((class color) (background dark)) (:foreground "salmon")))
119   "Git mode face used to highlight added and modified files."
120   :group 'git)
121
122 (defface git-unmerged-face
123   '((((class color) (background light)) (:foreground "red" :bold t))
124     (((class color) (background dark)) (:foreground "red" :bold t)))
125   "Git mode face used to highlight unmerged files."
126   :group 'git)
127
128 (defface git-unknown-face
129   '((((class color) (background light)) (:foreground "goldenrod" :bold t))
130     (((class color) (background dark)) (:foreground "goldenrod" :bold t)))
131   "Git mode face used to highlight unknown files."
132   :group 'git)
133
134 (defface git-uptodate-face
135   '((((class color) (background light)) (:foreground "grey60"))
136     (((class color) (background dark)) (:foreground "grey40")))
137   "Git mode face used to highlight up-to-date files."
138   :group 'git)
139
140 (defface git-ignored-face
141   '((((class color) (background light)) (:foreground "grey60"))
142     (((class color) (background dark)) (:foreground "grey40")))
143   "Git mode face used to highlight ignored files."
144   :group 'git)
145
146 (defface git-mark-face
147   '((((class color) (background light)) (:foreground "red" :bold t))
148     (((class color) (background dark)) (:foreground "tomato" :bold t)))
149   "Git mode face used for the file marks."
150   :group 'git)
151
152 (defface git-header-face
153   '((((class color) (background light)) (:foreground "blue"))
154     (((class color) (background dark)) (:foreground "blue")))
155   "Git mode face used for commit headers."
156   :group 'git)
157
158 (defface git-separator-face
159   '((((class color) (background light)) (:foreground "brown"))
160     (((class color) (background dark)) (:foreground "brown")))
161   "Git mode face used for commit separator."
162   :group 'git)
163
164 (defface git-permission-face
165   '((((class color) (background light)) (:foreground "green" :bold t))
166     (((class color) (background dark)) (:foreground "green" :bold t)))
167   "Git mode face used for permission changes."
168   :group 'git)
169
170
171 ;;;; Utilities
172 ;;;; ------------------------------------------------------------
173
174 (defconst git-log-msg-separator "--- log message follows this line ---")
175
176 (defvar git-log-edit-font-lock-keywords
177   `(("^\\(Author:\\|Date:\\|Parent:\\|Signed-off-by:\\)\\(.*\\)$"
178      (1 font-lock-keyword-face)
179      (2 font-lock-function-name-face))
180     (,(concat "^\\(" (regexp-quote git-log-msg-separator) "\\)$")
181      (1 font-lock-comment-face))))
182
183 (defun git-get-env-strings (env)
184   "Build a list of NAME=VALUE strings from a list of environment strings."
185   (mapcar (lambda (entry) (concat (car entry) "=" (cdr entry))) env))
186
187 (defun git-call-process-env (buffer env &rest args)
188   "Wrapper for call-process that sets environment strings."
189   (if env
190       (apply #'call-process "env" nil buffer nil
191              (append (git-get-env-strings env) (list "git") args))
192     (apply #'call-process "git" nil buffer nil args)))
193
194 (defun git-call-process-env-string (env &rest args)
195   "Wrapper for call-process that sets environment strings,
196 and returns the process output as a string."
197   (with-temp-buffer
198     (and (eq 0 (apply #' git-call-process-env t env args))
199          (buffer-string))))
200
201 (defun git-run-process-region (buffer start end program args)
202   "Run a git process with a buffer region as input."
203   (let ((output-buffer (current-buffer))
204         (dir default-directory))
205     (with-current-buffer buffer
206       (cd dir)
207       (apply #'call-process-region start end program
208              nil (list output-buffer nil) nil args))))
209
210 (defun git-run-command-buffer (buffer-name &rest args)
211   "Run a git command, sending the output to a buffer named BUFFER-NAME."
212   (let ((dir default-directory)
213         (buffer (get-buffer-create buffer-name)))
214     (message "Running git %s..." (car args))
215     (with-current-buffer buffer
216       (let ((default-directory dir)
217             (buffer-read-only nil))
218         (erase-buffer)
219         (apply #'git-call-process-env buffer nil args)))
220     (message "Running git %s...done" (car args))
221     buffer))
222
223 (defun git-run-command (buffer env &rest args)
224   (message "Running git %s..." (car args))
225   (apply #'git-call-process-env buffer env args)
226   (message "Running git %s...done" (car args)))
227
228 (defun git-run-command-region (buffer start end env &rest args)
229   "Run a git command with specified buffer region as input."
230   (message "Running git %s..." (car args))
231   (unless (eq 0 (if env
232                     (git-run-process-region
233                      buffer start end "env"
234                      (append (git-get-env-strings env) (list "git") args))
235                   (git-run-process-region
236                    buffer start end "git" args)))
237     (error "Failed to run \"git %s\":\n%s" (mapconcat (lambda (x) x) args " ") (buffer-string)))
238   (message "Running git %s...done" (car args)))
239
240 (defun git-run-hook (hook env &rest args)
241   "Run a git hook and display its output if any."
242   (let ((dir default-directory)
243         (hook-name (expand-file-name (concat ".git/hooks/" hook))))
244     (or (not (file-executable-p hook-name))
245         (let (status (buffer (get-buffer-create "*Git Hook Output*")))
246           (with-current-buffer buffer
247             (erase-buffer)
248             (cd dir)
249             (setq status
250                   (if env
251                       (apply #'call-process "env" nil (list buffer t) nil
252                              (append (git-get-env-strings env) (list hook-name) args))
253                     (apply #'call-process hook-name nil (list buffer t) nil args))))
254           (display-message-or-buffer buffer)
255           (eq 0 status)))))
256
257 (defun git-get-string-sha1 (string)
258   "Read a SHA1 from the specified string."
259   (and string
260        (string-match "[0-9a-f]\\{40\\}" string)
261        (match-string 0 string)))
262
263 (defun git-get-committer-name ()
264   "Return the name to use as GIT_COMMITTER_NAME."
265   ; copied from log-edit
266   (or git-committer-name
267       (git-config "user.name")
268       (and (boundp 'add-log-full-name) add-log-full-name)
269       (and (fboundp 'user-full-name) (user-full-name))
270       (and (boundp 'user-full-name) user-full-name)))
271
272 (defun git-get-committer-email ()
273   "Return the email address to use as GIT_COMMITTER_EMAIL."
274   ; copied from log-edit
275   (or git-committer-email
276       (git-config "user.email")
277       (and (boundp 'add-log-mailing-address) add-log-mailing-address)
278       (and (fboundp 'user-mail-address) (user-mail-address))
279       (and (boundp 'user-mail-address) user-mail-address)))
280
281 (defun git-get-commits-coding-system ()
282   "Return the coding system to use for commits."
283   (let ((repo-config (git-config "i18n.commitencoding")))
284     (or git-commits-coding-system
285         (and repo-config
286              (fboundp 'locale-charset-to-coding-system)
287              (locale-charset-to-coding-system repo-config))
288       'utf-8)))
289
290 (defun git-get-logoutput-coding-system ()
291   "Return the coding system used for git-log output."
292   (let ((repo-config (or (git-config "i18n.logoutputencoding")
293                          (git-config "i18n.commitencoding"))))
294     (or git-commits-coding-system
295         (and repo-config
296              (fboundp 'locale-charset-to-coding-system)
297              (locale-charset-to-coding-system repo-config))
298       'utf-8)))
299
300 (defun git-escape-file-name (name)
301   "Escape a file name if necessary."
302   (if (string-match "[\n\t\"\\]" name)
303       (concat "\""
304               (mapconcat (lambda (c)
305                    (case c
306                      (?\n "\\n")
307                      (?\t "\\t")
308                      (?\\ "\\\\")
309                      (?\" "\\\"")
310                      (t (char-to-string c))))
311                  name "")
312               "\"")
313     name))
314
315 (defun git-get-top-dir (dir)
316   "Retrieve the top-level directory of a git tree."
317   (let ((cdup (with-output-to-string
318                 (with-current-buffer standard-output
319                   (cd dir)
320                   (unless (eq 0 (call-process "git" nil t nil "rev-parse" "--show-cdup"))
321                     (error "cannot find top-level git tree for %s." dir))))))
322     (expand-file-name (concat (file-name-as-directory dir)
323                               (car (split-string cdup "\n"))))))
324
325 ;stolen from pcl-cvs
326 (defun git-append-to-ignore (file)
327   "Add a file name to the ignore file in its directory."
328   (let* ((fullname (expand-file-name file))
329          (dir (file-name-directory fullname))
330          (name (file-name-nondirectory fullname))
331          (ignore-name (expand-file-name git-per-dir-ignore-file dir))
332          (created (not (file-exists-p ignore-name))))
333   (save-window-excursion
334     (set-buffer (find-file-noselect ignore-name))
335     (goto-char (point-max))
336     (unless (zerop (current-column)) (insert "\n"))
337     (insert "/" name "\n")
338     (sort-lines nil (point-min) (point-max))
339     (save-buffer))
340   (when created
341     (git-run-command nil nil "update-index" "--add" "--" (file-relative-name ignore-name)))
342   (git-update-status-files (list (file-relative-name ignore-name)) 'unknown)))
343
344 ; propertize definition for XEmacs, stolen from erc-compat
345 (eval-when-compile
346   (unless (fboundp 'propertize)
347     (defun propertize (string &rest props)
348       (let ((string (copy-sequence string)))
349         (while props
350           (put-text-property 0 (length string) (nth 0 props) (nth 1 props) string)
351           (setq props (cddr props)))
352         string))))
353
354 ;;;; Wrappers for basic git commands
355 ;;;; ------------------------------------------------------------
356
357 (defun git-rev-parse (rev)
358   "Parse a revision name and return its SHA1."
359   (git-get-string-sha1
360    (git-call-process-env-string nil "rev-parse" rev)))
361
362 (defun git-config (key)
363   "Retrieve the value associated to KEY in the git repository config file."
364   (let ((str (git-call-process-env-string nil "config" key)))
365     (and str (car (split-string str "\n")))))
366
367 (defun git-symbolic-ref (ref)
368   "Wrapper for the git-symbolic-ref command."
369   (let ((str (git-call-process-env-string nil "symbolic-ref" ref)))
370     (and str (car (split-string str "\n")))))
371
372 (defun git-update-ref (ref newval &optional oldval reason)
373   "Update a reference by calling git-update-ref."
374   (let ((args (and oldval (list oldval))))
375     (push newval args)
376     (push ref args)
377     (when reason
378      (push reason args)
379      (push "-m" args))
380     (eq 0 (apply #'git-call-process-env nil nil "update-ref" args))))
381
382 (defun git-read-tree (tree &optional index-file)
383   "Read a tree into the index file."
384   (apply #'git-call-process-env nil
385          (if index-file `(("GIT_INDEX_FILE" . ,index-file)) nil)
386          "read-tree" (if tree (list tree))))
387
388 (defun git-write-tree (&optional index-file)
389   "Call git-write-tree and return the resulting tree SHA1 as a string."
390   (git-get-string-sha1
391    (git-call-process-env-string (and index-file `(("GIT_INDEX_FILE" . ,index-file))) "write-tree")))
392
393 (defun git-commit-tree (buffer tree head)
394   "Call git-commit-tree with buffer as input and return the resulting commit SHA1."
395   (let ((author-name (git-get-committer-name))
396         (author-email (git-get-committer-email))
397         (subject "commit (initial): ")
398         author-date log-start log-end args coding-system-for-write)
399     (when head
400       (setq subject "commit: ")
401       (push "-p" args)
402       (push head args))
403     (with-current-buffer buffer
404       (goto-char (point-min))
405       (if
406           (setq log-start (re-search-forward (concat "^" (regexp-quote git-log-msg-separator) "\n") nil t))
407           (save-restriction
408             (narrow-to-region (point-min) log-start)
409             (goto-char (point-min))
410             (when (re-search-forward "^Author: +\\(.*?\\) *<\\(.*\\)> *$" nil t)
411               (setq author-name (match-string 1)
412                     author-email (match-string 2)))
413             (goto-char (point-min))
414             (when (re-search-forward "^Date: +\\(.*\\)$" nil t)
415               (setq author-date (match-string 1)))
416             (goto-char (point-min))
417             (while (re-search-forward "^Parent: +\\([0-9a-f]+\\)" nil t)
418               (unless (string-equal head (match-string 1))
419                 (setq subject "commit (merge): ")
420                 (push "-p" args)
421                 (push (match-string 1) args))))
422         (setq log-start (point-min)))
423       (setq log-end (point-max))
424       (goto-char log-start)
425       (when (re-search-forward ".*$" nil t)
426         (setq subject (concat subject (match-string 0))))
427       (setq coding-system-for-write buffer-file-coding-system))
428     (let ((commit
429            (git-get-string-sha1
430             (with-output-to-string
431               (with-current-buffer standard-output
432                 (let ((env `(("GIT_AUTHOR_NAME" . ,author-name)
433                              ("GIT_AUTHOR_EMAIL" . ,author-email)
434                              ("GIT_COMMITTER_NAME" . ,(git-get-committer-name))
435                              ("GIT_COMMITTER_EMAIL" . ,(git-get-committer-email)))))
436                   (when author-date (push `("GIT_AUTHOR_DATE" . ,author-date) env))
437                   (apply #'git-run-command-region
438                          buffer log-start log-end env
439                          "commit-tree" tree (nreverse args))))))))
440       (and (git-update-ref "HEAD" commit head subject)
441            commit))))
442
443 (defun git-empty-db-p ()
444   "Check if the git db is empty (no commit done yet)."
445   (not (eq 0 (call-process "git" nil nil nil "rev-parse" "--verify" "HEAD"))))
446
447 (defun git-get-merge-heads ()
448   "Retrieve the merge heads from the MERGE_HEAD file if present."
449   (let (heads)
450     (when (file-readable-p ".git/MERGE_HEAD")
451       (with-temp-buffer
452         (insert-file-contents ".git/MERGE_HEAD" nil nil nil t)
453         (goto-char (point-min))
454         (while (re-search-forward "[0-9a-f]\\{40\\}" nil t)
455           (push (match-string 0) heads))))
456     (nreverse heads)))
457
458 (defun git-get-commit-description (commit)
459   "Get a one-line description of COMMIT."
460   (let ((coding-system-for-read (git-get-logoutput-coding-system)))
461     (let ((descr (git-call-process-env-string nil "log" "--max-count=1" "--pretty=oneline" commit)))
462       (if (and descr (string-match "\\`\\([0-9a-f]\\{40\\}\\) *\\(.*\\)$" descr))
463           (concat (substring (match-string 1 descr) 0 10) " - " (match-string 2 descr))
464         descr))))
465
466 ;;;; File info structure
467 ;;;; ------------------------------------------------------------
468
469 ; fileinfo structure stolen from pcl-cvs
470 (defstruct (git-fileinfo
471             (:copier nil)
472             (:constructor git-create-fileinfo (state name &optional old-perm new-perm rename-state orig-name marked))
473             (:conc-name git-fileinfo->))
474   marked              ;; t/nil
475   state               ;; current state
476   name                ;; file name
477   old-perm new-perm   ;; permission flags
478   rename-state        ;; rename or copy state
479   orig-name           ;; original name for renames or copies
480   needs-refresh)      ;; whether file needs to be refreshed
481
482 (defvar git-status nil)
483
484 (defun git-clear-status (status)
485   "Remove everything from the status list."
486   (ewoc-filter status (lambda (info) nil)))
487
488 (defun git-set-files-state (files state)
489   "Set the state of a list of files."
490   (dolist (info files)
491     (unless (eq (git-fileinfo->state info) state)
492       (setf (git-fileinfo->state info) state)
493       (setf (git-fileinfo->rename-state info) nil)
494       (setf (git-fileinfo->orig-name info) nil)
495       (setf (git-fileinfo->needs-refresh info) t))))
496
497 (defun git-status-filenames-map (status func files &rest args)
498   "Apply FUNC to the status files names in the FILES list."
499   (when files
500     (setq files (sort files #'string-lessp))
501     (let ((file (pop files))
502           (node (ewoc-nth status 0)))
503       (while (and file node)
504         (let ((info (ewoc-data node)))
505           (if (string-lessp (git-fileinfo->name info) file)
506               (setq node (ewoc-next status node))
507             (if (string-equal (git-fileinfo->name info) file)
508                 (apply func info args))
509             (setq file (pop files))))))))
510
511 (defun git-set-filenames-state (status files state)
512   "Set the state of a list of named files."
513   (when files
514     (git-status-filenames-map status
515                               (lambda (info state)
516                                 (unless (eq (git-fileinfo->state info) state)
517                                   (setf (git-fileinfo->state info) state)
518                                   (setf (git-fileinfo->rename-state info) nil)
519                                   (setf (git-fileinfo->orig-name info) nil)
520                                   (setf (git-fileinfo->needs-refresh info) t)))
521                               files state)
522     (unless state  ;; delete files whose state has been set to nil
523       (ewoc-filter status (lambda (info) (git-fileinfo->state info))))))
524
525 (defun git-state-code (code)
526   "Convert from a string to a added/deleted/modified state."
527   (case (string-to-char code)
528     (?M 'modified)
529     (?? 'unknown)
530     (?A 'added)
531     (?D 'deleted)
532     (?U 'unmerged)
533     (t nil)))
534
535 (defun git-status-code-as-string (code)
536   "Format a git status code as string."
537   (case code
538     ('modified (propertize "Modified" 'face 'git-status-face))
539     ('unknown  (propertize "Unknown " 'face 'git-unknown-face))
540     ('added    (propertize "Added   " 'face 'git-status-face))
541     ('deleted  (propertize "Deleted " 'face 'git-status-face))
542     ('unmerged (propertize "Unmerged" 'face 'git-unmerged-face))
543     ('uptodate (propertize "Uptodate" 'face 'git-uptodate-face))
544     ('ignored  (propertize "Ignored " 'face 'git-ignored-face))
545     (t "?       ")))
546
547 (defun git-rename-as-string (info)
548   "Return a string describing the copy or rename associated with INFO, or an empty string if none."
549   (let ((state (git-fileinfo->rename-state info)))
550     (if state
551         (propertize
552          (concat "   ("
553                  (if (eq state 'copy) "copied from "
554                    (if (eq (git-fileinfo->state info) 'added) "renamed from "
555                      "renamed to "))
556                  (git-escape-file-name (git-fileinfo->orig-name info))
557                  ")") 'face 'git-status-face)
558       "")))
559
560 (defun git-permissions-as-string (old-perm new-perm)
561   "Format a permission change as string."
562   (propertize
563    (if (or (not old-perm)
564            (not new-perm)
565            (eq 0 (logand ?\111 (logxor old-perm new-perm))))
566        "  "
567      (if (eq 0 (logand ?\111 old-perm)) "+x" "-x"))
568   'face 'git-permission-face))
569
570 (defun git-fileinfo-prettyprint (info)
571   "Pretty-printer for the git-fileinfo structure."
572   (insert (concat "   " (if (git-fileinfo->marked info) (propertize "*" 'face 'git-mark-face) " ")
573                   " " (git-status-code-as-string (git-fileinfo->state info))
574                   " " (git-permissions-as-string (git-fileinfo->old-perm info) (git-fileinfo->new-perm info))
575                   "  " (git-escape-file-name (git-fileinfo->name info))
576                   (git-rename-as-string info))))
577
578 (defun git-insert-info-list (status infolist)
579   "Insert a list of file infos in the status buffer, replacing existing ones if any."
580   (setq infolist (sort infolist
581                        (lambda (info1 info2)
582                          (string-lessp (git-fileinfo->name info1)
583                                        (git-fileinfo->name info2)))))
584   (let ((info (pop infolist))
585         (node (ewoc-nth status 0)))
586     (while info
587       (setf (git-fileinfo->needs-refresh info) t)
588       (cond ((not node)
589              (ewoc-enter-last status info)
590              (setq info (pop infolist)))
591             ((string-lessp (git-fileinfo->name (ewoc-data node))
592                            (git-fileinfo->name info))
593              (setq node (ewoc-next status node)))
594             ((string-equal (git-fileinfo->name (ewoc-data node))
595                            (git-fileinfo->name info))
596               ;; preserve the marked flag
597               (setf (git-fileinfo->marked info) (git-fileinfo->marked (ewoc-data node)))
598               (setf (ewoc-data node) info)
599               (setq info (pop infolist)))
600             (t
601              (ewoc-enter-before status node info)
602              (setq info (pop infolist)))))))
603
604 (defun git-run-diff-index (status files)
605   "Run git-diff-index on FILES and parse the results into STATUS.
606 Return the list of files that haven't been handled."
607   (let (infolist)
608     (with-temp-buffer
609       (apply #'git-run-command t nil "diff-index" "-z" "-M" "HEAD" "--" files)
610       (goto-char (point-min))
611       (while (re-search-forward
612               ":\\([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"
613               nil t 1)
614         (let ((old-perm (string-to-number (match-string 1) 8))
615               (new-perm (string-to-number (match-string 2) 8))
616               (state (or (match-string 4) (match-string 6)))
617               (name (or (match-string 5) (match-string 7)))
618               (new-name (match-string 8)))
619           (if new-name  ; copy or rename
620               (if (eq ?C (string-to-char state))
621                   (push (git-create-fileinfo 'added new-name old-perm new-perm 'copy name) infolist)
622                 (push (git-create-fileinfo 'deleted name 0 0 'rename new-name) infolist)
623                 (push (git-create-fileinfo 'added new-name old-perm new-perm 'rename name) infolist))
624             (push (git-create-fileinfo (git-state-code state) name old-perm new-perm) infolist))
625           (setq files (delete name files))
626           (when new-name (setq files (delete new-name files))))))
627     (git-insert-info-list status infolist)
628     files))
629
630 (defun git-find-status-file (status file)
631   "Find a given file in the status ewoc and return its node."
632   (let ((node (ewoc-nth status 0)))
633     (while (and node (not (string= file (git-fileinfo->name (ewoc-data node)))))
634       (setq node (ewoc-next status node)))
635     node))
636
637 (defun git-run-ls-files (status files default-state &rest options)
638   "Run git-ls-files on FILES and parse the results into STATUS.
639 Return the list of files that haven't been handled."
640   (let (infolist)
641     (with-temp-buffer
642       (apply #'git-run-command t nil "ls-files" "-z" (append options (list "--") files))
643       (goto-char (point-min))
644       (while (re-search-forward "\\([^\0]*\\)\0" nil t 1)
645         (let ((name (match-string 1)))
646           (push (git-create-fileinfo default-state name) infolist)
647           (setq files (delete name files)))))
648     (git-insert-info-list status infolist)
649     files))
650
651 (defun git-run-ls-unmerged (status files)
652   "Run git-ls-files -u on FILES and parse the results into STATUS."
653   (with-temp-buffer
654     (apply #'git-run-command t nil "ls-files" "-z" "-u" "--" files)
655     (goto-char (point-min))
656     (let (unmerged-files)
657       (while (re-search-forward "[0-7]\\{6\\} [0-9a-f]\\{40\\} [123]\t\\([^\0]+\\)\0" nil t)
658         (push (match-string 1) unmerged-files))
659       (git-set-filenames-state status unmerged-files 'unmerged))))
660
661 (defun git-get-exclude-files ()
662   "Get the list of exclude files to pass to git-ls-files."
663   (let (files
664         (config (git-config "core.excludesfile")))
665     (when (file-readable-p ".git/info/exclude")
666       (push ".git/info/exclude" files))
667     (when (and config (file-readable-p config))
668       (push config files))
669     files))
670
671 (defun git-run-ls-files-with-excludes (status files default-state &rest options)
672   "Run git-ls-files on FILES with appropriate --exclude-from options."
673   (let ((exclude-files (git-get-exclude-files)))
674     (apply #'git-run-ls-files status files default-state
675            (concat "--exclude-per-directory=" git-per-dir-ignore-file)
676            (append options (mapcar (lambda (f) (concat "--exclude-from=" f)) exclude-files)))))
677
678 (defun git-update-status-files (files &optional default-state)
679   "Update the status of FILES from the index."
680   (unless git-status (error "Not in git-status buffer."))
681   (unless files
682     (when git-show-uptodate (git-run-ls-files git-status nil 'uptodate "-c")))
683   (let* ((remaining-files
684           (if (git-empty-db-p) ; we need some special handling for an empty db
685               (git-run-ls-files git-status files 'added "-c")
686             (git-run-diff-index git-status files))))
687     (git-run-ls-unmerged git-status files)
688     (when (or remaining-files (and git-show-unknown (not files)))
689       (setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'unknown "-o")))
690     (when (or remaining-files (and git-show-ignored (not files)))
691       (setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'ignored "-o" "-i")))
692     (git-set-filenames-state git-status remaining-files default-state)
693     (git-refresh-files)
694     (git-refresh-ewoc-hf git-status)))
695
696 (defun git-marked-files ()
697   "Return a list of all marked files, or if none a list containing just the file at cursor position."
698   (unless git-status (error "Not in git-status buffer."))
699   (or (ewoc-collect git-status (lambda (info) (git-fileinfo->marked info)))
700       (list (ewoc-data (ewoc-locate git-status)))))
701
702 (defun git-marked-files-state (&rest states)
703   "Return marked files that are in the specified states."
704   (let ((files (git-marked-files))
705         result)
706     (dolist (info files)
707       (when (memq (git-fileinfo->state info) states)
708         (push info result)))
709     result))
710
711 (defun git-refresh-files ()
712   "Refresh all files that need it and clear the needs-refresh flag."
713   (unless git-status (error "Not in git-status buffer."))
714   (ewoc-map
715    (lambda (info)
716      (let ((refresh (git-fileinfo->needs-refresh info)))
717        (setf (git-fileinfo->needs-refresh info) nil)
718        refresh))
719    git-status)
720   ; move back to goal column
721   (when goal-column (move-to-column goal-column)))
722
723 (defun git-refresh-ewoc-hf (status)
724   "Refresh the ewoc header and footer."
725   (let ((branch (git-symbolic-ref "HEAD"))
726         (head (if (git-empty-db-p) "Nothing committed yet"
727                 (git-get-commit-description "HEAD")))
728         (merge-heads (git-get-merge-heads)))
729     (ewoc-set-hf status
730                  (format "Directory:  %s\nBranch:     %s\nHead:       %s%s\n"
731                          default-directory
732                          (if branch
733                              (if (string-match "^refs/heads/" branch)
734                                  (substring branch (match-end 0))
735                                branch)
736                            "none (detached HEAD)")
737                          head
738                          (if merge-heads
739                              (concat "\nMerging:    "
740                                      (mapconcat (lambda (str) (git-get-commit-description str)) merge-heads "\n            "))
741                            ""))
742                  (if (ewoc-nth status 0) "" "    No changes."))))
743
744 (defun git-get-filenames (files)
745   (mapcar (lambda (info) (git-fileinfo->name info)) files))
746
747 (defun git-update-index (index-file files)
748   "Run git-update-index on a list of files."
749   (let ((env (and index-file `(("GIT_INDEX_FILE" . ,index-file))))
750         added deleted modified)
751     (dolist (info files)
752       (case (git-fileinfo->state info)
753         ('added (push info added))
754         ('deleted (push info deleted))
755         ('modified (push info modified))))
756     (when added
757       (apply #'git-run-command nil env "update-index" "--add" "--" (git-get-filenames added)))
758     (when deleted
759       (apply #'git-run-command nil env "update-index" "--remove" "--" (git-get-filenames deleted)))
760     (when modified
761       (apply #'git-run-command nil env "update-index" "--" (git-get-filenames modified)))))
762
763 (defun git-run-pre-commit-hook ()
764   "Run the pre-commit hook if any."
765   (unless git-status (error "Not in git-status buffer."))
766   (let ((files (git-marked-files-state 'added 'deleted 'modified)))
767     (or (not files)
768         (not (file-executable-p ".git/hooks/pre-commit"))
769         (let ((index-file (make-temp-file "gitidx")))
770           (unwind-protect
771             (let ((head-tree (unless (git-empty-db-p) (git-rev-parse "HEAD^{tree}"))))
772               (git-read-tree head-tree index-file)
773               (git-update-index index-file files)
774               (git-run-hook "pre-commit" `(("GIT_INDEX_FILE" . ,index-file))))
775           (delete-file index-file))))))
776
777 (defun git-do-commit ()
778   "Perform the actual commit using the current buffer as log message."
779   (interactive)
780   (let ((buffer (current-buffer))
781         (index-file (make-temp-file "gitidx")))
782     (with-current-buffer log-edit-parent-buffer
783       (if (git-marked-files-state 'unmerged)
784           (message "You cannot commit unmerged files, resolve them first.")
785         (unwind-protect
786             (let ((files (git-marked-files-state 'added 'deleted 'modified))
787                   head head-tree)
788               (unless (git-empty-db-p)
789                 (setq head (git-rev-parse "HEAD")
790                       head-tree (git-rev-parse "HEAD^{tree}")))
791               (if files
792                   (progn
793                     (git-read-tree head-tree index-file)
794                     (git-update-index nil files)         ;update both the default index
795                     (git-update-index index-file files)  ;and the temporary one
796                     (let ((tree (git-write-tree index-file)))
797                       (if (or (not (string-equal tree head-tree))
798                               (yes-or-no-p "The tree was not modified, do you really want to perform an empty commit? "))
799                           (let ((commit (git-commit-tree buffer tree head)))
800                             (condition-case nil (delete-file ".git/MERGE_HEAD") (error nil))
801                             (condition-case nil (delete-file ".git/MERGE_MSG") (error nil))
802                             (with-current-buffer buffer (erase-buffer))
803                             (git-set-files-state files 'uptodate)
804                             (git-run-command nil nil "rerere")
805                             (git-refresh-files)
806                             (git-refresh-ewoc-hf git-status)
807                             (message "Committed %s." commit)
808                             (git-run-hook "post-commit" nil))
809                         (message "Commit aborted."))))
810                 (message "No files to commit.")))
811           (delete-file index-file))))))
812
813
814 ;;;; Interactive functions
815 ;;;; ------------------------------------------------------------
816
817 (defun git-mark-file ()
818   "Mark the file that the cursor is on and move to the next one."
819   (interactive)
820   (unless git-status (error "Not in git-status buffer."))
821   (let* ((pos (ewoc-locate git-status))
822          (info (ewoc-data pos)))
823     (setf (git-fileinfo->marked info) t)
824     (ewoc-invalidate git-status pos)
825     (ewoc-goto-next git-status 1)))
826
827 (defun git-unmark-file ()
828   "Unmark the file that the cursor is on and move to the next one."
829   (interactive)
830   (unless git-status (error "Not in git-status buffer."))
831   (let* ((pos (ewoc-locate git-status))
832          (info (ewoc-data pos)))
833     (setf (git-fileinfo->marked info) nil)
834     (ewoc-invalidate git-status pos)
835     (ewoc-goto-next git-status 1)))
836
837 (defun git-unmark-file-up ()
838   "Unmark the file that the cursor is on and move to the previous one."
839   (interactive)
840   (unless git-status (error "Not in git-status buffer."))
841   (let* ((pos (ewoc-locate git-status))
842          (info (ewoc-data pos)))
843     (setf (git-fileinfo->marked info) nil)
844     (ewoc-invalidate git-status pos)
845     (ewoc-goto-prev git-status 1)))
846
847 (defun git-mark-all ()
848   "Mark all files."
849   (interactive)
850   (unless git-status (error "Not in git-status buffer."))
851   (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) t) t) git-status)
852   ; move back to goal column after invalidate
853   (when goal-column (move-to-column goal-column)))
854
855 (defun git-unmark-all ()
856   "Unmark all files."
857   (interactive)
858   (unless git-status (error "Not in git-status buffer."))
859   (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) nil) t) git-status)
860   ; move back to goal column after invalidate
861   (when goal-column (move-to-column goal-column)))
862
863 (defun git-toggle-all-marks ()
864   "Toggle all file marks."
865   (interactive)
866   (unless git-status (error "Not in git-status buffer."))
867   (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) (not (git-fileinfo->marked info))) t) git-status)
868   ; move back to goal column after invalidate
869   (when goal-column (move-to-column goal-column)))
870
871 (defun git-next-file (&optional n)
872   "Move the selection down N files."
873   (interactive "p")
874   (unless git-status (error "Not in git-status buffer."))
875   (ewoc-goto-next git-status n))
876
877 (defun git-prev-file (&optional n)
878   "Move the selection up N files."
879   (interactive "p")
880   (unless git-status (error "Not in git-status buffer."))
881   (ewoc-goto-prev git-status n))
882
883 (defun git-next-unmerged-file (&optional n)
884   "Move the selection down N unmerged files."
885   (interactive "p")
886   (unless git-status (error "Not in git-status buffer."))
887   (let* ((last (ewoc-locate git-status))
888          (node (ewoc-next git-status last)))
889     (while (and node (> n 0))
890       (when (eq 'unmerged (git-fileinfo->state (ewoc-data node)))
891         (setq n (1- n))
892         (setq last node))
893       (setq node (ewoc-next git-status node)))
894     (ewoc-goto-node git-status last)))
895
896 (defun git-prev-unmerged-file (&optional n)
897   "Move the selection up N unmerged files."
898   (interactive "p")
899   (unless git-status (error "Not in git-status buffer."))
900   (let* ((last (ewoc-locate git-status))
901          (node (ewoc-prev git-status last)))
902     (while (and node (> n 0))
903       (when (eq 'unmerged (git-fileinfo->state (ewoc-data node)))
904         (setq n (1- n))
905         (setq last node))
906       (setq node (ewoc-prev git-status node)))
907     (ewoc-goto-node git-status last)))
908
909 (defun git-add-file ()
910   "Add marked file(s) to the index cache."
911   (interactive)
912   (let ((files (git-get-filenames (git-marked-files-state 'unknown 'ignored))))
913     (unless files
914       (push (file-relative-name (read-file-name "File to add: " nil nil t)) files))
915     (apply #'git-run-command nil nil "update-index" "--add" "--" files)
916     (git-update-status-files files 'uptodate)))
917
918 (defun git-ignore-file ()
919   "Add marked file(s) to the ignore list."
920   (interactive)
921   (let ((files (git-get-filenames (git-marked-files-state 'unknown))))
922     (unless files
923       (push (file-relative-name (read-file-name "File to ignore: " nil nil t)) files))
924     (dolist (f files) (git-append-to-ignore f))
925     (git-update-status-files files 'ignored)))
926
927 (defun git-remove-file ()
928   "Remove the marked file(s)."
929   (interactive)
930   (let ((files (git-get-filenames (git-marked-files-state 'added 'modified 'unknown 'uptodate 'ignored))))
931     (unless files
932       (push (file-relative-name (read-file-name "File to remove: " nil nil t)) files))
933     (if (yes-or-no-p
934          (format "Remove %d file%s? " (length files) (if (> (length files) 1) "s" "")))
935         (progn
936           (dolist (name files)
937             (when (file-exists-p name) (delete-file name)))
938           (apply #'git-run-command nil nil "update-index" "--remove" "--" files)
939           (git-update-status-files files nil))
940       (message "Aborting"))))
941
942 (defun git-revert-file ()
943   "Revert changes to the marked file(s)."
944   (interactive)
945   (let ((files (git-marked-files))
946         added modified)
947     (when (and files
948                (yes-or-no-p
949                 (format "Revert %d file%s? " (length files) (if (> (length files) 1) "s" ""))))
950       (dolist (info files)
951         (case (git-fileinfo->state info)
952           ('added (push (git-fileinfo->name info) added))
953           ('deleted (push (git-fileinfo->name info) modified))
954           ('unmerged (push (git-fileinfo->name info) modified))
955           ('modified (push (git-fileinfo->name info) modified))))
956       (when added
957         (apply #'git-run-command nil nil "update-index" "--force-remove" "--" added))
958       (when modified
959         (apply #'git-run-command nil nil "checkout" "HEAD" modified))
960       (git-update-status-files (append added modified) 'uptodate))))
961
962 (defun git-resolve-file ()
963   "Resolve conflicts in marked file(s)."
964   (interactive)
965   (let ((files (git-get-filenames (git-marked-files-state 'unmerged))))
966     (when files
967       (apply #'git-run-command nil nil "update-index" "--" files)
968       (git-update-status-files files 'uptodate))))
969
970 (defun git-remove-handled ()
971   "Remove handled files from the status list."
972   (interactive)
973   (ewoc-filter git-status
974                (lambda (info)
975                  (case (git-fileinfo->state info)
976                    ('ignored git-show-ignored)
977                    ('uptodate git-show-uptodate)
978                    ('unknown git-show-unknown)
979                    (t t))))
980   (unless (ewoc-nth git-status 0)  ; refresh header if list is empty
981     (git-refresh-ewoc-hf git-status)))
982
983 (defun git-toggle-show-uptodate ()
984   "Toogle the option for showing up-to-date files."
985   (interactive)
986   (if (setq git-show-uptodate (not git-show-uptodate))
987       (git-refresh-status)
988     (git-remove-handled)))
989
990 (defun git-toggle-show-ignored ()
991   "Toogle the option for showing ignored files."
992   (interactive)
993   (if (setq git-show-ignored (not git-show-ignored))
994       (progn
995         (git-run-ls-files-with-excludes git-status nil 'ignored "-o" "-i")
996         (git-refresh-files)
997         (git-refresh-ewoc-hf git-status))
998     (git-remove-handled)))
999
1000 (defun git-toggle-show-unknown ()
1001   "Toogle the option for showing unknown files."
1002   (interactive)
1003   (if (setq git-show-unknown (not git-show-unknown))
1004       (progn
1005         (git-run-ls-files-with-excludes git-status nil 'unknown "-o")
1006         (git-refresh-files)
1007         (git-refresh-ewoc-hf git-status))
1008     (git-remove-handled)))
1009
1010 (defun git-setup-diff-buffer (buffer)
1011   "Setup a buffer for displaying a diff."
1012   (let ((dir default-directory))
1013     (with-current-buffer buffer
1014       (diff-mode)
1015       (goto-char (point-min))
1016       (setq default-directory dir)
1017       (setq buffer-read-only t)))
1018   (display-buffer buffer)
1019   (shrink-window-if-larger-than-buffer))
1020
1021 (defun git-diff-file ()
1022   "Diff the marked file(s) against HEAD."
1023   (interactive)
1024   (let ((files (git-marked-files)))
1025     (git-setup-diff-buffer
1026      (apply #'git-run-command-buffer "*git-diff*" "diff-index" "-p" "-M" "HEAD" "--" (git-get-filenames files)))))
1027
1028 (defun git-diff-file-merge-head (arg)
1029   "Diff the marked file(s) against the first merge head (or the nth one with a numeric prefix)."
1030   (interactive "p")
1031   (let ((files (git-marked-files))
1032         (merge-heads (git-get-merge-heads)))
1033     (unless merge-heads (error "No merge in progress"))
1034     (git-setup-diff-buffer
1035      (apply #'git-run-command-buffer "*git-diff*" "diff-index" "-p" "-M"
1036             (or (nth (1- arg) merge-heads) "HEAD") "--" (git-get-filenames files)))))
1037
1038 (defun git-diff-unmerged-file (stage)
1039   "Diff the marked unmerged file(s) against the specified stage."
1040   (let ((files (git-marked-files)))
1041     (git-setup-diff-buffer
1042      (apply #'git-run-command-buffer "*git-diff*" "diff-files" "-p" stage "--" (git-get-filenames files)))))
1043
1044 (defun git-diff-file-base ()
1045   "Diff the marked unmerged file(s) against the common base file."
1046   (interactive)
1047   (git-diff-unmerged-file "-1"))
1048
1049 (defun git-diff-file-mine ()
1050   "Diff the marked unmerged file(s) against my pre-merge version."
1051   (interactive)
1052   (git-diff-unmerged-file "-2"))
1053
1054 (defun git-diff-file-other ()
1055   "Diff the marked unmerged file(s) against the other's pre-merge version."
1056   (interactive)
1057   (git-diff-unmerged-file "-3"))
1058
1059 (defun git-diff-file-combined ()
1060   "Do a combined diff of the marked unmerged file(s)."
1061   (interactive)
1062   (git-diff-unmerged-file "-c"))
1063
1064 (defun git-diff-file-idiff ()
1065   "Perform an interactive diff on the current file."
1066   (interactive)
1067   (let ((files (git-marked-files-state 'added 'deleted 'modified)))
1068     (unless (eq 1 (length files))
1069       (error "Cannot perform an interactive diff on multiple files."))
1070     (let* ((filename (car (git-get-filenames files)))
1071            (buff1 (find-file-noselect filename))
1072            (buff2 (git-run-command-buffer (concat filename ".~HEAD~") "cat-file" "blob" (concat "HEAD:" filename))))
1073       (ediff-buffers buff1 buff2))))
1074
1075 (defun git-log-file ()
1076   "Display a log of changes to the marked file(s)."
1077   (interactive)
1078   (let* ((files (git-marked-files))
1079          (coding-system-for-read git-commits-coding-system)
1080          (buffer (apply #'git-run-command-buffer "*git-log*" "rev-list" "--pretty" "HEAD" "--" (git-get-filenames files))))
1081     (with-current-buffer buffer
1082       ; (git-log-mode)  FIXME: implement log mode
1083       (goto-char (point-min))
1084       (setq buffer-read-only t))
1085     (display-buffer buffer)))
1086
1087 (defun git-log-edit-files ()
1088   "Return a list of marked files for use in the log-edit buffer."
1089   (with-current-buffer log-edit-parent-buffer
1090     (git-get-filenames (git-marked-files-state 'added 'deleted 'modified))))
1091
1092 (defun git-append-sign-off (name email)
1093   "Append a Signed-off-by entry to the current buffer, avoiding duplicates."
1094   (let ((sign-off (format "Signed-off-by: %s <%s>" name email))
1095         (case-fold-search t))
1096     (goto-char (point-min))
1097     (unless (re-search-forward (concat "^" (regexp-quote sign-off)) nil t)
1098       (goto-char (point-min))
1099       (unless (re-search-forward "^Signed-off-by: " nil t)
1100         (setq sign-off (concat "\n" sign-off)))
1101       (goto-char (point-max))
1102       (insert sign-off "\n"))))
1103
1104 (defun git-setup-log-buffer (buffer &optional author-name author-email subject date msg)
1105   "Setup the log buffer for a commit."
1106   (unless git-status (error "Not in git-status buffer."))
1107   (let ((merge-heads (git-get-merge-heads))
1108         (dir default-directory)
1109         (committer-name (git-get-committer-name))
1110         (committer-email (git-get-committer-email))
1111         (sign-off git-append-signed-off-by))
1112     (with-current-buffer buffer
1113       (cd dir)
1114       (erase-buffer)
1115       (insert
1116        (propertize
1117         (format "Author: %s <%s>\n%s%s"
1118                 (or author-name committer-name)
1119                 (or author-email committer-email)
1120                 (if date (format "Date: %s\n" date) "")
1121                 (if merge-heads
1122                     (format "Parent: %s\n%s\n"
1123                             (git-rev-parse "HEAD")
1124                             (mapconcat (lambda (str) (concat "Parent: " str)) merge-heads "\n"))
1125                   ""))
1126         'face 'git-header-face)
1127        (propertize git-log-msg-separator 'face 'git-separator-face)
1128        "\n")
1129       (when subject (insert subject "\n\n"))
1130       (cond (msg (insert msg "\n"))
1131             ((file-readable-p ".dotest/msg")
1132              (insert-file-contents ".dotest/msg"))
1133             ((file-readable-p ".git/MERGE_MSG")
1134              (insert-file-contents ".git/MERGE_MSG")))
1135       ; delete empty lines at end
1136       (goto-char (point-min))
1137       (when (re-search-forward "\n+\\'" nil t)
1138         (replace-match "\n" t t))
1139       (when sign-off (git-append-sign-off committer-name committer-email)))))
1140
1141 (defun git-commit-file ()
1142   "Commit the marked file(s), asking for a commit message."
1143   (interactive)
1144   (unless git-status (error "Not in git-status buffer."))
1145   (when (git-run-pre-commit-hook)
1146     (let ((buffer (get-buffer-create "*git-commit*"))
1147           (coding-system (git-get-commits-coding-system))
1148           author-name author-email subject date)
1149       (when (eq 0 (buffer-size buffer))
1150         (when (file-readable-p ".dotest/info")
1151           (with-temp-buffer
1152             (insert-file-contents ".dotest/info")
1153             (goto-char (point-min))
1154             (when (re-search-forward "^Author: \\(.*\\)\nEmail: \\(.*\\)$" nil t)
1155               (setq author-name (match-string 1))
1156               (setq author-email (match-string 2)))
1157             (goto-char (point-min))
1158             (when (re-search-forward "^Subject: \\(.*\\)$" nil t)
1159               (setq subject (match-string 1)))
1160             (goto-char (point-min))
1161             (when (re-search-forward "^Date: \\(.*\\)$" nil t)
1162               (setq date (match-string 1)))))
1163         (git-setup-log-buffer buffer author-name author-email subject date))
1164       (log-edit #'git-do-commit nil #'git-log-edit-files buffer)
1165       (setq font-lock-keywords (font-lock-compile-keywords git-log-edit-font-lock-keywords))
1166       (setq buffer-file-coding-system coding-system)
1167       (re-search-forward (regexp-quote (concat git-log-msg-separator "\n")) nil t))))
1168
1169 (defun git-find-file ()
1170   "Visit the current file in its own buffer."
1171   (interactive)
1172   (unless git-status (error "Not in git-status buffer."))
1173   (let ((info (ewoc-data (ewoc-locate git-status))))
1174     (find-file (git-fileinfo->name info))
1175     (when (eq 'unmerged (git-fileinfo->state info))
1176       (smerge-mode 1))))
1177
1178 (defun git-find-file-other-window ()
1179   "Visit the current file in its own buffer in another window."
1180   (interactive)
1181   (unless git-status (error "Not in git-status buffer."))
1182   (let ((info (ewoc-data (ewoc-locate git-status))))
1183     (find-file-other-window (git-fileinfo->name info))
1184     (when (eq 'unmerged (git-fileinfo->state info))
1185       (smerge-mode))))
1186
1187 (defun git-find-file-imerge ()
1188   "Visit the current file in interactive merge mode."
1189   (interactive)
1190   (unless git-status (error "Not in git-status buffer."))
1191   (let ((info (ewoc-data (ewoc-locate git-status))))
1192     (find-file (git-fileinfo->name info))
1193     (smerge-ediff)))
1194
1195 (defun git-view-file ()
1196   "View the current file in its own buffer."
1197   (interactive)
1198   (unless git-status (error "Not in git-status buffer."))
1199   (let ((info (ewoc-data (ewoc-locate git-status))))
1200     (view-file (git-fileinfo->name info))))
1201
1202 (defun git-refresh-status ()
1203   "Refresh the git status buffer."
1204   (interactive)
1205   (let* ((status git-status)
1206          (pos (ewoc-locate status))
1207          (marked-files (git-get-filenames (ewoc-collect status (lambda (info) (git-fileinfo->marked info)))))
1208          (cur-name (and pos (git-fileinfo->name (ewoc-data pos)))))
1209     (unless status (error "Not in git-status buffer."))
1210     (git-run-command nil nil "update-index" "--refresh")
1211     (git-clear-status status)
1212     (git-update-status-files nil)
1213     ; restore file marks
1214     (when marked-files
1215       (git-status-filenames-map status
1216                                 (lambda (info)
1217                                         (setf (git-fileinfo->marked info) t)
1218                                         (setf (git-fileinfo->needs-refresh info) t))
1219                                 marked-files)
1220       (git-refresh-files))
1221     ; move point to the current file name if any
1222     (let ((node (and cur-name (git-find-status-file status cur-name))))
1223       (when node (ewoc-goto-node status node)))))
1224
1225 (defun git-status-quit ()
1226   "Quit git-status mode."
1227   (interactive)
1228   (bury-buffer))
1229
1230 ;;;; Major Mode
1231 ;;;; ------------------------------------------------------------
1232
1233 (defvar git-status-mode-hook nil
1234   "Run after `git-status-mode' is setup.")
1235
1236 (defvar git-status-mode-map nil
1237   "Keymap for git major mode.")
1238
1239 (defvar git-status nil
1240   "List of all files managed by the git-status mode.")
1241
1242 (unless git-status-mode-map
1243   (let ((map (make-keymap))
1244         (diff-map (make-sparse-keymap))
1245         (toggle-map (make-sparse-keymap)))
1246     (suppress-keymap map)
1247     (define-key map "?"   'git-help)
1248     (define-key map "h"   'git-help)
1249     (define-key map " "   'git-next-file)
1250     (define-key map "a"   'git-add-file)
1251     (define-key map "c"   'git-commit-file)
1252     (define-key map "d"    diff-map)
1253     (define-key map "="   'git-diff-file)
1254     (define-key map "f"   'git-find-file)
1255     (define-key map "\r"  'git-find-file)
1256     (define-key map "g"   'git-refresh-status)
1257     (define-key map "i"   'git-ignore-file)
1258     (define-key map "l"   'git-log-file)
1259     (define-key map "m"   'git-mark-file)
1260     (define-key map "M"   'git-mark-all)
1261     (define-key map "n"   'git-next-file)
1262     (define-key map "N"   'git-next-unmerged-file)
1263     (define-key map "o"   'git-find-file-other-window)
1264     (define-key map "p"   'git-prev-file)
1265     (define-key map "P"   'git-prev-unmerged-file)
1266     (define-key map "q"   'git-status-quit)
1267     (define-key map "r"   'git-remove-file)
1268     (define-key map "R"   'git-resolve-file)
1269     (define-key map "t"    toggle-map)
1270     (define-key map "T"   'git-toggle-all-marks)
1271     (define-key map "u"   'git-unmark-file)
1272     (define-key map "U"   'git-revert-file)
1273     (define-key map "v"   'git-view-file)
1274     (define-key map "x"   'git-remove-handled)
1275     (define-key map "\C-?" 'git-unmark-file-up)
1276     (define-key map "\M-\C-?" 'git-unmark-all)
1277     ; the diff submap
1278     (define-key diff-map "b" 'git-diff-file-base)
1279     (define-key diff-map "c" 'git-diff-file-combined)
1280     (define-key diff-map "=" 'git-diff-file)
1281     (define-key diff-map "e" 'git-diff-file-idiff)
1282     (define-key diff-map "E" 'git-find-file-imerge)
1283     (define-key diff-map "h" 'git-diff-file-merge-head)
1284     (define-key diff-map "m" 'git-diff-file-mine)
1285     (define-key diff-map "o" 'git-diff-file-other)
1286     ; the toggle submap
1287     (define-key toggle-map "u" 'git-toggle-show-uptodate)
1288     (define-key toggle-map "i" 'git-toggle-show-ignored)
1289     (define-key toggle-map "k" 'git-toggle-show-unknown)
1290     (define-key toggle-map "m" 'git-toggle-all-marks)
1291     (setq git-status-mode-map map)))
1292
1293 ;; git mode should only run in the *git status* buffer
1294 (put 'git-status-mode 'mode-class 'special)
1295
1296 (defun git-status-mode ()
1297   "Major mode for interacting with Git.
1298 Commands:
1299 \\{git-status-mode-map}"
1300   (kill-all-local-variables)
1301   (buffer-disable-undo)
1302   (setq mode-name "git status"
1303         major-mode 'git-status-mode
1304         goal-column 17
1305         buffer-read-only t)
1306   (use-local-map git-status-mode-map)
1307   (let ((buffer-read-only nil))
1308     (erase-buffer)
1309   (let ((status (ewoc-create 'git-fileinfo-prettyprint "" "")))
1310     (set (make-local-variable 'git-status) status))
1311   (set (make-local-variable 'list-buffers-directory) default-directory)
1312   (make-local-variable 'git-show-uptodate)
1313   (make-local-variable 'git-show-ignored)
1314   (make-local-variable 'git-show-unknown)
1315   (run-hooks 'git-status-mode-hook)))
1316
1317 (defun git-find-status-buffer (dir)
1318   "Find the git status buffer handling a specified directory."
1319   (let ((list (buffer-list))
1320         (fulldir (expand-file-name dir))
1321         found)
1322     (while (and list (not found))
1323       (let ((buffer (car list)))
1324         (with-current-buffer buffer
1325           (when (and list-buffers-directory
1326                      (string-equal fulldir (expand-file-name list-buffers-directory))
1327                      (string-match "\\*git-status\\*$" (buffer-name buffer)))
1328             (setq found buffer))))
1329       (setq list (cdr list)))
1330     found))
1331
1332 (defun git-status (dir)
1333   "Entry point into git-status mode."
1334   (interactive "DSelect directory: ")
1335   (setq dir (git-get-top-dir dir))
1336   (if (file-directory-p (concat (file-name-as-directory dir) ".git"))
1337       (let ((buffer (or (and git-reuse-status-buffer (git-find-status-buffer dir))
1338                         (create-file-buffer (expand-file-name "*git-status*" dir)))))
1339         (switch-to-buffer buffer)
1340         (cd dir)
1341         (git-status-mode)
1342         (git-refresh-status)
1343         (goto-char (point-min)))
1344     (message "%s is not a git working tree." dir)))
1345
1346 (defun git-help ()
1347   "Display help for Git mode."
1348   (interactive)
1349   (describe-function 'git-status-mode))
1350
1351 (provide 'git)
1352 ;;; git.el ends here