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.32 2000/10/18 08:50:39 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
"blue1" :bold t
))
173 (((type tty pc
) (class color
) (background dark
))
174 (:foreground
"green" :bold t
))
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" :bold t
))
187 (((type tty pc
) (class color
) (background dark
))
188 (:foreground
"cyan" :bold t
))
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" :bold t
:italic t
))
225 (((type tty pc
) (class color
) (background dark
))
226 (:foreground
"yellow" :bold t
:italic t
))
228 "`diff-mode' face used to highlight changed lines."
230 (defvar diff-changed-face
'diff-changed-face
)
232 (defface diff-function-face
233 '((t (:inherit diff-context-face
)))
234 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
236 (defvar diff-function-face
'diff-function-face
)
238 (defface diff-context-face
239 '((((class color
) (background light
))
240 (:foreground
"grey50"))
241 (((class color
) (background dark
))
242 (:foreground
"grey70"))
244 "`diff-mode' face used to highlight context and other side-information."
246 (defvar diff-context-face
'diff-context-face
)
248 (defvar diff-font-lock-keywords
249 '(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
250 (1 diff-hunk-header-face
)
251 (2 diff-function-face
))
252 ("^--- .+ ----$" ;context
253 . diff-hunk-header-face
)
254 ("\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
255 (1 diff-hunk-header-face
)
256 (2 diff-function-face
))
257 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face
) ;context
258 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
259 (0 diff-header-face
) (2 diff-file-header-face prepend
))
260 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face
)
261 ("^!.*\n" . diff-changed-face
) ;context
262 ("^[+>].*\n" . diff-added-face
)
263 ("^[-<].*\n" . diff-removed-face
)
264 ("^Index: \\(.+\\).*\n" (0 diff-header-face
) (1 diff-index-face prepend
))
265 ("^#.*" . font-lock-string-face
)
266 ("^[^-=+*!<>].*\n" . diff-context-face
)))
268 (defconst diff-font-lock-defaults
269 '(diff-font-lock-keywords t nil nil nil
(font-lock-multiline . nil
)))
271 (defvar diff-imenu-generic-expression
272 ;; Prefer second name as first is most likely to be a backup or
273 ;; version-control name.
274 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)\t" 1) ; unidiffs
275 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
281 (defvar diff-file-regexp-alist
282 '(("Index: \\(.+\\)" 1)))
284 (defvar diff-error-regexp-alist
285 '(("@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@" nil
2)
286 ("--- \\([0-9]+\\),[0-9]+ ----" nil
1)
287 ("\\([0-9]+\\)\\(,[0-9]+\\)?[adc]\\([0-9]+\\)" nil
3)))
293 (defconst diff-hunk-header-re
"^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
294 (defconst diff-file-header-re
(concat "^\\(--- .+\n\\+\\+\\+\\|\\*\\*\\* .+\n---\\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re
1)))
295 (defvar diff-narrowed-to nil
)
297 (defun diff-end-of-hunk (&optional style
)
298 (if (looking-at diff-hunk-header-re
) (goto-char (match-end 0)))
299 (let ((end (and (re-search-forward (case style
300 (unified "^[^-+# \\]")
301 (context "^[^-+#! \\]")
305 (match-beginning 0))))
306 ;; The return value is used by easy-mmode-define-navigation.
307 (goto-char (or end
(point-max)))))
309 (defun diff-beginning-of-hunk ()
311 (unless (looking-at diff-hunk-header-re
)
314 (re-search-backward diff-hunk-header-re
)
315 (error (error "Can't find the beginning of the hunk")))))
317 (defun diff-beginning-of-file ()
319 (unless (looking-at diff-file-header-re
)
322 (re-search-backward diff-file-header-re
)
323 (error (error "Can't find the beginning of the file")))))
325 (defun diff-end-of-file ()
326 (re-search-forward "^[-+#!<>0-9@* \\]" nil t
)
327 (re-search-forward "^[^-+#!<>0-9@* \\]" nil
'move
)
330 ;; Define diff-{hunk,file}-{prev,next}
331 (easy-mmode-define-navigation
332 diff-hunk diff-hunk-header-re
"hunk" diff-end-of-hunk
)
333 (easy-mmode-define-navigation
334 diff-file diff-file-header-re
"file" diff-end-of-hunk
)
336 (defun diff-restrict-view (&optional arg
)
337 "Restrict the view to the current hunk.
338 If the prefix ARG is given, restrict the view to the current file instead."
341 (if arg
(diff-beginning-of-file) (diff-beginning-of-hunk))
342 (narrow-to-region (point)
343 (progn (if arg
(diff-end-of-file) (diff-end-of-hunk))
345 (set (make-local-variable 'diff-narrowed-to
) (if arg
'file
'hunk
))))
348 (defun diff-hunk-kill ()
351 (diff-beginning-of-hunk)
352 (let ((start (point))
353 (firsthunk (save-excursion
355 (diff-beginning-of-file) (diff-hunk-next) (point))))
356 (nexthunk (save-excursion
358 (diff-hunk-next) (point))))
359 (nextfile (save-excursion
361 (diff-file-next) (point)))))
362 (if (and firsthunk
(= firsthunk start
)
364 (and nextfile
(> nexthunk nextfile
))))
365 ;; we're the only hunk for this file, so kill the file
368 (kill-region start
(point)))))
370 (defun diff-file-kill ()
371 "Kill current file's hunks."
373 (diff-beginning-of-file)
374 (let* ((start (point))
375 (prevhunk (save-excursion
377 (diff-hunk-prev) (point))))
378 (index (save-excursion
379 (re-search-backward "^Index: " prevhunk t
))))
380 (when index
(setq start index
))
382 (kill-region start
(point))))
384 (defun diff-kill-junk ()
385 "Kill spurious empty diffs."
388 (let ((inhibit-read-only t
))
389 (goto-char (point-min))
390 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
391 "\\([^-+!* <>].*\n\\)*?"
392 "\\(\\(Index:\\) \\|"
393 diff-file-header-re
"\\)")
395 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
397 (beginning-of-line)))))
400 ;;;; jump to other buffers
403 (defvar diff-remembered-files-alist nil
)
405 (defun diff-filename-drop-dir (file)
406 (when (string-match "/" file
) (substring file
(match-end 0))))
408 (defun diff-merge-strings (ancestor from to
)
409 "Merge the diff between ANCESTOR and FROM into TO.
410 Returns the merged string if successful or nil otherwise.
411 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
412 If ANCESTOR = FROM, returns TO.
413 If ANCESTOR = TO, returns FROM.
414 The heuristic is simplistic and only really works for cases
415 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
417 ;; AMB ANB CMD -> CND
418 ;; but that's ambiguous if `foo' or `bar' is empty:
419 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
420 (let ((str (concat ancestor
"\n" from
"\n" to
)))
421 (when (and (string-match (concat
422 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
424 "\\(.*\\(\\2\\).*\\)\\'") str
)
425 (equal to
(match-string 5 str
)))
426 (concat (substring str
(match-beginning 5) (match-beginning 6))
428 (substring str
(match-end 6) (match-end 5))))))
430 (defun diff-find-file-name (&optional old
)
431 "Return the file corresponding to the current patch.
432 Non-nil OLD means that we want the old file."
434 (unless (looking-at diff-file-header-re
)
435 (or (ignore-errors (diff-beginning-of-file))
436 (re-search-forward diff-file-header-re nil t
)))
437 (let* ((limit (save-excursion
439 (progn (diff-hunk-prev) (point))
440 (error (point-min)))))
442 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
443 (list (if old
(match-string 1) (match-string 3))
444 (if old
(match-string 3) (match-string 1)))
445 (forward-line 1) nil
))
447 (when (save-excursion
448 (re-search-backward "^Index: \\(.+\\)" limit t
))
449 (list (match-string 1)))
451 (when (re-search-backward "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?" nil t
)
452 (list (if old
(match-string 2) (match-string 4))
453 (if old
(match-string 4) (match-string 2))))))
456 ;; use any previously used preference
457 (cdr (assoc fs diff-remembered-files-alist
))
458 ;; try to be clever and use previous choices as an inspiration
459 (dolist (rf diff-remembered-files-alist
)
460 (let ((newfile (diff-merge-strings (caar rf
) (car fs
) (cdr rf
))))
461 (if (and newfile
(file-exists-p newfile
)) (return newfile
))))
462 ;; look for each file in turn. If none found, try again but
463 ;; ignoring the first level of directory, ...
464 (do* ((files fs
(delq nil
(mapcar 'diff-filename-drop-dir files
)))
467 (setq file
(do* ((files files
(cdr files
))
468 (file (car files
) (car files
)))
469 ((or (null file
) (file-exists-p file
))
472 ;; <foo>.rej patches implicitly apply to <foo>
473 (and (string-match "\\.rej\\'" (or buffer-file-name
""))
474 (let ((file (substring buffer-file-name
0 (match-beginning 0))))
475 (when (file-exists-p file
) file
)))
476 ;; if all else fails, ask the user
477 (let ((file (read-file-name (format "Use file %s: " (or (first fs
) ""))
478 nil
(first fs
) t
(first fs
))))
479 (set (make-local-variable 'diff-remembered-files-alist
)
480 (cons (cons fs file
) diff-remembered-files-alist
))
484 (defun diff-mouse-goto-source (event)
485 "Run `diff-goto-source' for the diff at a mouse click."
488 (mouse-set-point event
)
492 (defun diff-ediff-patch ()
493 "Call `ediff-patch-file' on the current buffer."
496 (ediff-patch-file nil
(current-buffer))
497 (wrong-number-of-arguments (ediff-patch-file))))
500 ;;;; Conversion functions
503 ;;(defvar diff-inhibit-after-change nil
504 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
506 (defun diff-unified->context
(start end
)
507 "Convert unified diffs to context diffs.
508 START and END are either taken from the region (if a prefix arg is given) or
509 else cover the whole bufer."
510 (interactive (if current-prefix-arg
511 (list (mark) (point))
512 (list (point-min) (point-max))))
513 (unless (markerp end
) (setq end
(copy-marker end
)))
514 (let (;;(diff-inhibit-after-change t)
515 (inhibit-read-only t
))
518 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t
)
520 (combine-after-change-calls
521 (if (match-beginning 2)
522 ;; we matched a file header
524 ;; use reverse order to make sure the indices are kept valid
525 (replace-match "---" t t nil
3)
526 (replace-match "***" t t nil
2))
527 ;; we matched a hunk header
528 (let ((line1 (match-string 4))
529 (lines1 (match-string 5))
530 (line2 (match-string 6))
531 (lines2 (match-string 7)))
533 (concat "***************\n*** " line1
","
534 (number-to-string (+ (string-to-number line1
)
535 (string-to-number lines1
)
539 (narrow-to-region (point)
540 (progn (diff-end-of-hunk 'unified
) (point)))
541 (let ((hunk (buffer-string)))
542 (goto-char (point-min))
543 (if (not (save-excursion (re-search-forward "^-" nil t
)))
544 (delete-region (point) (point-max))
545 (goto-char (point-max))
546 (let ((modif nil
) last-pt
)
547 (while (progn (setq last-pt
(point))
548 (= (forward-line -
1) 0))
550 (?
(insert " ") (setq modif nil
) (backward-char 1))
551 (?
+ (delete-region (point) last-pt
) (setq modif t
))
553 (progn (forward-char 1)
558 (?
\\ (when (save-excursion (forward-line -
1)
560 (delete-region (point) last-pt
) (setq modif t
)))
561 (t (setq modif nil
))))))
562 (goto-char (point-max))
564 (insert "--- " line2
","
565 (number-to-string (+ (string-to-number line2
)
566 (string-to-number lines2
)
567 -
1)) " ----\n" hunk
))
568 ;;(goto-char (point-min))
570 (if (not (save-excursion (re-search-forward "^+" nil t
)))
571 (delete-region (point) (point-max))
572 (let ((modif nil
) (delete nil
))
575 (?
(insert " ") (setq modif nil
) (backward-char 1))
576 (?-
(setq delete t
) (setq modif t
))
578 (progn (forward-char 1)
583 (?
\\ (when (save-excursion (forward-line 1)
585 (setq delete t
) (setq modif t
)))
586 (t (setq modif nil
)))
587 (let ((last-pt (point)))
590 (delete-region last-pt
(point))
591 (setq delete nil
)))))))))))))))
593 (defun diff-context->unified
(start end
)
594 "Convert context diffs to unified diffs.
595 START and END are either taken from the region (if a prefix arg is given) or
596 else cover the whole bufer."
597 (interactive (if current-prefix-arg
598 (list (mark) (point))
599 (list (point-min) (point-max))))
600 (unless (markerp end
) (setq end
(copy-marker end
)))
601 (let (;;(diff-inhibit-after-change t)
602 (inhibit-read-only t
))
605 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t
)
607 (combine-after-change-calls
608 (if (match-beginning 2)
609 ;; we matched a file header
611 ;; use reverse order to make sure the indices are kept valid
612 (replace-match "+++" t t nil
3)
613 (replace-match "---" t t nil
2))
614 ;; we matched a hunk header
615 (let ((line1s (match-string 4))
616 (line1e (match-string 5))
617 (pt1 (match-beginning 0)))
619 (unless (re-search-forward
620 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t
)
621 (error "Can't find matching `--- n1,n2 ----' line"))
622 (let ((line2s (match-string 1))
623 (line2e (match-string 2))
625 (delete-region (progn (beginning-of-line) (point))
626 (progn (forward-line 1) (point)))
630 (while (< (point) pt2
)
632 ((?
! ?-
) (delete-char 2) (insert "-") (forward-line 1))
633 (?\
;merge with the other half of the chunk
636 (goto-char pt2
) (forward-line 1) (point)))
637 (c (char-after pt2
)))
641 (prog1 (buffer-substring (+ pt2
2) endline2
)
642 (delete-region pt2 endline2
))))
643 (?\
;FIXME: check consistency
644 (delete-region pt2 endline2
)
647 (?
\\ (forward-line 1))
648 (t (delete-char 1) (forward-line 1)))))
649 (t (forward-line 1))))
650 (while (looking-at "[+! ] ")
651 (if (/= (char-after) ?
!) (forward-char 1)
652 (delete-char 1) (insert "+"))
653 (delete-char 1) (forward-line 1))
656 (insert "@@ -" line1s
","
657 (number-to-string (- (string-to-number line1e
)
658 (string-to-number line1s
)
661 (number-to-string (- (string-to-number line2e
)
662 (string-to-number line2s
)
665 (defun diff-reverse-direction (start end
)
666 "Reverse the direction of the diffs.
667 START and END are either taken from the region (if a prefix arg is given) or
668 else cover the whole bufer."
669 (interactive (if current-prefix-arg
670 (list (mark) (point))
671 (list (point-min) (point-max))))
672 (unless (markerp end
) (setq end
(copy-marker end
)))
673 (let (;;(diff-inhibit-after-change t)
674 (inhibit-read-only t
))
677 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t
)
679 (combine-after-change-calls
682 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil
))
683 ;; a context-diff hunk header
685 (let ((pt-lines1 (match-beginning 6))
686 (lines1 (match-string 6)))
687 (replace-match "" nil nil nil
6)
689 (let ((half1s (point)))
690 (while (looking-at "[-! \\][ \t]\\|#")
691 (when (= (char-after) ?-
) (delete-char 1) (insert "+"))
693 (let ((half1 (delete-and-extract-region half1s
(point))))
694 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
696 (error "Can't find matching `--- n1,n2 ----' line"))
697 (let ((str1 (match-string 1)))
698 (replace-match lines1 nil nil nil
1)
700 (let ((half2s (point)))
701 (while (looking-at "[!+ \\][ \t]\\|#")
702 (when (= (char-after) ?
+) (delete-char 1) (insert "-"))
704 (let ((half2 (delete-and-extract-region half2s
(point))))
705 (insert (or half1
""))
707 (insert (or half2
""))))
708 (goto-char pt-lines1
)
710 ;; a unified-diff hunk header
712 (replace-match "@@ -\\8 +\\7 @@" nil
)
714 (let ((c (char-after)) first last
)
715 (while (case (setq c
(char-after))
716 (?-
(setq first
(or first
(point)))
717 (delete-char 1) (insert "+") t
)
718 (?
+ (setq last
(or last
(point)))
719 (delete-char 1) (insert "-") t
)
721 (t (when (and first last
(< first last
))
724 (delete-and-extract-region first last
))))
726 (setq first nil last nil
)
728 (forward-line 1))))))))))
730 (defun diff-fixup-modifs (start end
)
731 "Fixup the hunk headers (in case the buffer was modified).
732 START and END are either taken from the region (if a prefix arg is given) or
733 else cover the whole bufer."
734 (interactive (if current-prefix-arg
735 (list (mark) (point))
736 (list (point-min) (point-max))))
737 (let ((inhibit-read-only t
))
739 (goto-char end
) (diff-end-of-hunk)
740 (let ((plus 0) (minus 0) (space 0) (bang 0))
741 (while (and (= (forward-line -
1) 0) (<= start
(point)))
742 (if (not (looking-at "\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|[-*][-*][-*] .+ [-*][-*][-*][-*]\\)$"))
749 (t (setq space
0 plus
0 minus
0 bang
0)))
751 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
752 (let* ((old1 (match-string 1))
753 (old2 (match-string 2))
754 (new1 (number-to-string (+ space minus
)))
755 (new2 (number-to-string (+ space plus
))))
756 (unless (string= new2 old2
) (replace-match new2 t t nil
2))
757 (unless (string= new1 old1
) (replace-match new1 t t nil
1))))
758 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
759 (when (> (+ space bang plus
) 0)
760 (let* ((old1 (match-string 1))
761 (old2 (match-string 2))
762 (new (number-to-string
763 (+ space bang plus -
1 (string-to-number old1
)))))
764 (unless (string= new old2
) (replace-match new t t nil
2)))))
765 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
766 (when (> (+ space bang minus
) 0)
767 (let* ((old (match-string 1))
769 (concat "%0" (number-to-string (length old
)) "d")
770 (+ space bang minus -
1 (string-to-number old
)))))
771 (unless (string= new old
) (replace-match new t t nil
2))))))
772 (setq space
0 plus
0 minus
0 bang
0)))))))
778 (defun diff-write-contents-hooks ()
779 "Fixup hunk headers if necessary."
780 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
783 ;; It turns out that making changes in the buffer from within an
784 ;; *-change-function is asking for trouble, whereas making them
785 ;; from a post-command-hook doesn't pose much problems
786 (defvar diff-unhandled-changes nil
)
787 (defun diff-after-change-function (beg end len
)
788 "Remember to fixup the hunk header.
789 See `after-change-functions' for the meaning of BEG, END and LEN."
790 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
791 ;; incorrect, but it turns out that inhibit-read-only is normally not set
792 ;; inside editing commands, while it tends to be set when the buffer gets
793 ;; updated by an async process or by a conversion function, both of which
794 ;; would rather not be uselessly slowed down by this hook.
795 (when (and (not undo-in-progress
) (not inhibit-read-only
))
796 (if diff-unhandled-changes
797 (setq diff-unhandled-changes
798 (cons (min beg
(car diff-unhandled-changes
))
799 (max beg
(cdr diff-unhandled-changes
))))
800 (setq diff-unhandled-changes
(cons beg end
)))))
802 (defun diff-post-command-hook ()
803 "Fixup hunk headers if necessary."
804 (when (consp diff-unhandled-changes
)
807 (goto-char (car diff-unhandled-changes
))
808 (unless (ignore-errors
809 (diff-beginning-of-hunk)
812 (> (point) (car diff-unhandled-changes
))))
813 (goto-char (car diff-unhandled-changes
))
814 (re-search-forward diff-hunk-header-re
(cdr diff-unhandled-changes
))
815 (diff-beginning-of-hunk))
816 (diff-fixup-modifs (point) (cdr diff-unhandled-changes
))))
817 (setq diff-unhandled-changes nil
)))
820 ;;;; The main function
824 (define-derived-mode diff-mode fundamental-mode
"Diff"
825 "Major mode for viewing/editing context diffs.
826 Supports unified and context diffs as well as (to a lesser extent) normal diffs.
827 When the buffer is read-only, the ESC prefix is not necessary.
828 This mode runs `diff-mode-hook'.
830 (set (make-local-variable 'font-lock-defaults
) diff-font-lock-defaults
)
831 (set (make-local-variable 'outline-regexp
) diff-outline-regexp
)
832 (set (make-local-variable 'imenu-generic-expression
)
833 diff-imenu-generic-expression
)
834 ;; These are not perfect. They would be better done separately for
835 ;; context diffs and unidiffs.
836 ;; (set (make-local-variable 'paragraph-start)
837 ;; (concat "@@ " ; unidiff hunk
838 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
839 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
840 ;; ; start (first or second line)
841 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
842 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
844 (set (make-local-variable 'compilation-file-regexp-alist
)
845 diff-file-regexp-alist
)
846 (set (make-local-variable 'compilation-error-regexp-alist
)
847 diff-error-regexp-alist
)
848 (when (string-match "\\.rej\\'" (or buffer-file-name
""))
849 (set (make-local-variable 'compilation-current-file
)
850 (substring buffer-file-name
0 (match-beginning 0))))
851 (compilation-shell-minor-mode 1)
852 ;; setup change hooks
854 (if (not diff-update-on-the-fly-flag
)
855 (add-hook 'write-contents-hooks
'diff-write-contents-hooks
)
856 (make-local-variable 'diff-unhandled-changes
)
857 (add-hook 'after-change-functions
'diff-after-change-function nil t
)
858 (add-hook 'post-command-hook
'diff-post-command-hook nil t
))
859 ;; Neat trick from Dave Love to add more bindings in read-only mode:
860 (add-to-list (make-local-variable 'minor-mode-overriding-map-alist
)
861 (cons 'buffer-read-only diff-mode-shared-map
))
863 (set (make-local-variable 'add-log-current-defun-function
)
865 (set (make-local-variable 'add-log-buffer-file-name-function
)
866 'diff-find-file-name
))
869 (define-minor-mode diff-minor-mode
870 "Minor mode for viewing/editing context diffs.
871 \\{diff-minor-mode-map}"
873 ;; FIXME: setup font-lock
874 ;; setup change hooks
875 (if (not diff-update-on-the-fly-flag
)
876 (add-hook 'write-contents-hooks
'diff-write-contents-hooks
)
877 (make-local-variable 'diff-unhandled-changes
)
878 (add-hook 'after-change-functions
'diff-after-change-function nil t
)
879 (add-hook 'post-command-hook
'diff-post-command-hook nil t
)))
883 ;;; Misc operations that have proved useful at some point.
886 (defun diff-next-complex-hunk ()
887 "Jump to the next \"complex\" hunk.
888 \"Complex\" is approximated by \"the hunk changes the number of lines\".
889 Only works for unified diffs."
892 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
894 (equal (match-string 1) (match-string 2)))))
896 (defun diff-hunk-text (hunk destp
&optional char-offset
)
897 "Return the literal source text from HUNK.
898 if DESTP is nil return the source, otherwise the destination text.
899 If CHAR-OFFSET is non-nil, it should be a char-offset in
900 HUNK, and instead of a string, a cons cell is returned whose car is the
901 appropriate text, and whose cdr is the corresponding char-offset in that text."
904 (goto-char (point-min))
909 ;; Set the following variables:
910 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
911 ;; DST-POS buffer pos of the destination part of the hunk or nil
912 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
913 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
914 (cond ((looking-at "^@@")
916 (setq num-pfx-chars
1)
918 (setq src-pos
(point) dst-pos
(point)))
919 ((looking-at "^\\*\\*")
922 (setq src-pos
(point))
923 (re-search-forward "^--- " nil t
)
925 (setq divider-pos
(point))
927 (setq dst-pos
(point)))
928 ((looking-at "^[0-9]+a[0-9,]+$")
929 ;; normal diff, insert
931 (setq dst-pos
(point)))
932 ((looking-at "^[0-9,]+d[0-9]+$")
933 ;; normal diff, delete
935 (setq src-pos
(point)))
936 ((looking-at "^[0-9,]+c[0-9,]+$")
937 ;; normal diff, change
939 (setq src-pos
(point))
940 (re-search-forward "^---$" nil t
)
942 (setq divider-pos
(point))
944 (setq dst-pos
(point)))
946 (error "Unknown diff hunk type")))
948 (if (if destp
(null dst-pos
) (null src-pos
))
949 ;; Implied empty text
950 (if char-offset
'("" .
0) "")
952 ;; For context diffs, either side can be empty, (if there's only
953 ;; added or only removed text). We should then use the other side.
954 (cond ((equal src-pos divider-pos
) (setq src-pos dst-pos
))
955 ((equal dst-pos
(point-max)) (setq dst-pos src-pos
)))
957 (when char-offset
(goto-char (+ (point-min) char-offset
)))
959 ;; Get rid of anything except the desired text.
961 ;; Delete unused text region
962 (let ((keep (if destp dst-pos src-pos
)))
963 (when (and divider-pos
(> divider-pos keep
))
964 (delete-region divider-pos
(point-max)))
965 (delete-region (point-min) keep
))
966 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
967 (let ((kill-char (if destp ?- ?
+)))
968 (goto-char (point-min))
970 (if (eq (char-after) kill-char
)
971 (delete-region (point) (progn (forward-line 1) (point)))
972 (delete-char num-pfx-chars
)
975 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
976 (if char-offset
(cons text
(- (point) (point-min))) text
))))))
979 (defun diff-find-text (text)
980 "Return the buffer position of the nearest occurrence of TEXT.
981 If TEXT isn't found, nil is returned."
982 (let* ((orig (point))
983 (forw (and (search-forward text nil t
)
984 (match-beginning 0)))
985 (back (and (goto-char (+ orig
(length text
)))
986 (search-backward text nil t
)
987 (match-beginning 0))))
988 ;; Choose the closest match.
990 (if (> (- forw orig
) (- orig back
)) back forw
)
993 (defsubst diff-xor
(a b
) (if a
(not b
) b
))
995 (defun diff-find-source-location (&optional other-file reverse
)
996 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED)."
998 (let* ((other (diff-xor other-file diff-jump-to-old-file-flag
))
999 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1000 (hunk (buffer-substring (point)
1001 (save-excursion (diff-end-of-hunk) (point))))
1002 (old (diff-hunk-text hunk reverse char-offset
))
1003 (new (diff-hunk-text hunk
(not reverse
) char-offset
))
1004 ;; Find the location specification.
1005 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1006 (error "Can't find the hunk header")
1007 (if other
(match-string 1)
1008 (if (match-end 3) (match-string 3)
1009 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t
)
1010 (error "Can't find the hunk separator"))
1011 (match-string 1)))))
1012 (file (or (diff-find-file-name other
) (error "Can't find the file")))
1013 (buf (find-file-noselect file
)))
1014 ;; Update the user preference if he so wished.
1015 (when (> (prefix-numeric-value other-file
) 8)
1016 (setq diff-jump-to-old-file-flag other
))
1017 (with-current-buffer buf
1018 (goto-line (string-to-number line
))
1019 (let* ((orig-pos (point))
1020 (pos (diff-find-text (car old
)))
1023 (setq pos
(diff-find-text (car new
)) switched t
))
1026 (if pos
(list (count-lines orig-pos pos
) pos
) (list nil orig-pos
))
1027 (if switched
(list new old t
) (list old new
))))))))
1030 (defun diff-hunk-status-msg (line-offset reversed dry-run
)
1031 (let ((msg (if dry-run
1032 (if reversed
"already applied" "not yet applied")
1033 (if reversed
"undone" "applied"))))
1034 (message (cond ((null line-offset
) "Hunk text not found")
1035 ((= line-offset
0) "Hunk %s")
1036 ((= line-offset
1) "Hunk %s at offset %d line")
1037 (t "Hunk %s at offset %d lines"))
1041 (defun diff-apply-hunk (&optional reverse
)
1042 "Apply the current hunk to the source file and go to the next.
1043 By default, the new source file is patched, but if the variable
1044 `diff-jump-to-old-file-flag' is non-nil, then the old source file is
1045 patched instead (some commands, such as `diff-goto-source' can change
1046 the value of this variable when given an appropriate prefix argument).
1048 With a prefix argument, REVERSE the hunk."
1050 (destructuring-bind (buf line-offset pos old new
&optional switched
)
1051 (diff-find-source-location nil reverse
)
1054 (error "Can't find the text to patch"))
1056 ;; A reversed patch was detected, perhaps apply it in reverse
1057 (not (save-window-excursion
1059 (goto-char (+ pos
(cdr old
)))
1062 "Hunk hasn't been applied yet; apply it now? "
1063 "Hunk has already been applied; undo it? ")))))
1064 (message "(Nothing done)"))
1067 (with-current-buffer buf
1069 (delete-char (length (car old
)))
1071 ;; Display BUF in a window
1072 (set-window-point (display-buffer buf
) (+ pos
(cdr new
)))
1073 (diff-hunk-status-msg line-offset
(diff-xor switched reverse
) nil
)
1074 (when diff-advance-after-apply-hunk
1075 (diff-hunk-next))))))
1078 (defun diff-test-hunk (&optional reverse
)
1079 "See whether it's possible to apply the current hunk.
1080 With a prefix argument, try to REVERSE the hunk."
1082 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1083 (diff-find-source-location nil reverse
)
1084 (set-window-point (display-buffer buf
) (+ pos
(cdr src
)))
1085 (diff-hunk-status-msg line-offset
(diff-xor reverse switched
) t
)))
1088 (defun diff-goto-source (&optional other-file
)
1089 "Jump to the corresponding source line.
1090 `diff-jump-to-old-file-flag' (or its opposite if the OTHER-FILE prefix arg
1091 is given) determines whether to jump to the old or the new file.
1092 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1093 then `diff-jump-to-old-file-flag' is also set, for the next invocations."
1095 ;; When pointing at a removal line, we probably want to jump to
1096 ;; the old location, and else to the new (i.e. as if reverting).
1097 ;; This is a convenient detail when using smerge-diff.
1098 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1099 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1100 (diff-find-source-location other-file rev
)
1102 (goto-char (+ pos
(cdr src
)))
1103 (diff-hunk-status-msg line-offset
(diff-xor rev switched
) t
))))
1106 (defun diff-current-defun ()
1107 "Find the name of function at point.
1108 For use in `add-log-current-defun-function'."
1109 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1110 (diff-find-source-location)
1113 (or (when (memq (char-after) '(?
< ?-
))
1114 ;; Cursor is pointing at removed text. This could be a removed
1115 ;; function, in which case, going to the source buffer will
1116 ;; not help since the function is now removed. Instead,
1117 ;; try to figure out the function name just from the code-fragment.
1118 (let ((old (if switched dst src
)))
1121 (goto-char (cdr old
))
1122 (funcall (with-current-buffer buf major-mode
))
1123 (add-log-current-defun))))
1124 (with-current-buffer buf
1125 (goto-char (+ pos
(cdr src
)))
1126 (add-log-current-defun))))))
1128 ;; provide the package
1129 (provide 'diff-mode
)
1131 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1132 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1133 ;; (diff-mode-load-hook): dropped.
1134 ;; (auto-mode-alist): also catch *.diffs.
1135 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1136 ;; for *.rej files (that lack any file name indication).
1138 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1139 ;; added support for "\ No newline at end of file".
1141 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1142 ;; - added basic `compile' support.
1143 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1144 ;; - diff-kill-file now tries to kill the leading garbage as well.
1146 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1147 ;; - don't use CL in the autoloaded code
1148 ;; - accept diffs using -T
1150 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1151 ;; interface to ediff-patch
1153 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1154 ;; (ediff=patch-file): add bindings to call ediff-patch.
1155 ;; (diff-find-file-name): taken out of diff-goto-source.
1156 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1157 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1159 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1160 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1162 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1163 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1166 ;;; diff-mode.el ends here