1 ;;; diff-mode.el --- A mode for viewing/editing context diffs
3 ;; Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@cs.yale.edu>
6 ;; Keywords: patch diff
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; Provides support for font-lock, outline, navigation
28 ;; commands, editing and various conversions as well as jumping
29 ;; to the corresponding source file.
31 ;; inspired by Pavel Machek's patch-mode.el (<pavel@atrey.karlin.mff.cuni.cz>)
32 ;; some efforts were spent to have it somewhat compatible with XEmacs'
33 ;; diff-mode as well as with compilation-minor-mode
35 ;; to use it, simply add to your .emacs the following lines:
37 ;; (autoload 'diff-mode "diff-mode" "Diff major mode" t)
38 ;; (add-to-list 'auto-mode-alist '("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode))
42 ;; - Reverse doesn't work with normal diffs.
46 ;; - Improve narrowed-view support.
47 ;; - re-enable (conditionally) the `compile' support after improving it to use
48 ;; the same code as diff-goto-source.
49 ;; - Support for # comments in context->unified.
50 ;; - Do a fuzzy search in diff-goto-source.
51 ;; - Allow diff.el to use diff-mode.
52 ;; This mostly means ability to jump from half-hunk to half-hunk
53 ;; in context (and normal) diffs and to jump to the corresponding
54 ;; (i.e. new or old) file.
55 ;; - Handle `diff -b' output in context->unified.
58 ;; - Spice up the minor-mode with font-lock support.
59 ;; - Recognize pcl-cvs' special string for `cvs-execute-single'.
63 (eval-when-compile (require 'cl))
66 (defgroup diff-mode ()
67 "Major mode for viewing/editing diffs"
72 (defcustom diff-default-read-only t
73 "If non-nil, `diff-mode' buffers default to being read-only."
77 (defcustom diff-jump-to-old-file nil
78 "*Non-nil means `diff-goto-source' jumps to the old file.
79 Else, it jumps to the new file."
83 (defcustom diff-update-on-the-fly t
84 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
85 When editing a diff file, the line numbers in the hunk headers
86 need to be kept consistent with the actual diff. This can
87 either be done on the fly (but this sometimes interacts poorly with the
88 undo mechanism) or whenever the file is written (can be slow
89 when editing big diffs)."
93 (defcustom diff-advance-after-apply-hunk t
94 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
99 (defvar diff-mode-hook nil
100 "Run after setting up the `diff-mode' major mode.")
102 (defvar diff-outline-regexp
103 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
106 ;;;; keymap, menu, ...
109 (easy-mmode-defmap diff-mode-shared-map
110 '(;; From Pavel Machek's patch-mode.
111 ("n" . diff-hunk-next)
112 ("N" . diff-file-next)
113 ("p" . diff-hunk-prev)
114 ("P" . diff-file-prev)
115 ("k" . diff-hunk-kill)
116 ("K" . diff-file-kill)
117 ;; From compilation-minor-mode.
118 ("}" . diff-file-next)
119 ("{" . diff-file-prev)
120 ("\C-m" . diff-goto-source)
121 ([mouse-2] . diff-mouse-goto-source)
122 ;; From XEmacs' diff-mode.
124 ;;("." . diff-goto-source) ;display-buffer
125 ;;("f" . diff-goto-source) ;find-file
126 ("o" . diff-goto-source) ;other-window
127 ;;("w" . diff-goto-source) ;other-frame
128 ;;("N" . diff-narrow)
129 ;;("h" . diff-show-header)
130 ;;("j" . diff-show-difference) ;jump to Nth diff
133 ("\177" . scroll-down)
134 ;; Our very own bindings.
135 ("A" . diff-ediff-patch)
136 ("r" . diff-restrict-view)
137 ("R" . diff-reverse-direction)
138 ("U" . diff-context->unified)
139 ("C" . diff-unified->context))
140 "Basic keymap for `diff-mode', bound to various prefix keys.")
142 (easy-mmode-defmap diff-mode-map
143 `(("\e" . ,diff-mode-shared-map)
144 ;; From compilation-minor-mode.
145 ("\C-c\C-c" . diff-goto-source)
147 ("\C-c\C-s" . diff-split-hunk)
148 ("\C-c\C-a" . diff-apply-hunk)
149 ("\C-c\C-t" . diff-test-hunk))
150 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
152 (easy-menu-define diff-mode-menu diff-mode-map
153 "Menu for `diff-mode'."
155 ["Jump to Source" diff-goto-source t]
156 ["Apply hunk" diff-apply-hunk t]
157 ["Apply diff with Ediff" diff-ediff-patch t]
159 ["Reverse direction" diff-reverse-direction t]
160 ["Context -> Unified" diff-context->unified t]
161 ["Unified -> Context" diff-unified->context t]
162 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
165 (defcustom diff-minor-mode-prefix "\C-c="
166 "Prefix key for `diff-minor-mode' commands."
168 :type '(choice (string "\e") (string "C-c=") string))
170 (easy-mmode-defmap diff-minor-mode-map
171 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
172 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
176 ;;;; font-lock support
179 (defface diff-header-face
180 '((((type tty pc) (class color) (background light))
181 (:foreground "blue1" :bold t))
182 (((type tty pc) (class color) (background dark))
183 (:foreground "green" :bold t))
184 (((class color) (background light))
185 (:background "grey85"))
186 (((class color) (background dark))
187 (:background "grey45"))
189 "`diff-mode' face inherited by hunk and index header faces."
191 (defvar diff-header-face 'diff-header-face)
193 (defface diff-file-header-face
194 '((((type tty pc) (class color) (background light))
195 (:foreground "yellow" :bold t))
196 (((type tty pc) (class color) (background dark))
197 (:foreground "cyan" :bold t))
198 (((class color) (background light))
199 (:background "grey70" :bold t))
200 (((class color) (background dark))
201 (:background "grey60" :bold t))
202 (t (:bold t))) ; :height 1.3
203 "`diff-mode' face used to highlight file header lines."
205 (defvar diff-file-header-face 'diff-file-header-face)
207 (defface diff-index-face
208 '((t (:inherit diff-file-header-face)))
209 "`diff-mode' face used to highlight index header lines."
211 (defvar diff-index-face 'diff-index-face)
213 (defface diff-hunk-header-face
214 '((t (:inherit diff-header-face)))
215 "`diff-mode' face used to highlight hunk header lines."
217 (defvar diff-hunk-header-face 'diff-hunk-header-face)
219 (defface diff-removed-face
220 '((t (:inherit diff-changed-face)))
221 "`diff-mode' face used to highlight removed lines."
223 (defvar diff-removed-face 'diff-removed-face)
225 (defface diff-added-face
226 '((t (:inherit diff-changed-face)))
227 "`diff-mode' face used to highlight added lines."
229 (defvar diff-added-face 'diff-added-face)
231 (defface diff-changed-face
232 '((((type tty pc) (class color) (background light))
233 (:foreground "magenta" :bold t :italic t))
234 (((type tty pc) (class color) (background dark))
235 (:foreground "yellow" :bold t :italic t))
237 "`diff-mode' face used to highlight changed lines."
239 (defvar diff-changed-face 'diff-changed-face)
241 (defface diff-function-face
242 '((t (:inherit diff-context-face)))
243 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
245 (defvar diff-function-face 'diff-function-face)
247 (defface diff-context-face
248 '((((class color) (background light))
249 (:foreground "grey50"))
250 (((class color) (background dark))
251 (:foreground "grey70"))
253 "`diff-mode' face used to highlight context and other side-information."
255 (defvar diff-context-face 'diff-context-face)
257 (defface diff-nonexistent-face
258 '((t (:inherit diff-file-header-face)))
259 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
261 (defvar diff-nonexistent-face 'diff-nonexistent-face)
263 (defvar diff-font-lock-keywords
264 '(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
265 (1 diff-hunk-header-face)
266 (2 diff-function-face))
267 ("^--- .+ ----$" . diff-hunk-header-face) ;context
268 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
269 (1 diff-hunk-header-face)
270 (2 diff-function-face))
271 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
272 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
273 (0 diff-header-face) (2 diff-file-header-face prepend))
274 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face)
275 ("^!.*\n" . diff-changed-face) ;context
276 ("^[+>].*\n" . diff-added-face)
277 ("^[-<].*\n" . diff-removed-face)
278 ("^Index: \\(.+\\).*\n" (0 diff-header-face) (1 diff-index-face prepend))
279 ("^Only in .*\n" . diff-nonexistent-face)
280 ("^#.*" . font-lock-string-face)
281 ("^[^-=+*!<>].*\n" . diff-context-face)))
283 (defconst diff-font-lock-defaults
284 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
286 (defvar diff-imenu-generic-expression
287 ;; Prefer second name as first is most likely to be a backup or
288 ;; version-control name. The [\t\n] at the end of the unidiff pattern
289 ;; catches Debian source diff files (which lack the trailing date).
290 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
291 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
297 (defvar diff-file-regexp-alist
298 '(("Index: \\(.+\\)" 1)))
300 (defvar diff-error-regexp-alist
301 '(("@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@" nil 2)
302 ("--- \\([0-9]+\\),[0-9]+ ----" nil 1)
303 ("\\([0-9]+\\)\\(,[0-9]+\\)?[adc]\\([0-9]+\\)" nil 3)))
309 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
310 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+\\|\\*\\*\\* .+\n---\\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
311 (defvar diff-narrowed-to nil)
313 (defun diff-end-of-hunk (&optional style)
314 (if (looking-at diff-hunk-header-re) (goto-char (match-end 0)))
315 (let ((end (and (re-search-forward (case style
316 (unified "^[^-+# \\]")
317 (context "^[^-+#! \\]")
321 (match-beginning 0))))
322 ;; The return value is used by easy-mmode-define-navigation.
323 (goto-char (or end (point-max)))))
325 (defun diff-beginning-of-hunk ()
327 (unless (looking-at diff-hunk-header-re)
330 (re-search-backward diff-hunk-header-re)
331 (error (error "Can't find the beginning of the hunk")))))
333 (defun diff-beginning-of-file ()
335 (unless (looking-at diff-file-header-re)
338 (re-search-backward diff-file-header-re)
339 (error (error "Can't find the beginning of the file")))))
341 (defun diff-end-of-file ()
342 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
343 (re-search-forward "^[^-+#!<>0-9@* \\]" nil 'move)
346 ;; Define diff-{hunk,file}-{prev,next}
347 (easy-mmode-define-navigation
348 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk)
349 (easy-mmode-define-navigation
350 diff-file diff-file-header-re "file" diff-end-of-hunk)
352 (defun diff-restrict-view (&optional arg)
353 "Restrict the view to the current hunk.
354 If the prefix ARG is given, restrict the view to the current file instead."
357 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk))
358 (narrow-to-region (point)
359 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
361 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
364 (defun diff-hunk-kill ()
367 (diff-beginning-of-hunk)
368 (let ((start (point))
369 (firsthunk (save-excursion
371 (diff-beginning-of-file) (diff-hunk-next) (point))))
372 (nexthunk (save-excursion
374 (diff-hunk-next) (point))))
375 (nextfile (save-excursion
377 (diff-file-next) (point)))))
378 (if (and firsthunk (= firsthunk start)
380 (and nextfile (> nexthunk nextfile))))
381 ;; we're the only hunk for this file, so kill the file
384 (kill-region start (point)))))
386 (defun diff-file-kill ()
387 "Kill current file's hunks."
389 (diff-beginning-of-file)
390 (let* ((start (point))
391 (prevhunk (save-excursion
393 (diff-hunk-prev) (point))))
394 (index (save-excursion
395 (re-search-backward "^Index: " prevhunk t))))
396 (when index (setq start index))
398 (kill-region start (point))))
400 (defun diff-kill-junk ()
401 "Kill spurious empty diffs."
404 (let ((inhibit-read-only t))
405 (goto-char (point-min))
406 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
407 "\\([^-+!* <>].*\n\\)*?"
408 "\\(\\(Index:\\) \\|"
409 diff-file-header-re "\\)")
411 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
413 (beginning-of-line)))))
415 (defun diff-count-matches (re start end)
419 (while (re-search-forward re end t) (incf n))
422 (defun diff-split-hunk ()
423 "Split the current (unified diff) hunk at point into two hunks."
427 (start (progn (diff-beginning-of-hunk) (point))))
428 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
429 (error "diff-split-hunk only works on unified context diffs"))
431 (let* ((start1 (string-to-number (match-string 1)))
432 (start2 (string-to-number (match-string 2)))
433 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
434 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos))))
436 ;; Hopefully the after-change-function will not screw us over.
437 (insert "@@ -" (number-to-string newstart1) ",1 +"
438 (number-to-string newstart2) ",1 @@\n")
439 ;; Fix the original hunk-header.
440 (diff-fixup-modifs start pos))))
444 ;;;; jump to other buffers
447 (defvar diff-remembered-files-alist nil)
449 (defun diff-filename-drop-dir (file)
450 (when (string-match "/" file) (substring file (match-end 0))))
452 (defun diff-merge-strings (ancestor from to)
453 "Merge the diff between ANCESTOR and FROM into TO.
454 Returns the merged string if successful or nil otherwise.
455 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
456 If ANCESTOR = FROM, returns TO.
457 If ANCESTOR = TO, returns FROM.
458 The heuristic is simplistic and only really works for cases
459 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
461 ;; AMB ANB CMD -> CND
462 ;; but that's ambiguous if `foo' or `bar' is empty:
463 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
464 (let ((str (concat ancestor "\n" from "\n" to)))
465 (when (and (string-match (concat
466 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
468 "\\(.*\\(\\2\\).*\\)\\'") str)
469 (equal to (match-string 5 str)))
470 (concat (substring str (match-beginning 5) (match-beginning 6))
472 (substring str (match-end 6) (match-end 5))))))
474 (defun diff-find-file-name (&optional old)
475 "Return the file corresponding to the current patch.
476 Non-nil OLD means that we want the old file."
478 (unless (looking-at diff-file-header-re)
479 (or (ignore-errors (diff-beginning-of-file))
480 (re-search-forward diff-file-header-re nil t)))
481 (let* ((limit (save-excursion
483 (progn (diff-hunk-prev) (point))
484 (error (point-min)))))
486 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
487 (list (if old (match-string 1) (match-string 3))
488 (if old (match-string 3) (match-string 1)))
489 (forward-line 1) nil))
491 (when (save-excursion
492 (re-search-backward "^Index: \\(.+\\)" limit t))
493 (list (match-string 1)))
495 (when (re-search-backward "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?" nil t)
496 (list (if old (match-string 2) (match-string 4))
497 (if old (match-string 4) (match-string 2))))))
500 ;; use any previously used preference
501 (cdr (assoc fs diff-remembered-files-alist))
502 ;; try to be clever and use previous choices as an inspiration
503 (dolist (rf diff-remembered-files-alist)
504 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
505 (if (and newfile (file-exists-p newfile)) (return newfile))))
506 ;; look for each file in turn. If none found, try again but
507 ;; ignoring the first level of directory, ...
508 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
511 (setq file (do* ((files files (cdr files))
512 (file (car files) (car files)))
513 ((or (null file) (file-exists-p file))
516 ;; <foo>.rej patches implicitly apply to <foo>
517 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
518 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
519 (when (file-exists-p file) file)))
520 ;; if all else fails, ask the user
521 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
522 nil (first fs) t (first fs))))
523 (set (make-local-variable 'diff-remembered-files-alist)
524 (cons (cons fs file) diff-remembered-files-alist))
528 (defun diff-mouse-goto-source (event)
529 "Run `diff-goto-source' for the diff at a mouse click."
532 (mouse-set-point event)
536 (defun diff-ediff-patch ()
537 "Call `ediff-patch-file' on the current buffer."
540 (ediff-patch-file nil (current-buffer))
541 (wrong-number-of-arguments (ediff-patch-file))))
544 ;;;; Conversion functions
547 ;;(defvar diff-inhibit-after-change nil
548 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
550 (defun diff-unified->context (start end)
551 "Convert unified diffs to context diffs.
552 START and END are either taken from the region (if a prefix arg is given) or
553 else cover the whole bufer."
554 (interactive (if current-prefix-arg
555 (list (mark) (point))
556 (list (point-min) (point-max))))
557 (unless (markerp end) (setq end (copy-marker end)))
558 (let (;;(diff-inhibit-after-change t)
559 (inhibit-read-only t))
562 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
564 (combine-after-change-calls
565 (if (match-beginning 2)
566 ;; we matched a file header
568 ;; use reverse order to make sure the indices are kept valid
569 (replace-match "---" t t nil 3)
570 (replace-match "***" t t nil 2))
571 ;; we matched a hunk header
572 (let ((line1 (match-string 4))
573 (lines1 (match-string 5))
574 (line2 (match-string 6))
575 (lines2 (match-string 7)))
577 (concat "***************\n*** " line1 ","
578 (number-to-string (+ (string-to-number line1)
579 (string-to-number lines1)
583 (narrow-to-region (point)
584 (progn (diff-end-of-hunk 'unified) (point)))
585 (let ((hunk (buffer-string)))
586 (goto-char (point-min))
587 (if (not (save-excursion (re-search-forward "^-" nil t)))
588 (delete-region (point) (point-max))
589 (goto-char (point-max))
590 (let ((modif nil) last-pt)
591 (while (progn (setq last-pt (point))
592 (= (forward-line -1) 0))
594 (? (insert " ") (setq modif nil) (backward-char 1))
595 (?+ (delete-region (point) last-pt) (setq modif t))
597 (progn (forward-char 1)
602 (?\\ (when (save-excursion (forward-line -1)
604 (delete-region (point) last-pt) (setq modif t)))
605 (t (setq modif nil))))))
606 (goto-char (point-max))
608 (insert "--- " line2 ","
609 (number-to-string (+ (string-to-number line2)
610 (string-to-number lines2)
611 -1)) " ----\n" hunk))
612 ;;(goto-char (point-min))
614 (if (not (save-excursion (re-search-forward "^+" nil t)))
615 (delete-region (point) (point-max))
616 (let ((modif nil) (delete nil))
619 (? (insert " ") (setq modif nil) (backward-char 1))
620 (?- (setq delete t) (setq modif t))
622 (progn (forward-char 1)
627 (?\\ (when (save-excursion (forward-line 1)
629 (setq delete t) (setq modif t)))
630 (t (setq modif nil)))
631 (let ((last-pt (point)))
634 (delete-region last-pt (point))
635 (setq delete nil)))))))))))))))
637 (defun diff-context->unified (start end)
638 "Convert context diffs to unified diffs.
639 START and END are either taken from the region (if a prefix arg is given) or
640 else cover the whole bufer."
641 (interactive (if current-prefix-arg
642 (list (mark) (point))
643 (list (point-min) (point-max))))
644 (unless (markerp end) (setq end (copy-marker end)))
645 (let (;;(diff-inhibit-after-change t)
646 (inhibit-read-only t))
649 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
651 (combine-after-change-calls
652 (if (match-beginning 2)
653 ;; we matched a file header
655 ;; use reverse order to make sure the indices are kept valid
656 (replace-match "+++" t t nil 3)
657 (replace-match "---" t t nil 2))
658 ;; we matched a hunk header
659 (let ((line1s (match-string 4))
660 (line1e (match-string 5))
661 (pt1 (match-beginning 0)))
663 (unless (re-search-forward
664 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
665 (error "Can't find matching `--- n1,n2 ----' line"))
666 (let ((line2s (match-string 1))
667 (line2e (match-string 2))
669 (delete-region (progn (beginning-of-line) (point))
670 (progn (forward-line 1) (point)))
674 (while (< (point) pt2)
676 ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
677 (?\ ;merge with the other half of the chunk
680 (goto-char pt2) (forward-line 1) (point)))
681 (c (char-after pt2)))
685 (prog1 (buffer-substring (+ pt2 2) endline2)
686 (delete-region pt2 endline2))))
687 (?\ ;FIXME: check consistency
688 (delete-region pt2 endline2)
691 (?\\ (forward-line 1))
692 (t (delete-char 1) (forward-line 1)))))
693 (t (forward-line 1))))
694 (while (looking-at "[+! ] ")
695 (if (/= (char-after) ?!) (forward-char 1)
696 (delete-char 1) (insert "+"))
697 (delete-char 1) (forward-line 1))
700 (insert "@@ -" line1s ","
701 (number-to-string (- (string-to-number line1e)
702 (string-to-number line1s)
705 (number-to-string (- (string-to-number line2e)
706 (string-to-number line2s)
709 (defun diff-reverse-direction (start end)
710 "Reverse the direction of the diffs.
711 START and END are either taken from the region (if a prefix arg is given) or
712 else cover the whole bufer."
713 (interactive (if current-prefix-arg
714 (list (mark) (point))
715 (list (point-min) (point-max))))
716 (unless (markerp end) (setq end (copy-marker end)))
717 (let (;;(diff-inhibit-after-change t)
718 (inhibit-read-only t))
721 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
723 (combine-after-change-calls
726 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
727 ;; a context-diff hunk header
729 (let ((pt-lines1 (match-beginning 6))
730 (lines1 (match-string 6)))
731 (replace-match "" nil nil nil 6)
733 (let ((half1s (point)))
734 (while (looking-at "[-! \\][ \t]\\|#")
735 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
737 (let ((half1 (delete-and-extract-region half1s (point))))
738 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
740 (error "Can't find matching `--- n1,n2 ----' line"))
741 (let ((str1 (match-string 1)))
742 (replace-match lines1 nil nil nil 1)
744 (let ((half2s (point)))
745 (while (looking-at "[!+ \\][ \t]\\|#")
746 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
748 (let ((half2 (delete-and-extract-region half2s (point))))
749 (insert (or half1 ""))
751 (insert (or half2 ""))))
752 (goto-char pt-lines1)
754 ;; a unified-diff hunk header
756 (replace-match "@@ -\\8 +\\7 @@" nil)
758 (let ((c (char-after)) first last)
759 (while (case (setq c (char-after))
760 (?- (setq first (or first (point)))
761 (delete-char 1) (insert "+") t)
762 (?+ (setq last (or last (point)))
763 (delete-char 1) (insert "-") t)
765 (t (when (and first last (< first last))
768 (delete-and-extract-region first last))))
770 (setq first nil last nil)
772 (forward-line 1))))))))))
774 (defun diff-fixup-modifs (start end)
775 "Fixup the hunk headers (in case the buffer was modified).
776 START and END are either taken from the region (if a prefix arg is given) or
777 else cover the whole bufer."
778 (interactive (if current-prefix-arg
779 (list (mark) (point))
780 (list (point-min) (point-max))))
781 (let ((inhibit-read-only t))
783 (goto-char end) (diff-end-of-hunk)
784 (let ((plus 0) (minus 0) (space 0) (bang 0))
785 (while (and (= (forward-line -1) 0) (<= start (point)))
786 (if (not (looking-at "\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|[-*][-*][-*] .+ [-*][-*][-*][-*]\\)$"))
793 (t (setq space 0 plus 0 minus 0 bang 0)))
795 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
796 (let* ((old1 (match-string 1))
797 (old2 (match-string 2))
798 (new1 (number-to-string (+ space minus)))
799 (new2 (number-to-string (+ space plus))))
800 (unless (string= new2 old2) (replace-match new2 t t nil 2))
801 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
802 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
803 (when (> (+ space bang plus) 0)
804 (let* ((old1 (match-string 1))
805 (old2 (match-string 2))
806 (new (number-to-string
807 (+ space bang plus -1 (string-to-number old1)))))
808 (unless (string= new old2) (replace-match new t t nil 2)))))
809 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
810 (when (> (+ space bang minus) 0)
811 (let* ((old (match-string 1))
813 (concat "%0" (number-to-string (length old)) "d")
814 (+ space bang minus -1 (string-to-number old)))))
815 (unless (string= new old) (replace-match new t t nil 2))))))
816 (setq space 0 plus 0 minus 0 bang 0)))))))
822 (defun diff-write-contents-hooks ()
823 "Fixup hunk headers if necessary."
824 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
827 ;; It turns out that making changes in the buffer from within an
828 ;; *-change-function is asking for trouble, whereas making them
829 ;; from a post-command-hook doesn't pose much problems
830 (defvar diff-unhandled-changes nil)
831 (defun diff-after-change-function (beg end len)
832 "Remember to fixup the hunk header.
833 See `after-change-functions' for the meaning of BEG, END and LEN."
834 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
835 ;; incorrect, but it turns out that inhibit-read-only is normally not set
836 ;; inside editing commands, while it tends to be set when the buffer gets
837 ;; updated by an async process or by a conversion function, both of which
838 ;; would rather not be uselessly slowed down by this hook.
839 (when (and (not undo-in-progress) (not inhibit-read-only))
840 (if diff-unhandled-changes
841 (setq diff-unhandled-changes
842 (cons (min beg (car diff-unhandled-changes))
843 (max beg (cdr diff-unhandled-changes))))
844 (setq diff-unhandled-changes (cons beg end)))))
846 (defun diff-post-command-hook ()
847 "Fixup hunk headers if necessary."
848 (when (consp diff-unhandled-changes)
851 (goto-char (car diff-unhandled-changes))
852 (unless (ignore-errors
853 (diff-beginning-of-hunk)
856 (> (point) (car diff-unhandled-changes))))
857 (goto-char (car diff-unhandled-changes))
858 (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
859 (diff-beginning-of-hunk))
860 (diff-fixup-modifs (point) (cdr diff-unhandled-changes))))
861 (setq diff-unhandled-changes nil)))
864 ;;;; The main function
868 (define-derived-mode diff-mode fundamental-mode "Diff"
869 "Major mode for viewing/editing context diffs.
870 Supports unified and context diffs as well as (to a lesser extent)
872 When the buffer is read-only, the ESC prefix is not necessary."
873 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
874 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
875 (set (make-local-variable 'imenu-generic-expression)
876 diff-imenu-generic-expression)
877 ;; These are not perfect. They would be better done separately for
878 ;; context diffs and unidiffs.
879 ;; (set (make-local-variable 'paragraph-start)
880 ;; (concat "@@ " ; unidiff hunk
881 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
882 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
883 ;; ; start (first or second line)
884 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
885 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
888 ;;;; compile support is not good enough yet. Also it can be annoying
889 ;; and should thus only be enabled conditionally.
890 ;; (set (make-local-variable 'compilation-file-regexp-alist)
891 ;; diff-file-regexp-alist)
892 ;; (set (make-local-variable 'compilation-error-regexp-alist)
893 ;; diff-error-regexp-alist)
894 ;; (when (string-match "\\.rej\\'" (or buffer-file-name ""))
895 ;; (set (make-local-variable 'compilation-current-file)
896 ;; (substring buffer-file-name 0 (match-beginning 0))))
897 ;; (compilation-shell-minor-mode 1)
899 (when (and (> (point-max) (point-min)) diff-default-read-only)
900 (toggle-read-only t))
901 ;; setup change hooks
902 (if (not diff-update-on-the-fly)
903 (add-hook 'write-contents-hooks 'diff-write-contents-hooks)
904 (make-local-variable 'diff-unhandled-changes)
905 (add-hook 'after-change-functions 'diff-after-change-function nil t)
906 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
907 ;; Neat trick from Dave Love to add more bindings in read-only mode:
908 (add-to-list (make-local-variable 'minor-mode-overriding-map-alist)
909 (cons 'buffer-read-only diff-mode-shared-map))
911 (set (make-local-variable 'add-log-current-defun-function)
913 (set (make-local-variable 'add-log-buffer-file-name-function)
914 'diff-find-file-name))
917 (define-minor-mode diff-minor-mode
918 "Minor mode for viewing/editing context diffs.
919 \\{diff-minor-mode-map}"
921 ;; FIXME: setup font-lock
922 ;; setup change hooks
923 (if (not diff-update-on-the-fly)
924 (add-hook 'write-contents-hooks 'diff-write-contents-hooks)
925 (make-local-variable 'diff-unhandled-changes)
926 (add-hook 'after-change-functions 'diff-after-change-function nil t)
927 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
931 ;;; Misc operations that have proved useful at some point.
934 (defun diff-next-complex-hunk ()
935 "Jump to the next \"complex\" hunk.
936 \"Complex\" is approximated by \"the hunk changes the number of lines\".
937 Only works for unified diffs."
940 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
942 (equal (match-string 1) (match-string 2)))))
944 (defun diff-hunk-text (hunk destp &optional char-offset)
945 "Return the literal source text from HUNK.
946 if DESTP is nil return the source, otherwise the destination text.
947 If CHAR-OFFSET is non-nil, it should be a char-offset in
948 HUNK, and instead of a string, a cons cell is returned whose car is the
949 appropriate text, and whose cdr is the corresponding char-offset in that text."
952 (goto-char (point-min))
957 ;; Set the following variables:
958 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
959 ;; DST-POS buffer pos of the destination part of the hunk or nil
960 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
961 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
962 (cond ((looking-at "^@@")
964 (setq num-pfx-chars 1)
966 (setq src-pos (point) dst-pos (point)))
967 ((looking-at "^\\*\\*")
970 (setq src-pos (point))
971 (re-search-forward "^--- " nil t)
973 (setq divider-pos (point))
975 (setq dst-pos (point)))
976 ((looking-at "^[0-9]+a[0-9,]+$")
977 ;; normal diff, insert
979 (setq dst-pos (point)))
980 ((looking-at "^[0-9,]+d[0-9]+$")
981 ;; normal diff, delete
983 (setq src-pos (point)))
984 ((looking-at "^[0-9,]+c[0-9,]+$")
985 ;; normal diff, change
987 (setq src-pos (point))
988 (re-search-forward "^---$" nil t)
990 (setq divider-pos (point))
992 (setq dst-pos (point)))
994 (error "Unknown diff hunk type")))
996 (if (if destp (null dst-pos) (null src-pos))
997 ;; Implied empty text
998 (if char-offset '("" . 0) "")
1000 ;; For context diffs, either side can be empty, (if there's only
1001 ;; added or only removed text). We should then use the other side.
1002 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1003 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1005 (when char-offset (goto-char (+ (point-min) char-offset)))
1007 ;; Get rid of anything except the desired text.
1009 ;; Delete unused text region
1010 (let ((keep (if destp dst-pos src-pos)))
1011 (when (and divider-pos (> divider-pos keep))
1012 (delete-region divider-pos (point-max)))
1013 (delete-region (point-min) keep))
1014 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1015 (let ((kill-char (if destp ?- ?+)))
1016 (goto-char (point-min))
1018 (if (eq (char-after) kill-char)
1019 (delete-region (point) (progn (forward-line 1) (point)))
1020 (delete-char num-pfx-chars)
1021 (forward-line 1)))))
1023 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1024 (if char-offset (cons text (- (point) (point-min))) text))))))
1027 (defun diff-find-text (text)
1028 "Return the buffer position of the nearest occurrence of TEXT.
1029 If TEXT isn't found, nil is returned."
1030 (let* ((orig (point))
1031 (forw (and (search-forward text nil t)
1032 (match-beginning 0)))
1033 (back (and (goto-char (+ orig (length text)))
1034 (search-backward text nil t)
1035 (match-beginning 0))))
1036 ;; Choose the closest match.
1038 (if (> (- forw orig) (- orig back)) back forw)
1041 (defsubst diff-xor (a b) (if a (not b) b))
1043 (defun diff-find-source-location (&optional other-file reverse)
1044 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED)."
1046 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1047 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1048 (hunk (buffer-substring (point)
1049 (save-excursion (diff-end-of-hunk) (point))))
1050 (old (diff-hunk-text hunk reverse char-offset))
1051 (new (diff-hunk-text hunk (not reverse) char-offset))
1052 ;; Find the location specification.
1053 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1054 (error "Can't find the hunk header")
1055 (if other (match-string 1)
1056 (if (match-end 3) (match-string 3)
1057 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1058 (error "Can't find the hunk separator"))
1059 (match-string 1)))))
1060 (file (or (diff-find-file-name other) (error "Can't find the file")))
1061 (buf (find-file-noselect file)))
1062 ;; Update the user preference if he so wished.
1063 (when (> (prefix-numeric-value other-file) 8)
1064 (setq diff-jump-to-old-file other))
1065 (with-current-buffer buf
1066 (goto-line (string-to-number line))
1067 (let* ((orig-pos (point))
1068 (pos (diff-find-text (car old)))
1071 (setq pos (diff-find-text (car new)) switched t))
1074 (if pos (list (count-lines orig-pos pos) pos) (list nil orig-pos))
1075 (if switched (list new old t) (list old new))))))))
1078 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1079 (let ((msg (if dry-run
1080 (if reversed "already applied" "not yet applied")
1081 (if reversed "undone" "applied"))))
1082 (message (cond ((null line-offset) "Hunk text not found")
1083 ((= line-offset 0) "Hunk %s")
1084 ((= line-offset 1) "Hunk %s at offset %d line")
1085 (t "Hunk %s at offset %d lines"))
1089 (defun diff-apply-hunk (&optional reverse)
1090 "Apply the current hunk to the source file and go to the next.
1091 By default, the new source file is patched, but if the variable
1092 `diff-jump-to-old-file' is non-nil, then the old source file is
1093 patched instead (some commands, such as `diff-goto-source' can change
1094 the value of this variable when given an appropriate prefix argument).
1096 With a prefix argument, REVERSE the hunk."
1098 (destructuring-bind (buf line-offset pos old new &optional switched)
1099 (diff-find-source-location nil reverse)
1102 (error "Can't find the text to patch"))
1104 ;; A reversed patch was detected, perhaps apply it in reverse.
1105 (not (save-window-excursion
1107 (goto-char (+ pos (cdr old)))
1110 "Hunk hasn't been applied yet; apply it now? "
1111 "Hunk has already been applied; undo it? ")))))
1112 (message "(Nothing done)"))
1115 (with-current-buffer buf
1117 (delete-char (length (car old)))
1119 ;; Display BUF in a window
1120 (set-window-point (display-buffer buf) (+ pos (cdr new)))
1121 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1122 (when diff-advance-after-apply-hunk
1123 (diff-hunk-next))))))
1126 (defun diff-test-hunk (&optional reverse)
1127 "See whether it's possible to apply the current hunk.
1128 With a prefix argument, try to REVERSE the hunk."
1130 (destructuring-bind (buf line-offset pos src dst &optional switched)
1131 (diff-find-source-location nil reverse)
1132 (set-window-point (display-buffer buf) (+ pos (cdr src)))
1133 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1136 (defun diff-goto-source (&optional other-file)
1137 "Jump to the corresponding source line.
1138 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1139 is given) determines whether to jump to the old or the new file.
1140 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1141 then `diff-jump-to-old-file' is also set, for the next invocations."
1143 ;; When pointing at a removal line, we probably want to jump to
1144 ;; the old location, and else to the new (i.e. as if reverting).
1145 ;; This is a convenient detail when using smerge-diff.
1146 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1147 (destructuring-bind (buf line-offset pos src dst &optional switched)
1148 (diff-find-source-location other-file rev)
1150 (goto-char (+ pos (cdr src)))
1151 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1154 (defun diff-current-defun ()
1155 "Find the name of function at point.
1156 For use in `add-log-current-defun-function'."
1157 (destructuring-bind (buf line-offset pos src dst &optional switched)
1158 (diff-find-source-location)
1161 (or (when (memq (char-after) '(?< ?-))
1162 ;; Cursor is pointing at removed text. This could be a removed
1163 ;; function, in which case, going to the source buffer will
1164 ;; not help since the function is now removed. Instead,
1165 ;; try to figure out the function name just from the code-fragment.
1166 (let ((old (if switched dst src)))
1169 (goto-char (cdr old))
1170 (funcall (with-current-buffer buf major-mode))
1171 (add-log-current-defun))))
1172 (with-current-buffer buf
1173 (goto-char (+ pos (cdr src)))
1174 (add-log-current-defun))))))
1176 ;; provide the package
1177 (provide 'diff-mode)
1179 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1180 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1181 ;; (diff-mode-load-hook): dropped.
1182 ;; (auto-mode-alist): also catch *.diffs.
1183 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1184 ;; for *.rej files (that lack any file name indication).
1186 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1187 ;; added support for "\ No newline at end of file".
1189 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1190 ;; - added basic `compile' support.
1191 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1192 ;; - diff-kill-file now tries to kill the leading garbage as well.
1194 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1195 ;; - don't use CL in the autoloaded code
1196 ;; - accept diffs using -T
1198 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1199 ;; interface to ediff-patch
1201 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1202 ;; (ediff=patch-file): add bindings to call ediff-patch.
1203 ;; (diff-find-file-name): taken out of diff-goto-source.
1204 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1205 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1207 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1208 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1210 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1211 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1214 ;;; diff-mode.el ends here