Code

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