Code

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