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.12 2000/09/11 13:49:38 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.
44 ;; - (nitpick) The mark is not always quite right in diff-goto-source.
48 ;; - Add change-log support.
49 ;; - Spice up the minor-mode with font-lock support.
50 ;; - Improve narrowed-view support.
51 ;; - Improve the `compile' support (?).
52 ;; - Recognize pcl-cvs' special string for `cvs-execute-single'.
53 ;; - Support for # comments in context->unified.
54 ;; - Do a fuzzy search in diff-goto-source.
55 ;; - Allow diff.el to use diff-mode.
56 ;; This mostly means ability to jump from half-hunk to half-hunk
57 ;; in context (and normal) diffs and to jump to the corresponding
58 ;; (i.e. new or old) file.
59 ;; - Handle `diff -b' output in context->unified.
63 (eval-when-compile (require 'cl
))
66 (defgroup diff-mode
()
67 "Major-mode for viewing/editing diffs"
72 (defcustom diff-jump-to-old-file-flag nil
73 "*Non-nil means `diff-goto-source' jumps to the old file.
74 Else, it jumps to the new file."
78 (defcustom diff-update-on-the-fly-flag t
79 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
80 When editing a diff file, the line numbers in the hunk headers
81 need to be kept consistent with the actual diff. This can
82 either be done on the fly (but this sometimes interacts poorly with the
83 undo mechanism) or whenever the file is written (can be slow
84 when editing big diffs)."
88 (defvar diff-mode-hook nil
89 "Run after setting up the `diff-mode' major mode.")
91 (defvar diff-outline-regexp
92 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
95 ;;;; keymap, menu, ...
98 (easy-mmode-defmap diff-mode-shared-map
99 '(;; From Pavel Machek's patch-mode.
100 ("n" . diff-hunk-next
)
101 ("N" . diff-file-next
)
102 ("p" . diff-hunk-prev
)
103 ("P" . diff-file-prev
)
104 ("k" . diff-hunk-kill
)
105 ("K" . diff-file-kill
)
106 ;; From compilation-minor-mode.
107 ("}" . diff-file-next
)
108 ("{" . diff-file-prev
)
109 ("\C-m" . diff-goto-source
)
110 ([mouse-2
] . diff-mouse-goto-source
)
111 ;; From XEmacs' diff-mode.
113 ;;("." . diff-goto-source) ;display-buffer
114 ;;("f" . diff-goto-source) ;find-file
115 ("o" . diff-goto-source
) ;other-window
116 ;;("w" . diff-goto-source) ;other-frame
117 ;;("N" . diff-narrow)
118 ;;("h" . diff-show-header)
119 ;;("j" . diff-show-difference) ;jump to Nth diff
122 ("\177" . scroll-down
)
123 ;; Our very own bindings.
124 ("A" . diff-ediff-patch
)
125 ("r" . diff-restrict-view
)
126 ("R" . diff-reverse-direction
)
127 ("U" . diff-context-
>unified
)
128 ("C" . diff-unified-
>context
))
129 "Basic keymap for `diff-mode', bound to various prefix keys.")
131 (easy-mmode-defmap diff-mode-map
132 `(("\e" .
,diff-mode-shared-map
)
133 ;; From compilation-minor-mode.
134 ("\C-c\C-c" . diff-goto-source
)
136 ("\C-cda" . diff-apply-hunk
)
137 ("\C-cdt" . diff-test-hunk
))
138 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
140 (easy-menu-define diff-mode-menu diff-mode-map
141 "Menu for `diff-mode'."
143 ["Jump to Source" diff-goto-source t
]
144 ["Apply with Ediff" diff-ediff-patch t
]
146 ["Reverse direction" diff-reverse-direction t
]
147 ["Context -> Unified" diff-context-
>unified t
]
148 ["Unified -> Context" diff-unified-
>context t
]
149 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
152 (defcustom diff-minor-mode-prefix
"\C-cd"
153 "Prefix key for `diff-minor-mode' commands."
155 :type
'(choice (string "\e") (string "C-cd") string
))
157 (easy-mmode-defmap diff-minor-mode-map
158 `((,diff-minor-mode-prefix .
,diff-mode-shared-map
))
159 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
163 ;;;; font-lock support
166 (defface diff-file-header-face
167 '((((class color
) (background light
))
168 (:background
"grey70" :bold t
))
170 "diff-mode face used to highlight file header lines."
172 (defvar diff-file-header-face
'diff-file-header-face
)
174 (defface diff-index-face
175 '((((class color
) (background light
))
176 (:background
"grey70" :bold t
))
178 "diff-mode face used to highlight index header lines."
180 (defvar diff-index-face
'diff-index-face
)
182 (defface diff-hunk-header-face
183 '((((class color
) (background light
))
184 (:background
"grey85"))
186 "diff-mode face used to highlight hunk header lines."
188 (defvar diff-hunk-header-face
'diff-hunk-header-face
)
190 (defface diff-removed-face
192 "diff-mode face used to highlight removed lines."
194 (defvar diff-removed-face
'diff-removed-face
)
196 (defface diff-added-face
198 "diff-mode face used to highlight added lines."
200 (defvar diff-added-face
'diff-added-face
)
202 (defface diff-changed-face
204 "diff-mode face used to highlight changed lines."
206 (defvar diff-changed-face
'diff-changed-face
)
208 (defvar diff-font-lock-keywords
209 '(("^@@ \\(-[0-9,]+ \\+[0-9,]+\\) @@\\(.*\\)$" ;unified
210 (1 diff-hunk-header-face
)
211 (2 font-lock-comment-face
))
212 ("^--- \\(.+\\) ----$" ;context
213 (1 diff-hunk-header-face
))
214 ("\\(\\*\\{15\\}\\)\\(.*\\)\n" ;context
215 (1 diff-hunk-header-face
)
216 (2 font-lock-comment-face
))
217 ("^\\*\\*\\* \\(.+\\) \\*\\*\\*" ;context
218 (1 diff-hunk-header-face
))
219 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)" (2 diff-file-header-face
))
220 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face
)
221 ("^!.*\n" . diff-changed-face
) ;context
222 ("^[+>].*\n" . diff-added-face
)
223 ("^[-<].*\n" . diff-removed-face
)
224 ("^Index: \\(.+\\)$" (1 diff-index-face
))
225 ("^#.*" . font-lock-string-face
)
226 ("^[^-=+*!<>].*\n" . font-lock-comment-face
)))
228 (defconst diff-font-lock-defaults
229 '(diff-font-lock-keywords t nil nil nil
(font-lock-multiline . nil
)))
231 (defvar diff-imenu-generic-expression
232 ;; Prefer second name as first is most likely to be a backup or
233 ;; version-control name.
234 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)\t" 1) ; unidiffs
235 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
241 (defvar diff-file-regexp-alist
242 '(("Index: \\(.+\\)" 1)))
244 (defvar diff-error-regexp-alist
245 '(("@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@" nil
2)
246 ("--- \\([0-9]+\\),[0-9]+ ----" nil
1)
247 ("\\([0-9]+\\)\\(,[0-9]+\\)?[adc]\\([0-9]+\\)" nil
3)))
253 (defconst diff-hunk-header-re
"^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
254 (defconst diff-file-header-re
(concat "^\\(--- .+\n\\+\\+\\+\\|\\*\\*\\* .+\n---\\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re
1)))
255 (defvar diff-narrowed-to nil
)
257 (defun diff-end-of-hunk (&optional style
)
258 (if (looking-at diff-hunk-header-re
) (goto-char (match-end 0)))
259 (let ((end (and (re-search-forward (case style
260 (unified "^[^-+# \\]")
261 (context "^[^-+#! \\]")
265 (match-beginning 0))))
266 ;; The return value is used by easy-mmode-define-navigation.
267 (goto-char (or end
(point-max)))))
269 (defun diff-beginning-of-hunk ()
271 (unless (looking-at diff-hunk-header-re
)
274 (re-search-backward diff-hunk-header-re
)
275 (error (error "Can't find the beginning of the hunk")))))
277 (defun diff-beginning-of-file ()
279 (unless (looking-at diff-file-header-re
)
282 (re-search-backward diff-file-header-re
)
283 (error (error "Can't find the beginning of the file")))))
285 (defun diff-end-of-file ()
286 (re-search-forward "^[-+#!<>0-9@* \\]" nil t
)
287 (re-search-forward "^[^-+#!<>0-9@* \\]" nil
'move
)
290 ;; Define diff-{hunk,file}-{prev,next}
291 (easy-mmode-define-navigation
292 diff-hunk diff-hunk-header-re
"hunk" diff-end-of-hunk
)
293 (easy-mmode-define-navigation
294 diff-file diff-file-header-re
"file" diff-end-of-hunk
)
296 (defun diff-restrict-view (&optional arg
)
297 "Restrict the view to the current hunk.
298 If the prefix ARG is given, restrict the view to the current file instead."
301 (if arg
(diff-beginning-of-file) (diff-beginning-of-hunk))
302 (narrow-to-region (point)
303 (progn (if arg
(diff-end-of-file) (diff-end-of-hunk))
305 (set (make-local-variable 'diff-narrowed-to
) (if arg
'file
'hunk
))))
308 (defun diff-hunk-kill ()
311 (diff-beginning-of-hunk)
312 (let ((start (point))
313 (firsthunk (save-excursion
315 (diff-beginning-of-file) (diff-hunk-next) (point))))
316 (nexthunk (save-excursion
318 (diff-hunk-next) (point))))
319 (nextfile (save-excursion
321 (diff-file-next) (point)))))
322 (if (and firsthunk
(= firsthunk start
)
324 (and nextfile
(> nexthunk nextfile
))))
325 ;; we're the only hunk for this file, so kill the file
328 (kill-region start
(point)))))
330 (defun diff-file-kill ()
331 "Kill current file's hunks."
333 (diff-beginning-of-file)
334 (let* ((start (point))
335 (prevhunk (save-excursion
337 (diff-hunk-prev) (point))))
338 (index (save-excursion
339 (re-search-backward "^Index: " prevhunk t
))))
340 (when index
(setq start index
))
342 (kill-region start
(point))))
344 (defun diff-kill-junk ()
345 "Kill spurious empty diffs."
348 (let ((inhibit-read-only t
))
349 (goto-char (point-min))
350 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
351 "\\([^-+!* <>].*\n\\)*?"
352 "\\(\\(Index:\\) \\|"
353 diff-file-header-re
"\\)")
355 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
357 (beginning-of-line)))))
360 ;;;; jump to other buffers
363 (defvar diff-remembered-files-alist nil
)
365 (defun diff-filename-drop-dir (file)
366 (when (string-match "/" file
) (substring file
(match-end 0))))
368 (defun diff-merge-strings (ancestor from to
)
369 "Merge the diff between ANCESTOR and FROM into TO.
370 Returns the merged string if successful or nil otherwise.
371 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
372 If ANCESTOR = FROM, returns TO.
373 If ANCESTOR = TO, returns FROM.
374 The heuristic is simplistic and only really works for cases
375 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
377 ;; AMB ANB CMD -> CND
378 ;; but that's ambiguous if `foo' or `bar' is empty:
379 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
380 (let ((str (concat ancestor
"\n" from
"\n" to
)))
381 (when (and (string-match (concat
382 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
384 "\\(.*\\(\\2\\).*\\)\\'") str
)
385 (equal to
(match-string 5 str
)))
386 (concat (substring str
(match-beginning 5) (match-beginning 6))
388 (substring str
(match-end 6) (match-end 5))))))
390 (defun diff-find-file-name (&optional old
)
391 "Return the file corresponding to the current patch.
392 Non-nil OLD means that we want the old file."
394 (unless (looking-at diff-file-header-re
)
395 (or (ignore-errors (diff-beginning-of-file))
396 (re-search-forward diff-file-header-re nil t
)))
397 (let* ((limit (save-excursion
399 (progn (diff-hunk-prev) (point))
400 (error (point-min)))))
402 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\s-.*\n[-+][-+][-+] \\(\\S-+\\)\\s-.*$")
403 (list (if old
(match-string 1) (match-string 2))
404 (if old
(match-string 2) (match-string 1)))
405 (forward-line 1) nil
))
407 (when (save-excursion
408 (re-search-backward "^Index: \\(.+\\)" limit t
))
409 (list (match-string 1)))
411 (when (re-search-backward "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?" nil t
)
412 (list (if old
(match-string 2) (match-string 4))
413 (if old
(match-string 4) (match-string 2))))))
416 ;; use any previously used preference
417 (cdr (assoc fs diff-remembered-files-alist
))
418 ;; try to be clever and use previous choices as an inspiration
419 (dolist (rf diff-remembered-files-alist
)
420 (let ((newfile (diff-merge-strings (caar rf
) (car fs
) (cdr rf
))))
421 (if (and newfile
(file-exists-p newfile
)) (return newfile
))))
422 ;; look for each file in turn. If none found, try again but
423 ;; ignoring the first level of directory, ...
424 (do* ((files fs
(delq nil
(mapcar 'diff-filename-drop-dir files
)))
427 (setq file
(do* ((files files
(cdr files
))
428 (file (car files
) (car files
)))
429 ((or (null file
) (file-exists-p file
))
432 ;; <foo>.rej patches implicitly apply to <foo>
433 (and (string-match "\\.rej\\'" (or buffer-file-name
""))
434 (let ((file (substring buffer-file-name
0 (match-beginning 0))))
435 (when (file-exists-p file
) file
)))
436 ;; if all else fails, ask the user
437 (let ((file (read-file-name (format "Use file %s: " (or (first fs
) ""))
438 nil
(first fs
) t
(first fs
))))
439 (set (make-local-variable 'diff-remembered-files-alist
)
440 (cons (cons fs file
) diff-remembered-files-alist
))
443 (defun diff-find-source-location (&optional other-file
)
444 "Find out (FILE LINE SPAN)."
446 (diff-beginning-of-hunk)
447 (let* ((old (if (not other-file
) diff-jump-to-old-file-flag
448 (not diff-jump-to-old-file-flag
)))
449 ;; Find the location specification.
450 (loc (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
451 (error "Can't find the hunk header")
452 (if old
(match-string 1)
453 (if (match-end 3) (match-string 3)
454 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t
)
455 (error "Can't find the hunk separator"))
457 ;; Extract the actual line number.
458 (lines (if (string-match "^\\([0-9]*\\),\\([0-9]*\\)" loc
)
459 (cons (string-to-number (match-string 1 loc
))
460 (string-to-number (match-string 2 loc
)))
461 (cons (string-to-number loc
) nil
)))
462 (file (diff-find-file-name old
))
464 (span (if (or (null (cdr lines
)) (< (cdr lines
) 0)) 0
466 (if (< (cdr lines
) line
) (cdr lines
)
467 (- (cdr lines
) line
)))))
468 ;; Update the user preference if he so wished.
469 (when (> (prefix-numeric-value other-file
) 8)
470 (setq diff-jump-to-old-file-flag old
))
471 (if (null file
) (error "Can't find the file")
472 (list file line span
)))))
474 (defun diff-mouse-goto-source (event)
475 "Run `diff-goto-source' for the diff at a mouse click."
478 (mouse-set-point event
)
481 (defun diff-ediff-patch ()
482 "Call `ediff-patch-file' on the current buffer."
485 (ediff-patch-file nil
(current-buffer))
486 (wrong-number-of-arguments (ediff-patch-file))))
489 ;;;; Conversion functions
492 ;;(defvar diff-inhibit-after-change nil
493 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
495 (defun diff-unified->context
(start end
)
496 "Convert unified diffs to context diffs.
497 START and END are either taken from the region (if a prefix arg is given) or
498 else cover the whole bufer."
499 (interactive (if current-prefix-arg
500 (list (mark) (point))
501 (list (point-min) (point-max))))
502 (unless (markerp end
) (setq end
(copy-marker end
)))
503 (let (;;(diff-inhibit-after-change t)
504 (inhibit-read-only t
))
507 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t
)
509 (combine-after-change-calls
510 (if (match-beginning 2)
511 ;; we matched a file header
513 ;; use reverse order to make sure the indices are kept valid
514 (replace-match "---" t t nil
3)
515 (replace-match "***" t t nil
2))
516 ;; we matched a hunk header
517 (let ((line1 (match-string 4))
518 (lines1 (match-string 5))
519 (line2 (match-string 6))
520 (lines2 (match-string 7)))
522 (concat "***************\n*** " line1
","
523 (number-to-string (+ (string-to-number line1
)
524 (string-to-number lines1
)
528 (narrow-to-region (point)
529 (progn (diff-end-of-hunk 'unified
) (point)))
530 (let ((hunk (buffer-string)))
531 (goto-char (point-min))
532 (if (not (save-excursion (re-search-forward "^-" nil t
)))
533 (delete-region (point) (point-max))
534 (goto-char (point-max))
535 (let ((modif nil
) last-pt
)
536 (while (progn (setq last-pt
(point))
537 (= (forward-line -
1) 0))
539 (?
(insert " ") (setq modif nil
) (backward-char 1))
540 (?
+ (delete-region (point) last-pt
) (setq modif t
))
542 (progn (forward-char 1)
547 (?
\\ (when (save-excursion (forward-line -
1)
549 (delete-region (point) last-pt
) (setq modif t
)))
550 (t (setq modif nil
))))))
551 (goto-char (point-max))
553 (insert "--- " line2
","
554 (number-to-string (+ (string-to-number line2
)
555 (string-to-number lines2
)
556 -
1)) " ----\n" hunk
))
557 ;;(goto-char (point-min))
559 (if (not (save-excursion (re-search-forward "^+" nil t
)))
560 (delete-region (point) (point-max))
561 (let ((modif nil
) (delete nil
))
564 (?
(insert " ") (setq modif nil
) (backward-char 1))
565 (?-
(setq delete t
) (setq modif t
))
567 (progn (forward-char 1)
572 (?
\\ (when (save-excursion (forward-line 1)
574 (setq delete t
) (setq modif t
)))
575 (t (setq modif nil
)))
576 (let ((last-pt (point)))
579 (delete-region last-pt
(point))
580 (setq delete nil
)))))))))))))))
582 (defun diff-context->unified
(start end
)
583 "Convert context diffs to unified diffs.
584 START and END are either taken from the region (if a prefix arg is given) or
585 else cover the whole bufer."
586 (interactive (if current-prefix-arg
587 (list (mark) (point))
588 (list (point-min) (point-max))))
589 (unless (markerp end
) (setq end
(copy-marker end
)))
590 (let (;;(diff-inhibit-after-change t)
591 (inhibit-read-only t
))
594 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t
)
596 (combine-after-change-calls
597 (if (match-beginning 2)
598 ;; we matched a file header
600 ;; use reverse order to make sure the indices are kept valid
601 (replace-match "+++" t t nil
3)
602 (replace-match "---" t t nil
2))
603 ;; we matched a hunk header
604 (let ((line1s (match-string 4))
605 (line1e (match-string 5))
606 (pt1 (match-beginning 0)))
608 (unless (re-search-forward
609 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t
)
610 (error "Can't find matching `--- n1,n2 ----' line"))
611 (let ((line2s (match-string 1))
612 (line2e (match-string 2))
614 (delete-region (progn (beginning-of-line) (point))
615 (progn (forward-line 1) (point)))
619 (while (< (point) pt2
)
621 ((?
! ?-
) (delete-char 2) (insert "-") (forward-line 1))
622 (?\
;merge with the other half of the chunk
625 (goto-char pt2
) (forward-line 1) (point)))
626 (c (char-after pt2
)))
630 (prog1 (buffer-substring (+ pt2
2) endline2
)
631 (delete-region pt2 endline2
))))
632 (?\
;FIXME: check consistency
633 (delete-region pt2 endline2
)
636 (?
\\ (forward-line 1))
637 (t (delete-char 1) (forward-line 1)))))
638 (t (forward-line 1))))
639 (while (looking-at "[+! ] ")
640 (if (/= (char-after) ?
!) (forward-char 1)
641 (delete-char 1) (insert "+"))
642 (delete-char 1) (forward-line 1))
645 (insert "@@ -" line1s
","
646 (number-to-string (- (string-to-number line1e
)
647 (string-to-number line1s
)
650 (number-to-string (- (string-to-number line2e
)
651 (string-to-number line2s
)
654 (defun diff-reverse-direction (start end
)
655 "Reverse the direction of the diffs.
656 START and END are either taken from the region (if a prefix arg is given) or
657 else cover the whole bufer."
658 (interactive (if current-prefix-arg
659 (list (mark) (point))
660 (list (point-min) (point-max))))
661 (unless (markerp end
) (setq end
(copy-marker end
)))
662 (let (;;(diff-inhibit-after-change t)
663 (inhibit-read-only t
))
666 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t
)
668 (combine-after-change-calls
671 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil
))
672 ;; a context-diff hunk header
674 (let ((pt-lines1 (match-beginning 6))
675 (lines1 (match-string 6)))
676 (replace-match "" nil nil nil
6)
678 (let ((half1s (point)))
679 (while (looking-at "[-! \\][ \t]\\|#")
680 (when (= (char-after) ?-
) (delete-char 1) (insert "+"))
682 (let ((half1 (delete-and-extract-region half1s
(point))))
683 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
685 (error "Can't find matching `--- n1,n2 ----' line"))
686 (let ((str1 (match-string 1)))
687 (replace-match lines1 nil nil nil
1)
689 (let ((half2s (point)))
690 (while (looking-at "[!+ \\][ \t]\\|#")
691 (when (= (char-after) ?
+) (delete-char 1) (insert "-"))
693 (let ((half2 (delete-and-extract-region half2s
(point))))
694 (insert (or half1
""))
696 (insert (or half2
""))))
697 (goto-char pt-lines1
)
699 ;; a unified-diff hunk header
701 (replace-match "@@ -\\8 +\\7 @@" nil
)
703 (let ((c (char-after)) first last
)
704 (while (case (setq c
(char-after))
705 (?-
(setq first
(or first
(point)))
706 (delete-char 1) (insert "+") t
)
707 (?
+ (setq last
(or last
(point)))
708 (delete-char 1) (insert "-") t
)
710 (t (when (and first last
(< first last
))
713 (delete-and-extract-region first last
))))
715 (setq first nil last nil
)
717 (forward-line 1))))))))))
719 (defun diff-fixup-modifs (start end
)
720 "Fixup the hunk headers (in case the buffer was modified).
721 START and END are either taken from the region (if a prefix arg is given) or
722 else cover the whole bufer."
723 (interactive (if current-prefix-arg
724 (list (mark) (point))
725 (list (point-min) (point-max))))
726 (let ((inhibit-read-only t
))
728 (goto-char end
) (diff-end-of-hunk)
729 (let ((plus 0) (minus 0) (space 0) (bang 0))
730 (while (and (= (forward-line -
1) 0) (<= start
(point)))
731 (if (not (looking-at "\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|[-*][-*][-*] .+ [-*][-*][-*][-*]\\)$"))
738 (t (setq space
0 plus
0 minus
0 bang
0)))
740 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
741 (let* ((old1 (match-string 1))
742 (old2 (match-string 2))
743 (new1 (number-to-string (+ space minus
)))
744 (new2 (number-to-string (+ space plus
))))
745 (unless (string= new2 old2
) (replace-match new2 t t nil
2))
746 (unless (string= new1 old1
) (replace-match new1 t t nil
1))))
747 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
748 (when (> (+ space bang plus
) 0)
749 (let* ((old1 (match-string 1))
750 (old2 (match-string 2))
751 (new (number-to-string
752 (+ space bang plus -
1 (string-to-number old1
)))))
753 (unless (string= new old2
) (replace-match new t t nil
2)))))
754 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
755 (when (> (+ space bang minus
) 0)
756 (let* ((old (match-string 1))
758 (concat "%0" (number-to-string (length old
)) "d")
759 (+ space bang minus -
1 (string-to-number old
)))))
760 (unless (string= new old
) (replace-match new t t nil
2))))))
761 (setq space
0 plus
0 minus
0 bang
0)))))))
767 (defun diff-write-contents-hooks ()
768 "Fixup hunk headers if necessary."
769 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
772 ;; It turns out that making changes in the buffer from within an
773 ;; *-change-function is asking for trouble, whereas making them
774 ;; from a post-command-hook doesn't pose much problems
775 (defvar diff-unhandled-changes nil
)
776 (defun diff-after-change-function (beg end len
)
777 "Remember to fixup the hunk header.
778 See `after-change-functions' for the meaning of BEG, END and LEN."
779 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
780 ;; incorrect, but it turns out that inhibit-read-only is normally not set
781 ;; inside editing commands, while it tends to be set when the buffer gets
782 ;; updated by an async process or by a conversion function, both of which
783 ;; would rather not be uselessly slowed down by this hook.
784 (when (and (not undo-in-progress
) (not inhibit-read-only
))
785 (if diff-unhandled-changes
786 (setq diff-unhandled-changes
787 (cons (min beg
(car diff-unhandled-changes
))
788 (max beg
(cdr diff-unhandled-changes
))))
789 (setq diff-unhandled-changes
(cons beg end
)))))
791 (defun diff-post-command-hook ()
792 "Fixup hunk headers if necessary."
793 (when (consp diff-unhandled-changes
)
796 (goto-char (car diff-unhandled-changes
))
797 (unless (ignore-errors
798 (diff-beginning-of-hunk)
801 (> (point) (car diff-unhandled-changes
))))
802 (goto-char (car diff-unhandled-changes
))
803 (re-search-forward diff-hunk-header-re
(cdr diff-unhandled-changes
))
804 (diff-beginning-of-hunk))
805 (diff-fixup-modifs (point) (cdr diff-unhandled-changes
))))
806 (setq diff-unhandled-changes nil
)))
809 ;;;; The main function
813 (define-derived-mode diff-mode fundamental-mode
"Diff"
814 "Major mode for viewing/editing context diffs.
815 Supports unified and context diffs as well as (to a lesser extent) normal diffs.
816 When the buffer is read-only, the ESC prefix is not necessary.
817 This mode runs `diff-mode-hook'.
819 (set (make-local-variable 'font-lock-defaults
) diff-font-lock-defaults
)
820 (set (make-local-variable 'outline-regexp
) diff-outline-regexp
)
821 (set (make-local-variable 'imenu-generic-expression
)
822 diff-imenu-generic-expression
)
823 ;; These are not perfect. They would be better done separately for
824 ;; context diffs and unidiffs.
825 ;; (set (make-local-variable 'paragraph-start)
826 ;; (concat "@@ " ; unidiff hunk
827 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
828 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
829 ;; ; start (first or second line)
830 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
831 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
833 (set (make-local-variable 'compilation-file-regexp-alist
)
834 diff-file-regexp-alist
)
835 (set (make-local-variable 'compilation-error-regexp-alist
)
836 diff-error-regexp-alist
)
837 (when (string-match "\\.rej\\'" (or buffer-file-name
""))
838 (set (make-local-variable 'compilation-current-file
)
839 (substring buffer-file-name
0 (match-beginning 0))))
840 (compilation-shell-minor-mode 1)
841 ;; setup change hooks
843 (if (not diff-update-on-the-fly-flag
)
844 (add-hook 'write-contents-hooks
'diff-write-contents-hooks
)
845 (make-local-variable 'diff-unhandled-changes
)
846 (add-hook (make-local-hook 'after-change-functions
)
847 'diff-after-change-function nil t
)
848 (add-hook (make-local-hook 'post-command-hook
)
849 'diff-post-command-hook nil t
))
850 ;; Neat trick from Dave Love to add more bindings in read-only mode:
851 (add-to-list (make-local-variable 'minor-mode-overriding-map-alist
)
852 (cons 'buffer-read-only diff-mode-shared-map
)))
855 (define-minor-mode diff-minor-mode
856 "Minor mode for viewing/editing context diffs.
857 \\{diff-minor-mode-map}"
859 ;; FIXME: setup font-lock
860 ;; setup change hooks
861 (if (not diff-update-on-the-fly-flag
)
862 (add-hook 'write-contents-hooks
'diff-write-contents-hooks
)
863 (make-local-variable 'diff-unhandled-changes
)
864 (add-hook (make-local-hook 'after-change-functions
)
865 'diff-after-change-function nil t
)
866 (add-hook (make-local-hook 'post-command-hook
)
867 'diff-post-command-hook nil t
)))
871 ;;; Misc operations that have proved useful at some point.
874 (defun diff-next-complex-hunk ()
875 "Jump to the next \"complex\" hunk.
876 \"Complex\" is approximated by \"the hunk changes the number of lines\".
877 Only works for unified diffs."
880 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
882 (equal (match-string 1) (match-string 2)))))
884 (defun diff-hunk-text (hunk dest
)
885 "Returns the literal source text from HUNK, if DEST is nil, otherwise
886 the destination text."
890 (goto-char (point-min))
895 (cond ((looking-at "^@@")
897 (setq num-pfx-chars
1)
899 (setq src
(point) dst
(point)))
900 ((looking-at "^\\*\\*")
904 (re-search-forward "^--- " nil t
)
906 (setq divider
(point))
909 ((looking-at "^[0-9]+a[0-9,]+$")
910 ;; normal diff, insert
913 ((looking-at "^[0-9,]+d[0-9]+$")
914 ;; normal diff, delete
917 ((looking-at "^[0-9,]+c[0-9,]+$")
918 ;; normal diff, change
921 (re-search-forward "^---$" nil t
)
923 (setq divider
(point))
927 (error "Unknown diff hunk type")))
929 (if (if dest
(null dst
) (null src
))
930 ;; Implied empty text
935 ;; Delete unused text region
936 (let ((keep (if dest dst src
))
937 (kill (or divider
(if dest src dst
))))
938 (when (and kill
(> kill keep
))
939 (delete-region kill
(point-max)))
940 (delete-region (point-min) keep
))
942 ;; Remove line-prefix characters, and unneeded lines (for
944 (let ((kill-char (if dest ?- ?
+)))
945 (goto-char (point-min))
947 (if (eq (char-after) kill-char
)
948 (delete-region (point) (progn (forward-line 1) (point)))
949 (delete-char num-pfx-chars
)
952 (buffer-substring-no-properties (point-min) (point-max))))))
954 (defun diff-find-text (text line
)
955 "Return the buffer position of the nearest occurance of TEXT to line LINE.
956 If TEXT isn't found, nil is returned."
958 (let* ((orig (point))
959 (forw (and (search-forward text nil t
)
960 (match-beginning 0)))
961 (back (and (goto-char (+ orig
(length text
)))
962 (search-backward text nil t
)
963 (match-beginning 0))))
964 ;; Choose the closest match.
966 (if (> (- forw orig
) (- orig back
)) back forw
)
969 (defun diff-apply-hunk (&optional reverse other-file dry-run popup noerror
)
970 "Apply the current hunk to the source file.
971 By default, the new source file is patched, but if the variable
972 `diff-jump-to-old-file-flag' is non-nil, then the old source file is
973 patched instead (some commands, such as `diff-goto-source' can change
974 the value of this variable when given an appropriate prefix argument).
976 With a prefix argument, REVERSE the hunk.
977 If OTHER-FILE is non-nil, patch the old file by default, and reverse the
978 sense of `diff-jump-to-old-file-flag'.
979 If DRY-RUN is non-nil, don't actually modify anything, just see whether
980 it's possible to do so.
981 If POPUP is non-nil, pop up the patched file in another window; if POPUP
982 is `select' then select the new window too.
983 If NOERROR is non-nil, then no error is signaled in the case where the hunk
984 cannot be found in the source file (other errors may still be signaled).
986 Return values are `t' if the hunk was sucessfully applied (or could be
987 applied, in the case where DRY-RUN was non-nil), `reversed' if the hunk
988 was applied backwards, or nil if the hunk couldn't be found and NOERROR
990 (interactive (list current-prefix-arg nil nil t
))
993 ;; OTHER-FILE inverts the sense of the hunk
994 (setq reverse
(not reverse
)))
995 (when diff-jump-to-old-file-flag
996 ;; The global variable `diff-jump-to-old-file-flag' inverts the
997 ;; sense of OTHER-FILE (in `diff-find-source-location')
998 (setq reverse
(not reverse
)))
1000 (let* ((loc (diff-find-source-location other-file
))
1001 (buf (find-file-noselect (car loc
)))
1002 (patch-line (cadr loc
))
1005 (diff-beginning-of-hunk)
1006 (unless (looking-at diff-hunk-header-re
)
1007 (error "Malformed hunk"))
1008 (buffer-substring (point) (progn (diff-end-of-hunk) (point)))))
1009 (src (diff-hunk-text hunk reverse
))
1010 (dst (diff-hunk-text hunk
(not reverse
)))
1012 (with-current-buffer buf
(diff-find-text src patch-line
)))
1015 (with-current-buffer buf
(diff-find-text dst patch-line
)))))
1017 (when (and reversed-pos popup
)
1018 ;; A reversed patch was detected, perhaps apply it in reverse
1019 ;; (this is only done in `interactive' mode, when POPUP is non-nil).
1021 (save-window-excursion
1023 (goto-char reversed-pos
)
1026 "Hunk hasn't been applied yet, so can't reverse it; apply it now? ")
1027 (y-or-n-p "Hunk has already been applied; undo it? "))))
1029 ;; Set up things to reverse the diff
1031 (setq pos reversed-pos
)
1035 ;; The user has chosen not to apply the reversed hunk, but we
1036 ;; don't want to given an error message, so set things up so
1037 ;; nothing else gets done down below
1038 (message "(Nothing done)")
1042 ;; POS is nil, so we couldn't find the source text.
1044 (error "Can't find the text to patch"))
1046 (let ((reversed (if reversed-pos
(not reverse
) reverse
)))
1049 (with-current-buffer buf
1051 (delete-char (length src
))
1055 ;; Show a message describing what was done
1057 (1+ (with-current-buffer buf
(count-lines (point-min) pos
))))
1060 (if reversed
"already applied" "not yet applied")
1061 (if reversed
"undone" "applied"))))
1062 (cond ((= real-line patch-line
)
1063 (message "Hunk %s" msg
))
1064 ((= real-line
(1+ patch-line
))
1065 (message "Hunk %s at offset 1 line" msg
))
1067 (message "Hunk %s at offset %d lines"
1069 (- real-line patch-line
)))))
1071 ;; Display BUF in a window, and maybe select it
1072 (let ((win (display-buffer buf
)))
1073 (set-window-point win pos
)
1074 (when (eq popup
'select
)
1075 (select-window win
))))
1077 ;; Return an appropriate indicator of success
1078 (if reversed
'reversed t
)))))
1081 (defun diff-test-hunk (&optional reverse
)
1082 "See whether it's possible to apply the current hunk.
1083 With a prefix argument, REVERSE the hunk."
1085 (diff-apply-hunk reverse nil t t
))
1087 (defun diff-goto-source (&optional other-file
)
1088 "Jump to the corresponding source line.
1089 `diff-jump-to-old-file-flag' (or its opposite if the OTHER-FILE prefix arg
1090 is give) determines whether to jump to the old or the new file.
1091 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1092 then `diff-jump-to-old-file-flag' is also set, for the next invocations."
1094 (or (diff-apply-hunk nil other-file t
'select t
)
1095 ;; couldn't actually find the hunk, just obey the hunk line number
1096 (let ((loc (diff-find-source-location other-file
)))
1097 (find-file-other-window (car loc
))
1098 (goto-line (cadr loc
))
1099 (error "Hunk text not found"))))
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