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