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.30 2000/10/17 12:12:00 eliz 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 '((((type tty pc
) (class color
) (background light
))
172 (:foreground
"lightblue"))
173 (((type tty pc
) (class color
) (background dark
))
174 (:foreground
"green"))
175 (((class color
) (background light
))
176 (:background
"grey85"))
177 (((class color
) (background dark
))
178 (:background
"grey45"))
180 "`diff-mode' face inherited by hunk and index header faces."
182 (defvar diff-header-face
'diff-header-face
)
184 (defface diff-file-header-face
185 '((((type tty pc
) (class color
) (background light
))
186 (:foreground
"yellow"))
187 (((type tty pc
) (class color
) (background dark
))
188 (:foreground
"cyan"))
189 (((class color
) (background light
))
190 (:background
"grey70" :bold t
))
191 (((class color
) (background dark
))
192 (:background
"grey60" :bold t
))
193 (t (:bold t
))) ; :height 1.3
194 "`diff-mode' face used to highlight file header lines."
196 (defvar diff-file-header-face
'diff-file-header-face
)
198 (defface diff-index-face
199 '((t (:inherit diff-file-header-face
)))
200 "`diff-mode' face used to highlight index header lines."
202 (defvar diff-index-face
'diff-index-face
)
204 (defface diff-hunk-header-face
205 '((t (:inherit diff-header-face
)))
206 "`diff-mode' face used to highlight hunk header lines."
208 (defvar diff-hunk-header-face
'diff-hunk-header-face
)
210 (defface diff-removed-face
211 '((t (:inherit diff-changed-face
)))
212 "`diff-mode' face used to highlight removed lines."
214 (defvar diff-removed-face
'diff-removed-face
)
216 (defface diff-added-face
217 '((t (:inherit diff-changed-face
)))
218 "`diff-mode' face used to highlight added lines."
220 (defvar diff-added-face
'diff-added-face
)
222 (defface diff-changed-face
223 '((((type tty pc
) (class color
) (background light
))
224 (:foreground
"magenta"))
225 (((type tty pc
) (class color
) (background dark
))
226 (:foreground
"yellow"))
228 "`diff-mode' face used to highlight changed lines."
230 (defvar diff-changed-face
'diff-changed-face
)
232 (defface diff-context-face
233 '((((class color
) (background light
))
234 (:foreground
"grey50"))
235 (((class color
) (background dark
))
236 (:foreground
"grey70"))
238 "`diff-mode' face used to highlight context and other side-information."
240 (defvar diff-context-face
'diff-context-face
)
242 (defvar diff-font-lock-keywords
243 '(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
244 (1 diff-hunk-header-face
)
245 (2 diff-context-face
))
246 ("^--- .+ ----$" ;context
247 . diff-hunk-header-face
)
248 ("\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
249 (1 diff-hunk-header-face
)
250 (2 diff-context-face
))
251 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face
) ;context
252 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
253 (0 diff-header-face
) (2 diff-file-header-face prepend
))
254 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face
)
255 ("^!.*\n" . diff-changed-face
) ;context
256 ("^[+>].*\n" . diff-added-face
)
257 ("^[-<].*\n" . diff-removed-face
)
258 ("^Index: \\(.+\\).*\n" (0 diff-header-face
) (1 diff-index-face prepend
))
259 ("^#.*" . font-lock-string-face
)
260 ("^[^-=+*!<>].*\n" . diff-context-face
)))
262 (defconst diff-font-lock-defaults
263 '(diff-font-lock-keywords t nil nil nil
(font-lock-multiline . nil
)))
265 (defvar diff-imenu-generic-expression
266 ;; Prefer second name as first is most likely to be a backup or
267 ;; version-control name.
268 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)\t" 1) ; unidiffs
269 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
275 (defvar diff-file-regexp-alist
276 '(("Index: \\(.+\\)" 1)))
278 (defvar diff-error-regexp-alist
279 '(("@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@" nil
2)
280 ("--- \\([0-9]+\\),[0-9]+ ----" nil
1)
281 ("\\([0-9]+\\)\\(,[0-9]+\\)?[adc]\\([0-9]+\\)" nil
3)))
287 (defconst diff-hunk-header-re
"^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
288 (defconst diff-file-header-re
(concat "^\\(--- .+\n\\+\\+\\+\\|\\*\\*\\* .+\n---\\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re
1)))
289 (defvar diff-narrowed-to nil
)
291 (defun diff-end-of-hunk (&optional style
)
292 (if (looking-at diff-hunk-header-re
) (goto-char (match-end 0)))
293 (let ((end (and (re-search-forward (case style
294 (unified "^[^-+# \\]")
295 (context "^[^-+#! \\]")
299 (match-beginning 0))))
300 ;; The return value is used by easy-mmode-define-navigation.
301 (goto-char (or end
(point-max)))))
303 (defun diff-beginning-of-hunk ()
305 (unless (looking-at diff-hunk-header-re
)
308 (re-search-backward diff-hunk-header-re
)
309 (error (error "Can't find the beginning of the hunk")))))
311 (defun diff-beginning-of-file ()
313 (unless (looking-at diff-file-header-re
)
316 (re-search-backward diff-file-header-re
)
317 (error (error "Can't find the beginning of the file")))))
319 (defun diff-end-of-file ()
320 (re-search-forward "^[-+#!<>0-9@* \\]" nil t
)
321 (re-search-forward "^[^-+#!<>0-9@* \\]" nil
'move
)
324 ;; Define diff-{hunk,file}-{prev,next}
325 (easy-mmode-define-navigation
326 diff-hunk diff-hunk-header-re
"hunk" diff-end-of-hunk
)
327 (easy-mmode-define-navigation
328 diff-file diff-file-header-re
"file" diff-end-of-hunk
)
330 (defun diff-restrict-view (&optional arg
)
331 "Restrict the view to the current hunk.
332 If the prefix ARG is given, restrict the view to the current file instead."
335 (if arg
(diff-beginning-of-file) (diff-beginning-of-hunk))
336 (narrow-to-region (point)
337 (progn (if arg
(diff-end-of-file) (diff-end-of-hunk))
339 (set (make-local-variable 'diff-narrowed-to
) (if arg
'file
'hunk
))))
342 (defun diff-hunk-kill ()
345 (diff-beginning-of-hunk)
346 (let ((start (point))
347 (firsthunk (save-excursion
349 (diff-beginning-of-file) (diff-hunk-next) (point))))
350 (nexthunk (save-excursion
352 (diff-hunk-next) (point))))
353 (nextfile (save-excursion
355 (diff-file-next) (point)))))
356 (if (and firsthunk
(= firsthunk start
)
358 (and nextfile
(> nexthunk nextfile
))))
359 ;; we're the only hunk for this file, so kill the file
362 (kill-region start
(point)))))
364 (defun diff-file-kill ()
365 "Kill current file's hunks."
367 (diff-beginning-of-file)
368 (let* ((start (point))
369 (prevhunk (save-excursion
371 (diff-hunk-prev) (point))))
372 (index (save-excursion
373 (re-search-backward "^Index: " prevhunk t
))))
374 (when index
(setq start index
))
376 (kill-region start
(point))))
378 (defun diff-kill-junk ()
379 "Kill spurious empty diffs."
382 (let ((inhibit-read-only t
))
383 (goto-char (point-min))
384 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
385 "\\([^-+!* <>].*\n\\)*?"
386 "\\(\\(Index:\\) \\|"
387 diff-file-header-re
"\\)")
389 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
391 (beginning-of-line)))))
394 ;;;; jump to other buffers
397 (defvar diff-remembered-files-alist nil
)
399 (defun diff-filename-drop-dir (file)
400 (when (string-match "/" file
) (substring file
(match-end 0))))
402 (defun diff-merge-strings (ancestor from to
)
403 "Merge the diff between ANCESTOR and FROM into TO.
404 Returns the merged string if successful or nil otherwise.
405 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
406 If ANCESTOR = FROM, returns TO.
407 If ANCESTOR = TO, returns FROM.
408 The heuristic is simplistic and only really works for cases
409 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
411 ;; AMB ANB CMD -> CND
412 ;; but that's ambiguous if `foo' or `bar' is empty:
413 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
414 (let ((str (concat ancestor
"\n" from
"\n" to
)))
415 (when (and (string-match (concat
416 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
418 "\\(.*\\(\\2\\).*\\)\\'") str
)
419 (equal to
(match-string 5 str
)))
420 (concat (substring str
(match-beginning 5) (match-beginning 6))
422 (substring str
(match-end 6) (match-end 5))))))
424 (defun diff-find-file-name (&optional old
)
425 "Return the file corresponding to the current patch.
426 Non-nil OLD means that we want the old file."
428 (unless (looking-at diff-file-header-re
)
429 (or (ignore-errors (diff-beginning-of-file))
430 (re-search-forward diff-file-header-re nil t
)))
431 (let* ((limit (save-excursion
433 (progn (diff-hunk-prev) (point))
434 (error (point-min)))))
436 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
437 (list (if old
(match-string 1) (match-string 2))
438 (if old
(match-string 2) (match-string 1)))
439 (forward-line 1) nil
))
441 (when (save-excursion
442 (re-search-backward "^Index: \\(.+\\)" limit t
))
443 (list (match-string 1)))
445 (when (re-search-backward "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?" nil t
)
446 (list (if old
(match-string 2) (match-string 4))
447 (if old
(match-string 4) (match-string 2))))))
450 ;; use any previously used preference
451 (cdr (assoc fs diff-remembered-files-alist
))
452 ;; try to be clever and use previous choices as an inspiration
453 (dolist (rf diff-remembered-files-alist
)
454 (let ((newfile (diff-merge-strings (caar rf
) (car fs
) (cdr rf
))))
455 (if (and newfile
(file-exists-p newfile
)) (return newfile
))))
456 ;; look for each file in turn. If none found, try again but
457 ;; ignoring the first level of directory, ...
458 (do* ((files fs
(delq nil
(mapcar 'diff-filename-drop-dir files
)))
461 (setq file
(do* ((files files
(cdr files
))
462 (file (car files
) (car files
)))
463 ((or (null file
) (file-exists-p file
))
466 ;; <foo>.rej patches implicitly apply to <foo>
467 (and (string-match "\\.rej\\'" (or buffer-file-name
""))
468 (let ((file (substring buffer-file-name
0 (match-beginning 0))))
469 (when (file-exists-p file
) file
)))
470 ;; if all else fails, ask the user
471 (let ((file (read-file-name (format "Use file %s: " (or (first fs
) ""))
472 nil
(first fs
) t
(first fs
))))
473 (set (make-local-variable 'diff-remembered-files-alist
)
474 (cons (cons fs file
) diff-remembered-files-alist
))
478 (defun diff-mouse-goto-source (event)
479 "Run `diff-goto-source' for the diff at a mouse click."
482 (mouse-set-point event
)
486 (defun diff-ediff-patch ()
487 "Call `ediff-patch-file' on the current buffer."
490 (ediff-patch-file nil
(current-buffer))
491 (wrong-number-of-arguments (ediff-patch-file))))
494 ;;;; Conversion functions
497 ;;(defvar diff-inhibit-after-change nil
498 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
500 (defun diff-unified->context
(start end
)
501 "Convert unified diffs to context diffs.
502 START and END are either taken from the region (if a prefix arg is given) or
503 else cover the whole bufer."
504 (interactive (if current-prefix-arg
505 (list (mark) (point))
506 (list (point-min) (point-max))))
507 (unless (markerp end
) (setq end
(copy-marker end
)))
508 (let (;;(diff-inhibit-after-change t)
509 (inhibit-read-only t
))
512 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t
)
514 (combine-after-change-calls
515 (if (match-beginning 2)
516 ;; we matched a file header
518 ;; use reverse order to make sure the indices are kept valid
519 (replace-match "---" t t nil
3)
520 (replace-match "***" t t nil
2))
521 ;; we matched a hunk header
522 (let ((line1 (match-string 4))
523 (lines1 (match-string 5))
524 (line2 (match-string 6))
525 (lines2 (match-string 7)))
527 (concat "***************\n*** " line1
","
528 (number-to-string (+ (string-to-number line1
)
529 (string-to-number lines1
)
533 (narrow-to-region (point)
534 (progn (diff-end-of-hunk 'unified
) (point)))
535 (let ((hunk (buffer-string)))
536 (goto-char (point-min))
537 (if (not (save-excursion (re-search-forward "^-" nil t
)))
538 (delete-region (point) (point-max))
539 (goto-char (point-max))
540 (let ((modif nil
) last-pt
)
541 (while (progn (setq last-pt
(point))
542 (= (forward-line -
1) 0))
544 (?
(insert " ") (setq modif nil
) (backward-char 1))
545 (?
+ (delete-region (point) last-pt
) (setq modif t
))
547 (progn (forward-char 1)
552 (?
\\ (when (save-excursion (forward-line -
1)
554 (delete-region (point) last-pt
) (setq modif t
)))
555 (t (setq modif nil
))))))
556 (goto-char (point-max))
558 (insert "--- " line2
","
559 (number-to-string (+ (string-to-number line2
)
560 (string-to-number lines2
)
561 -
1)) " ----\n" hunk
))
562 ;;(goto-char (point-min))
564 (if (not (save-excursion (re-search-forward "^+" nil t
)))
565 (delete-region (point) (point-max))
566 (let ((modif nil
) (delete nil
))
569 (?
(insert " ") (setq modif nil
) (backward-char 1))
570 (?-
(setq delete t
) (setq modif t
))
572 (progn (forward-char 1)
577 (?
\\ (when (save-excursion (forward-line 1)
579 (setq delete t
) (setq modif t
)))
580 (t (setq modif nil
)))
581 (let ((last-pt (point)))
584 (delete-region last-pt
(point))
585 (setq delete nil
)))))))))))))))
587 (defun diff-context->unified
(start end
)
588 "Convert context diffs to unified diffs.
589 START and END are either taken from the region (if a prefix arg is given) or
590 else cover the whole bufer."
591 (interactive (if current-prefix-arg
592 (list (mark) (point))
593 (list (point-min) (point-max))))
594 (unless (markerp end
) (setq end
(copy-marker end
)))
595 (let (;;(diff-inhibit-after-change t)
596 (inhibit-read-only t
))
599 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t
)
601 (combine-after-change-calls
602 (if (match-beginning 2)
603 ;; we matched a file header
605 ;; use reverse order to make sure the indices are kept valid
606 (replace-match "+++" t t nil
3)
607 (replace-match "---" t t nil
2))
608 ;; we matched a hunk header
609 (let ((line1s (match-string 4))
610 (line1e (match-string 5))
611 (pt1 (match-beginning 0)))
613 (unless (re-search-forward
614 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t
)
615 (error "Can't find matching `--- n1,n2 ----' line"))
616 (let ((line2s (match-string 1))
617 (line2e (match-string 2))
619 (delete-region (progn (beginning-of-line) (point))
620 (progn (forward-line 1) (point)))
624 (while (< (point) pt2
)
626 ((?
! ?-
) (delete-char 2) (insert "-") (forward-line 1))
627 (?\
;merge with the other half of the chunk
630 (goto-char pt2
) (forward-line 1) (point)))
631 (c (char-after pt2
)))
635 (prog1 (buffer-substring (+ pt2
2) endline2
)
636 (delete-region pt2 endline2
))))
637 (?\
;FIXME: check consistency
638 (delete-region pt2 endline2
)
641 (?
\\ (forward-line 1))
642 (t (delete-char 1) (forward-line 1)))))
643 (t (forward-line 1))))
644 (while (looking-at "[+! ] ")
645 (if (/= (char-after) ?
!) (forward-char 1)
646 (delete-char 1) (insert "+"))
647 (delete-char 1) (forward-line 1))
650 (insert "@@ -" line1s
","
651 (number-to-string (- (string-to-number line1e
)
652 (string-to-number line1s
)
655 (number-to-string (- (string-to-number line2e
)
656 (string-to-number line2s
)
659 (defun diff-reverse-direction (start end
)
660 "Reverse the direction of the diffs.
661 START and END are either taken from the region (if a prefix arg is given) or
662 else cover the whole bufer."
663 (interactive (if current-prefix-arg
664 (list (mark) (point))
665 (list (point-min) (point-max))))
666 (unless (markerp end
) (setq end
(copy-marker end
)))
667 (let (;;(diff-inhibit-after-change t)
668 (inhibit-read-only t
))
671 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t
)
673 (combine-after-change-calls
676 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil
))
677 ;; a context-diff hunk header
679 (let ((pt-lines1 (match-beginning 6))
680 (lines1 (match-string 6)))
681 (replace-match "" nil nil nil
6)
683 (let ((half1s (point)))
684 (while (looking-at "[-! \\][ \t]\\|#")
685 (when (= (char-after) ?-
) (delete-char 1) (insert "+"))
687 (let ((half1 (delete-and-extract-region half1s
(point))))
688 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
690 (error "Can't find matching `--- n1,n2 ----' line"))
691 (let ((str1 (match-string 1)))
692 (replace-match lines1 nil nil nil
1)
694 (let ((half2s (point)))
695 (while (looking-at "[!+ \\][ \t]\\|#")
696 (when (= (char-after) ?
+) (delete-char 1) (insert "-"))
698 (let ((half2 (delete-and-extract-region half2s
(point))))
699 (insert (or half1
""))
701 (insert (or half2
""))))
702 (goto-char pt-lines1
)
704 ;; a unified-diff hunk header
706 (replace-match "@@ -\\8 +\\7 @@" nil
)
708 (let ((c (char-after)) first last
)
709 (while (case (setq c
(char-after))
710 (?-
(setq first
(or first
(point)))
711 (delete-char 1) (insert "+") t
)
712 (?
+ (setq last
(or last
(point)))
713 (delete-char 1) (insert "-") t
)
715 (t (when (and first last
(< first last
))
718 (delete-and-extract-region first last
))))
720 (setq first nil last nil
)
722 (forward-line 1))))))))))
724 (defun diff-fixup-modifs (start end
)
725 "Fixup the hunk headers (in case the buffer was modified).
726 START and END are either taken from the region (if a prefix arg is given) or
727 else cover the whole bufer."
728 (interactive (if current-prefix-arg
729 (list (mark) (point))
730 (list (point-min) (point-max))))
731 (let ((inhibit-read-only t
))
733 (goto-char end
) (diff-end-of-hunk)
734 (let ((plus 0) (minus 0) (space 0) (bang 0))
735 (while (and (= (forward-line -
1) 0) (<= start
(point)))
736 (if (not (looking-at "\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|[-*][-*][-*] .+ [-*][-*][-*][-*]\\)$"))
743 (t (setq space
0 plus
0 minus
0 bang
0)))
745 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
746 (let* ((old1 (match-string 1))
747 (old2 (match-string 2))
748 (new1 (number-to-string (+ space minus
)))
749 (new2 (number-to-string (+ space plus
))))
750 (unless (string= new2 old2
) (replace-match new2 t t nil
2))
751 (unless (string= new1 old1
) (replace-match new1 t t nil
1))))
752 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
753 (when (> (+ space bang plus
) 0)
754 (let* ((old1 (match-string 1))
755 (old2 (match-string 2))
756 (new (number-to-string
757 (+ space bang plus -
1 (string-to-number old1
)))))
758 (unless (string= new old2
) (replace-match new t t nil
2)))))
759 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
760 (when (> (+ space bang minus
) 0)
761 (let* ((old (match-string 1))
763 (concat "%0" (number-to-string (length old
)) "d")
764 (+ space bang minus -
1 (string-to-number old
)))))
765 (unless (string= new old
) (replace-match new t t nil
2))))))
766 (setq space
0 plus
0 minus
0 bang
0)))))))
772 (defun diff-write-contents-hooks ()
773 "Fixup hunk headers if necessary."
774 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
777 ;; It turns out that making changes in the buffer from within an
778 ;; *-change-function is asking for trouble, whereas making them
779 ;; from a post-command-hook doesn't pose much problems
780 (defvar diff-unhandled-changes nil
)
781 (defun diff-after-change-function (beg end len
)
782 "Remember to fixup the hunk header.
783 See `after-change-functions' for the meaning of BEG, END and LEN."
784 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
785 ;; incorrect, but it turns out that inhibit-read-only is normally not set
786 ;; inside editing commands, while it tends to be set when the buffer gets
787 ;; updated by an async process or by a conversion function, both of which
788 ;; would rather not be uselessly slowed down by this hook.
789 (when (and (not undo-in-progress
) (not inhibit-read-only
))
790 (if diff-unhandled-changes
791 (setq diff-unhandled-changes
792 (cons (min beg
(car diff-unhandled-changes
))
793 (max beg
(cdr diff-unhandled-changes
))))
794 (setq diff-unhandled-changes
(cons beg end
)))))
796 (defun diff-post-command-hook ()
797 "Fixup hunk headers if necessary."
798 (when (consp diff-unhandled-changes
)
801 (goto-char (car diff-unhandled-changes
))
802 (unless (ignore-errors
803 (diff-beginning-of-hunk)
806 (> (point) (car diff-unhandled-changes
))))
807 (goto-char (car diff-unhandled-changes
))
808 (re-search-forward diff-hunk-header-re
(cdr diff-unhandled-changes
))
809 (diff-beginning-of-hunk))
810 (diff-fixup-modifs (point) (cdr diff-unhandled-changes
))))
811 (setq diff-unhandled-changes nil
)))
814 ;;;; The main function
818 (define-derived-mode diff-mode fundamental-mode
"Diff"
819 "Major mode for viewing/editing context diffs.
820 Supports unified and context diffs as well as (to a lesser extent) normal diffs.
821 When the buffer is read-only, the ESC prefix is not necessary.
822 This mode runs `diff-mode-hook'.
824 (set (make-local-variable 'font-lock-defaults
) diff-font-lock-defaults
)
825 (set (make-local-variable 'outline-regexp
) diff-outline-regexp
)
826 (set (make-local-variable 'imenu-generic-expression
)
827 diff-imenu-generic-expression
)
828 ;; These are not perfect. They would be better done separately for
829 ;; context diffs and unidiffs.
830 ;; (set (make-local-variable 'paragraph-start)
831 ;; (concat "@@ " ; unidiff hunk
832 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
833 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
834 ;; ; start (first or second line)
835 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
836 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
838 (set (make-local-variable 'compilation-file-regexp-alist
)
839 diff-file-regexp-alist
)
840 (set (make-local-variable 'compilation-error-regexp-alist
)
841 diff-error-regexp-alist
)
842 (when (string-match "\\.rej\\'" (or buffer-file-name
""))
843 (set (make-local-variable 'compilation-current-file
)
844 (substring buffer-file-name
0 (match-beginning 0))))
845 (compilation-shell-minor-mode 1)
846 ;; setup change hooks
848 (if (not diff-update-on-the-fly-flag
)
849 (add-hook 'write-contents-hooks
'diff-write-contents-hooks
)
850 (make-local-variable 'diff-unhandled-changes
)
851 (add-hook 'after-change-functions
'diff-after-change-function nil t
)
852 (add-hook 'post-command-hook
'diff-post-command-hook nil t
))
853 ;; Neat trick from Dave Love to add more bindings in read-only mode:
854 (add-to-list (make-local-variable 'minor-mode-overriding-map-alist
)
855 (cons 'buffer-read-only diff-mode-shared-map
))
857 (set (make-local-variable 'add-log-current-defun-function
)
859 (set (make-local-variable 'add-log-buffer-file-name-function
)
860 'diff-find-file-name
))
863 (define-minor-mode diff-minor-mode
864 "Minor mode for viewing/editing context diffs.
865 \\{diff-minor-mode-map}"
867 ;; FIXME: setup font-lock
868 ;; setup change hooks
869 (if (not diff-update-on-the-fly-flag
)
870 (add-hook 'write-contents-hooks
'diff-write-contents-hooks
)
871 (make-local-variable 'diff-unhandled-changes
)
872 (add-hook 'after-change-functions
'diff-after-change-function nil t
)
873 (add-hook 'post-command-hook
'diff-post-command-hook nil t
)))
877 ;;; Misc operations that have proved useful at some point.
880 (defun diff-next-complex-hunk ()
881 "Jump to the next \"complex\" hunk.
882 \"Complex\" is approximated by \"the hunk changes the number of lines\".
883 Only works for unified diffs."
886 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
888 (equal (match-string 1) (match-string 2)))))
890 (defun diff-hunk-text (hunk destp
&optional char-offset
)
891 "Return the literal source text from HUNK.
892 if DESTP is nil return the source, otherwise the destination text.
893 If CHAR-OFFSET is non-nil, it should be a char-offset in
894 HUNK, and instead of a string, a cons cell is returned whose car is the
895 appropriate text, and whose cdr is the corresponding char-offset in that text."
898 (goto-char (point-min))
903 ;; Set the following variables:
904 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
905 ;; DST-POS buffer pos of the destination part of the hunk or nil
906 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
907 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
908 (cond ((looking-at "^@@")
910 (setq num-pfx-chars
1)
912 (setq src-pos
(point) dst-pos
(point)))
913 ((looking-at "^\\*\\*")
916 (setq src-pos
(point))
917 (re-search-forward "^--- " nil t
)
919 (setq divider-pos
(point))
921 (setq dst-pos
(point)))
922 ((looking-at "^[0-9]+a[0-9,]+$")
923 ;; normal diff, insert
925 (setq dst-pos
(point)))
926 ((looking-at "^[0-9,]+d[0-9]+$")
927 ;; normal diff, delete
929 (setq src-pos
(point)))
930 ((looking-at "^[0-9,]+c[0-9,]+$")
931 ;; normal diff, change
933 (setq src-pos
(point))
934 (re-search-forward "^---$" nil t
)
936 (setq divider-pos
(point))
938 (setq dst-pos
(point)))
940 (error "Unknown diff hunk type")))
942 (if (if destp
(null dst-pos
) (null src-pos
))
943 ;; Implied empty text
944 (if char-offset
'("" .
0) "")
946 ;; For context diffs, either side can be empty, (if there's only
947 ;; added or only removed text). We should then use the other side.
948 (cond ((equal src-pos divider-pos
) (setq src-pos dst-pos
))
949 ((equal dst-pos
(point-max)) (setq dst-pos src-pos
)))
951 (when char-offset
(goto-char (+ (point-min) char-offset
)))
953 ;; Get rid of anything except the desired text.
955 ;; Delete unused text region
956 (let ((keep (if destp dst-pos src-pos
)))
957 (when (and divider-pos
(> divider-pos keep
))
958 (delete-region divider-pos
(point-max)))
959 (delete-region (point-min) keep
))
960 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
961 (let ((kill-char (if destp ?- ?
+)))
962 (goto-char (point-min))
964 (if (eq (char-after) kill-char
)
965 (delete-region (point) (progn (forward-line 1) (point)))
966 (delete-char num-pfx-chars
)
969 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
970 (if char-offset
(cons text
(- (point) (point-min))) text
))))))
973 (defun diff-find-text (text)
974 "Return the buffer position of the nearest occurrence of TEXT.
975 If TEXT isn't found, nil is returned."
976 (let* ((orig (point))
977 (forw (and (search-forward text nil t
)
978 (match-beginning 0)))
979 (back (and (goto-char (+ orig
(length text
)))
980 (search-backward text nil t
)
981 (match-beginning 0))))
982 ;; Choose the closest match.
984 (if (> (- forw orig
) (- orig back
)) back forw
)
987 (defsubst diff-xor
(a b
) (if a
(not b
) b
))
989 (defun diff-find-source-location (&optional other-file reverse
)
990 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED)."
992 (let* ((other (diff-xor other-file diff-jump-to-old-file-flag
))
993 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
994 (hunk (buffer-substring (point)
995 (save-excursion (diff-end-of-hunk) (point))))
996 (old (diff-hunk-text hunk reverse char-offset
))
997 (new (diff-hunk-text hunk
(not reverse
) char-offset
))
998 ;; Find the location specification.
999 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1000 (error "Can't find the hunk header")
1001 (if other
(match-string 1)
1002 (if (match-end 3) (match-string 3)
1003 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t
)
1004 (error "Can't find the hunk separator"))
1005 (match-string 1)))))
1006 (file (or (diff-find-file-name other
) (error "Can't find the file")))
1007 (buf (find-file-noselect file
)))
1008 ;; Update the user preference if he so wished.
1009 (when (> (prefix-numeric-value other-file
) 8)
1010 (setq diff-jump-to-old-file-flag other
))
1011 (with-current-buffer buf
1012 (goto-line (string-to-number line
))
1013 (let* ((orig-pos (point))
1014 (pos (diff-find-text (car old
)))
1017 (setq pos
(diff-find-text (car new
)) switched t
))
1020 (if pos
(list (count-lines orig-pos pos
) pos
) (list nil orig-pos
))
1021 (if switched
(list new old t
) (list old new
))))))))
1024 (defun diff-hunk-status-msg (line-offset reversed dry-run
)
1025 (let ((msg (if dry-run
1026 (if reversed
"already applied" "not yet applied")
1027 (if reversed
"undone" "applied"))))
1028 (message (cond ((null line-offset
) "Hunk text not found")
1029 ((= line-offset
0) "Hunk %s")
1030 ((= line-offset
1) "Hunk %s at offset %d line")
1031 (t "Hunk %s at offset %d lines"))
1035 (defun diff-apply-hunk (&optional reverse
)
1036 "Apply the current hunk to the source file and go to the next.
1037 By default, the new source file is patched, but if the variable
1038 `diff-jump-to-old-file-flag' is non-nil, then the old source file is
1039 patched instead (some commands, such as `diff-goto-source' can change
1040 the value of this variable when given an appropriate prefix argument).
1042 With a prefix argument, REVERSE the hunk."
1044 (destructuring-bind (buf line-offset pos old new
&optional switched
)
1045 (diff-find-source-location nil reverse
)
1048 (error "Can't find the text to patch"))
1050 ;; A reversed patch was detected, perhaps apply it in reverse
1051 (not (save-window-excursion
1053 (goto-char (+ pos
(cdr old
)))
1056 "Hunk hasn't been applied yet; apply it now? "
1057 "Hunk has already been applied; undo it? ")))))
1058 (message "(Nothing done)"))
1061 (with-current-buffer buf
1063 (delete-char (length (car old
)))
1065 ;; Display BUF in a window
1066 (set-window-point (display-buffer buf
) (+ pos
(cdr new
)))
1067 (diff-hunk-status-msg line-offset
(diff-xor switched reverse
) nil
)
1068 (when diff-advance-after-apply-hunk
1069 (diff-hunk-next))))))
1072 (defun diff-test-hunk (&optional reverse
)
1073 "See whether it's possible to apply the current hunk.
1074 With a prefix argument, try to REVERSE the hunk."
1076 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1077 (diff-find-source-location nil reverse
)
1078 (set-window-point (display-buffer buf
) (+ pos
(cdr src
)))
1079 (diff-hunk-status-msg line-offset
(diff-xor reverse switched
) t
)))
1082 (defun diff-goto-source (&optional other-file
)
1083 "Jump to the corresponding source line.
1084 `diff-jump-to-old-file-flag' (or its opposite if the OTHER-FILE prefix arg
1085 is given) determines whether to jump to the old or the new file.
1086 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1087 then `diff-jump-to-old-file-flag' is also set, for the next invocations."
1089 ;; When pointing at a removal line, we probably want to jump to
1090 ;; the old location, and else to the new (i.e. as if reverting).
1091 ;; This is a convenient detail when using smerge-diff.
1092 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1093 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1094 (diff-find-source-location other-file rev
)
1096 (goto-char (+ pos
(cdr src
)))
1097 (diff-hunk-status-msg line-offset
(diff-xor rev switched
) t
))))
1100 (defun diff-current-defun ()
1101 "Find the name of function at point.
1102 For use in `add-log-current-defun-function'."
1103 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1104 (diff-find-source-location)
1107 (or (when (memq (char-after) '(?
< ?-
))
1108 ;; Cursor is pointing at removed text. This could be a removed
1109 ;; function, in which case, going to the source buffer will
1110 ;; not help since the function is now removed. Instead,
1111 ;; try to figure out the function name just from the code-fragment.
1112 (let ((old (if switched dst src
)))
1115 (goto-char (cdr old
))
1116 (funcall (with-current-buffer buf major-mode
))
1117 (add-log-current-defun))))
1118 (with-current-buffer buf
1119 (goto-char (+ pos
(cdr src
)))
1120 (add-log-current-defun))))))
1122 ;; provide the package
1123 (provide 'diff-mode
)
1125 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1126 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1127 ;; (diff-mode-load-hook): dropped.
1128 ;; (auto-mode-alist): also catch *.diffs.
1129 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1130 ;; for *.rej files (that lack any file name indication).
1132 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1133 ;; added support for "\ No newline at end of file".
1135 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1136 ;; - added basic `compile' support.
1137 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1138 ;; - diff-kill-file now tries to kill the leading garbage as well.
1140 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1141 ;; - don't use CL in the autoloaded code
1142 ;; - accept diffs using -T
1144 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1145 ;; interface to ediff-patch
1147 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1148 ;; (ediff=patch-file): add bindings to call ediff-patch.
1149 ;; (diff-find-file-name): taken out of diff-goto-source.
1150 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1151 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1153 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1154 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1156 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1157 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1160 ;;; diff-mode.el ends here