1 ;;; diff-mode.el --- a mode for viewing/editing context diffs
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006 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".
50 ;; - Refine hunk on a word-by-word basis.
52 ;; - Handle `diff -b' output in context->unified.
56 (eval-when-compile (require 'cl))
58 (defvar add-log-buffer-file-name-function)
61 (defgroup diff-mode ()
62 "Major mode for viewing/editing diffs."
67 (defcustom diff-default-read-only nil
68 "If non-nil, `diff-mode' buffers default to being read-only."
72 (defcustom diff-jump-to-old-file 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 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 (defcustom diff-advance-after-apply-hunk t
89 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
94 (defcustom diff-mode-hook nil
95 "Run after setting up the `diff-mode' major mode."
97 :options '(diff-delete-empty-files diff-make-unified)
100 (defvar diff-outline-regexp
101 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
104 ;;;; keymap, menu, ...
107 (easy-mmode-defmap diff-mode-shared-map
108 '(;; From Pavel Machek's patch-mode.
109 ("n" . diff-hunk-next)
110 ("N" . diff-file-next)
111 ("p" . diff-hunk-prev)
112 ("P" . diff-file-prev)
113 ("k" . diff-hunk-kill)
114 ("K" . diff-file-kill)
115 ;; From compilation-minor-mode.
116 ("}" . diff-file-next)
117 ("{" . diff-file-prev)
118 ("\C-m" . diff-goto-source)
119 ([mouse-2] . diff-goto-source)
120 ;; From XEmacs' diff-mode.
121 ;; Standard M-w is useful, so don't change M-W.
123 ;;("." . diff-goto-source) ;display-buffer
124 ;;("f" . diff-goto-source) ;find-file
125 ("o" . diff-goto-source) ;other-window
126 ;;("w" . diff-goto-source) ;other-frame
127 ;;("N" . diff-narrow)
128 ;;("h" . diff-show-header)
129 ;;("j" . diff-show-difference) ;jump to Nth diff
131 ;; Not useful if you have to metafy them.
133 ;; ("\177" . scroll-down)
134 ;; Standard M-a is useful, so don't change M-A.
135 ;; ("A" . diff-ediff-patch)
136 ;; Standard M-r is useful, so don't change M-r or M-R.
137 ;; ("r" . diff-restrict-view)
138 ;; ("R" . diff-reverse-direction)
140 "Basic keymap for `diff-mode', bound to various prefix keys.")
142 (easy-mmode-defmap diff-mode-map
143 `(("\e" . ,diff-mode-shared-map)
144 ;; From compilation-minor-mode.
145 ("\C-c\C-c" . diff-goto-source)
147 ("\C-c\C-a" . diff-apply-hunk)
148 ("\C-c\C-e" . diff-ediff-patch)
149 ("\C-c\C-n" . diff-restrict-view)
150 ("\C-c\C-r" . diff-reverse-direction)
151 ("\C-c\C-s" . diff-split-hunk)
152 ("\C-c\C-t" . diff-test-hunk)
153 ("\C-c\C-u" . diff-context->unified)
154 ("\C-c\C-w" . diff-refine-hunk)
155 ("\C-c\C-f" . next-error-follow-minor-mode))
156 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
158 (easy-menu-define diff-mode-menu diff-mode-map
159 "Menu for `diff-mode'."
161 ["Jump to Source" diff-goto-source t]
162 ["Apply hunk" diff-apply-hunk t]
163 ["Apply diff with Ediff" diff-ediff-patch t]
165 ["Reverse direction" diff-reverse-direction t]
166 ["Context -> Unified" diff-context->unified t]
167 ["Unified -> Context" diff-unified->context t]
168 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
171 (defcustom diff-minor-mode-prefix "\C-c="
172 "Prefix key for `diff-minor-mode' commands."
173 :type '(choice (string "\e") (string "C-c=") string)
176 (easy-mmode-defmap diff-minor-mode-map
177 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
178 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
182 ;;;; font-lock support
186 '((((class color) (min-colors 88) (background light))
187 :background "grey85")
188 (((class color) (min-colors 88) (background dark))
189 :background "grey45")
190 (((class color) (background light))
191 :foreground "blue1" :weight bold)
192 (((class color) (background dark))
193 :foreground "green" :weight bold)
195 "`diff-mode' face inherited by hunk and index header faces."
197 ;; backward-compatibility alias
198 (put 'diff-header-face 'face-alias 'diff-header)
199 (defvar diff-header-face 'diff-header)
201 (defface diff-file-header
202 '((((class color) (min-colors 88) (background light))
203 :background "grey70" :weight bold)
204 (((class color) (min-colors 88) (background dark))
205 :background "grey60" :weight bold)
206 (((class color) (background light))
207 :foreground "green" :weight bold)
208 (((class color) (background dark))
209 :foreground "cyan" :weight bold)
210 (t :weight bold)) ; :height 1.3
211 "`diff-mode' face used to highlight file header lines."
213 ;; backward-compatibility alias
214 (put 'diff-file-header-face 'face-alias 'diff-file-header)
215 (defvar diff-file-header-face 'diff-file-header)
218 '((t :inherit diff-file-header))
219 "`diff-mode' face used to highlight index header lines."
221 ;; backward-compatibility alias
222 (put 'diff-index-face 'face-alias 'diff-index)
223 (defvar diff-index-face 'diff-index)
225 (defface diff-hunk-header
226 '((t :inherit diff-header))
227 "`diff-mode' face used to highlight hunk header lines."
229 ;; backward-compatibility alias
230 (put 'diff-hunk-header-face 'face-alias 'diff-hunk-header)
231 (defvar diff-hunk-header-face 'diff-hunk-header)
233 (defface diff-removed
234 '((t :inherit diff-changed))
235 "`diff-mode' face used to highlight removed lines."
237 ;; backward-compatibility alias
238 (put 'diff-removed-face 'face-alias 'diff-removed)
239 (defvar diff-removed-face 'diff-removed)
242 '((t :inherit diff-changed))
243 "`diff-mode' face used to highlight added lines."
245 ;; backward-compatibility alias
246 (put 'diff-added-face 'face-alias 'diff-added)
247 (defvar diff-added-face 'diff-added)
249 (defface diff-changed
250 '((((type tty pc) (class color) (background light))
251 :foreground "magenta" :weight bold :slant italic)
252 (((type tty pc) (class color) (background dark))
253 :foreground "yellow" :weight bold :slant italic))
254 "`diff-mode' face used to highlight changed lines."
256 ;; backward-compatibility alias
257 (put 'diff-changed-face 'face-alias 'diff-changed)
258 (defvar diff-changed-face 'diff-changed)
260 (defface diff-indicator-removed
261 '((t :inherit diff-removed))
262 "`diff-mode' face used to highlight indicator of removed lines (-, <)."
265 (defvar diff-indicator-removed-face 'diff-indicator-removed)
267 (defface diff-indicator-added
268 '((t :inherit diff-added))
269 "`diff-mode' face used to highlight indicator of added lines (+, >)."
272 (defvar diff-indicator-added-face 'diff-indicator-added)
274 (defface diff-indicator-changed
275 '((t :inherit diff-changed))
276 "`diff-mode' face used to highlight indicator of changed lines."
279 (defvar diff-indicator-changed-face 'diff-indicator-changed)
281 (defface diff-function
282 '((t :inherit diff-header))
283 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
285 ;; backward-compatibility alias
286 (put 'diff-function-face 'face-alias 'diff-function)
287 (defvar diff-function-face 'diff-function)
289 (defface diff-context
290 '((((class color grayscale) (min-colors 88)) :inherit shadow))
291 "`diff-mode' face used to highlight context and other side-information."
293 ;; backward-compatibility alias
294 (put 'diff-context-face 'face-alias 'diff-context)
295 (defvar diff-context-face 'diff-context)
297 (defface diff-nonexistent
298 '((t :inherit diff-file-header))
299 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
301 ;; backward-compatibility alias
302 (put 'diff-nonexistent-face 'face-alias 'diff-nonexistent)
303 (defvar diff-nonexistent-face 'diff-nonexistent)
305 (defconst diff-yank-handler '(diff-yank-function))
306 (defun diff-yank-function (text)
307 ;; FIXME: the yank-handler is now called separately on each piece of text
308 ;; with a yank-handler property, so the next-single-property-change call
309 ;; below will always return nil :-( --stef
310 (let ((mixed (next-single-property-change 0 'yank-handler text))
312 ;; First insert the text.
314 ;; If the text does not include any diff markers and if we're not
315 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
316 (unless (or mixed (derived-mode-p 'diff-mode))
317 (undo-boundary) ; Just in case the user wanted the prefixes.
318 (let ((re (save-excursion
319 (if (re-search-backward "^[><!][ \t]" start t)
320 (if (eq (char-after) ?!)
321 "^[!+- ][ \t]" "^[<>][ \t]")
324 (while (re-search-backward re start t)
325 (replace-match "" t t)))))))
328 (defvar diff-font-lock-keywords
329 `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
330 (1 diff-hunk-header-face) (2 diff-function-face))
331 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
332 (1 diff-hunk-header-face) (2 diff-function-face))
333 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
334 ("^--- .+ ----$" . diff-hunk-header-face) ;context
335 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face) ;normal
336 ("^---$" . diff-hunk-header-face) ;normal
337 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
338 (0 diff-header-face) (2 diff-file-header-face prepend))
339 ("^\\([-<]\\)\\(.*\n\\)"
340 (1 diff-indicator-removed-face) (2 diff-removed-face))
341 ("^\\([+>]\\)\\(.*\n\\)"
342 (1 diff-indicator-added-face) (2 diff-added-face))
343 ("^\\(!\\)\\(.*\n\\)"
344 (1 diff-indicator-changed-face) (2 diff-changed-face))
345 ("^Index: \\(.+\\).*\n"
346 (0 diff-header-face) (1 diff-index-face prepend))
347 ("^Only in .*\n" . diff-nonexistent-face)
349 (1 font-lock-comment-delimiter-face)
350 (2 font-lock-comment-face))
351 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
353 (defconst diff-font-lock-defaults
354 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
356 (defvar diff-imenu-generic-expression
357 ;; Prefer second name as first is most likely to be a backup or
358 ;; version-control name. The [\t\n] at the end of the unidiff pattern
359 ;; catches Debian source diff files (which lack the trailing date).
360 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
361 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
367 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
368 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
369 (defvar diff-narrowed-to nil)
371 (defun diff-end-of-hunk (&optional style)
372 (when (looking-at diff-hunk-header-re)
374 ;; Especially important for unified (because headers are ambiguous).
375 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context))))))
376 (goto-char (match-end 0)))
377 (let ((end (and (re-search-forward (case style
378 ;; A `unified' header is ambiguous.
379 (unified (concat "^[^-+# \\]\\|"
380 diff-file-header-re))
381 (context "^[^-+#! \\]")
385 (match-beginning 0))))
386 ;; The return value is used by easy-mmode-define-navigation.
387 (goto-char (or end (point-max)))))
389 (defun diff-beginning-of-hunk ()
391 (unless (looking-at diff-hunk-header-re)
394 (re-search-backward diff-hunk-header-re)
395 (error (error "Can't find the beginning of the hunk")))))
397 (defun diff-beginning-of-file ()
399 (unless (looking-at diff-file-header-re)
402 (re-search-backward diff-file-header-re)
403 (error (error "Can't find the beginning of the file")))))
405 (defun diff-end-of-file ()
406 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
407 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
409 (if (match-beginning 1)
410 (goto-char (match-beginning 1))
411 (beginning-of-line)))
413 ;; Define diff-{hunk,file}-{prev,next}
414 (easy-mmode-define-navigation
415 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
416 (easy-mmode-define-navigation
417 diff-file diff-file-header-re "file" diff-end-of-hunk)
419 (defun diff-restrict-view (&optional arg)
420 "Restrict the view to the current hunk.
421 If the prefix ARG is given, restrict the view to the current file instead."
424 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk))
425 (narrow-to-region (point)
426 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
428 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
431 (defun diff-hunk-kill ()
434 (diff-beginning-of-hunk)
435 (let* ((start (point))
436 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
437 (match-beginning 0)))
438 (firsthunk (ignore-errors
440 (diff-beginning-of-file) (diff-hunk-next) (point)))
441 (nextfile (ignore-errors (diff-file-next) (point)))
442 (inhibit-read-only t))
444 (if (and firsthunk (= firsthunk start)
446 (and nextfile (> nexthunk nextfile))))
447 ;; It's the only hunk for this file, so kill the file.
450 (kill-region start (point)))))
452 (defun diff-file-kill ()
453 "Kill current file's hunks."
455 (diff-beginning-of-file)
456 (let* ((start (point))
457 (prevhunk (save-excursion
459 (diff-hunk-prev) (point))))
460 (index (save-excursion
461 (re-search-backward "^Index: " prevhunk t)))
462 (inhibit-read-only t))
463 (when index (setq start index))
465 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
466 (kill-region start (point))))
468 (defun diff-kill-junk ()
469 "Kill spurious empty diffs."
472 (let ((inhibit-read-only t))
473 (goto-char (point-min))
474 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
475 "\\([^-+!* <>].*\n\\)*?"
476 "\\(\\(Index:\\) \\|"
477 diff-file-header-re "\\)")
479 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
481 (beginning-of-line)))))
483 (defun diff-count-matches (re start end)
487 (while (re-search-forward re end t) (incf n))
490 (defun diff-split-hunk ()
491 "Split the current (unified diff) hunk at point into two hunks."
495 (start (progn (diff-beginning-of-hunk) (point))))
496 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
497 (error "diff-split-hunk only works on unified context diffs"))
499 (let* ((start1 (string-to-number (match-string 1)))
500 (start2 (string-to-number (match-string 2)))
501 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
502 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
503 (inhibit-read-only t))
505 ;; Hopefully the after-change-function will not screw us over.
506 (insert "@@ -" (number-to-string newstart1) ",1 +"
507 (number-to-string newstart2) ",1 @@\n")
508 ;; Fix the original hunk-header.
509 (diff-fixup-modifs start pos))))
513 ;;;; jump to other buffers
516 (defvar diff-remembered-files-alist nil)
518 (defun diff-filename-drop-dir (file)
519 (when (string-match "/" file) (substring file (match-end 0))))
521 (defun diff-merge-strings (ancestor from to)
522 "Merge the diff between ANCESTOR and FROM into TO.
523 Returns the merged string if successful or nil otherwise.
524 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
525 If ANCESTOR = FROM, returns TO.
526 If ANCESTOR = TO, returns FROM.
527 The heuristic is simplistic and only really works for cases
528 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
530 ;; AMB ANB CMD -> CND
531 ;; but that's ambiguous if `foo' or `bar' is empty:
532 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
533 (let ((str (concat ancestor "\n" from "\n" to)))
534 (when (and (string-match (concat
535 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
537 "\\(.*\\(\\2\\).*\\)\\'") str)
538 (equal to (match-string 5 str)))
539 (concat (substring str (match-beginning 5) (match-beginning 6))
541 (substring str (match-end 6) (match-end 5))))))
543 (defun diff-tell-file-name (old name)
544 "Tell Emacs where the find the source file of the current hunk.
545 If the OLD prefix arg is passed, tell the file NAME of the old file."
547 (let* ((old current-prefix-arg)
548 (fs (diff-hunk-file-names current-prefix-arg)))
549 (unless fs (error "No file name to look for"))
550 (list old (read-file-name (format "File for %s: " (car fs))
551 nil (diff-find-file-name old) t))))
552 (let ((fs (diff-hunk-file-names old)))
553 (unless fs (error "No file name to look for"))
554 (push (cons fs name) diff-remembered-files-alist)))
556 (defun diff-hunk-file-names (&optional old)
557 "Give the list of file names textually mentioned for the current hunk."
559 (unless (looking-at diff-file-header-re)
560 (or (ignore-errors (diff-beginning-of-file))
561 (re-search-forward diff-file-header-re nil t)))
562 (let ((limit (save-excursion
564 (progn (diff-hunk-prev) (point))
565 (error (point-min)))))
567 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
568 (list (if old (match-string 1) (match-string 3))
569 (if old (match-string 3) (match-string 1)))
570 (forward-line 1) nil)))
575 (re-search-backward "^Index: \\(.+\\)" limit t)))
576 (list (match-string 1)))
578 (when (re-search-backward
579 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
581 (list (if old (match-string 2) (match-string 4))
582 (if old (match-string 4) (match-string 2)))))))))
584 (defun diff-find-file-name (&optional old)
585 "Return the file corresponding to the current patch.
586 Non-nil OLD means that we want the old file."
588 (unless (looking-at diff-file-header-re)
589 (or (ignore-errors (diff-beginning-of-file))
590 (re-search-forward diff-file-header-re nil t)))
591 (let ((fs (diff-hunk-file-names old)))
593 ;; use any previously used preference
594 (cdr (assoc fs diff-remembered-files-alist))
595 ;; try to be clever and use previous choices as an inspiration
596 (dolist (rf diff-remembered-files-alist)
597 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
598 (if (and newfile (file-exists-p newfile)) (return newfile))))
599 ;; look for each file in turn. If none found, try again but
600 ;; ignoring the first level of directory, ...
601 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
604 (setq file (do* ((files files (cdr files))
605 (file (car files) (car files)))
606 ((or (null file) (file-exists-p file))
609 ;; <foo>.rej patches implicitly apply to <foo>
610 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
611 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
612 (when (file-exists-p file) file)))
613 ;; if all else fails, ask the user
614 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
615 nil (first fs) t (first fs))))
616 (set (make-local-variable 'diff-remembered-files-alist)
617 (cons (cons fs file) diff-remembered-files-alist))
621 (defun diff-ediff-patch ()
622 "Call `ediff-patch-file' on the current buffer."
625 (ediff-patch-file nil (current-buffer))
626 (wrong-number-of-arguments (ediff-patch-file))))
629 ;;;; Conversion functions
632 ;;(defvar diff-inhibit-after-change nil
633 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
635 (defun diff-unified->context (start end)
636 "Convert unified diffs to context diffs.
637 START and END are either taken from the region (if a prefix arg is given) or
638 else cover the whole bufer."
639 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
640 (list (region-beginning) (region-end))
641 (list (point-min) (point-max))))
642 (unless (markerp end) (setq end (copy-marker end)))
643 (let (;;(diff-inhibit-after-change t)
644 (inhibit-read-only t))
647 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
649 (combine-after-change-calls
650 (if (match-beginning 2)
651 ;; we matched a file header
653 ;; use reverse order to make sure the indices are kept valid
654 (replace-match "---" t t nil 3)
655 (replace-match "***" t t nil 2))
656 ;; we matched a hunk header
657 (let ((line1 (match-string 4))
658 (lines1 (match-string 5))
659 (line2 (match-string 6))
660 (lines2 (match-string 7)))
662 (concat "***************\n*** " line1 ","
663 (number-to-string (+ (string-to-number line1)
664 (string-to-number lines1)
668 (narrow-to-region (point)
669 (progn (diff-end-of-hunk 'unified) (point)))
670 (let ((hunk (buffer-string)))
671 (goto-char (point-min))
672 (if (not (save-excursion (re-search-forward "^-" nil t)))
673 (delete-region (point) (point-max))
674 (goto-char (point-max))
675 (let ((modif nil) last-pt)
676 (while (progn (setq last-pt (point))
677 (= (forward-line -1) 0))
679 (?\s (insert " ") (setq modif nil) (backward-char 1))
680 (?+ (delete-region (point) last-pt) (setq modif t))
682 (progn (forward-char 1)
687 (?\\ (when (save-excursion (forward-line -1)
689 (delete-region (point) last-pt) (setq modif t)))
690 (t (setq modif nil))))))
691 (goto-char (point-max))
693 (insert "--- " line2 ","
694 (number-to-string (+ (string-to-number line2)
695 (string-to-number lines2)
696 -1)) " ----\n" hunk))
697 ;;(goto-char (point-min))
699 (if (not (save-excursion (re-search-forward "^+" nil t)))
700 (delete-region (point) (point-max))
701 (let ((modif nil) (delete nil))
704 (?\s (insert " ") (setq modif nil) (backward-char 1))
705 (?- (setq delete t) (setq modif t))
707 (progn (forward-char 1)
712 (?\\ (when (save-excursion (forward-line 1)
714 (setq delete t) (setq modif t)))
715 (t (setq modif nil)))
716 (let ((last-pt (point)))
719 (delete-region last-pt (point))
720 (setq delete nil)))))))))))))))
722 (defun diff-context->unified (start end &optional to-context)
723 "Convert context diffs to unified diffs.
724 START and END are either taken from the region
725 \(when it is highlighted) or else cover the whole buffer.
726 With a prefix argument, convert unified format to context format."
727 (interactive (if (and transient-mark-mode mark-active)
728 (list (region-beginning) (region-end) current-prefix-arg)
729 (list (point-min) (point-max) current-prefix-arg)))
731 (diff-unified->context start end)
732 (unless (markerp end) (setq end (copy-marker end)))
733 (let ( ;;(diff-inhibit-after-change t)
734 (inhibit-read-only t))
737 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
739 (combine-after-change-calls
740 (if (match-beginning 2)
741 ;; we matched a file header
743 ;; use reverse order to make sure the indices are kept valid
744 (replace-match "+++" t t nil 3)
745 (replace-match "---" t t nil 2))
746 ;; we matched a hunk header
747 (let ((line1s (match-string 4))
748 (line1e (match-string 5))
749 (pt1 (match-beginning 0)))
751 (unless (re-search-forward
752 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
753 (error "Can't find matching `--- n1,n2 ----' line"))
754 (let ((line2s (match-string 1))
755 (line2e (match-string 2))
757 (delete-region (progn (beginning-of-line) (point))
758 (progn (forward-line 1) (point)))
762 (while (< (point) pt2)
764 ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
765 (?\s ;merge with the other half of the chunk
768 (goto-char pt2) (forward-line 1) (point)))
769 (c (char-after pt2)))
773 (prog1 (buffer-substring (+ pt2 2) endline2)
774 (delete-region pt2 endline2))))
775 (?\s ;FIXME: check consistency
776 (delete-region pt2 endline2)
779 (?\\ (forward-line 1))
780 (t (delete-char 1) (forward-line 1)))))
781 (t (forward-line 1))))
782 (while (looking-at "[+! ] ")
783 (if (/= (char-after) ?!) (forward-char 1)
784 (delete-char 1) (insert "+"))
785 (delete-char 1) (forward-line 1))
788 (insert "@@ -" line1s ","
789 (number-to-string (- (string-to-number line1e)
790 (string-to-number line1s)
793 (number-to-string (- (string-to-number line2e)
794 (string-to-number line2s)
795 -1)) " @@")))))))))))
797 (defun diff-reverse-direction (start end)
798 "Reverse the direction of the diffs.
799 START and END are either taken from the region (if a prefix arg is given) or
800 else cover the whole bufer."
801 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
802 (list (region-beginning) (region-end))
803 (list (point-min) (point-max))))
804 (unless (markerp end) (setq end (copy-marker end)))
805 (let (;;(diff-inhibit-after-change t)
806 (inhibit-read-only t))
809 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
811 (combine-after-change-calls
814 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
815 ;; a context-diff hunk header
817 (let ((pt-lines1 (match-beginning 6))
818 (lines1 (match-string 6)))
819 (replace-match "" nil nil nil 6)
821 (let ((half1s (point)))
822 (while (looking-at "[-! \\][ \t]\\|#")
823 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
825 (let ((half1 (delete-and-extract-region half1s (point))))
826 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
828 (error "Can't find matching `--- n1,n2 ----' line"))
829 (let ((str1 (match-string 1)))
830 (replace-match lines1 nil nil nil 1)
832 (let ((half2s (point)))
833 (while (looking-at "[!+ \\][ \t]\\|#")
834 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
836 (let ((half2 (delete-and-extract-region half2s (point))))
837 (insert (or half1 ""))
839 (insert (or half2 ""))))
840 (goto-char pt-lines1)
842 ;; a unified-diff hunk header
844 (replace-match "@@ -\\8 +\\7 @@" nil)
846 (let ((c (char-after)) first last)
847 (while (case (setq c (char-after))
848 (?- (setq first (or first (point)))
849 (delete-char 1) (insert "+") t)
850 (?+ (setq last (or last (point)))
851 (delete-char 1) (insert "-") t)
853 (t (when (and first last (< first last))
854 (insert (delete-and-extract-region first last)))
855 (setq first nil last nil)
857 (forward-line 1))))))))))
859 (defun diff-fixup-modifs (start end)
860 "Fixup the hunk headers (in case the buffer was modified).
861 START and END are either taken from the region (if a prefix arg is given) or
862 else cover the whole bufer."
863 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
864 (list (region-beginning) (region-end))
865 (list (point-min) (point-max))))
866 (let ((inhibit-read-only t))
868 (goto-char end) (diff-end-of-hunk)
869 (let ((plus 0) (minus 0) (space 0) (bang 0))
870 (while (and (= (forward-line -1) 0) (<= start (point)))
872 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
873 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
874 "\\|--- .+\n\\+\\+\\+ ")))
881 (t (setq space 0 plus 0 minus 0 bang 0)))
883 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
884 (let* ((old1 (match-string 1))
885 (old2 (match-string 2))
886 (new1 (number-to-string (+ space minus)))
887 (new2 (number-to-string (+ space plus))))
888 (unless (string= new2 old2) (replace-match new2 t t nil 2))
889 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
890 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
891 (when (> (+ space bang plus) 0)
892 (let* ((old1 (match-string 1))
893 (old2 (match-string 2))
894 (new (number-to-string
895 (+ space bang plus -1 (string-to-number old1)))))
896 (unless (string= new old2) (replace-match new t t nil 2)))))
897 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
898 (when (> (+ space bang minus) 0)
899 (let* ((old (match-string 1))
901 (concat "%0" (number-to-string (length old)) "d")
902 (+ space bang minus -1 (string-to-number old)))))
903 (unless (string= new old) (replace-match new t t nil 2))))))
904 (setq space 0 plus 0 minus 0 bang 0)))))))
910 (defun diff-write-contents-hooks ()
911 "Fixup hunk headers if necessary."
912 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
915 ;; It turns out that making changes in the buffer from within an
916 ;; *-change-function is asking for trouble, whereas making them
917 ;; from a post-command-hook doesn't pose much problems
918 (defvar diff-unhandled-changes nil)
919 (defun diff-after-change-function (beg end len)
920 "Remember to fixup the hunk header.
921 See `after-change-functions' for the meaning of BEG, END and LEN."
922 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
923 ;; incorrect, but it turns out that inhibit-read-only is normally not set
924 ;; inside editing commands, while it tends to be set when the buffer gets
925 ;; updated by an async process or by a conversion function, both of which
926 ;; would rather not be uselessly slowed down by this hook.
927 (when (and (not undo-in-progress) (not inhibit-read-only))
928 (if diff-unhandled-changes
929 (setq diff-unhandled-changes
930 (cons (min beg (car diff-unhandled-changes))
931 (max end (cdr diff-unhandled-changes))))
932 (setq diff-unhandled-changes (cons beg end)))))
934 (defun diff-post-command-hook ()
935 "Fixup hunk headers if necessary."
936 (when (consp diff-unhandled-changes)
939 (goto-char (car diff-unhandled-changes))
940 ;; Maybe we've cut the end of the hunk before point.
941 (if (and (bolp) (not (bobp))) (backward-char 1))
942 ;; We used to fixup modifs on all the changes, but it turns out
943 ;; that it's safer not to do it on big changes, for example
944 ;; when yanking a big diff, since we might then screw up perfectly
945 ;; correct values. -stef
946 ;; (unless (ignore-errors
947 ;; (diff-beginning-of-hunk)
949 ;; (diff-end-of-hunk)
950 ;; (> (point) (car diff-unhandled-changes))))
951 ;; (goto-char (car diff-unhandled-changes))
952 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
953 ;; (diff-beginning-of-hunk))
954 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
955 (diff-beginning-of-hunk)
956 (when (save-excursion
958 (>= (point) (cdr diff-unhandled-changes)))
959 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
960 (setq diff-unhandled-changes nil)))
962 (defun diff-next-error (arg reset)
963 ;; Select a window that displays the current buffer so that point
964 ;; movements are reflected in that window. Otherwise, the user might
965 ;; never see the hunk corresponding to the source she's jumping to.
966 (pop-to-buffer (current-buffer))
967 (if reset (goto-char (point-min)))
972 (define-derived-mode diff-mode fundamental-mode "Diff"
973 "Major mode for viewing/editing context diffs.
974 Supports unified and context diffs as well as (to a lesser extent)
976 When the buffer is read-only, the ESC prefix is not necessary.
977 If you edit the buffer manually, diff-mode will try to update the hunk
978 headers for you on-the-fly.
980 You can also switch between context diff and unified diff with \\[diff-context->unified],
981 or vice versa with \\[diff-unified->context] and you can also reverse the direction of
982 a diff with \\[diff-reverse-direction]."
983 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
984 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
985 (set (make-local-variable 'imenu-generic-expression)
986 diff-imenu-generic-expression)
987 ;; These are not perfect. They would be better done separately for
988 ;; context diffs and unidiffs.
989 ;; (set (make-local-variable 'paragraph-start)
990 ;; (concat "@@ " ; unidiff hunk
991 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
992 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
993 ;; ; start (first or second line)
994 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
995 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
997 (set (make-local-variable 'next-error-function) 'diff-next-error)
999 (setq buffer-read-only diff-default-read-only)
1000 ;; setup change hooks
1001 (if (not diff-update-on-the-fly)
1002 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1003 (make-local-variable 'diff-unhandled-changes)
1004 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1005 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
1006 ;; Neat trick from Dave Love to add more bindings in read-only mode:
1007 (let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
1008 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1009 ;; Turn off this little trick in case the buffer is put in view-mode.
1010 (add-hook 'view-mode-hook
1012 (setq minor-mode-overriding-map-alist
1013 (delq ',ro-bind minor-mode-overriding-map-alist)))
1016 (set (make-local-variable 'add-log-current-defun-function)
1017 'diff-current-defun)
1018 (set (make-local-variable 'add-log-buffer-file-name-function)
1019 'diff-find-file-name))
1022 (define-minor-mode diff-minor-mode
1023 "Minor mode for viewing/editing context diffs.
1024 \\{diff-minor-mode-map}"
1025 :group 'diff-mode :lighter " Diff"
1026 ;; FIXME: setup font-lock
1027 ;; setup change hooks
1028 (if (not diff-update-on-the-fly)
1029 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1030 (make-local-variable 'diff-unhandled-changes)
1031 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1032 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
1034 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1036 (defun diff-delete-if-empty ()
1037 ;; An empty diff file means there's no more diffs to integrate, so we
1038 ;; can just remove the file altogether. Very handy for .rej files if we
1039 ;; remove hunks as we apply them.
1040 (when (and buffer-file-name
1041 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1042 (delete-file buffer-file-name)))
1044 (defun diff-delete-empty-files ()
1045 "Arrange for empty diff files to be removed."
1046 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1048 (defun diff-make-unified ()
1049 "Turn context diffs into unified diffs if applicable."
1051 (goto-char (point-min))
1052 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
1053 (let ((mod (buffer-modified-p)))
1055 (diff-context->unified (point-min) (point-max))
1056 (restore-buffer-modified-p mod)))))
1059 ;;; Misc operations that have proved useful at some point.
1062 (defun diff-next-complex-hunk ()
1063 "Jump to the next \"complex\" hunk.
1064 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1065 Only works for unified diffs."
1068 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1070 (equal (match-string 1) (match-string 2)))))
1072 (defun diff-hunk-text (hunk destp char-offset)
1073 "Return the literal source text from HUNK as (TEXT . OFFSET).
1074 If DESTP is nil, TEXT is the source, otherwise the destination text.
1075 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1076 char-offset in TEXT."
1079 (goto-char (point-min))
1084 ;; Set the following variables:
1085 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1086 ;; DST-POS buffer pos of the destination part of the hunk or nil
1087 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1088 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1089 (cond ((looking-at "^@@")
1091 (setq num-pfx-chars 1)
1093 (setq src-pos (point) dst-pos (point)))
1094 ((looking-at "^\\*\\*")
1097 (setq src-pos (point))
1098 (re-search-forward "^--- " nil t)
1100 (setq divider-pos (point))
1102 (setq dst-pos (point)))
1103 ((looking-at "^[0-9]+a[0-9,]+$")
1104 ;; normal diff, insert
1106 (setq dst-pos (point)))
1107 ((looking-at "^[0-9,]+d[0-9]+$")
1108 ;; normal diff, delete
1110 (setq src-pos (point)))
1111 ((looking-at "^[0-9,]+c[0-9,]+$")
1112 ;; normal diff, change
1114 (setq src-pos (point))
1115 (re-search-forward "^---$" nil t)
1117 (setq divider-pos (point))
1119 (setq dst-pos (point)))
1121 (error "Unknown diff hunk type")))
1123 (if (if destp (null dst-pos) (null src-pos))
1124 ;; Implied empty text
1125 (if char-offset '("" . 0) "")
1127 ;; For context diffs, either side can be empty, (if there's only
1128 ;; added or only removed text). We should then use the other side.
1129 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1130 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1132 (when char-offset (goto-char (+ (point-min) char-offset)))
1134 ;; Get rid of anything except the desired text.
1136 ;; Delete unused text region
1137 (let ((keep (if destp dst-pos src-pos)))
1138 (when (and divider-pos (> divider-pos keep))
1139 (delete-region divider-pos (point-max)))
1140 (delete-region (point-min) keep))
1141 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1142 (let ((kill-char (if destp ?- ?+)))
1143 (goto-char (point-min))
1145 (if (eq (char-after) kill-char)
1146 (delete-region (point) (progn (forward-line 1) (point)))
1147 (delete-char num-pfx-chars)
1148 (forward-line 1)))))
1150 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1151 (if char-offset (cons text (- (point) (point-min))) text))))))
1154 (defun diff-find-text (text)
1155 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1156 If TEXT isn't found, nil is returned."
1157 (let* ((orig (point))
1158 (forw (and (search-forward text nil t)
1159 (cons (match-beginning 0) (match-end 0))))
1160 (back (and (goto-char (+ orig (length text)))
1161 (search-backward text nil t)
1162 (cons (match-beginning 0) (match-end 0)))))
1163 ;; Choose the closest match.
1165 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1168 (defun diff-find-approx-text (text)
1169 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1170 Whitespace differences are ignored."
1171 (let* ((orig (point))
1172 (re (concat "^[ \t\n
\f]*"
1173 (mapconcat 'regexp-quote (split-string text) "[ \t\n
\f]+")
1175 (forw (and (re-search-forward re nil t)
1176 (cons (match-beginning 0) (match-end 0))))
1177 (back (and (goto-char (+ orig (length text)))
1178 (re-search-backward re nil t)
1179 (cons (match-beginning 0) (match-end 0)))))
1180 ;; Choose the closest match.
1182 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1185 (defsubst diff-xor (a b) (if a (not b) b))
1187 (defun diff-find-source-location (&optional other-file reverse)
1188 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1189 BUF is the buffer corresponding to the source file.
1190 LINE-OFFSET is the offset between the expected and actual positions
1191 of the text of the hunk or nil if the text was not found.
1192 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1193 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1194 SRC is the variant that was found in the buffer.
1195 SWITCHED is non-nil if the patch is already applied."
1197 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1198 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1199 (hunk (buffer-substring (point)
1200 (save-excursion (diff-end-of-hunk) (point))))
1201 (old (diff-hunk-text hunk reverse char-offset))
1202 (new (diff-hunk-text hunk (not reverse) char-offset))
1203 ;; Find the location specification.
1204 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1205 (error "Can't find the hunk header")
1206 (if other (match-string 1)
1207 (if (match-end 3) (match-string 3)
1208 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1209 (error "Can't find the hunk separator"))
1210 (match-string 1)))))
1211 (file (or (diff-find-file-name other) (error "Can't find the file")))
1212 (buf (find-file-noselect file)))
1213 ;; Update the user preference if he so wished.
1214 (when (> (prefix-numeric-value other-file) 8)
1215 (setq diff-jump-to-old-file other))
1216 (with-current-buffer buf
1217 (goto-line (string-to-number line))
1218 (let* ((orig-pos (point))
1220 ;; FIXME: Check for case where both OLD and NEW are found.
1221 (pos (or (diff-find-text (car old))
1222 (progn (setq switched t) (diff-find-text (car new)))
1223 (progn (setq switched nil)
1225 (diff-find-approx-text (car old))
1226 (invalid-regexp nil))) ;Regex too big.
1227 (progn (setq switched t)
1229 (diff-find-approx-text (car new))
1230 (invalid-regexp nil))) ;Regex too big.
1231 (progn (setq switched nil) nil))))
1235 (list (count-lines orig-pos (car pos)) pos)
1236 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1237 (if switched (list new old t) (list old new))))))))
1240 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1241 (let ((msg (if dry-run
1242 (if reversed "already applied" "not yet applied")
1243 (if reversed "undone" "applied"))))
1244 (message (cond ((null line-offset) "Hunk text not found")
1245 ((= line-offset 0) "Hunk %s")
1246 ((= line-offset 1) "Hunk %s at offset %d line")
1247 (t "Hunk %s at offset %d lines"))
1251 (defun diff-apply-hunk (&optional reverse)
1252 "Apply the current hunk to the source file and go to the next.
1253 By default, the new source file is patched, but if the variable
1254 `diff-jump-to-old-file' is non-nil, then the old source file is
1255 patched instead (some commands, such as `diff-goto-source' can change
1256 the value of this variable when given an appropriate prefix argument).
1258 With a prefix argument, REVERSE the hunk."
1260 (destructuring-bind (buf line-offset pos old new &optional switched)
1261 ;; If REVERSE go to the new file, otherwise go to the old.
1262 (diff-find-source-location (not reverse) reverse)
1265 (error "Can't find the text to patch"))
1267 ;; A reversed patch was detected, perhaps apply it in reverse.
1268 (not (save-window-excursion
1270 (goto-char (+ (car pos) (cdr old)))
1273 "Hunk hasn't been applied yet; apply it now? "
1274 "Hunk has already been applied; undo it? ")))))
1275 (message "(Nothing done)"))
1278 (with-current-buffer buf
1279 (goto-char (car pos))
1280 (delete-region (car pos) (cdr pos))
1282 ;; Display BUF in a window
1283 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1284 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1285 (when diff-advance-after-apply-hunk
1286 (diff-hunk-next))))))
1289 (defun diff-test-hunk (&optional reverse)
1290 "See whether it's possible to apply the current hunk.
1291 With a prefix argument, try to REVERSE the hunk."
1293 (destructuring-bind (buf line-offset pos src dst &optional switched)
1294 ;; If REVERSE go to the new file, otherwise go to the old.
1295 (diff-find-source-location (not reverse) reverse)
1296 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1297 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1300 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1302 (defun diff-goto-source (&optional other-file event)
1303 "Jump to the corresponding source line.
1304 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1305 is given) determines whether to jump to the old or the new file.
1306 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1307 then `diff-jump-to-old-file' is also set, for the next invocations."
1308 (interactive (list current-prefix-arg last-input-event))
1309 ;; When pointing at a removal line, we probably want to jump to
1310 ;; the old location, and else to the new (i.e. as if reverting).
1311 ;; This is a convenient detail when using smerge-diff.
1312 (if event (posn-set-point (event-end event)))
1313 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1314 (destructuring-bind (buf line-offset pos src dst &optional switched)
1315 (diff-find-source-location other-file rev)
1317 (goto-char (+ (car pos) (cdr src)))
1318 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1321 (defun diff-current-defun ()
1322 "Find the name of function at point.
1323 For use in `add-log-current-defun-function'."
1325 (when (looking-at diff-hunk-header-re)
1327 (re-search-forward "^[^ ]" nil t))
1328 (destructuring-bind (buf line-offset pos src dst &optional switched)
1329 (diff-find-source-location)
1331 (or (when (memq (char-after) '(?< ?-))
1332 ;; Cursor is pointing at removed text. This could be a removed
1333 ;; function, in which case, going to the source buffer will
1334 ;; not help since the function is now removed. Instead,
1335 ;; try to figure out the function name just from the code-fragment.
1336 (let ((old (if switched dst src)))
1339 (funcall (with-current-buffer buf major-mode))
1340 (goto-char (+ (point-min) (cdr old)))
1341 (add-log-current-defun))))
1342 (with-current-buffer buf
1343 (goto-char (+ (car pos) (cdr src)))
1344 (add-log-current-defun))))))
1346 (defun diff-refine-hunk ()
1347 "Refine the current hunk by ignoring space differences."
1349 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1350 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1351 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1352 (error "Can't find line number"))
1353 (string-to-number (match-string 1))))
1354 (hunk (delete-and-extract-region
1355 (point) (save-excursion (diff-end-of-hunk) (point))))
1356 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1357 (file1 (make-temp-file "diff1"))
1358 (file2 (make-temp-file "diff2"))
1359 (coding-system-for-read buffer-file-coding-system)
1360 (inhibit-read-only t)
1364 (setq old (diff-hunk-text hunk nil char-offset))
1365 (setq new (diff-hunk-text hunk t char-offset))
1366 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1367 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1370 (call-process diff-command nil t nil
1373 (0 nil) ;Nothing to reformat.
1374 (1 (goto-char (point-min))
1375 ;; Remove the file-header.
1376 (when (re-search-forward diff-hunk-header-re nil t)
1377 (delete-region (point-min) (match-beginning 0))))
1378 (t (goto-char (point-max))
1379 (unless (bolp) (insert "\n"))
1381 (setq hunk (buffer-string))
1382 (unless (memq status '(0 1))
1383 (error "Diff returned: %s" status)))))
1384 ;; Whatever happens, put back some equivalent text: either the new
1385 ;; one or the original one in case some error happened.
1388 (delete-file file2))))
1390 ;; provide the package
1391 (provide 'diff-mode)
1393 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1394 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1395 ;; (diff-mode-load-hook): dropped.
1396 ;; (auto-mode-alist): also catch *.diffs.
1397 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1398 ;; for *.rej files (that lack any file name indication).
1400 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1401 ;; added support for "\ No newline at end of file".
1403 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1404 ;; - added basic `compile' support.
1405 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1406 ;; - diff-kill-file now tries to kill the leading garbage as well.
1408 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1409 ;; - don't use CL in the autoloaded code
1410 ;; - accept diffs using -T
1412 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1413 ;; interface to ediff-patch
1415 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1416 ;; (ediff=patch-file): add bindings to call ediff-patch.
1417 ;; (diff-find-file-name): taken out of diff-goto-source.
1418 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1419 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1421 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1422 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1424 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1425 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1428 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1429 ;;; diff-mode.el ends here