Code

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