1 ;;; diff-mode.el --- A mode for viewing/editing context diffs
3 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@cs.yale.edu>
6 ;; Keywords: patch diff
7 ;; Revision: $Id: diff-mode.el,v 1.26 2000/10/02 06:49:21 miles Exp $
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
28 ;; Provides support for font-lock patterns, outline-regexps, navigation
29 ;; commands, editing and various conversions as well as jumping
30 ;; to the corresponding source file.
32 ;; inspired by Pavel Machek's patch-mode.el (<pavel@atrey.karlin.mff.cuni.cz>)
33 ;; some efforts were spent to have it somewhat compatible with XEmacs'
34 ;; diff-mode as well as with compilation-minor-mode
36 ;; to use it, simply add to your .emacs the following lines:
38 ;; (autoload 'diff-mode "diff-mode" "Diff major mode" t)
39 ;; (add-to-list 'auto-mode-alist '("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode))
43 ;; - Reverse doesn't work with normal diffs.
47 ;; - Spice up the minor-mode with font-lock support.
48 ;; - Improve narrowed-view support.
49 ;; - Improve the `compile' support (?).
50 ;; - Recognize pcl-cvs' special string for `cvs-execute-single'.
51 ;; - Support for # comments in context->unified.
52 ;; - Do a fuzzy search in diff-goto-source.
53 ;; - Allow diff.el to use diff-mode.
54 ;; This mostly means ability to jump from half-hunk to half-hunk
55 ;; in context (and normal) diffs and to jump to the corresponding
56 ;; (i.e. new or old) file.
57 ;; - Handle `diff -b' output in context->unified.
61 (eval-when-compile (require 'cl
))
64 (defgroup diff-mode
()
65 "Major mode for viewing/editing diffs"
70 (defcustom diff-jump-to-old-file-flag nil
71 "*Non-nil means `diff-goto-source' jumps to the old file.
72 Else, it jumps to the new file."
76 (defcustom diff-update-on-the-fly-flag t
77 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
78 When editing a diff file, the line numbers in the hunk headers
79 need to be kept consistent with the actual diff. This can
80 either be done on the fly (but this sometimes interacts poorly with the
81 undo mechanism) or whenever the file is written (can be slow
82 when editing big diffs)."
86 (defcustom diff-advance-after-apply-hunk t
87 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
92 (defvar diff-mode-hook nil
93 "Run after setting up the `diff-mode' major mode.")
95 (defvar diff-outline-regexp
96 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
99 ;;;; keymap, menu, ...
102 (easy-mmode-defmap diff-mode-shared-map
103 '(;; From Pavel Machek's patch-mode.
104 ("n" . diff-hunk-next
)
105 ("N" . diff-file-next
)
106 ("p" . diff-hunk-prev
)
107 ("P" . diff-file-prev
)
108 ("k" . diff-hunk-kill
)
109 ("K" . diff-file-kill
)
110 ;; From compilation-minor-mode.
111 ("}" . diff-file-next
)
112 ("{" . diff-file-prev
)
113 ("\C-m" . diff-goto-source
)
114 ([mouse-2
] . diff-mouse-goto-source
)
115 ;; From XEmacs' diff-mode.
117 ;;("." . diff-goto-source) ;display-buffer
118 ;;("f" . diff-goto-source) ;find-file
119 ("o" . diff-goto-source
) ;other-window
120 ;;("w" . diff-goto-source) ;other-frame
121 ;;("N" . diff-narrow)
122 ;;("h" . diff-show-header)
123 ;;("j" . diff-show-difference) ;jump to Nth diff
126 ("\177" . scroll-down
)
127 ;; Our very own bindings.
128 ("A" . diff-ediff-patch
)
129 ("r" . diff-restrict-view
)
130 ("R" . diff-reverse-direction
)
131 ("U" . diff-context-
>unified
)
132 ("C" . diff-unified-
>context
))
133 "Basic keymap for `diff-mode', bound to various prefix keys.")
135 (easy-mmode-defmap diff-mode-map
136 `(("\e" .
,diff-mode-shared-map
)
137 ;; From compilation-minor-mode.
138 ("\C-c\C-c" . diff-goto-source
)
140 ("\C-c\C-a" . diff-apply-hunk
)
141 ("\C-c\C-t" . diff-test-hunk
))
142 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
144 (easy-menu-define diff-mode-menu diff-mode-map
145 "Menu for `diff-mode'."
147 ["Jump to Source" diff-goto-source t
]
148 ["Apply with Ediff" diff-ediff-patch t
]
150 ["Reverse direction" diff-reverse-direction t
]
151 ["Context -> Unified" diff-context-
>unified t
]
152 ["Unified -> Context" diff-unified-
>context t
]
153 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
156 (defcustom diff-minor-mode-prefix
"\C-c="
157 "Prefix key for `diff-minor-mode' commands."
159 :type
'(choice (string "\e") (string "C-c=") string
))
161 (easy-mmode-defmap diff-minor-mode-map
162 `((,diff-minor-mode-prefix .
,diff-mode-shared-map
))
163 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
167 ;;;; font-lock support
170 (defface diff-header-face
171 '((((class color
) (background light
))
172 (:background
"grey85"))
174 "`diff-mode' face inherited by hunk, file and index header faces."
176 (defvar diff-header-face
'diff-header-face
)
178 (defface diff-file-header-face
179 '((((class color
) (background light
))
180 (:background
"grey70" :bold t
))
181 (t (:bold t
))) ; :height 1.3
182 "`diff-mode' face used to highlight file header lines."
184 (defvar diff-file-header-face
'diff-file-header-face
)
186 (defface diff-index-face
187 '((t (:inherit diff-file-header-face
)))
188 "`diff-mode' face used to highlight index header lines."
190 (defvar diff-index-face
'diff-index-face
)
192 (defface diff-hunk-header-face
193 '((t (:inherit diff-header-face
)))
194 "`diff-mode' face used to highlight hunk header lines."
196 (defvar diff-hunk-header-face
'diff-hunk-header-face
)
198 (defface diff-removed-face
199 '((t (:inherit diff-changed-face
)))
200 "`diff-mode' face used to highlight removed lines."
202 (defvar diff-removed-face
'diff-removed-face
)
204 (defface diff-added-face
205 '((t (:inherit diff-changed-face
)))
206 "`diff-mode' face used to highlight added lines."
208 (defvar diff-added-face
'diff-added-face
)
210 (defface diff-changed-face
212 "`diff-mode' face used to highlight changed lines."
214 (defvar diff-changed-face
'diff-changed-face
)
216 (defface diff-comment-face
217 '((t (:inherit font-lock-comment-face
)))
218 "`diff-mode' face used to highlight context and other side-information."
220 (defvar diff-comment-face
'diff-comment-face
)
222 (defvar diff-font-lock-keywords
223 '(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
224 (1 diff-hunk-header-face
)
225 (2 diff-comment-face
))
226 ("^--- .+ ----$" ;context
227 . diff-hunk-header-face
)
228 ("\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
229 (1 diff-hunk-header-face
)
230 (2 diff-comment-face
))
231 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face
) ;context
232 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
233 (0 diff-header-face
) (2 diff-file-header-face prepend
))
234 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face
)
235 ("^!.*\n" . diff-changed-face
) ;context
236 ("^[+>].*\n" . diff-added-face
)
237 ("^[-<].*\n" . diff-removed-face
)
238 ("^Index: \\(.+\\).*\n" (0 diff-header-face
) (1 diff-index-face prepend
))
239 ("^#.*" . font-lock-string-face
)
240 ("^[^-=+*!<>].*\n" . diff-comment-face
)))
242 (defconst diff-font-lock-defaults
243 '(diff-font-lock-keywords t nil nil nil
(font-lock-multiline . nil
)))
245 (defvar diff-imenu-generic-expression
246 ;; Prefer second name as first is most likely to be a backup or
247 ;; version-control name.
248 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)\t" 1) ; unidiffs
249 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
255 (defvar diff-file-regexp-alist
256 '(("Index: \\(.+\\)" 1)))
258 (defvar diff-error-regexp-alist
259 '(("@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@" nil
2)
260 ("--- \\([0-9]+\\),[0-9]+ ----" nil
1)
261 ("\\([0-9]+\\)\\(,[0-9]+\\)?[adc]\\([0-9]+\\)" nil
3)))
267 (defconst diff-hunk-header-re
"^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
268 (defconst diff-file-header-re
(concat "^\\(--- .+\n\\+\\+\\+\\|\\*\\*\\* .+\n---\\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re
1)))
269 (defvar diff-narrowed-to nil
)
271 (defun diff-end-of-hunk (&optional style
)
272 (if (looking-at diff-hunk-header-re
) (goto-char (match-end 0)))
273 (let ((end (and (re-search-forward (case style
274 (unified "^[^-+# \\]")
275 (context "^[^-+#! \\]")
279 (match-beginning 0))))
280 ;; The return value is used by easy-mmode-define-navigation.
281 (goto-char (or end
(point-max)))))
283 (defun diff-beginning-of-hunk ()
285 (unless (looking-at diff-hunk-header-re
)
288 (re-search-backward diff-hunk-header-re
)
289 (error (error "Can't find the beginning of the hunk")))))
291 (defun diff-beginning-of-file ()
293 (unless (looking-at diff-file-header-re
)
296 (re-search-backward diff-file-header-re
)
297 (error (error "Can't find the beginning of the file")))))
299 (defun diff-end-of-file ()
300 (re-search-forward "^[-+#!<>0-9@* \\]" nil t
)
301 (re-search-forward "^[^-+#!<>0-9@* \\]" nil
'move
)
304 ;; Define diff-{hunk,file}-{prev,next}
305 (easy-mmode-define-navigation
306 diff-hunk diff-hunk-header-re
"hunk" diff-end-of-hunk
)
307 (easy-mmode-define-navigation
308 diff-file diff-file-header-re
"file" diff-end-of-hunk
)
310 (defun diff-restrict-view (&optional arg
)
311 "Restrict the view to the current hunk.
312 If the prefix ARG is given, restrict the view to the current file instead."
315 (if arg
(diff-beginning-of-file) (diff-beginning-of-hunk))
316 (narrow-to-region (point)
317 (progn (if arg
(diff-end-of-file) (diff-end-of-hunk))
319 (set (make-local-variable 'diff-narrowed-to
) (if arg
'file
'hunk
))))
322 (defun diff-hunk-kill ()
325 (diff-beginning-of-hunk)
326 (let ((start (point))
327 (firsthunk (save-excursion
329 (diff-beginning-of-file) (diff-hunk-next) (point))))
330 (nexthunk (save-excursion
332 (diff-hunk-next) (point))))
333 (nextfile (save-excursion
335 (diff-file-next) (point)))))
336 (if (and firsthunk
(= firsthunk start
)
338 (and nextfile
(> nexthunk nextfile
))))
339 ;; we're the only hunk for this file, so kill the file
342 (kill-region start
(point)))))
344 (defun diff-file-kill ()
345 "Kill current file's hunks."
347 (diff-beginning-of-file)
348 (let* ((start (point))
349 (prevhunk (save-excursion
351 (diff-hunk-prev) (point))))
352 (index (save-excursion
353 (re-search-backward "^Index: " prevhunk t
))))
354 (when index
(setq start index
))
356 (kill-region start
(point))))
358 (defun diff-kill-junk ()
359 "Kill spurious empty diffs."
362 (let ((inhibit-read-only t
))
363 (goto-char (point-min))
364 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
365 "\\([^-+!* <>].*\n\\)*?"
366 "\\(\\(Index:\\) \\|"
367 diff-file-header-re
"\\)")
369 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
371 (beginning-of-line)))))
374 ;;;; jump to other buffers
377 (defvar diff-remembered-files-alist nil
)
379 (defun diff-filename-drop-dir (file)
380 (when (string-match "/" file
) (substring file
(match-end 0))))
382 (defun diff-merge-strings (ancestor from to
)
383 "Merge the diff between ANCESTOR and FROM into TO.
384 Returns the merged string if successful or nil otherwise.
385 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
386 If ANCESTOR = FROM, returns TO.
387 If ANCESTOR = TO, returns FROM.
388 The heuristic is simplistic and only really works for cases
389 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
391 ;; AMB ANB CMD -> CND
392 ;; but that's ambiguous if `foo' or `bar' is empty:
393 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
394 (let ((str (concat ancestor
"\n" from
"\n" to
)))
395 (when (and (string-match (concat
396 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
398 "\\(.*\\(\\2\\).*\\)\\'") str
)
399 (equal to
(match-string 5 str
)))
400 (concat (substring str
(match-beginning 5) (match-beginning 6))
402 (substring str
(match-end 6) (match-end 5))))))
404 (defun diff-find-file-name (&optional old
)
405 "Return the file corresponding to the current patch.
406 Non-nil OLD means that we want the old file."
408 (unless (looking-at diff-file-header-re
)
409 (or (ignore-errors (diff-beginning-of-file))
410 (re-search-forward diff-file-header-re nil t
)))
411 (let* ((limit (save-excursion
413 (progn (diff-hunk-prev) (point))
414 (error (point-min)))))
416 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\s-.*\n[-+][-+][-+] \\(\\S-+\\)\\s-.*$")
417 (list (if old
(match-string 1) (match-string 2))
418 (if old
(match-string 2) (match-string 1)))
419 (forward-line 1) nil
))
421 (when (save-excursion
422 (re-search-backward "^Index: \\(.+\\)" limit t
))
423 (list (match-string 1)))
425 (when (re-search-backward "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?" nil t
)
426 (list (if old
(match-string 2) (match-string 4))
427 (if old
(match-string 4) (match-string 2))))))
430 ;; use any previously used preference
431 (cdr (assoc fs diff-remembered-files-alist
))
432 ;; try to be clever and use previous choices as an inspiration
433 (dolist (rf diff-remembered-files-alist
)
434 (let ((newfile (diff-merge-strings (caar rf
) (car fs
) (cdr rf
))))
435 (if (and newfile
(file-exists-p newfile
)) (return newfile
))))
436 ;; look for each file in turn. If none found, try again but
437 ;; ignoring the first level of directory, ...
438 (do* ((files fs
(delq nil
(mapcar 'diff-filename-drop-dir files
)))
441 (setq file
(do* ((files files
(cdr files
))
442 (file (car files
) (car files
)))
443 ((or (null file
) (file-exists-p file
))
446 ;; <foo>.rej patches implicitly apply to <foo>
447 (and (string-match "\\.rej\\'" (or buffer-file-name
""))
448 (let ((file (substring buffer-file-name
0 (match-beginning 0))))
449 (when (file-exists-p file
) file
)))
450 ;; if all else fails, ask the user
451 (let ((file (read-file-name (format "Use file %s: " (or (first fs
) ""))
452 nil
(first fs
) t
(first fs
))))
453 (set (make-local-variable 'diff-remembered-files-alist
)
454 (cons (cons fs file
) diff-remembered-files-alist
))
458 (defun diff-mouse-goto-source (event)
459 "Run `diff-goto-source' for the diff at a mouse click."
462 (mouse-set-point event
)
466 (defun diff-ediff-patch ()
467 "Call `ediff-patch-file' on the current buffer."
470 (ediff-patch-file nil
(current-buffer))
471 (wrong-number-of-arguments (ediff-patch-file))))
474 ;;;; Conversion functions
477 ;;(defvar diff-inhibit-after-change nil
478 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
480 (defun diff-unified->context
(start end
)
481 "Convert unified diffs to context diffs.
482 START and END are either taken from the region (if a prefix arg is given) or
483 else cover the whole bufer."
484 (interactive (if current-prefix-arg
485 (list (mark) (point))
486 (list (point-min) (point-max))))
487 (unless (markerp end
) (setq end
(copy-marker end
)))
488 (let (;;(diff-inhibit-after-change t)
489 (inhibit-read-only t
))
492 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t
)
494 (combine-after-change-calls
495 (if (match-beginning 2)
496 ;; we matched a file header
498 ;; use reverse order to make sure the indices are kept valid
499 (replace-match "---" t t nil
3)
500 (replace-match "***" t t nil
2))
501 ;; we matched a hunk header
502 (let ((line1 (match-string 4))
503 (lines1 (match-string 5))
504 (line2 (match-string 6))
505 (lines2 (match-string 7)))
507 (concat "***************\n*** " line1
","
508 (number-to-string (+ (string-to-number line1
)
509 (string-to-number lines1
)
513 (narrow-to-region (point)
514 (progn (diff-end-of-hunk 'unified
) (point)))
515 (let ((hunk (buffer-string)))
516 (goto-char (point-min))
517 (if (not (save-excursion (re-search-forward "^-" nil t
)))
518 (delete-region (point) (point-max))
519 (goto-char (point-max))
520 (let ((modif nil
) last-pt
)
521 (while (progn (setq last-pt
(point))
522 (= (forward-line -
1) 0))
524 (?
(insert " ") (setq modif nil
) (backward-char 1))
525 (?
+ (delete-region (point) last-pt
) (setq modif t
))
527 (progn (forward-char 1)
532 (?
\\ (when (save-excursion (forward-line -
1)
534 (delete-region (point) last-pt
) (setq modif t
)))
535 (t (setq modif nil
))))))
536 (goto-char (point-max))
538 (insert "--- " line2
","
539 (number-to-string (+ (string-to-number line2
)
540 (string-to-number lines2
)
541 -
1)) " ----\n" hunk
))
542 ;;(goto-char (point-min))
544 (if (not (save-excursion (re-search-forward "^+" nil t
)))
545 (delete-region (point) (point-max))
546 (let ((modif nil
) (delete nil
))
549 (?
(insert " ") (setq modif nil
) (backward-char 1))
550 (?-
(setq delete t
) (setq modif t
))
552 (progn (forward-char 1)
557 (?
\\ (when (save-excursion (forward-line 1)
559 (setq delete t
) (setq modif t
)))
560 (t (setq modif nil
)))
561 (let ((last-pt (point)))
564 (delete-region last-pt
(point))
565 (setq delete nil
)))))))))))))))
567 (defun diff-context->unified
(start end
)
568 "Convert context diffs to unified diffs.
569 START and END are either taken from the region (if a prefix arg is given) or
570 else cover the whole bufer."
571 (interactive (if current-prefix-arg
572 (list (mark) (point))
573 (list (point-min) (point-max))))
574 (unless (markerp end
) (setq end
(copy-marker end
)))
575 (let (;;(diff-inhibit-after-change t)
576 (inhibit-read-only t
))
579 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t
)
581 (combine-after-change-calls
582 (if (match-beginning 2)
583 ;; we matched a file header
585 ;; use reverse order to make sure the indices are kept valid
586 (replace-match "+++" t t nil
3)
587 (replace-match "---" t t nil
2))
588 ;; we matched a hunk header
589 (let ((line1s (match-string 4))
590 (line1e (match-string 5))
591 (pt1 (match-beginning 0)))
593 (unless (re-search-forward
594 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t
)
595 (error "Can't find matching `--- n1,n2 ----' line"))
596 (let ((line2s (match-string 1))
597 (line2e (match-string 2))
599 (delete-region (progn (beginning-of-line) (point))
600 (progn (forward-line 1) (point)))
604 (while (< (point) pt2
)
606 ((?
! ?-
) (delete-char 2) (insert "-") (forward-line 1))
607 (?\
;merge with the other half of the chunk
610 (goto-char pt2
) (forward-line 1) (point)))
611 (c (char-after pt2
)))
615 (prog1 (buffer-substring (+ pt2
2) endline2
)
616 (delete-region pt2 endline2
))))
617 (?\
;FIXME: check consistency
618 (delete-region pt2 endline2
)
621 (?
\\ (forward-line 1))
622 (t (delete-char 1) (forward-line 1)))))
623 (t (forward-line 1))))
624 (while (looking-at "[+! ] ")
625 (if (/= (char-after) ?
!) (forward-char 1)
626 (delete-char 1) (insert "+"))
627 (delete-char 1) (forward-line 1))
630 (insert "@@ -" line1s
","
631 (number-to-string (- (string-to-number line1e
)
632 (string-to-number line1s
)
635 (number-to-string (- (string-to-number line2e
)
636 (string-to-number line2s
)
639 (defun diff-reverse-direction (start end
)
640 "Reverse the direction of the diffs.
641 START and END are either taken from the region (if a prefix arg is given) or
642 else cover the whole bufer."
643 (interactive (if current-prefix-arg
644 (list (mark) (point))
645 (list (point-min) (point-max))))
646 (unless (markerp end
) (setq end
(copy-marker end
)))
647 (let (;;(diff-inhibit-after-change t)
648 (inhibit-read-only t
))
651 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t
)
653 (combine-after-change-calls
656 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil
))
657 ;; a context-diff hunk header
659 (let ((pt-lines1 (match-beginning 6))
660 (lines1 (match-string 6)))
661 (replace-match "" nil nil nil
6)
663 (let ((half1s (point)))
664 (while (looking-at "[-! \\][ \t]\\|#")
665 (when (= (char-after) ?-
) (delete-char 1) (insert "+"))
667 (let ((half1 (delete-and-extract-region half1s
(point))))
668 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
670 (error "Can't find matching `--- n1,n2 ----' line"))
671 (let ((str1 (match-string 1)))
672 (replace-match lines1 nil nil nil
1)
674 (let ((half2s (point)))
675 (while (looking-at "[!+ \\][ \t]\\|#")
676 (when (= (char-after) ?
+) (delete-char 1) (insert "-"))
678 (let ((half2 (delete-and-extract-region half2s
(point))))
679 (insert (or half1
""))
681 (insert (or half2
""))))
682 (goto-char pt-lines1
)
684 ;; a unified-diff hunk header
686 (replace-match "@@ -\\8 +\\7 @@" nil
)
688 (let ((c (char-after)) first last
)
689 (while (case (setq c
(char-after))
690 (?-
(setq first
(or first
(point)))
691 (delete-char 1) (insert "+") t
)
692 (?
+ (setq last
(or last
(point)))
693 (delete-char 1) (insert "-") t
)
695 (t (when (and first last
(< first last
))
698 (delete-and-extract-region first last
))))
700 (setq first nil last nil
)
702 (forward-line 1))))))))))
704 (defun diff-fixup-modifs (start end
)
705 "Fixup the hunk headers (in case the buffer was modified).
706 START and END are either taken from the region (if a prefix arg is given) or
707 else cover the whole bufer."
708 (interactive (if current-prefix-arg
709 (list (mark) (point))
710 (list (point-min) (point-max))))
711 (let ((inhibit-read-only t
))
713 (goto-char end
) (diff-end-of-hunk)
714 (let ((plus 0) (minus 0) (space 0) (bang 0))
715 (while (and (= (forward-line -
1) 0) (<= start
(point)))
716 (if (not (looking-at "\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|[-*][-*][-*] .+ [-*][-*][-*][-*]\\)$"))
723 (t (setq space
0 plus
0 minus
0 bang
0)))
725 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
726 (let* ((old1 (match-string 1))
727 (old2 (match-string 2))
728 (new1 (number-to-string (+ space minus
)))
729 (new2 (number-to-string (+ space plus
))))
730 (unless (string= new2 old2
) (replace-match new2 t t nil
2))
731 (unless (string= new1 old1
) (replace-match new1 t t nil
1))))
732 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
733 (when (> (+ space bang plus
) 0)
734 (let* ((old1 (match-string 1))
735 (old2 (match-string 2))
736 (new (number-to-string
737 (+ space bang plus -
1 (string-to-number old1
)))))
738 (unless (string= new old2
) (replace-match new t t nil
2)))))
739 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
740 (when (> (+ space bang minus
) 0)
741 (let* ((old (match-string 1))
743 (concat "%0" (number-to-string (length old
)) "d")
744 (+ space bang minus -
1 (string-to-number old
)))))
745 (unless (string= new old
) (replace-match new t t nil
2))))))
746 (setq space
0 plus
0 minus
0 bang
0)))))))
752 (defun diff-write-contents-hooks ()
753 "Fixup hunk headers if necessary."
754 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
757 ;; It turns out that making changes in the buffer from within an
758 ;; *-change-function is asking for trouble, whereas making them
759 ;; from a post-command-hook doesn't pose much problems
760 (defvar diff-unhandled-changes nil
)
761 (defun diff-after-change-function (beg end len
)
762 "Remember to fixup the hunk header.
763 See `after-change-functions' for the meaning of BEG, END and LEN."
764 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
765 ;; incorrect, but it turns out that inhibit-read-only is normally not set
766 ;; inside editing commands, while it tends to be set when the buffer gets
767 ;; updated by an async process or by a conversion function, both of which
768 ;; would rather not be uselessly slowed down by this hook.
769 (when (and (not undo-in-progress
) (not inhibit-read-only
))
770 (if diff-unhandled-changes
771 (setq diff-unhandled-changes
772 (cons (min beg
(car diff-unhandled-changes
))
773 (max beg
(cdr diff-unhandled-changes
))))
774 (setq diff-unhandled-changes
(cons beg end
)))))
776 (defun diff-post-command-hook ()
777 "Fixup hunk headers if necessary."
778 (when (consp diff-unhandled-changes
)
781 (goto-char (car diff-unhandled-changes
))
782 (unless (ignore-errors
783 (diff-beginning-of-hunk)
786 (> (point) (car diff-unhandled-changes
))))
787 (goto-char (car diff-unhandled-changes
))
788 (re-search-forward diff-hunk-header-re
(cdr diff-unhandled-changes
))
789 (diff-beginning-of-hunk))
790 (diff-fixup-modifs (point) (cdr diff-unhandled-changes
))))
791 (setq diff-unhandled-changes nil
)))
794 ;;;; The main function
798 (define-derived-mode diff-mode fundamental-mode
"Diff"
799 "Major mode for viewing/editing context diffs.
800 Supports unified and context diffs as well as (to a lesser extent) normal diffs.
801 When the buffer is read-only, the ESC prefix is not necessary.
802 This mode runs `diff-mode-hook'.
804 (set (make-local-variable 'font-lock-defaults
) diff-font-lock-defaults
)
805 (set (make-local-variable 'outline-regexp
) diff-outline-regexp
)
806 (set (make-local-variable 'imenu-generic-expression
)
807 diff-imenu-generic-expression
)
808 ;; These are not perfect. They would be better done separately for
809 ;; context diffs and unidiffs.
810 ;; (set (make-local-variable 'paragraph-start)
811 ;; (concat "@@ " ; unidiff hunk
812 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
813 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
814 ;; ; start (first or second line)
815 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
816 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
818 (set (make-local-variable 'compilation-file-regexp-alist
)
819 diff-file-regexp-alist
)
820 (set (make-local-variable 'compilation-error-regexp-alist
)
821 diff-error-regexp-alist
)
822 (when (string-match "\\.rej\\'" (or buffer-file-name
""))
823 (set (make-local-variable 'compilation-current-file
)
824 (substring buffer-file-name
0 (match-beginning 0))))
825 (compilation-shell-minor-mode 1)
826 ;; setup change hooks
828 (if (not diff-update-on-the-fly-flag
)
829 (add-hook 'write-contents-hooks
'diff-write-contents-hooks
)
830 (make-local-variable 'diff-unhandled-changes
)
831 (add-hook 'after-change-functions
'diff-after-change-function nil t
)
832 (add-hook 'post-command-hook
'diff-post-command-hook nil t
))
833 ;; Neat trick from Dave Love to add more bindings in read-only mode:
834 (add-to-list (make-local-variable 'minor-mode-overriding-map-alist
)
835 (cons 'buffer-read-only diff-mode-shared-map
))
837 (set (make-local-variable 'add-log-current-defun-function
)
839 (set (make-local-variable 'add-log-buffer-file-name-function
)
840 'diff-find-file-name
))
843 (define-minor-mode diff-minor-mode
844 "Minor mode for viewing/editing context diffs.
845 \\{diff-minor-mode-map}"
847 ;; FIXME: setup font-lock
848 ;; setup change hooks
849 (if (not diff-update-on-the-fly-flag
)
850 (add-hook 'write-contents-hooks
'diff-write-contents-hooks
)
851 (make-local-variable 'diff-unhandled-changes
)
852 (add-hook 'after-change-functions
'diff-after-change-function nil t
)
853 (add-hook 'post-command-hook
'diff-post-command-hook nil t
)))
857 ;;; Misc operations that have proved useful at some point.
860 (defun diff-next-complex-hunk ()
861 "Jump to the next \"complex\" hunk.
862 \"Complex\" is approximated by \"the hunk changes the number of lines\".
863 Only works for unified diffs."
866 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
868 (equal (match-string 1) (match-string 2)))))
870 (defun diff-hunk-text (hunk destp
&optional char-offset
)
871 "Return the literal source text from HUNK.
872 if DESTP is nil return the source, otherwise the destination text.
873 If CHAR-OFFSET is non-nil, it should be a char-offset in
874 HUNK, and instead of a string, a cons cell is returned whose car is the
875 appropriate text, and whose cdr is the corresponding char-offset in that text."
878 (goto-char (point-min))
883 ;; Set the following variables:
884 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
885 ;; DST-POS buffer pos of the destination part of the hunk or nil
886 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
887 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
888 (cond ((looking-at "^@@")
890 (setq num-pfx-chars
1)
892 (setq src-pos
(point) dst-pos
(point)))
893 ((looking-at "^\\*\\*")
896 (setq src-pos
(point))
897 (re-search-forward "^--- " nil t
)
899 (setq divider-pos
(point))
901 (setq dst-pos
(point)))
902 ((looking-at "^[0-9]+a[0-9,]+$")
903 ;; normal diff, insert
905 (setq dst-pos
(point)))
906 ((looking-at "^[0-9,]+d[0-9]+$")
907 ;; normal diff, delete
909 (setq src-pos
(point)))
910 ((looking-at "^[0-9,]+c[0-9,]+$")
911 ;; normal diff, change
913 (setq src-pos
(point))
914 (re-search-forward "^---$" nil t
)
916 (setq divider-pos
(point))
918 (setq dst-pos
(point)))
920 (error "Unknown diff hunk type")))
922 (if (if destp
(null dst-pos
) (null src-pos
))
923 ;; Implied empty text
924 (if char-offset
'("" .
0) "")
926 ;; For context diffs, either side can be empty, (if there's only
927 ;; added or only removed text). We should then use the other side.
928 (cond ((equal src-pos divider-pos
) (setq src-pos dst-pos
))
929 ((equal dst-pos
(point-max)) (setq dst-pos src-pos
)))
931 (when char-offset
(goto-char (+ (point-min) char-offset
)))
933 ;; Get rid of anything except the desired text.
935 ;; Delete unused text region
936 (let ((keep (if destp dst-pos src-pos
)))
937 (when (and divider-pos
(> divider-pos keep
))
938 (delete-region divider-pos
(point-max)))
939 (delete-region (point-min) keep
))
940 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
941 (let ((kill-char (if destp ?- ?
+)))
942 (goto-char (point-min))
944 (if (eq (char-after) kill-char
)
945 (delete-region (point) (progn (forward-line 1) (point)))
946 (delete-char num-pfx-chars
)
949 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
950 (if char-offset
(cons text
(- (point) (point-min))) text
))))))
953 (defun diff-find-text (text)
954 "Return the buffer position of the nearest occurrence of TEXT.
955 If TEXT isn't found, nil is returned."
956 (let* ((orig (point))
957 (forw (and (search-forward text nil t
)
958 (match-beginning 0)))
959 (back (and (goto-char (+ orig
(length text
)))
960 (search-backward text nil t
)
961 (match-beginning 0))))
962 ;; Choose the closest match.
964 (if (> (- forw orig
) (- orig back
)) back forw
)
967 (defsubst diff-xor
(a b
) (if a
(not b
) b
))
969 (defun diff-find-source-location (&optional other-file reverse
)
970 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED)."
972 (let* ((other (diff-xor other-file diff-jump-to-old-file-flag
))
973 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
974 (hunk (buffer-substring (point)
975 (save-excursion (diff-end-of-hunk) (point))))
976 (old (diff-hunk-text hunk reverse char-offset
))
977 (new (diff-hunk-text hunk
(not reverse
) char-offset
))
978 ;; Find the location specification.
979 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
980 (error "Can't find the hunk header")
981 (if other
(match-string 1)
982 (if (match-end 3) (match-string 3)
983 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t
)
984 (error "Can't find the hunk separator"))
986 (file (or (diff-find-file-name other
) (error "Can't find the file")))
987 (buf (find-file-noselect file
)))
988 ;; Update the user preference if he so wished.
989 (when (> (prefix-numeric-value other-file
) 8)
990 (setq diff-jump-to-old-file-flag other
))
991 (with-current-buffer buf
992 (goto-line (string-to-number line
))
993 (let* ((orig-pos (point))
994 (pos (diff-find-text (car old
)))
997 (setq pos
(diff-find-text (car new
)) switched t
))
1000 (if pos
(list (count-lines orig-pos pos
) pos
) (list nil orig-pos
))
1001 (if switched
(list new old t
) (list old new
))))))))
1004 (defun diff-hunk-status-msg (line-offset reversed dry-run
)
1005 (let ((msg (if dry-run
1006 (if reversed
"already applied" "not yet applied")
1007 (if reversed
"undone" "applied"))))
1008 (message (cond ((null line-offset
) "Hunk text not found")
1009 ((= line-offset
0) "Hunk %s")
1010 ((= line-offset
1) "Hunk %s at offset %d line")
1011 (t "Hunk %s at offset %d lines"))
1015 (defun diff-apply-hunk (&optional reverse
)
1016 "Apply the current hunk to the source file and go to the next.
1017 By default, the new source file is patched, but if the variable
1018 `diff-jump-to-old-file-flag' is non-nil, then the old source file is
1019 patched instead (some commands, such as `diff-goto-source' can change
1020 the value of this variable when given an appropriate prefix argument).
1022 With a prefix argument, REVERSE the hunk."
1024 (destructuring-bind (buf line-offset pos old new
&optional switched
)
1025 (diff-find-source-location nil reverse
)
1028 (error "Can't find the text to patch"))
1030 ;; A reversed patch was detected, perhaps apply it in reverse
1031 (not (save-window-excursion
1033 (goto-char (+ pos
(cdr old
)))
1036 "Hunk hasn't been applied yet; apply it now? "
1037 "Hunk has already been applied; undo it? ")))))
1038 (message "(Nothing done)"))
1041 (with-current-buffer buf
1043 (delete-char (length (car old
)))
1045 ;; Display BUF in a window
1046 (set-window-point (display-buffer buf
) (+ pos
(cdr new
)))
1047 (diff-hunk-status-msg line-offset
(diff-xor switched reverse
) nil
)
1048 (when diff-advance-after-apply-hunk
1049 (diff-hunk-next))))))
1052 (defun diff-test-hunk (&optional reverse
)
1053 "See whether it's possible to apply the current hunk.
1054 With a prefix argument, try to REVERSE the hunk."
1056 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1057 (diff-find-source-location nil reverse
)
1058 (set-window-point (display-buffer buf
) (+ pos
(cdr src
)))
1059 (diff-hunk-status-msg line-offset
(diff-xor reverse switched
) t
)))
1062 (defun diff-goto-source (&optional other-file
)
1063 "Jump to the corresponding source line.
1064 `diff-jump-to-old-file-flag' (or its opposite if the OTHER-FILE prefix arg
1065 is given) determines whether to jump to the old or the new file.
1066 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1067 then `diff-jump-to-old-file-flag' is also set, for the next invocations."
1069 ;; When pointing at a removal line, we probably want to jump to
1070 ;; the old location, and else to the new (i.e. as if reverting).
1071 ;; This is a convenient detail when using smerge-diff.
1072 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1073 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1074 (diff-find-source-location other-file rev
)
1076 (goto-char (+ pos
(cdr src
)))
1077 (diff-hunk-status-msg line-offset
(not switched
) t
))))
1080 (defun diff-current-defun ()
1081 "Find the name of function at point.
1082 For use in `add-log-current-defun-function'."
1083 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1084 (diff-find-source-location)
1087 (or (when (memq (char-after) '(?
< ?-
))
1088 ;; Cursor is pointing at removed text. This could be a removed
1089 ;; function, in which case, going to the source buffer will
1090 ;; not help since the function is now removed. Instead,
1091 ;; try to figure out the function name just from the code-fragment.
1092 (let ((old (if switched dst src
)))
1095 (goto-char (cdr old
))
1096 (funcall (with-current-buffer buf major-mode
))
1097 (add-log-current-defun))))
1098 (with-current-buffer buf
1099 (goto-char (+ pos
(cdr src
)))
1100 (add-log-current-defun))))))
1102 ;; provide the package
1103 (provide 'diff-mode
)
1105 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1106 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1107 ;; (diff-mode-load-hook): dropped.
1108 ;; (auto-mode-alist): also catch *.diffs.
1109 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1110 ;; for *.rej files (that lack any file name indication).
1112 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1113 ;; added support for "\ No newline at end of file".
1115 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1116 ;; - added basic `compile' support.
1117 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1118 ;; - diff-kill-file now tries to kill the leading garbage as well.
1120 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1121 ;; - don't use CL in the autoloaded code
1122 ;; - accept diffs using -T
1124 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1125 ;; interface to ediff-patch
1127 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1128 ;; (ediff=patch-file): add bindings to call ediff-patch.
1129 ;; (diff-find-file-name): taken out of diff-goto-source.
1130 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1131 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1133 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1134 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1136 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1137 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1140 ;;; diff-mode.el ends here