1 ;;; diff-mode.el --- a mode for viewing/editing context diffs
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007 Free Software Foundation, Inc.
6 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; Keywords: convenience patch diff
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., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
28 ;; Provides support for font-lock, outline, 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
38 ;; - Reverse doesn't work with normal diffs.
42 ;; - Add a `delete-after-apply' so C-c C-a automatically deletes hunks.
43 ;; Also allow C-c C-a to delete already-applied hunks.
45 ;; - Try `diff <file> <hunk>' to try and fuzzily discover the source location
46 ;; of a hunk. Show then the changes between <file> and <hunk> and make it
47 ;; possible to apply them to <file>, <hunk-src>, or <hunk-dst>.
48 ;; Or maybe just make it into a ".rej to diff3-markers converter".
49 ;; Maybe just use `wiggle' (by Neil Brown) to do it for us.
51 ;; - Refine hunk on a word-by-word basis.
53 ;; - in diff-apply-hunk, strip context in replace-match to better
54 ;; preserve markers and spacing.
55 ;; - Handle `diff -b' output in context->unified.
58 (eval-when-compile (require 'cl
))
60 (defvar add-log-buffer-file-name-function
)
63 (defgroup diff-mode
()
64 "Major mode for viewing/editing diffs."
69 (defcustom diff-default-read-only nil
70 "If non-nil, `diff-mode' buffers default to being read-only."
74 (defcustom diff-jump-to-old-file nil
75 "Non-nil means `diff-goto-source' jumps to the old file.
76 Else, it jumps to the new file."
80 (defcustom diff-update-on-the-fly t
81 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
82 When editing a diff file, the line numbers in the hunk headers
83 need to be kept consistent with the actual diff. This can
84 either be done on the fly (but this sometimes interacts poorly with the
85 undo mechanism) or whenever the file is written (can be slow
86 when editing big diffs)."
90 (defcustom diff-advance-after-apply-hunk t
91 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
96 (defcustom diff-mode-hook nil
97 "Run after setting up the `diff-mode' major mode."
99 :options
'(diff-delete-empty-files diff-make-unified
)
102 (defvar diff-outline-regexp
103 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
106 ;;;; keymap, menu, ...
109 (easy-mmode-defmap diff-mode-shared-map
110 '(;; From Pavel Machek's patch-mode.
111 ("n" . diff-hunk-next
)
112 ("N" . diff-file-next
)
113 ("p" . diff-hunk-prev
)
114 ("P" . diff-file-prev
)
115 ("k" . diff-hunk-kill
)
116 ("K" . diff-file-kill
)
117 ;; From compilation-minor-mode.
118 ("}" . diff-file-next
)
119 ("{" . diff-file-prev
)
120 ("\C-m" . diff-goto-source
)
121 ([mouse-2
] . diff-goto-source
)
122 ;; From XEmacs' diff-mode.
123 ;; Standard M-w is useful, so don't change M-W.
125 ;;("." . diff-goto-source) ;display-buffer
126 ;;("f" . diff-goto-source) ;find-file
127 ("o" . diff-goto-source
) ;other-window
128 ;;("w" . diff-goto-source) ;other-frame
129 ;;("N" . diff-narrow)
130 ;;("h" . diff-show-header)
131 ;;("j" . diff-show-difference) ;jump to Nth diff
133 ;; Not useful if you have to metafy them.
135 ;;("\177" . scroll-down)
136 ;; Standard M-a is useful, so don't change M-A.
137 ;;("A" . diff-ediff-patch)
138 ;; Standard M-r is useful, so don't change M-r or M-R.
139 ;;("r" . diff-restrict-view)
140 ;;("R" . diff-reverse-direction)
142 "Basic keymap for `diff-mode', bound to various prefix keys.")
144 (easy-mmode-defmap diff-mode-map
145 `(("\e" .
,diff-mode-shared-map
)
146 ;; From compilation-minor-mode.
147 ("\C-c\C-c" . diff-goto-source
)
149 ("\C-c\C-a" . diff-apply-hunk
)
150 ("\C-c\C-e" . diff-ediff-patch
)
151 ("\C-c\C-n" . diff-restrict-view
)
152 ("\C-c\C-r" . diff-reverse-direction
)
153 ("\C-c\C-s" . diff-split-hunk
)
154 ("\C-c\C-t" . diff-test-hunk
)
155 ("\C-c\C-u" . diff-context-
>unified
)
156 ;; `d' because it duplicates the context :-( --Stef
157 ("\C-c\C-d" . diff-unified-
>context
)
158 ("\C-c\C-w" . diff-refine-hunk
)
159 ("\C-c\C-f" . next-error-follow-minor-mode
))
160 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
162 (easy-menu-define diff-mode-menu diff-mode-map
163 "Menu for `diff-mode'."
165 ["Jump to Source" diff-goto-source t
]
166 ["Apply hunk" diff-apply-hunk t
]
167 ["Apply diff with Ediff" diff-ediff-patch t
]
169 ["Reverse direction" diff-reverse-direction t
]
170 ["Context -> Unified" diff-context-
>unified t
]
171 ["Unified -> Context" diff-unified-
>context t
]
172 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
175 (defcustom diff-minor-mode-prefix
"\C-c="
176 "Prefix key for `diff-minor-mode' commands."
177 :type
'(choice (string "\e") (string "C-c=") string
)
180 (easy-mmode-defmap diff-minor-mode-map
181 `((,diff-minor-mode-prefix .
,diff-mode-shared-map
))
182 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
186 ;;;; font-lock support
190 '((((class color
) (min-colors 88) (background light
))
191 :background
"grey85")
192 (((class color
) (min-colors 88) (background dark
))
193 :background
"grey45")
194 (((class color
) (background light
))
195 :foreground
"blue1" :weight bold
)
196 (((class color
) (background dark
))
197 :foreground
"green" :weight bold
)
199 "`diff-mode' face inherited by hunk and index header faces."
201 ;; backward-compatibility alias
202 (put 'diff-header-face
'face-alias
'diff-header
)
203 (defvar diff-header-face
'diff-header
)
205 (defface diff-file-header
206 '((((class color
) (min-colors 88) (background light
))
207 :background
"grey70" :weight bold
)
208 (((class color
) (min-colors 88) (background dark
))
209 :background
"grey60" :weight bold
)
210 (((class color
) (background light
))
211 :foreground
"green" :weight bold
)
212 (((class color
) (background dark
))
213 :foreground
"cyan" :weight bold
)
214 (t :weight bold
)) ; :height 1.3
215 "`diff-mode' face used to highlight file header lines."
217 ;; backward-compatibility alias
218 (put 'diff-file-header-face
'face-alias
'diff-file-header
)
219 (defvar diff-file-header-face
'diff-file-header
)
222 '((t :inherit diff-file-header
))
223 "`diff-mode' face used to highlight index header lines."
225 ;; backward-compatibility alias
226 (put 'diff-index-face
'face-alias
'diff-index
)
227 (defvar diff-index-face
'diff-index
)
229 (defface diff-hunk-header
230 '((t :inherit diff-header
))
231 "`diff-mode' face used to highlight hunk header lines."
233 ;; backward-compatibility alias
234 (put 'diff-hunk-header-face
'face-alias
'diff-hunk-header
)
235 (defvar diff-hunk-header-face
'diff-hunk-header
)
237 (defface diff-removed
238 '((t :inherit diff-changed
))
239 "`diff-mode' face used to highlight removed lines."
241 ;; backward-compatibility alias
242 (put 'diff-removed-face
'face-alias
'diff-removed
)
243 (defvar diff-removed-face
'diff-removed
)
246 '((t :inherit diff-changed
))
247 "`diff-mode' face used to highlight added lines."
249 ;; backward-compatibility alias
250 (put 'diff-added-face
'face-alias
'diff-added
)
251 (defvar diff-added-face
'diff-added
)
253 (defface diff-changed
254 '((((type tty pc
) (class color
) (background light
))
255 :foreground
"magenta" :weight bold
:slant italic
)
256 (((type tty pc
) (class color
) (background dark
))
257 :foreground
"yellow" :weight bold
:slant italic
))
258 "`diff-mode' face used to highlight changed lines."
260 ;; backward-compatibility alias
261 (put 'diff-changed-face
'face-alias
'diff-changed
)
262 (defvar diff-changed-face
'diff-changed
)
264 (defface diff-indicator-removed
265 '((t :inherit diff-removed
))
266 "`diff-mode' face used to highlight indicator of removed lines (-, <)."
269 (defvar diff-indicator-removed-face
'diff-indicator-removed
)
271 (defface diff-indicator-added
272 '((t :inherit diff-added
))
273 "`diff-mode' face used to highlight indicator of added lines (+, >)."
276 (defvar diff-indicator-added-face
'diff-indicator-added
)
278 (defface diff-indicator-changed
279 '((t :inherit diff-changed
))
280 "`diff-mode' face used to highlight indicator of changed lines."
283 (defvar diff-indicator-changed-face
'diff-indicator-changed
)
285 (defface diff-function
286 '((t :inherit diff-header
))
287 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
289 ;; backward-compatibility alias
290 (put 'diff-function-face
'face-alias
'diff-function
)
291 (defvar diff-function-face
'diff-function
)
293 (defface diff-context
294 '((((class color grayscale
) (min-colors 88)) :inherit shadow
))
295 "`diff-mode' face used to highlight context and other side-information."
297 ;; backward-compatibility alias
298 (put 'diff-context-face
'face-alias
'diff-context
)
299 (defvar diff-context-face
'diff-context
)
301 (defface diff-nonexistent
302 '((t :inherit diff-file-header
))
303 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
305 ;; backward-compatibility alias
306 (put 'diff-nonexistent-face
'face-alias
'diff-nonexistent
)
307 (defvar diff-nonexistent-face
'diff-nonexistent
)
309 (defconst diff-yank-handler
'(diff-yank-function))
310 (defun diff-yank-function (text)
311 ;; FIXME: the yank-handler is now called separately on each piece of text
312 ;; with a yank-handler property, so the next-single-property-change call
313 ;; below will always return nil :-( --stef
314 (let ((mixed (next-single-property-change 0 'yank-handler text
))
316 ;; First insert the text.
318 ;; If the text does not include any diff markers and if we're not
319 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
320 (unless (or mixed
(derived-mode-p 'diff-mode
))
321 (undo-boundary) ; Just in case the user wanted the prefixes.
322 (let ((re (save-excursion
323 (if (re-search-backward "^[><!][ \t]" start t
)
324 (if (eq (char-after) ?
!)
325 "^[!+- ][ \t]" "^[<>][ \t]")
328 (while (re-search-backward re start t
)
329 (replace-match "" t t
)))))))
332 (defvar diff-font-lock-keywords
333 `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
334 (1 diff-hunk-header-face
) (2 diff-function-face
))
335 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
336 (1 diff-hunk-header-face
) (2 diff-function-face
))
337 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face
) ;context
338 ("^--- .+ ----$" . diff-hunk-header-face
) ;context
339 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face
) ;normal
340 ("^---$" . diff-hunk-header-face
) ;normal
341 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\([^\t\n]+\\)\\(.*[^*-]\\)?\n"
342 (0 diff-header-face
) (2 diff-file-header-face prepend
))
343 ("^\\([-<]\\)\\(.*\n\\)"
344 (1 diff-indicator-removed-face
) (2 diff-removed-face
))
345 ("^\\([+>]\\)\\(.*\n\\)"
346 (1 diff-indicator-added-face
) (2 diff-added-face
))
347 ("^\\(!\\)\\(.*\n\\)"
348 (1 diff-indicator-changed-face
) (2 diff-changed-face
))
349 ("^Index: \\(.+\\).*\n"
350 (0 diff-header-face
) (1 diff-index-face prepend
))
351 ("^Only in .*\n" . diff-nonexistent-face
)
353 (1 font-lock-comment-delimiter-face
)
354 (2 font-lock-comment-face
))
355 ("^[^-=+*!<>#].*\n" (0 diff-context-face
))))
357 (defconst diff-font-lock-defaults
358 '(diff-font-lock-keywords t nil nil nil
(font-lock-multiline . nil
)))
360 (defvar diff-imenu-generic-expression
361 ;; Prefer second name as first is most likely to be a backup or
362 ;; version-control name. The [\t\n] at the end of the unidiff pattern
363 ;; catches Debian source diff files (which lack the trailing date).
364 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
365 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
371 (defconst diff-hunk-header-re
"^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
372 (defconst diff-file-header-re
(concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re
1)))
373 (defvar diff-narrowed-to nil
)
375 (defun diff-end-of-hunk (&optional style
)
376 (when (looking-at diff-hunk-header-re
)
378 ;; Especially important for unified (because headers are ambiguous).
379 (setq style
(cdr (assq (char-after) '((?
@ . unified
) (?
* . context
))))))
380 (goto-char (match-end 0)))
381 (let ((end (and (re-search-forward (case style
382 ;; A `unified' header is ambiguous.
383 (unified (concat "^[^-+# \\]\\|"
384 diff-file-header-re
))
385 (context "^[^-+#! \\]")
389 (match-beginning 0))))
390 ;; The return value is used by easy-mmode-define-navigation.
391 (goto-char (or end
(point-max)))))
393 (defun diff-beginning-of-hunk (&optional try-harder
)
394 "Move back to beginning of hunk.
395 If TRY-HARDER is non-nil, try to cater to the case where we're not in a hunk
396 but in the file header instead, in which case move forward to the first hunk."
398 (unless (looking-at diff-hunk-header-re
)
401 (re-search-backward diff-hunk-header-re
)
404 (error "Can't find the beginning of the hunk")
405 (diff-beginning-of-file-and-junk)
406 (diff-hunk-next))))))
408 (defun diff-beginning-of-file ()
410 (unless (looking-at diff-file-header-re
)
413 (re-search-backward diff-file-header-re
)
414 (error (error "Can't find the beginning of the file")))))
416 (defun diff-end-of-file ()
417 (re-search-forward "^[-+#!<>0-9@* \\]" nil t
)
418 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re
)
420 (if (match-beginning 1)
421 (goto-char (match-beginning 1))
422 (beginning-of-line)))
424 ;; Define diff-{hunk,file}-{prev,next}
425 (easy-mmode-define-navigation
426 diff-hunk diff-hunk-header-re
"hunk" diff-end-of-hunk diff-restrict-view
)
427 (easy-mmode-define-navigation
428 diff-file diff-file-header-re
"file" diff-end-of-hunk
)
430 (defun diff-restrict-view (&optional arg
)
431 "Restrict the view to the current hunk.
432 If the prefix ARG is given, restrict the view to the current file instead."
435 (if arg
(diff-beginning-of-file) (diff-beginning-of-hunk 'try-harder
))
436 (narrow-to-region (point)
437 (progn (if arg
(diff-end-of-file) (diff-end-of-hunk))
439 (set (make-local-variable 'diff-narrowed-to
) (if arg
'file
'hunk
))))
442 (defun diff-hunk-kill ()
445 (diff-beginning-of-hunk)
446 (let* ((start (point))
447 (nexthunk (when (re-search-forward diff-hunk-header-re nil t
)
448 (match-beginning 0)))
449 (firsthunk (ignore-errors
451 (diff-beginning-of-file) (diff-hunk-next) (point)))
452 (nextfile (ignore-errors (diff-file-next) (point)))
453 (inhibit-read-only t
))
455 (if (and firsthunk
(= firsthunk start
)
457 (and nextfile
(> nexthunk nextfile
))))
458 ;; It's the only hunk for this file, so kill the file.
461 (kill-region start
(point)))))
463 (defun diff-beginning-of-file-and-junk ()
464 "Go to the beginning of file-related diff-info.
465 This is like `diff-beginning-of-file' except it tries to skip back over leading
466 data such as \"Index: ...\" and such."
467 (let ((start (point))
468 (file (condition-case err
(progn (diff-beginning-of-file) (point))
470 ;; prevhunk is one of the limits.
471 (prevhunk (save-excursion (ignore-errors (diff-hunk-prev) (point))))
474 ;; Presumably, we started before the file header, in the leading junk.
478 (let ((index (save-excursion
479 (re-search-backward "^Index: " prevhunk t
))))
480 (when index
(setq file index
))
483 ;; File starts *after* the starting point: we really weren't in
484 ;; a file diff but elsewhere.
486 (signal (car err
) (cdr err
))))))
488 (defun diff-file-kill ()
489 "Kill current file's hunks."
491 (diff-beginning-of-file-and-junk)
492 (let* ((start (point))
493 (inhibit-read-only t
))
495 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
496 (kill-region start
(point))))
498 (defun diff-kill-junk ()
499 "Kill spurious empty diffs."
502 (let ((inhibit-read-only t
))
503 (goto-char (point-min))
504 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
505 "\\([^-+!* <>].*\n\\)*?"
506 "\\(\\(Index:\\) \\|"
507 diff-file-header-re
"\\)")
509 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
511 (beginning-of-line)))))
513 (defun diff-count-matches (re start end
)
517 (while (re-search-forward re end t
) (incf n
))
520 (defun diff-split-hunk ()
521 "Split the current (unified diff) hunk at point into two hunks."
525 (start (progn (diff-beginning-of-hunk) (point))))
526 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
527 (error "diff-split-hunk only works on unified context diffs"))
529 (let* ((start1 (string-to-number (match-string 1)))
530 (start2 (string-to-number (match-string 2)))
531 (newstart1 (+ start1
(diff-count-matches "^[- \t]" (point) pos
)))
532 (newstart2 (+ start2
(diff-count-matches "^[+ \t]" (point) pos
)))
533 (inhibit-read-only t
))
535 ;; Hopefully the after-change-function will not screw us over.
536 (insert "@@ -" (number-to-string newstart1
) ",1 +"
537 (number-to-string newstart2
) ",1 @@\n")
538 ;; Fix the original hunk-header.
539 (diff-fixup-modifs start pos
))))
543 ;;;; jump to other buffers
546 (defvar diff-remembered-files-alist nil
)
548 (defun diff-filename-drop-dir (file)
549 (when (string-match "/" file
) (substring file
(match-end 0))))
551 (defun diff-merge-strings (ancestor from to
)
552 "Merge the diff between ANCESTOR and FROM into TO.
553 Returns the merged string if successful or nil otherwise.
554 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
555 If ANCESTOR = FROM, returns TO.
556 If ANCESTOR = TO, returns FROM.
557 The heuristic is simplistic and only really works for cases
558 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
560 ;; AMB ANB CMD -> CND
561 ;; but that's ambiguous if `foo' or `bar' is empty:
562 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
563 (let ((str (concat ancestor
"\n" from
"\n" to
)))
564 (when (and (string-match (concat
565 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
567 "\\(.*\\(\\2\\).*\\)\\'") str
)
568 (equal to
(match-string 5 str
)))
569 (concat (substring str
(match-beginning 5) (match-beginning 6))
571 (substring str
(match-end 6) (match-end 5))))))
573 (defun diff-tell-file-name (old name
)
574 "Tell Emacs where the find the source file of the current hunk.
575 If the OLD prefix arg is passed, tell the file NAME of the old file."
577 (let* ((old current-prefix-arg
)
578 (fs (diff-hunk-file-names current-prefix-arg
)))
579 (unless fs
(error "No file name to look for"))
580 (list old
(read-file-name (format "File for %s: " (car fs
))
581 nil
(diff-find-file-name old
) t
))))
582 (let ((fs (diff-hunk-file-names old
)))
583 (unless fs
(error "No file name to look for"))
584 (push (cons fs name
) diff-remembered-files-alist
)))
586 (defun diff-hunk-file-names (&optional old
)
587 "Give the list of file names textually mentioned for the current hunk."
589 (unless (looking-at diff-file-header-re
)
590 (or (ignore-errors (diff-beginning-of-file))
591 (re-search-forward diff-file-header-re nil t
)))
592 (let ((limit (save-excursion
594 (progn (diff-hunk-prev) (point))
595 (error (point-min)))))
597 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
598 (list (if old
(match-string 1) (match-string 3))
599 (if old
(match-string 3) (match-string 1)))
600 (forward-line 1) nil
)))
605 (re-search-backward "^Index: \\(.+\\)" limit t
)))
606 (list (match-string 1)))
608 (when (re-search-backward
609 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
611 (list (if old
(match-string 2) (match-string 4))
612 (if old
(match-string 4) (match-string 2)))))))))
614 (defun diff-find-file-name (&optional old batch prefix
)
615 "Return the file corresponding to the current patch.
616 Non-nil OLD means that we want the old file.
617 Non-nil BATCH means to prefer returning an incorrect answer than to prompt
619 PREFIX is only used internally: don't use it."
621 (unless (looking-at diff-file-header-re
)
622 (or (ignore-errors (diff-beginning-of-file))
623 (re-search-forward diff-file-header-re nil t
)))
624 (let ((fs (diff-hunk-file-names old
)))
625 (if prefix
(setq fs
(mapcar (lambda (f) (concat prefix f
)) fs
)))
627 ;; use any previously used preference
628 (cdr (assoc fs diff-remembered-files-alist
))
629 ;; try to be clever and use previous choices as an inspiration
630 (dolist (rf diff-remembered-files-alist
)
631 (let ((newfile (diff-merge-strings (caar rf
) (car fs
) (cdr rf
))))
632 (if (and newfile
(file-exists-p newfile
)) (return newfile
))))
633 ;; look for each file in turn. If none found, try again but
634 ;; ignoring the first level of directory, ...
635 (do* ((files fs
(delq nil
(mapcar 'diff-filename-drop-dir files
)))
638 (setq file
(do* ((files files
(cdr files
))
639 (file (car files
) (car files
)))
640 ((or (null file
) (file-exists-p file
))
643 ;; <foo>.rej patches implicitly apply to <foo>
644 (and (string-match "\\.rej\\'" (or buffer-file-name
""))
645 (let ((file (substring buffer-file-name
0 (match-beginning 0))))
646 (when (file-exists-p file
) file
)))
647 ;; If we haven't found the file, maybe it's because we haven't paid
648 ;; attention to the PCL-CVS hint.
650 (boundp 'cvs-pcl-cvs-dirchange-re
)
652 (re-search-backward cvs-pcl-cvs-dirchange-re nil t
))
653 (diff-find-file-name old batch
(match-string 1)))
654 ;; Invent something, if necessary.
656 (or (car fs
) default-directory
))
657 ;; if all else fails, ask the user
658 (let ((file (read-file-name (format "Use file %s: " (or (first fs
) ""))
659 nil
(first fs
) t
(first fs
))))
660 (set (make-local-variable 'diff-remembered-files-alist
)
661 (cons (cons fs file
) diff-remembered-files-alist
))
665 (defun diff-ediff-patch ()
666 "Call `ediff-patch-file' on the current buffer."
669 (ediff-patch-file nil
(current-buffer))
670 (wrong-number-of-arguments (ediff-patch-file))))
673 ;;;; Conversion functions
676 ;;(defvar diff-inhibit-after-change nil
677 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
679 (defun diff-unified->context
(start end
)
680 "Convert unified diffs to context diffs.
681 START and END are either taken from the region (if a prefix arg is given) or
682 else cover the whole bufer."
683 (interactive (if (or current-prefix-arg
(and transient-mark-mode mark-active
))
684 (list (region-beginning) (region-end))
685 (list (point-min) (point-max))))
686 (unless (markerp end
) (setq end
(copy-marker end t
)))
687 (let (;;(diff-inhibit-after-change t)
688 (inhibit-read-only t
))
691 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t
)
693 (combine-after-change-calls
694 (if (match-beginning 2)
695 ;; we matched a file header
697 ;; use reverse order to make sure the indices are kept valid
698 (replace-match "---" t t nil
3)
699 (replace-match "***" t t nil
2))
700 ;; we matched a hunk header
701 (let ((line1 (match-string 4))
702 (lines1 (match-string 5))
703 (line2 (match-string 6))
704 (lines2 (match-string 7)))
706 (concat "***************\n*** " line1
","
707 (number-to-string (+ (string-to-number line1
)
708 (string-to-number lines1
)
712 (narrow-to-region (point)
713 (progn (diff-end-of-hunk 'unified
) (point)))
714 (let ((hunk (buffer-string)))
715 (goto-char (point-min))
716 (if (not (save-excursion (re-search-forward "^-" nil t
)))
717 (delete-region (point) (point-max))
718 (goto-char (point-max))
719 (let ((modif nil
) last-pt
)
720 (while (progn (setq last-pt
(point))
721 (= (forward-line -
1) 0))
723 (?\s
(insert " ") (setq modif nil
) (backward-char 1))
724 (?
+ (delete-region (point) last-pt
) (setq modif t
))
726 (progn (forward-char 1)
731 (?
\\ (when (save-excursion (forward-line -
1)
733 (delete-region (point) last-pt
) (setq modif t
)))
734 (t (setq modif nil
))))))
735 (goto-char (point-max))
737 (insert "--- " line2
","
738 (number-to-string (+ (string-to-number line2
)
739 (string-to-number lines2
)
740 -
1)) " ----\n" hunk
))
741 ;;(goto-char (point-min))
743 (if (not (save-excursion (re-search-forward "^+" nil t
)))
744 (delete-region (point) (point-max))
745 (let ((modif nil
) (delete nil
))
748 (?\s
(insert " ") (setq modif nil
) (backward-char 1))
749 (?-
(setq delete t
) (setq modif t
))
751 (progn (forward-char 1)
756 (?
\\ (when (save-excursion (forward-line 1)
758 (setq delete t
) (setq modif t
)))
759 (t (setq modif nil
)))
760 (let ((last-pt (point)))
763 (delete-region last-pt
(point))
764 (setq delete nil
)))))))))))))))
766 (defun diff-context->unified
(start end
&optional to-context
)
767 "Convert context diffs to unified diffs.
768 START and END are either taken from the region
769 \(when it is highlighted) or else cover the whole buffer.
770 With a prefix argument, convert unified format to context format."
771 (interactive (if (and transient-mark-mode mark-active
)
772 (list (region-beginning) (region-end) current-prefix-arg
)
773 (list (point-min) (point-max) current-prefix-arg
)))
775 (diff-unified->context start end
)
776 (unless (markerp end
) (setq end
(copy-marker end t
)))
777 (let ( ;;(diff-inhibit-after-change t)
778 (inhibit-read-only t
))
781 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t
)
783 (combine-after-change-calls
784 (if (match-beginning 2)
785 ;; we matched a file header
787 ;; use reverse order to make sure the indices are kept valid
788 (replace-match "+++" t t nil
3)
789 (replace-match "---" t t nil
2))
790 ;; we matched a hunk header
791 (let ((line1s (match-string 4))
792 (line1e (match-string 5))
793 (pt1 (match-beginning 0)))
795 (unless (re-search-forward
796 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t
)
797 (error "Can't find matching `--- n1,n2 ----' line"))
798 (let ((line2s (match-string 1))
799 (line2e (match-string 2))
801 (delete-region (progn (beginning-of-line) (point))
802 (progn (forward-line 1) (point)))
806 (while (< (point) pt2
)
808 ((?
! ?-
) (delete-char 2) (insert "-") (forward-line 1))
809 (?\s
;merge with the other half of the chunk
812 (goto-char pt2
) (forward-line 1) (point)))
813 (c (char-after pt2
)))
817 (prog1 (buffer-substring (+ pt2
2) endline2
)
818 (delete-region pt2 endline2
))))
819 (?\s
;FIXME: check consistency
820 (delete-region pt2 endline2
)
823 (?
\\ (forward-line 1))
824 (t (delete-char 1) (forward-line 1)))))
825 (t (forward-line 1))))
826 (while (looking-at "[+! ] ")
827 (if (/= (char-after) ?
!) (forward-char 1)
828 (delete-char 1) (insert "+"))
829 (delete-char 1) (forward-line 1))
832 (insert "@@ -" line1s
","
833 (number-to-string (- (string-to-number line1e
)
834 (string-to-number line1s
)
837 (number-to-string (- (string-to-number line2e
)
838 (string-to-number line2s
)
839 -
1)) " @@")))))))))))
841 (defun diff-reverse-direction (start end
)
842 "Reverse the direction of the diffs.
843 START and END are either taken from the region (if a prefix arg is given) or
844 else cover the whole bufer."
845 (interactive (if (or current-prefix-arg
(and transient-mark-mode mark-active
))
846 (list (region-beginning) (region-end))
847 (list (point-min) (point-max))))
848 (unless (markerp end
) (setq end
(copy-marker end t
)))
849 (let (;;(diff-inhibit-after-change t)
850 (inhibit-read-only t
))
853 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t
)
855 (combine-after-change-calls
858 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil
))
859 ;; a context-diff hunk header
861 (let ((pt-lines1 (match-beginning 6))
862 (lines1 (match-string 6)))
863 (replace-match "" nil nil nil
6)
865 (let ((half1s (point)))
866 (while (looking-at "[-! \\][ \t]\\|#")
867 (when (= (char-after) ?-
) (delete-char 1) (insert "+"))
869 (let ((half1 (delete-and-extract-region half1s
(point))))
870 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
872 (error "Can't find matching `--- n1,n2 ----' line"))
873 (let ((str1 (match-string 1)))
874 (replace-match lines1 nil nil nil
1)
876 (let ((half2s (point)))
877 (while (looking-at "[!+ \\][ \t]\\|#")
878 (when (= (char-after) ?
+) (delete-char 1) (insert "-"))
880 (let ((half2 (delete-and-extract-region half2s
(point))))
881 (insert (or half1
""))
883 (insert (or half2
""))))
884 (goto-char pt-lines1
)
886 ;; a unified-diff hunk header
888 (replace-match "@@ -\\8 +\\7 @@" nil
)
890 (let ((c (char-after)) first last
)
891 (while (case (setq c
(char-after))
892 (?-
(setq first
(or first
(point)))
893 (delete-char 1) (insert "+") t
)
894 (?
+ (setq last
(or last
(point)))
895 (delete-char 1) (insert "-") t
)
897 (t (when (and first last
(< first last
))
898 (insert (delete-and-extract-region first last
)))
899 (setq first nil last nil
)
901 (forward-line 1))))))))))
903 (defun diff-fixup-modifs (start end
)
904 "Fixup the hunk headers (in case the buffer was modified).
905 START and END are either taken from the region (if a prefix arg is given) or
906 else cover the whole bufer."
907 (interactive (if (or current-prefix-arg
(and transient-mark-mode mark-active
))
908 (list (region-beginning) (region-end))
909 (list (point-min) (point-max))))
910 (let ((inhibit-read-only t
))
912 (goto-char end
) (diff-end-of-hunk)
913 (let ((plus 0) (minus 0) (space 0) (bang 0))
914 (while (and (= (forward-line -
1) 0) (<= start
(point)))
916 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
917 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
918 "\\|--- .+\n\\+\\+\\+ ")))
925 (t (setq space
0 plus
0 minus
0 bang
0)))
927 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
928 (let* ((old1 (match-string 1))
929 (old2 (match-string 2))
930 (new1 (number-to-string (+ space minus
)))
931 (new2 (number-to-string (+ space plus
))))
932 (unless (string= new2 old2
) (replace-match new2 t t nil
2))
933 (unless (string= new1 old1
) (replace-match new1 t t nil
1))))
934 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
935 (when (> (+ space bang plus
) 0)
936 (let* ((old1 (match-string 1))
937 (old2 (match-string 2))
938 (new (number-to-string
939 (+ space bang plus -
1 (string-to-number old1
)))))
940 (unless (string= new old2
) (replace-match new t t nil
2)))))
941 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
942 (when (> (+ space bang minus
) 0)
943 (let* ((old (match-string 1))
945 (concat "%0" (number-to-string (length old
)) "d")
946 (+ space bang minus -
1 (string-to-number old
)))))
947 (unless (string= new old
) (replace-match new t t nil
2))))))
948 (setq space
0 plus
0 minus
0 bang
0)))))))
954 (defun diff-write-contents-hooks ()
955 "Fixup hunk headers if necessary."
956 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
959 ;; It turns out that making changes in the buffer from within an
960 ;; *-change-function is asking for trouble, whereas making them
961 ;; from a post-command-hook doesn't pose much problems
962 (defvar diff-unhandled-changes nil
)
963 (defun diff-after-change-function (beg end len
)
964 "Remember to fixup the hunk header.
965 See `after-change-functions' for the meaning of BEG, END and LEN."
966 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
967 ;; incorrect, but it turns out that inhibit-read-only is normally not set
968 ;; inside editing commands, while it tends to be set when the buffer gets
969 ;; updated by an async process or by a conversion function, both of which
970 ;; would rather not be uselessly slowed down by this hook.
971 (when (and (not undo-in-progress
) (not inhibit-read-only
))
972 (if diff-unhandled-changes
973 (setq diff-unhandled-changes
974 (cons (min beg
(car diff-unhandled-changes
))
975 (max end
(cdr diff-unhandled-changes
))))
976 (setq diff-unhandled-changes
(cons beg end
)))))
978 (defun diff-post-command-hook ()
979 "Fixup hunk headers if necessary."
980 (when (consp diff-unhandled-changes
)
983 (goto-char (car diff-unhandled-changes
))
984 ;; Maybe we've cut the end of the hunk before point.
985 (if (and (bolp) (not (bobp))) (backward-char 1))
986 ;; We used to fixup modifs on all the changes, but it turns out
987 ;; that it's safer not to do it on big changes, for example
988 ;; when yanking a big diff, since we might then screw up perfectly
989 ;; correct values. -stef
990 ;; (unless (ignore-errors
991 ;; (diff-beginning-of-hunk)
993 ;; (diff-end-of-hunk)
994 ;; (> (point) (car diff-unhandled-changes))))
995 ;; (goto-char (car diff-unhandled-changes))
996 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
997 ;; (diff-beginning-of-hunk))
998 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
999 (diff-beginning-of-hunk)
1000 (when (save-excursion
1002 (>= (point) (cdr diff-unhandled-changes
)))
1003 (diff-fixup-modifs (point) (cdr diff-unhandled-changes
)))))
1004 (setq diff-unhandled-changes nil
)))
1006 (defun diff-next-error (arg reset
)
1007 ;; Select a window that displays the current buffer so that point
1008 ;; movements are reflected in that window. Otherwise, the user might
1009 ;; never see the hunk corresponding to the source she's jumping to.
1010 (pop-to-buffer (current-buffer))
1011 (if reset
(goto-char (point-min)))
1012 (diff-hunk-next arg
)
1016 (define-derived-mode diff-mode fundamental-mode
"Diff"
1017 "Major mode for viewing/editing context diffs.
1018 Supports unified and context diffs as well as (to a lesser extent)
1021 When the buffer is read-only, the ESC prefix is not necessary.
1022 If you edit the buffer manually, diff-mode will try to update the hunk
1023 headers for you on-the-fly.
1025 You can also switch between context diff and unified diff with \\[diff-context->unified],
1026 or vice versa with \\[diff-unified->context] and you can also reverse the direction of
1027 a diff with \\[diff-reverse-direction].
1031 (set (make-local-variable 'font-lock-defaults
) diff-font-lock-defaults
)
1032 (set (make-local-variable 'outline-regexp
) diff-outline-regexp
)
1033 (set (make-local-variable 'imenu-generic-expression
)
1034 diff-imenu-generic-expression
)
1035 ;; These are not perfect. They would be better done separately for
1036 ;; context diffs and unidiffs.
1037 ;; (set (make-local-variable 'paragraph-start)
1038 ;; (concat "@@ " ; unidiff hunk
1039 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1040 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1041 ;; ; start (first or second line)
1042 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1043 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1045 (set (make-local-variable 'next-error-function
) 'diff-next-error
)
1047 (setq buffer-read-only diff-default-read-only
)
1048 ;; setup change hooks
1049 (if (not diff-update-on-the-fly
)
1050 (add-hook 'write-contents-functions
'diff-write-contents-hooks nil t
)
1051 (make-local-variable 'diff-unhandled-changes
)
1052 (add-hook 'after-change-functions
'diff-after-change-function nil t
)
1053 (add-hook 'post-command-hook
'diff-post-command-hook nil t
))
1054 ;; Neat trick from Dave Love to add more bindings in read-only mode:
1055 (lexical-let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map
)))
1056 (add-to-list 'minor-mode-overriding-map-alist ro-bind
)
1057 ;; Turn off this little trick in case the buffer is put in view-mode.
1058 (add-hook 'view-mode-hook
1060 (setq minor-mode-overriding-map-alist
1061 (delq ro-bind minor-mode-overriding-map-alist
)))
1064 (set (make-local-variable 'add-log-current-defun-function
)
1065 'diff-current-defun
)
1066 (set (make-local-variable 'add-log-buffer-file-name-function
)
1067 'diff-find-file-name
))
1070 (define-minor-mode diff-minor-mode
1071 "Minor mode for viewing/editing context diffs.
1072 \\{diff-minor-mode-map}"
1073 :group
'diff-mode
:lighter
" Diff"
1074 ;; FIXME: setup font-lock
1075 ;; setup change hooks
1076 (if (not diff-update-on-the-fly
)
1077 (add-hook 'write-contents-functions
'diff-write-contents-hooks nil t
)
1078 (make-local-variable 'diff-unhandled-changes
)
1079 (add-hook 'after-change-functions
'diff-after-change-function nil t
)
1080 (add-hook 'post-command-hook
'diff-post-command-hook nil t
)))
1082 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1084 (defun diff-delete-if-empty ()
1085 ;; An empty diff file means there's no more diffs to integrate, so we
1086 ;; can just remove the file altogether. Very handy for .rej files if we
1087 ;; remove hunks as we apply them.
1088 (when (and buffer-file-name
1089 (eq 0 (nth 7 (file-attributes buffer-file-name
))))
1090 (delete-file buffer-file-name
)))
1092 (defun diff-delete-empty-files ()
1093 "Arrange for empty diff files to be removed."
1094 (add-hook 'after-save-hook
'diff-delete-if-empty nil t
))
1096 (defun diff-make-unified ()
1097 "Turn context diffs into unified diffs if applicable."
1099 (goto-char (point-min))
1100 (and (looking-at diff-hunk-header-re
) (eq (char-after) ?
*)))
1101 (let ((mod (buffer-modified-p)))
1103 (diff-context->unified
(point-min) (point-max))
1104 (restore-buffer-modified-p mod
)))))
1107 ;;; Misc operations that have proved useful at some point.
1110 (defun diff-next-complex-hunk ()
1111 "Jump to the next \"complex\" hunk.
1112 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1113 Only works for unified diffs."
1116 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1118 (equal (match-string 1) (match-string 2)))))
1120 (defun diff-sanity-check-context-hunk-half (lines)
1121 (let ((count lines
))
1124 ((and (memq (char-after) '(?\s ?
! ?
+ ?-
))
1125 (memq (char-after (1+ (point))) '(?\s ?
\t)))
1127 ((or (zerop count
) (= count lines
)) nil
)
1128 ((memq (char-after) '(?
! ?
+ ?-
))
1129 (if (not (and (eq (char-after (1+ (point))) ?
\n)
1130 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1131 (error "End of hunk ambiguously marked")
1132 (forward-char 1) (insert " ") (forward-line -
1) t
))
1134 (error "End of hunk ambiguously marked"))
1135 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1137 ((eolp) (insert " ") (forward-line -
1) t
)
1138 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t
))
1141 (defun diff-sanity-check-hunk ()
1142 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1143 ;; OK to override a read-only setting.
1144 (inhibit-read-only t
))
1147 ((not (looking-at diff-hunk-header-re
))
1148 (error "Not recognizable hunk header"))
1151 ((eq (char-after) ?
*)
1152 (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\),\\([0-9]+\\) \\*\\*\\*\\*"))
1153 (error "Unrecognized context diff first hunk header format")
1155 (diff-sanity-check-context-hunk-half
1156 (1+ (- (string-to-number (match-string 2))
1157 (string-to-number (match-string 1)))))
1158 (if (not (looking-at "--- \\([0-9]+\\),\\([0-9]+\\) ----$"))
1159 (error "Unrecognized context diff second hunk header format")
1161 (diff-sanity-check-context-hunk-half
1162 (1+ (- (string-to-number (match-string 2))
1163 (string-to-number (match-string 1))))))))
1166 ((eq (char-after) ?
@)
1167 (if (not (looking-at
1168 "@@ -[0-9]+,\\([0-9]+\\) \\+[0-9]+,\\([0-9]+\\) @@"))
1169 (error "Unrecognized unified diff hunk header format")
1170 (let ((before (string-to-number (match-string 1)))
1171 (after (string-to-number (match-string 2))))
1175 (?\s
(decf before
) (decf after
) t
)
1176 (?-
(decf before
) t
)
1180 ((and (zerop before
) (zerop after
)) nil
)
1181 ((or (< before
0) (< after
0))
1182 (error (if (or (zerop before
) (zerop after
))
1183 "End of hunk ambiguously marked"
1184 "Hunk seriously messed up")))
1185 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1187 ((eolp) (insert " ") (forward-line -
1) t
)
1189 (delete-region (- (point) 2) (- (point) 1)) t
))))
1197 (defun diff-hunk-text (hunk destp char-offset
)
1198 "Return the literal source text from HUNK as (TEXT . OFFSET).
1199 If DESTP is nil, TEXT is the source, otherwise the destination text.
1200 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1201 char-offset in TEXT."
1204 (goto-char (point-min))
1209 ;; Set the following variables:
1210 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1211 ;; DST-POS buffer pos of the destination part of the hunk or nil
1212 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1213 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1214 (cond ((looking-at "^@@")
1216 (setq num-pfx-chars
1)
1218 (setq src-pos
(point) dst-pos
(point)))
1219 ((looking-at "^\\*\\*")
1222 (setq src-pos
(point))
1223 (re-search-forward "^--- " nil t
)
1225 (setq divider-pos
(point))
1227 (setq dst-pos
(point)))
1228 ((looking-at "^[0-9]+a[0-9,]+$")
1229 ;; normal diff, insert
1231 (setq dst-pos
(point)))
1232 ((looking-at "^[0-9,]+d[0-9]+$")
1233 ;; normal diff, delete
1235 (setq src-pos
(point)))
1236 ((looking-at "^[0-9,]+c[0-9,]+$")
1237 ;; normal diff, change
1239 (setq src-pos
(point))
1240 (re-search-forward "^---$" nil t
)
1242 (setq divider-pos
(point))
1244 (setq dst-pos
(point)))
1246 (error "Unknown diff hunk type")))
1248 (if (if destp
(null dst-pos
) (null src-pos
))
1249 ;; Implied empty text
1250 (if char-offset
'("" .
0) "")
1252 ;; For context diffs, either side can be empty, (if there's only
1253 ;; added or only removed text). We should then use the other side.
1254 (cond ((equal src-pos divider-pos
) (setq src-pos dst-pos
))
1255 ((equal dst-pos
(point-max)) (setq dst-pos src-pos
)))
1257 (when char-offset
(goto-char (+ (point-min) char-offset
)))
1259 ;; Get rid of anything except the desired text.
1261 ;; Delete unused text region
1262 (let ((keep (if destp dst-pos src-pos
)))
1263 (when (and divider-pos
(> divider-pos keep
))
1264 (delete-region divider-pos
(point-max)))
1265 (delete-region (point-min) keep
))
1266 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1267 (let ((kill-char (if destp ?- ?
+)))
1268 (goto-char (point-min))
1270 (if (eq (char-after) kill-char
)
1271 (delete-region (point) (progn (forward-line 1) (point)))
1272 (delete-char num-pfx-chars
)
1273 (forward-line 1)))))
1275 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1276 (if char-offset
(cons text
(- (point) (point-min))) text
))))))
1279 (defun diff-find-text (text)
1280 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1281 If TEXT isn't found, nil is returned."
1282 (let* ((orig (point))
1283 (forw (and (search-forward text nil t
)
1284 (cons (match-beginning 0) (match-end 0))))
1285 (back (and (goto-char (+ orig
(length text
)))
1286 (search-backward text nil t
)
1287 (cons (match-beginning 0) (match-end 0)))))
1288 ;; Choose the closest match.
1290 (if (> (- (car forw
) orig
) (- orig
(car back
))) back forw
)
1293 (defun diff-find-approx-text (text)
1294 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1295 Whitespace differences are ignored."
1296 (let* ((orig (point))
1297 (re (concat "^[ \t\n\f]*"
1298 (mapconcat 'regexp-quote
(split-string text
) "[ \t\n\f]+")
1300 (forw (and (re-search-forward re nil t
)
1301 (cons (match-beginning 0) (match-end 0))))
1302 (back (and (goto-char (+ orig
(length text
)))
1303 (re-search-backward re nil t
)
1304 (cons (match-beginning 0) (match-end 0)))))
1305 ;; Choose the closest match.
1307 (if (> (- (car forw
) orig
) (- orig
(car back
))) back forw
)
1310 (defsubst diff-xor
(a b
) (if a
(if (not b
) a
) b
))
1312 (defun diff-find-source-location (&optional other-file reverse
)
1313 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1314 BUF is the buffer corresponding to the source file.
1315 LINE-OFFSET is the offset between the expected and actual positions
1316 of the text of the hunk or nil if the text was not found.
1317 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1318 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1319 SRC is the variant that was found in the buffer.
1320 SWITCHED is non-nil if the patch is already applied."
1322 (let* ((other (diff-xor other-file diff-jump-to-old-file
))
1323 (char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder
)
1325 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1326 ;; the user may disagree on what constitutes the hunk
1327 ;; (e.g. because an empty line truncates the hunk mid-course),
1328 ;; leading to potentially nasty surprises for the user.
1329 (_ (diff-sanity-check-hunk))
1330 (hunk (buffer-substring (point)
1331 (save-excursion (diff-end-of-hunk) (point))))
1332 (old (diff-hunk-text hunk reverse char-offset
))
1333 (new (diff-hunk-text hunk
(not reverse
) char-offset
))
1334 ;; Find the location specification.
1335 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1336 (error "Can't find the hunk header")
1337 (if other
(match-string 1)
1338 (if (match-end 3) (match-string 3)
1339 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t
)
1340 (error "Can't find the hunk separator"))
1341 (match-string 1)))))
1342 (file (or (diff-find-file-name other
) (error "Can't find the file")))
1343 (buf (find-file-noselect file
)))
1344 ;; Update the user preference if he so wished.
1345 (when (> (prefix-numeric-value other-file
) 8)
1346 (setq diff-jump-to-old-file other
))
1347 (with-current-buffer buf
1348 (goto-line (string-to-number line
))
1349 (let* ((orig-pos (point))
1351 ;; FIXME: Check for case where both OLD and NEW are found.
1352 (pos (or (diff-find-text (car old
))
1353 (progn (setq switched t
) (diff-find-text (car new
)))
1354 (progn (setq switched nil
)
1356 (diff-find-approx-text (car old
))
1357 (invalid-regexp nil
))) ;Regex too big.
1358 (progn (setq switched t
)
1360 (diff-find-approx-text (car new
))
1361 (invalid-regexp nil
))) ;Regex too big.
1362 (progn (setq switched nil
) nil
))))
1366 (list (count-lines orig-pos
(car pos
)) pos
)
1367 (list nil
(cons orig-pos
(+ orig-pos
(length (car old
))))))
1368 (if switched
(list new old t
) (list old new
))))))))
1371 (defun diff-hunk-status-msg (line-offset reversed dry-run
)
1372 (let ((msg (if dry-run
1373 (if reversed
"already applied" "not yet applied")
1374 (if reversed
"undone" "applied"))))
1375 (message (cond ((null line-offset
) "Hunk text not found")
1376 ((= line-offset
0) "Hunk %s")
1377 ((= line-offset
1) "Hunk %s at offset %d line")
1378 (t "Hunk %s at offset %d lines"))
1381 (defvar diff-apply-hunk-to-backup-file nil
)
1383 (defun diff-apply-hunk (&optional reverse
)
1384 "Apply the current hunk to the source file and go to the next.
1385 By default, the new source file is patched, but if the variable
1386 `diff-jump-to-old-file' is non-nil, then the old source file is
1387 patched instead (some commands, such as `diff-goto-source' can change
1388 the value of this variable when given an appropriate prefix argument).
1390 With a prefix argument, REVERSE the hunk."
1392 (destructuring-bind (buf line-offset pos old new
&optional switched
)
1393 ;; Sometimes we'd like to have the following behavior: if REVERSE go
1394 ;; to the new file, otherwise go to the old. But that means that by
1395 ;; default we use the old file, which is the opposite of the default
1396 ;; for diff-goto-source, and is thus confusing. Also when you don't
1397 ;; know about it it's pretty surprising.
1398 ;; TODO: make it possible to ask explicitly for this behavior.
1400 ;; This is duplicated in diff-test-hunk.
1401 (diff-find-source-location nil reverse
)
1404 (error "Can't find the text to patch"))
1405 ((with-current-buffer buf
1406 (and buffer-file-name
1407 (backup-file-name-p buffer-file-name
)
1408 (not diff-apply-hunk-to-backup-file
)
1409 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file
)
1410 (yes-or-no-p (format "Really apply this hunk to %s? "
1411 (file-name-nondirectory
1412 buffer-file-name
)))))))
1414 (substitute-command-keys
1415 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1416 (if (not reverse
) "\\[universal-argument] ")))))
1418 ;; A reversed patch was detected, perhaps apply it in reverse.
1419 (not (save-window-excursion
1421 (goto-char (+ (car pos
) (cdr old
)))
1424 "Hunk hasn't been applied yet; apply it now? "
1425 "Hunk has already been applied; undo it? ")))))
1426 (message "(Nothing done)"))
1429 (with-current-buffer buf
1430 (goto-char (car pos
))
1431 (delete-region (car pos
) (cdr pos
))
1433 ;; Display BUF in a window
1434 (set-window-point (display-buffer buf
) (+ (car pos
) (cdr new
)))
1435 (diff-hunk-status-msg line-offset
(diff-xor switched reverse
) nil
)
1436 (when diff-advance-after-apply-hunk
1437 (diff-hunk-next))))))
1440 (defun diff-test-hunk (&optional reverse
)
1441 "See whether it's possible to apply the current hunk.
1442 With a prefix argument, try to REVERSE the hunk."
1444 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1445 (diff-find-source-location nil reverse
)
1446 (set-window-point (display-buffer buf
) (+ (car pos
) (cdr src
)))
1447 (diff-hunk-status-msg line-offset
(diff-xor reverse switched
) t
)))
1450 (defalias 'diff-mouse-goto-source
'diff-goto-source
)
1452 (defun diff-goto-source (&optional other-file event
)
1453 "Jump to the corresponding source line.
1454 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1455 is given) determines whether to jump to the old or the new file.
1456 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1457 then `diff-jump-to-old-file' is also set, for the next invocations."
1458 (interactive (list current-prefix-arg last-input-event
))
1459 ;; When pointing at a removal line, we probably want to jump to
1460 ;; the old location, and else to the new (i.e. as if reverting).
1461 ;; This is a convenient detail when using smerge-diff.
1462 (if event
(posn-set-point (event-end event
)))
1463 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1464 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1465 (diff-find-source-location other-file rev
)
1467 (goto-char (+ (car pos
) (cdr src
)))
1468 (diff-hunk-status-msg line-offset
(diff-xor rev switched
) t
))))
1471 (defun diff-current-defun ()
1472 "Find the name of function at point.
1473 For use in `add-log-current-defun-function'."
1475 (when (looking-at diff-hunk-header-re
)
1477 (re-search-forward "^[^ ]" nil t
))
1478 (destructuring-bind (buf line-offset pos src dst
&optional switched
)
1479 (diff-find-source-location)
1481 (or (when (memq (char-after) '(?
< ?-
))
1482 ;; Cursor is pointing at removed text. This could be a removed
1483 ;; function, in which case, going to the source buffer will
1484 ;; not help since the function is now removed. Instead,
1485 ;; try to figure out the function name just from the code-fragment.
1486 (let ((old (if switched dst src
)))
1489 (funcall (with-current-buffer buf major-mode
))
1490 (goto-char (+ (point-min) (cdr old
)))
1491 (add-log-current-defun))))
1492 (with-current-buffer buf
1493 (goto-char (+ (car pos
) (cdr src
)))
1494 (add-log-current-defun))))))
1496 (defun diff-refine-hunk ()
1497 "Refine the current hunk by ignoring space differences."
1499 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder
)
1501 (opts (case (char-after) (?
@ "-bu") (?
* "-bc") (t "-b")))
1502 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1503 (error "Can't find line number"))
1504 (string-to-number (match-string 1))))
1505 (hunk (delete-and-extract-region
1506 (point) (save-excursion (diff-end-of-hunk) (point))))
1507 (lead (make-string (1- line-nb
) ?
\n)) ;Line nums start at 1.
1508 (file1 (make-temp-file "diff1"))
1509 (file2 (make-temp-file "diff2"))
1510 (coding-system-for-read buffer-file-coding-system
)
1511 (inhibit-read-only t
)
1515 (setq old
(diff-hunk-text hunk nil char-offset
))
1516 (setq new
(diff-hunk-text hunk t char-offset
))
1517 (write-region (concat lead
(car old
)) nil file1 nil
'nomessage
)
1518 (write-region (concat lead
(car new
)) nil file2 nil
'nomessage
)
1521 (call-process diff-command nil t nil
1524 (0 nil
) ;Nothing to reformat.
1525 (1 (goto-char (point-min))
1526 ;; Remove the file-header.
1527 (when (re-search-forward diff-hunk-header-re nil t
)
1528 (delete-region (point-min) (match-beginning 0))))
1529 (t (goto-char (point-max))
1530 (unless (bolp) (insert "\n"))
1532 (setq hunk
(buffer-string))
1533 (unless (memq status
'(0 1))
1534 (error "Diff returned: %s" status
)))))
1535 ;; Whatever happens, put back some equivalent text: either the new
1536 ;; one or the original one in case some error happened.
1539 (delete-file file2
))))
1541 ;; provide the package
1542 (provide 'diff-mode
)
1544 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1545 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1546 ;; (diff-mode-load-hook): dropped.
1547 ;; (auto-mode-alist): also catch *.diffs.
1548 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1549 ;; for *.rej files (that lack any file name indication).
1551 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1552 ;; added support for "\ No newline at end of file".
1554 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1555 ;; - added basic `compile' support.
1556 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1557 ;; - diff-kill-file now tries to kill the leading garbage as well.
1559 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1560 ;; - don't use CL in the autoloaded code
1561 ;; - accept diffs using -T
1563 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1564 ;; interface to ediff-patch
1566 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1567 ;; (ediff=patch-file): add bindings to call ediff-patch.
1568 ;; (diff-find-file-name): taken out of diff-goto-source.
1569 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1570 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1572 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1573 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1575 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1576 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1579 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1580 ;;; diff-mode.el ends here