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