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