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