(diff-mode-map): Bind toggle-next-error-follow-mode.
[emacs.git] / lisp / diff-mode.el
blobf31ab09218928e3bb9c52f9621a0446b88b48b5c
1 ;;; diff-mode.el --- a mode for viewing/editing context diffs
3 ;; Copyright (C) 1998,1999,2000,01,02,03,2004 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@cs.yale.edu>
6 ;; Keywords: convenience patch diff
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
25 ;;; Commentary:
27 ;; Provides support for font-lock, outline, navigation
28 ;; commands, editing and various conversions as well as jumping
29 ;; to the corresponding source file.
31 ;; Inspired by Pavel Machek's patch-mode.el (<pavel@@atrey.karlin.mff.cuni.cz>)
32 ;; Some efforts were spent to have it somewhat compatible with XEmacs'
33 ;; diff-mode as well as with compilation-minor-mode
35 ;; Bugs:
37 ;; - Reverse doesn't work with normal diffs.
39 ;; Todo:
41 ;; - Add a `delete-after-apply' so C-c C-a automatically deletes hunks.
42 ;; Also allow C-c C-a to delete already-applied hunks.
44 ;; - Try `diff <file> <hunk>' to try and fuzzily discover the source location
45 ;; of a hunk. Show then the changes between <file> and <hunk> and make it
46 ;; possible to apply them to <file>, <hunk-src>, or <hunk-dst>.
47 ;; Or maybe just make it into a ".rej to diff3-markers converter".
49 ;; - Refine hunk on a word-by-word basis.
51 ;; - Handle `diff -b' output in context->unified.
53 ;;; Code:
55 (eval-when-compile (require 'cl))
58 (defgroup diff-mode ()
59 "Major mode for viewing/editing diffs"
60 :version "21.1"
61 :group 'tools
62 :group 'diff)
64 (defcustom diff-default-read-only nil
65 "If non-nil, `diff-mode' buffers default to being read-only."
66 :type 'boolean
67 :group 'diff-mode)
69 (defcustom diff-jump-to-old-file nil
70 "*Non-nil means `diff-goto-source' jumps to the old file.
71 Else, it jumps to the new file."
72 :type '(boolean))
74 (defcustom diff-update-on-the-fly t
75 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
76 When editing a diff file, the line numbers in the hunk headers
77 need to be kept consistent with the actual diff. This can
78 either be done on the fly (but this sometimes interacts poorly with the
79 undo mechanism) or whenever the file is written (can be slow
80 when editing big diffs)."
81 :type '(boolean))
83 (defcustom diff-advance-after-apply-hunk t
84 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
85 :type 'boolean)
88 (defcustom diff-mode-hook nil
89 "Run after setting up the `diff-mode' major mode."
90 :type 'hook
91 :options '(diff-delete-empty-files diff-make-unified))
93 (defvar diff-outline-regexp
94 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
96 ;;;;
97 ;;;; keymap, menu, ...
98 ;;;;
100 (easy-mmode-defmap diff-mode-shared-map
101 '(;; From Pavel Machek's patch-mode.
102 ("n" . diff-hunk-next)
103 ("N" . diff-file-next)
104 ("p" . diff-hunk-prev)
105 ("P" . diff-file-prev)
106 ("k" . diff-hunk-kill)
107 ("K" . diff-file-kill)
108 ;; From compilation-minor-mode.
109 ("}" . diff-file-next)
110 ("{" . diff-file-prev)
111 ("\C-m" . diff-goto-source)
112 ([mouse-2] . diff-goto-source)
113 ;; From XEmacs' diff-mode.
114 ("W" . widen)
115 ;;("." . diff-goto-source) ;display-buffer
116 ;;("f" . diff-goto-source) ;find-file
117 ("o" . diff-goto-source) ;other-window
118 ;;("w" . diff-goto-source) ;other-frame
119 ;;("N" . diff-narrow)
120 ;;("h" . diff-show-header)
121 ;;("j" . diff-show-difference) ;jump to Nth diff
122 ;;("q" . diff-quit)
123 (" " . scroll-up)
124 ("\177" . scroll-down)
125 ;; Our very own bindings.
126 ("A" . diff-ediff-patch)
127 ("r" . diff-restrict-view)
128 ("R" . diff-reverse-direction)
129 ("U" . diff-context->unified)
130 ("C" . diff-unified->context)
131 ("q" . quit-window))
132 "Basic keymap for `diff-mode', bound to various prefix keys.")
134 (easy-mmode-defmap diff-mode-map
135 `(("\e" . ,diff-mode-shared-map)
136 ;; From compilation-minor-mode.
137 ("\C-c\C-c" . diff-goto-source)
138 ;; Misc operations.
139 ("\C-c\C-r" . diff-refine-hunk)
140 ("\C-c\C-s" . diff-split-hunk)
141 ("\C-c\C-a" . diff-apply-hunk)
142 ("\C-c\C-t" . diff-test-hunk)
143 ("\C-c\C-f" . next-error-follow-mode))
144 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
146 (easy-menu-define diff-mode-menu diff-mode-map
147 "Menu for `diff-mode'."
148 '("Diff"
149 ["Jump to Source" diff-goto-source t]
150 ["Apply hunk" diff-apply-hunk t]
151 ["Apply diff with Ediff" diff-ediff-patch t]
152 ["-----" nil nil]
153 ["Reverse direction" diff-reverse-direction t]
154 ["Context -> Unified" diff-context->unified t]
155 ["Unified -> Context" diff-unified->context t]
156 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
159 (defcustom diff-minor-mode-prefix "\C-c="
160 "Prefix key for `diff-minor-mode' commands."
161 :type '(choice (string "\e") (string "C-c=") string))
163 (easy-mmode-defmap diff-minor-mode-map
164 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
165 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
168 ;;;;
169 ;;;; font-lock support
170 ;;;;
172 (defface diff-header-face
173 '((((class color) (min-colors 88) (background light))
174 (:background "grey85"))
175 (((class color) (min-colors 88) (background dark))
176 (:background "grey45"))
177 (((class color) (background light))
178 (:foreground "blue1" :weight bold))
179 (((class color) (background dark))
180 (:foreground "green" :weight bold))
181 (t (:weight bold)))
182 "`diff-mode' face inherited by hunk and index header faces.")
183 (defvar diff-header-face 'diff-header-face)
185 (defface diff-file-header-face
186 '((((class color) (min-colors 88) (background light))
187 (:background "grey70" :weight bold))
188 (((class color) (min-colors 88) (background dark))
189 (:background "grey60" :weight bold))
190 (((class color) (background light))
191 (:foreground "yellow" :weight bold))
192 (((class color) (background dark))
193 (:foreground "cyan" :weight bold))
194 (t (:weight bold))) ; :height 1.3
195 "`diff-mode' face used to highlight file header lines.")
196 (defvar diff-file-header-face 'diff-file-header-face)
198 (defface diff-index-face
199 '((t (:inherit diff-file-header-face)))
200 "`diff-mode' face used to highlight index header lines.")
201 (defvar diff-index-face 'diff-index-face)
203 (defface diff-hunk-header-face
204 '((t (:inherit diff-header-face)))
205 "`diff-mode' face used to highlight hunk header lines.")
206 (defvar diff-hunk-header-face 'diff-hunk-header-face)
208 (defface diff-removed-face
209 '((t (:inherit diff-changed-face)))
210 "`diff-mode' face used to highlight removed lines.")
211 (defvar diff-removed-face 'diff-removed-face)
213 (defface diff-added-face
214 '((t (:inherit diff-changed-face)))
215 "`diff-mode' face used to highlight added lines.")
216 (defvar diff-added-face 'diff-added-face)
218 (defface diff-changed-face
219 '((((type tty pc) (class color) (background light))
220 (:foreground "magenta" :weight bold :slant italic))
221 (((type tty pc) (class color) (background dark))
222 (:foreground "yellow" :weight bold :slant italic))
223 (t ()))
224 "`diff-mode' face used to highlight changed lines.")
225 (defvar diff-changed-face 'diff-changed-face)
227 (defface diff-function-face
228 '((t (:inherit diff-context-face)))
229 "`diff-mode' face used to highlight function names produced by \"diff -p\".")
230 (defvar diff-function-face 'diff-function-face)
232 (defface diff-context-face
233 '((((class color) (background light))
234 (:foreground "grey50"))
235 (((class color) (background dark))
236 (:foreground "grey70"))
237 (t ))
238 "`diff-mode' face used to highlight context and other side-information.")
239 (defvar diff-context-face 'diff-context-face)
241 (defface diff-nonexistent-face
242 '((t (:inherit diff-file-header-face)))
243 "`diff-mode' face used to highlight nonexistent files in recursive diffs.")
244 (defvar diff-nonexistent-face 'diff-nonexistent-face)
246 (defconst diff-yank-handler '(diff-yank-function))
247 (defun diff-yank-function (text)
248 ;; FIXME: the yank-handler is now called separately on each piece of text
249 ;; with a yank-handler property, so the next-single-property-change call
250 ;; below will always return nil :-( --stef
251 (let ((mixed (next-single-property-change 0 'yank-handler text))
252 (start (point)))
253 ;; First insert the text.
254 (insert text)
255 ;; If the text does not include any diff markers and if we're not
256 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
257 (unless (or mixed (derived-mode-p 'diff-mode))
258 (undo-boundary) ; Just in case the user wanted the prefixes.
259 (let ((re (save-excursion
260 (if (re-search-backward "^[><!][ \t]" start t)
261 (if (eq (char-after) ?!)
262 "^[!+- ][ \t]" "^[<>][ \t]")
263 "^[ <>!+-]"))))
264 (save-excursion
265 (while (re-search-backward re start t)
266 (replace-match "" t t)))))))
269 (defvar diff-font-lock-keywords
270 `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
271 (1 diff-hunk-header-face)
272 (2 diff-function-face))
273 ("^--- .+ ----$" . diff-hunk-header-face) ;context
274 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
275 (1 diff-hunk-header-face)
276 (2 diff-function-face))
277 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
278 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
279 (0 diff-header-face) (2 diff-file-header-face prepend))
280 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face)
281 ("^!.*\n" (0 diff-changed-face))
282 ("^[+>].*\n" (0 diff-added-face))
283 ("^[-<].*\n" (0 diff-removed-face))
284 ("^Index: \\(.+\\).*\n" (0 diff-header-face) (1 diff-index-face prepend))
285 ("^Only in .*\n" . diff-nonexistent-face)
286 ("^#.*" . font-lock-string-face)
287 ("^[^-=+*!<>].*\n" (0 diff-context-face))))
289 (defconst diff-font-lock-defaults
290 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
292 (defvar diff-imenu-generic-expression
293 ;; Prefer second name as first is most likely to be a backup or
294 ;; version-control name. The [\t\n] at the end of the unidiff pattern
295 ;; catches Debian source diff files (which lack the trailing date).
296 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
297 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
299 ;;;;
300 ;;;; Movement
301 ;;;;
303 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
304 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+\\|\\*\\*\\* .+\n---\\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
305 (defvar diff-narrowed-to nil)
307 (defun diff-end-of-hunk (&optional style)
308 (when (looking-at diff-hunk-header-re)
309 (unless style
310 ;; Especially important for unified (because headers are ambiguous).
311 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context))))))
312 (goto-char (match-end 0)))
313 (let ((end (and (re-search-forward (case style
314 ;; A `unified' header is ambiguous.
315 (unified (concat "^[^-+# \\]\\|"
316 diff-file-header-re))
317 (context "^[^-+#! \\]")
318 (normal "^[^<>#\\]")
319 (t "^[^-+#!<> \\]"))
320 nil t)
321 (match-beginning 0))))
322 ;; The return value is used by easy-mmode-define-navigation.
323 (goto-char (or end (point-max)))))
325 (defun diff-beginning-of-hunk ()
326 (beginning-of-line)
327 (unless (looking-at diff-hunk-header-re)
328 (forward-line 1)
329 (condition-case ()
330 (re-search-backward diff-hunk-header-re)
331 (error (error "Can't find the beginning of the hunk")))))
333 (defun diff-beginning-of-file ()
334 (beginning-of-line)
335 (unless (looking-at diff-file-header-re)
336 (forward-line 2)
337 (condition-case ()
338 (re-search-backward diff-file-header-re)
339 (error (error "Can't find the beginning of the file")))))
341 (defun diff-end-of-file ()
342 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
343 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
344 nil 'move)
345 (if (match-beginning 1)
346 (goto-char (match-beginning 1))
347 (beginning-of-line)))
349 ;; Define diff-{hunk,file}-{prev,next}
350 (easy-mmode-define-navigation
351 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
352 (easy-mmode-define-navigation
353 diff-file diff-file-header-re "file" diff-end-of-hunk)
355 (defun diff-restrict-view (&optional arg)
356 "Restrict the view to the current hunk.
357 If the prefix ARG is given, restrict the view to the current file instead."
358 (interactive "P")
359 (save-excursion
360 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk))
361 (narrow-to-region (point)
362 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
363 (point)))
364 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
367 (defun diff-hunk-kill ()
368 "Kill current hunk."
369 (interactive)
370 (diff-beginning-of-hunk)
371 (let* ((start (point))
372 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
373 (match-beginning 0)))
374 (firsthunk (ignore-errors
375 (goto-char start)
376 (diff-beginning-of-file) (diff-hunk-next) (point)))
377 (nextfile (ignore-errors (diff-file-next) (point))))
378 (goto-char start)
379 (if (and firsthunk (= firsthunk start)
380 (or (null nexthunk)
381 (and nextfile (> nexthunk nextfile))))
382 ;; It's the only hunk for this file, so kill the file.
383 (diff-file-kill)
384 (diff-end-of-hunk)
385 (kill-region start (point)))))
387 (defun diff-file-kill ()
388 "Kill current file's hunks."
389 (interactive)
390 (diff-beginning-of-file)
391 (let* ((start (point))
392 (prevhunk (save-excursion
393 (ignore-errors
394 (diff-hunk-prev) (point))))
395 (index (save-excursion
396 (re-search-backward "^Index: " prevhunk t))))
397 (when index (setq start index))
398 (diff-end-of-file)
399 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
400 (kill-region start (point))))
402 (defun diff-kill-junk ()
403 "Kill spurious empty diffs."
404 (interactive)
405 (save-excursion
406 (let ((inhibit-read-only t))
407 (goto-char (point-min))
408 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
409 "\\([^-+!* <>].*\n\\)*?"
410 "\\(\\(Index:\\) \\|"
411 diff-file-header-re "\\)")
412 nil t)
413 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
414 (match-beginning 3))
415 (beginning-of-line)))))
417 (defun diff-count-matches (re start end)
418 (save-excursion
419 (let ((n 0))
420 (goto-char start)
421 (while (re-search-forward re end t) (incf n))
422 n)))
424 (defun diff-split-hunk ()
425 "Split the current (unified diff) hunk at point into two hunks."
426 (interactive)
427 (beginning-of-line)
428 (let ((pos (point))
429 (start (progn (diff-beginning-of-hunk) (point))))
430 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
431 (error "diff-split-hunk only works on unified context diffs"))
432 (forward-line 1)
433 (let* ((start1 (string-to-number (match-string 1)))
434 (start2 (string-to-number (match-string 2)))
435 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
436 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos))))
437 (goto-char pos)
438 ;; Hopefully the after-change-function will not screw us over.
439 (insert "@@ -" (number-to-string newstart1) ",1 +"
440 (number-to-string newstart2) ",1 @@\n")
441 ;; Fix the original hunk-header.
442 (diff-fixup-modifs start pos))))
445 ;;;;
446 ;;;; jump to other buffers
447 ;;;;
449 (defvar diff-remembered-files-alist nil)
451 (defun diff-filename-drop-dir (file)
452 (when (string-match "/" file) (substring file (match-end 0))))
454 (defun diff-merge-strings (ancestor from to)
455 "Merge the diff between ANCESTOR and FROM into TO.
456 Returns the merged string if successful or nil otherwise.
457 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
458 If ANCESTOR = FROM, returns TO.
459 If ANCESTOR = TO, returns FROM.
460 The heuristic is simplistic and only really works for cases
461 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
462 ;; Ideally, we want:
463 ;; AMB ANB CMD -> CND
464 ;; but that's ambiguous if `foo' or `bar' is empty:
465 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
466 (let ((str (concat ancestor "\n" from "\n" to)))
467 (when (and (string-match (concat
468 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
469 "\\1\\(.*\\)\\3\n"
470 "\\(.*\\(\\2\\).*\\)\\'") str)
471 (equal to (match-string 5 str)))
472 (concat (substring str (match-beginning 5) (match-beginning 6))
473 (match-string 4 str)
474 (substring str (match-end 6) (match-end 5))))))
476 (defun diff-tell-file-name (old name)
477 "Tell Emacs where the find the source file of the current hunk.
478 If the OLD prefix arg is passed, tell the file NAME of the old file."
479 (interactive
480 (let* ((old current-prefix-arg)
481 (fs (diff-hunk-file-names current-prefix-arg)))
482 (unless fs (error "No file name to look for"))
483 (list old (read-file-name (format "File for %s: " (car fs))
484 nil (diff-find-file-name old) t))))
485 (let ((fs (diff-hunk-file-names old)))
486 (unless fs (error "No file name to look for"))
487 (push (cons fs name) diff-remembered-files-alist)))
489 (defun diff-hunk-file-names (&optional old)
490 "Give the list of file names textually mentioned for the current hunk."
491 (save-excursion
492 (unless (looking-at diff-file-header-re)
493 (or (ignore-errors (diff-beginning-of-file))
494 (re-search-forward diff-file-header-re nil t)))
495 (let ((limit (save-excursion
496 (condition-case ()
497 (progn (diff-hunk-prev) (point))
498 (error (point-min)))))
499 (header-files
500 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
501 (list (if old (match-string 1) (match-string 3))
502 (if old (match-string 3) (match-string 1)))
503 (forward-line 1) nil)))
504 (delq nil
505 (append
506 (when (and (not old)
507 (save-excursion
508 (re-search-backward "^Index: \\(.+\\)" limit t)))
509 (list (match-string 1)))
510 header-files
511 (when (re-search-backward
512 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
513 nil t)
514 (list (if old (match-string 2) (match-string 4))
515 (if old (match-string 4) (match-string 2)))))))))
517 (defun diff-find-file-name (&optional old)
518 "Return the file corresponding to the current patch.
519 Non-nil OLD means that we want the old file."
520 (save-excursion
521 (unless (looking-at diff-file-header-re)
522 (or (ignore-errors (diff-beginning-of-file))
523 (re-search-forward diff-file-header-re nil t)))
524 (let ((fs (diff-hunk-file-names old)))
526 ;; use any previously used preference
527 (cdr (assoc fs diff-remembered-files-alist))
528 ;; try to be clever and use previous choices as an inspiration
529 (dolist (rf diff-remembered-files-alist)
530 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
531 (if (and newfile (file-exists-p newfile)) (return newfile))))
532 ;; look for each file in turn. If none found, try again but
533 ;; ignoring the first level of directory, ...
534 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
535 (file nil nil))
536 ((or (null files)
537 (setq file (do* ((files files (cdr files))
538 (file (car files) (car files)))
539 ((or (null file) (file-exists-p file))
540 file))))
541 file))
542 ;; <foo>.rej patches implicitly apply to <foo>
543 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
544 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
545 (when (file-exists-p file) file)))
546 ;; if all else fails, ask the user
547 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
548 nil (first fs) t (first fs))))
549 (set (make-local-variable 'diff-remembered-files-alist)
550 (cons (cons fs file) diff-remembered-files-alist))
551 file)))))
554 (defun diff-ediff-patch ()
555 "Call `ediff-patch-file' on the current buffer."
556 (interactive)
557 (condition-case err
558 (ediff-patch-file nil (current-buffer))
559 (wrong-number-of-arguments (ediff-patch-file))))
561 ;;;;
562 ;;;; Conversion functions
563 ;;;;
565 ;;(defvar diff-inhibit-after-change nil
566 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
568 (defun diff-unified->context (start end)
569 "Convert unified diffs to context diffs.
570 START and END are either taken from the region (if a prefix arg is given) or
571 else cover the whole bufer."
572 (interactive (if current-prefix-arg
573 (list (mark) (point))
574 (list (point-min) (point-max))))
575 (unless (markerp end) (setq end (copy-marker end)))
576 (let (;;(diff-inhibit-after-change t)
577 (inhibit-read-only t))
578 (save-excursion
579 (goto-char start)
580 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
581 (< (point) end))
582 (combine-after-change-calls
583 (if (match-beginning 2)
584 ;; we matched a file header
585 (progn
586 ;; use reverse order to make sure the indices are kept valid
587 (replace-match "---" t t nil 3)
588 (replace-match "***" t t nil 2))
589 ;; we matched a hunk header
590 (let ((line1 (match-string 4))
591 (lines1 (match-string 5))
592 (line2 (match-string 6))
593 (lines2 (match-string 7)))
594 (replace-match
595 (concat "***************\n*** " line1 ","
596 (number-to-string (+ (string-to-number line1)
597 (string-to-number lines1)
598 -1)) " ****"))
599 (forward-line 1)
600 (save-restriction
601 (narrow-to-region (point)
602 (progn (diff-end-of-hunk 'unified) (point)))
603 (let ((hunk (buffer-string)))
604 (goto-char (point-min))
605 (if (not (save-excursion (re-search-forward "^-" nil t)))
606 (delete-region (point) (point-max))
607 (goto-char (point-max))
608 (let ((modif nil) last-pt)
609 (while (progn (setq last-pt (point))
610 (= (forward-line -1) 0))
611 (case (char-after)
612 (? (insert " ") (setq modif nil) (backward-char 1))
613 (?+ (delete-region (point) last-pt) (setq modif t))
614 (?- (if (not modif)
615 (progn (forward-char 1)
616 (insert " "))
617 (delete-char 1)
618 (insert "! "))
619 (backward-char 2))
620 (?\\ (when (save-excursion (forward-line -1)
621 (= (char-after) ?+))
622 (delete-region (point) last-pt) (setq modif t)))
623 (t (setq modif nil))))))
624 (goto-char (point-max))
625 (save-excursion
626 (insert "--- " line2 ","
627 (number-to-string (+ (string-to-number line2)
628 (string-to-number lines2)
629 -1)) " ----\n" hunk))
630 ;;(goto-char (point-min))
631 (forward-line 1)
632 (if (not (save-excursion (re-search-forward "^+" nil t)))
633 (delete-region (point) (point-max))
634 (let ((modif nil) (delete nil))
635 (while (not (eobp))
636 (case (char-after)
637 (? (insert " ") (setq modif nil) (backward-char 1))
638 (?- (setq delete t) (setq modif t))
639 (?+ (if (not modif)
640 (progn (forward-char 1)
641 (insert " "))
642 (delete-char 1)
643 (insert "! "))
644 (backward-char 2))
645 (?\\ (when (save-excursion (forward-line 1)
646 (not (eobp)))
647 (setq delete t) (setq modif t)))
648 (t (setq modif nil)))
649 (let ((last-pt (point)))
650 (forward-line 1)
651 (when delete
652 (delete-region last-pt (point))
653 (setq delete nil)))))))))))))))
655 (defun diff-context->unified (start end)
656 "Convert context diffs to unified diffs.
657 START and END are either taken from the region (if a prefix arg is given) or
658 else cover the whole bufer."
659 (interactive (if current-prefix-arg
660 (list (mark) (point))
661 (list (point-min) (point-max))))
662 (unless (markerp end) (setq end (copy-marker end)))
663 (let (;;(diff-inhibit-after-change t)
664 (inhibit-read-only t))
665 (save-excursion
666 (goto-char start)
667 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
668 (< (point) end))
669 (combine-after-change-calls
670 (if (match-beginning 2)
671 ;; we matched a file header
672 (progn
673 ;; use reverse order to make sure the indices are kept valid
674 (replace-match "+++" t t nil 3)
675 (replace-match "---" t t nil 2))
676 ;; we matched a hunk header
677 (let ((line1s (match-string 4))
678 (line1e (match-string 5))
679 (pt1 (match-beginning 0)))
680 (replace-match "")
681 (unless (re-search-forward
682 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
683 (error "Can't find matching `--- n1,n2 ----' line"))
684 (let ((line2s (match-string 1))
685 (line2e (match-string 2))
686 (pt2 (progn
687 (delete-region (progn (beginning-of-line) (point))
688 (progn (forward-line 1) (point)))
689 (point-marker))))
690 (goto-char pt1)
691 (forward-line 1)
692 (while (< (point) pt2)
693 (case (char-after)
694 ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
695 (?\ ;merge with the other half of the chunk
696 (let* ((endline2
697 (save-excursion
698 (goto-char pt2) (forward-line 1) (point)))
699 (c (char-after pt2)))
700 (case c
701 ((?! ?+)
702 (insert "+"
703 (prog1 (buffer-substring (+ pt2 2) endline2)
704 (delete-region pt2 endline2))))
705 (?\ ;FIXME: check consistency
706 (delete-region pt2 endline2)
707 (delete-char 1)
708 (forward-line 1))
709 (?\\ (forward-line 1))
710 (t (delete-char 1) (forward-line 1)))))
711 (t (forward-line 1))))
712 (while (looking-at "[+! ] ")
713 (if (/= (char-after) ?!) (forward-char 1)
714 (delete-char 1) (insert "+"))
715 (delete-char 1) (forward-line 1))
716 (save-excursion
717 (goto-char pt1)
718 (insert "@@ -" line1s ","
719 (number-to-string (- (string-to-number line1e)
720 (string-to-number line1s)
721 -1))
722 " +" line2s ","
723 (number-to-string (- (string-to-number line2e)
724 (string-to-number line2s)
725 -1)) " @@"))))))))))
727 (defun diff-reverse-direction (start end)
728 "Reverse the direction of the diffs.
729 START and END are either taken from the region (if a prefix arg is given) or
730 else cover the whole bufer."
731 (interactive (if current-prefix-arg
732 (list (mark) (point))
733 (list (point-min) (point-max))))
734 (unless (markerp end) (setq end (copy-marker end)))
735 (let (;;(diff-inhibit-after-change t)
736 (inhibit-read-only t))
737 (save-excursion
738 (goto-char start)
739 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
740 (< (point) end))
741 (combine-after-change-calls
742 (cond
743 ;; a file header
744 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
745 ;; a context-diff hunk header
746 ((match-beginning 6)
747 (let ((pt-lines1 (match-beginning 6))
748 (lines1 (match-string 6)))
749 (replace-match "" nil nil nil 6)
750 (forward-line 1)
751 (let ((half1s (point)))
752 (while (looking-at "[-! \\][ \t]\\|#")
753 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
754 (forward-line 1))
755 (let ((half1 (delete-and-extract-region half1s (point))))
756 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
757 (insert half1)
758 (error "Can't find matching `--- n1,n2 ----' line"))
759 (let ((str1 (match-string 1)))
760 (replace-match lines1 nil nil nil 1)
761 (forward-line 1)
762 (let ((half2s (point)))
763 (while (looking-at "[!+ \\][ \t]\\|#")
764 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
765 (forward-line 1))
766 (let ((half2 (delete-and-extract-region half2s (point))))
767 (insert (or half1 ""))
768 (goto-char half1s)
769 (insert (or half2 ""))))
770 (goto-char pt-lines1)
771 (insert str1))))))
772 ;; a unified-diff hunk header
773 ((match-beginning 7)
774 (replace-match "@@ -\\8 +\\7 @@" nil)
775 (forward-line 1)
776 (let ((c (char-after)) first last)
777 (while (case (setq c (char-after))
778 (?- (setq first (or first (point)))
779 (delete-char 1) (insert "+") t)
780 (?+ (setq last (or last (point)))
781 (delete-char 1) (insert "-") t)
782 ((?\\ ?#) t)
783 (t (when (and first last (< first last))
784 (insert (delete-and-extract-region first last)))
785 (setq first nil last nil)
786 (equal ?\ c)))
787 (forward-line 1))))))))))
789 (defun diff-fixup-modifs (start end)
790 "Fixup the hunk headers (in case the buffer was modified).
791 START and END are either taken from the region (if a prefix arg is given) or
792 else cover the whole bufer."
793 (interactive (if current-prefix-arg
794 (list (mark) (point))
795 (list (point-min) (point-max))))
796 (let ((inhibit-read-only t))
797 (save-excursion
798 (goto-char end) (diff-end-of-hunk)
799 (let ((plus 0) (minus 0) (space 0) (bang 0))
800 (while (and (= (forward-line -1) 0) (<= start (point)))
801 (if (not (looking-at "\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|[-*][-*][-*] .+ [-*][-*][-*][-*]\\)$"))
802 (case (char-after)
803 (?\ (incf space))
804 (?+ (incf plus))
805 (?- (incf minus))
806 (?! (incf bang))
807 ((?\\ ?#) nil)
808 (t (setq space 0 plus 0 minus 0 bang 0)))
809 (cond
810 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
811 (let* ((old1 (match-string 1))
812 (old2 (match-string 2))
813 (new1 (number-to-string (+ space minus)))
814 (new2 (number-to-string (+ space plus))))
815 (unless (string= new2 old2) (replace-match new2 t t nil 2))
816 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
817 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
818 (when (> (+ space bang plus) 0)
819 (let* ((old1 (match-string 1))
820 (old2 (match-string 2))
821 (new (number-to-string
822 (+ space bang plus -1 (string-to-number old1)))))
823 (unless (string= new old2) (replace-match new t t nil 2)))))
824 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
825 (when (> (+ space bang minus) 0)
826 (let* ((old (match-string 1))
827 (new (format
828 (concat "%0" (number-to-string (length old)) "d")
829 (+ space bang minus -1 (string-to-number old)))))
830 (unless (string= new old) (replace-match new t t nil 2))))))
831 (setq space 0 plus 0 minus 0 bang 0)))))))
833 ;;;;
834 ;;;; Hooks
835 ;;;;
837 (defun diff-write-contents-hooks ()
838 "Fixup hunk headers if necessary."
839 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
840 nil)
842 ;; It turns out that making changes in the buffer from within an
843 ;; *-change-function is asking for trouble, whereas making them
844 ;; from a post-command-hook doesn't pose much problems
845 (defvar diff-unhandled-changes nil)
846 (defun diff-after-change-function (beg end len)
847 "Remember to fixup the hunk header.
848 See `after-change-functions' for the meaning of BEG, END and LEN."
849 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
850 ;; incorrect, but it turns out that inhibit-read-only is normally not set
851 ;; inside editing commands, while it tends to be set when the buffer gets
852 ;; updated by an async process or by a conversion function, both of which
853 ;; would rather not be uselessly slowed down by this hook.
854 (when (and (not undo-in-progress) (not inhibit-read-only))
855 (if diff-unhandled-changes
856 (setq diff-unhandled-changes
857 (cons (min beg (car diff-unhandled-changes))
858 (max end (cdr diff-unhandled-changes))))
859 (setq diff-unhandled-changes (cons beg end)))))
861 (defun diff-post-command-hook ()
862 "Fixup hunk headers if necessary."
863 (when (consp diff-unhandled-changes)
864 (ignore-errors
865 (save-excursion
866 (goto-char (car diff-unhandled-changes))
867 ;; Maybe we've cut the end of the hunk before point.
868 (if (and (bolp) (not (bobp))) (backward-char 1))
869 ;; We used to fixup modifs on all the changes, but it turns out
870 ;; that it's safer not to do it on big changes, for example
871 ;; when yanking a big diff, since we might then screw up perfectly
872 ;; correct values. -stef
873 ;; (unless (ignore-errors
874 ;; (diff-beginning-of-hunk)
875 ;; (save-excursion
876 ;; (diff-end-of-hunk)
877 ;; (> (point) (car diff-unhandled-changes))))
878 ;; (goto-char (car diff-unhandled-changes))
879 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
880 ;; (diff-beginning-of-hunk))
881 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
882 (diff-beginning-of-hunk)
883 (when (save-excursion
884 (diff-end-of-hunk)
885 (>= (point) (cdr diff-unhandled-changes)))
886 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
887 (setq diff-unhandled-changes nil)))
889 (defun diff-next-error (arg reset)
890 ;; Select a window that displays the current buffer so that point
891 ;; movements are reflected in that window. Otherwise, the user might
892 ;; never see the hunk corresponding to the source she's jumping to.
893 (pop-to-buffer (current-buffer))
894 (if reset (goto-char (point-min)))
895 (diff-hunk-next arg)
896 (diff-goto-source))
898 ;;;###autoload
899 (define-derived-mode diff-mode fundamental-mode "Diff"
900 "Major mode for viewing/editing context diffs.
901 Supports unified and context diffs as well as (to a lesser extent)
902 normal diffs.
903 When the buffer is read-only, the ESC prefix is not necessary.
904 IF you edit the buffer manually, diff-mode will try to update the hunk
905 headers for you on-the-fly.
907 You can also switch between context diff and unified diff with \\[diff-context->unified],
908 or vice versa with \\[diff-unified->context] and you can also revert the direction of
909 a diff with \\[diff-reverse-direction]."
910 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
911 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
912 (set (make-local-variable 'imenu-generic-expression)
913 diff-imenu-generic-expression)
914 ;; These are not perfect. They would be better done separately for
915 ;; context diffs and unidiffs.
916 ;; (set (make-local-variable 'paragraph-start)
917 ;; (concat "@@ " ; unidiff hunk
918 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
919 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
920 ;; ; start (first or second line)
921 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
922 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
923 ;; compile support
924 (set (make-local-variable 'next-error-function) 'diff-next-error)
926 (when (and (> (point-max) (point-min)) diff-default-read-only)
927 (toggle-read-only t))
928 ;; setup change hooks
929 (if (not diff-update-on-the-fly)
930 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
931 (make-local-variable 'diff-unhandled-changes)
932 (add-hook 'after-change-functions 'diff-after-change-function nil t)
933 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
934 ;; Neat trick from Dave Love to add more bindings in read-only mode:
935 (let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
936 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
937 ;; Turn off this little trick in case the buffer is put in view-mode.
938 (add-hook 'view-mode-hook
939 `(lambda ()
940 (setq minor-mode-overriding-map-alist
941 (delq ',ro-bind minor-mode-overriding-map-alist)))
942 nil t))
943 ;; add-log support
944 (set (make-local-variable 'add-log-current-defun-function)
945 'diff-current-defun)
946 (set (make-local-variable 'add-log-buffer-file-name-function)
947 'diff-find-file-name))
949 ;;;###autoload
950 (define-minor-mode diff-minor-mode
951 "Minor mode for viewing/editing context diffs.
952 \\{diff-minor-mode-map}"
953 nil " Diff" nil
954 ;; FIXME: setup font-lock
955 ;; setup change hooks
956 (if (not diff-update-on-the-fly)
957 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
958 (make-local-variable 'diff-unhandled-changes)
959 (add-hook 'after-change-functions 'diff-after-change-function nil t)
960 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
962 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
964 (defun diff-delete-if-empty ()
965 ;; An empty diff file means there's no more diffs to integrate, so we
966 ;; can just remove the file altogether. Very handy for .rej files if we
967 ;; remove hunks as we apply them.
968 (when (and buffer-file-name
969 (eq 0 (nth 7 (file-attributes buffer-file-name))))
970 (delete-file buffer-file-name)))
972 (defun diff-delete-empty-files ()
973 "Arrange for empty diff files to be removed."
974 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
976 (defun diff-make-unified ()
977 "Turn context diffs into unified diffs if applicable."
978 (if (save-excursion
979 (goto-char (point-min))
980 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
981 (let ((mod (buffer-modified-p)))
982 (unwind-protect
983 (diff-context->unified (point-min) (point-max))
984 (restore-buffer-modified-p mod)))))
987 ;;; Misc operations that have proved useful at some point.
990 (defun diff-next-complex-hunk ()
991 "Jump to the next \"complex\" hunk.
992 \"Complex\" is approximated by \"the hunk changes the number of lines\".
993 Only works for unified diffs."
994 (interactive)
995 (while
996 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
997 nil t)
998 (equal (match-string 1) (match-string 2)))))
1000 (defun diff-hunk-text (hunk destp char-offset)
1001 "Return the literal source text from HUNK as (TEXT . OFFSET).
1002 if DESTP is nil TEXT is the source, otherwise the destination text.
1003 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1004 char-offset in TEXT."
1005 (with-temp-buffer
1006 (insert hunk)
1007 (goto-char (point-min))
1008 (let ((src-pos nil)
1009 (dst-pos nil)
1010 (divider-pos nil)
1011 (num-pfx-chars 2))
1012 ;; Set the following variables:
1013 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1014 ;; DST-POS buffer pos of the destination part of the hunk or nil
1015 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1016 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1017 (cond ((looking-at "^@@")
1018 ;; unified diff
1019 (setq num-pfx-chars 1)
1020 (forward-line 1)
1021 (setq src-pos (point) dst-pos (point)))
1022 ((looking-at "^\\*\\*")
1023 ;; context diff
1024 (forward-line 2)
1025 (setq src-pos (point))
1026 (re-search-forward "^--- " nil t)
1027 (forward-line 0)
1028 (setq divider-pos (point))
1029 (forward-line 1)
1030 (setq dst-pos (point)))
1031 ((looking-at "^[0-9]+a[0-9,]+$")
1032 ;; normal diff, insert
1033 (forward-line 1)
1034 (setq dst-pos (point)))
1035 ((looking-at "^[0-9,]+d[0-9]+$")
1036 ;; normal diff, delete
1037 (forward-line 1)
1038 (setq src-pos (point)))
1039 ((looking-at "^[0-9,]+c[0-9,]+$")
1040 ;; normal diff, change
1041 (forward-line 1)
1042 (setq src-pos (point))
1043 (re-search-forward "^---$" nil t)
1044 (forward-line 0)
1045 (setq divider-pos (point))
1046 (forward-line 1)
1047 (setq dst-pos (point)))
1049 (error "Unknown diff hunk type")))
1051 (if (if destp (null dst-pos) (null src-pos))
1052 ;; Implied empty text
1053 (if char-offset '("" . 0) "")
1055 ;; For context diffs, either side can be empty, (if there's only
1056 ;; added or only removed text). We should then use the other side.
1057 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1058 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1060 (when char-offset (goto-char (+ (point-min) char-offset)))
1062 ;; Get rid of anything except the desired text.
1063 (save-excursion
1064 ;; Delete unused text region
1065 (let ((keep (if destp dst-pos src-pos)))
1066 (when (and divider-pos (> divider-pos keep))
1067 (delete-region divider-pos (point-max)))
1068 (delete-region (point-min) keep))
1069 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1070 (let ((kill-char (if destp ?- ?+)))
1071 (goto-char (point-min))
1072 (while (not (eobp))
1073 (if (eq (char-after) kill-char)
1074 (delete-region (point) (progn (forward-line 1) (point)))
1075 (delete-char num-pfx-chars)
1076 (forward-line 1)))))
1078 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1079 (if char-offset (cons text (- (point) (point-min))) text))))))
1082 (defun diff-find-text (text)
1083 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1084 If TEXT isn't found, nil is returned."
1085 (let* ((orig (point))
1086 (forw (and (search-forward text nil t)
1087 (cons (match-beginning 0) (match-end 0))))
1088 (back (and (goto-char (+ orig (length text)))
1089 (search-backward text nil t)
1090 (cons (match-beginning 0) (match-end 0)))))
1091 ;; Choose the closest match.
1092 (if (and forw back)
1093 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1094 (or back forw))))
1096 (defun diff-find-approx-text (text)
1097 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1098 Whitespace differences are ignored."
1099 (let* ((orig (point))
1100 (re (concat "^[ \t\n\f]*"
1101 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1102 "[ \t\n\f]*\n"))
1103 (forw (and (re-search-forward re nil t)
1104 (cons (match-beginning 0) (match-end 0))))
1105 (back (and (goto-char (+ orig (length text)))
1106 (re-search-backward re nil t)
1107 (cons (match-beginning 0) (match-end 0)))))
1108 ;; Choose the closest match.
1109 (if (and forw back)
1110 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1111 (or back forw))))
1113 (defsubst diff-xor (a b) (if a (not b) b))
1115 (defun diff-find-source-location (&optional other-file reverse)
1116 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1117 BUF is the buffer corresponding to the source file.
1118 LINE-OFFSET is the offset between the expected and actual positions
1119 of the text of the hunk or nil if the text was not found.
1120 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1121 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1122 SRC is the variant that was found in the buffer.
1123 SWITCHED is non-nil if the patch is already applied."
1124 (save-excursion
1125 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1126 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1127 (hunk (buffer-substring (point)
1128 (save-excursion (diff-end-of-hunk) (point))))
1129 (old (diff-hunk-text hunk reverse char-offset))
1130 (new (diff-hunk-text hunk (not reverse) char-offset))
1131 ;; Find the location specification.
1132 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1133 (error "Can't find the hunk header")
1134 (if other (match-string 1)
1135 (if (match-end 3) (match-string 3)
1136 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1137 (error "Can't find the hunk separator"))
1138 (match-string 1)))))
1139 (file (or (diff-find-file-name other) (error "Can't find the file")))
1140 (buf (find-file-noselect file)))
1141 ;; Update the user preference if he so wished.
1142 (when (> (prefix-numeric-value other-file) 8)
1143 (setq diff-jump-to-old-file other))
1144 (with-current-buffer buf
1145 (goto-line (string-to-number line))
1146 (let* ((orig-pos (point))
1147 (switched nil)
1148 ;; FIXME: Check for case where both OLD and NEW are found.
1149 (pos (or (diff-find-text (car old))
1150 (progn (setq switched t) (diff-find-text (car new)))
1151 (progn (setq switched nil)
1152 (condition-case nil
1153 (diff-find-approx-text (car old))
1154 (invalid-regexp nil))) ;Regex too big.
1155 (progn (setq switched t)
1156 (condition-case nil
1157 (diff-find-approx-text (car new))
1158 (invalid-regexp nil))) ;Regex too big.
1159 (progn (setq switched nil) nil))))
1160 (nconc
1161 (list buf)
1162 (if pos
1163 (list (count-lines orig-pos (car pos)) pos)
1164 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1165 (if switched (list new old t) (list old new))))))))
1168 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1169 (let ((msg (if dry-run
1170 (if reversed "already applied" "not yet applied")
1171 (if reversed "undone" "applied"))))
1172 (message (cond ((null line-offset) "Hunk text not found")
1173 ((= line-offset 0) "Hunk %s")
1174 ((= line-offset 1) "Hunk %s at offset %d line")
1175 (t "Hunk %s at offset %d lines"))
1176 msg line-offset)))
1179 (defun diff-apply-hunk (&optional reverse)
1180 "Apply the current hunk to the source file and go to the next.
1181 By default, the new source file is patched, but if the variable
1182 `diff-jump-to-old-file' is non-nil, then the old source file is
1183 patched instead (some commands, such as `diff-goto-source' can change
1184 the value of this variable when given an appropriate prefix argument).
1186 With a prefix argument, REVERSE the hunk."
1187 (interactive "P")
1188 (destructuring-bind (buf line-offset pos old new &optional switched)
1189 ;; If REVERSE go to the new file, otherwise go to the old.
1190 (diff-find-source-location (not reverse) reverse)
1191 (cond
1192 ((null line-offset)
1193 (error "Can't find the text to patch"))
1194 ((and switched
1195 ;; A reversed patch was detected, perhaps apply it in reverse.
1196 (not (save-window-excursion
1197 (pop-to-buffer buf)
1198 (goto-char (+ (car pos) (cdr old)))
1199 (y-or-n-p
1200 (if reverse
1201 "Hunk hasn't been applied yet; apply it now? "
1202 "Hunk has already been applied; undo it? ")))))
1203 (message "(Nothing done)"))
1205 ;; Apply the hunk
1206 (with-current-buffer buf
1207 (goto-char (car pos))
1208 (delete-region (car pos) (cdr pos))
1209 (insert (car new)))
1210 ;; Display BUF in a window
1211 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1212 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1213 (when diff-advance-after-apply-hunk
1214 (diff-hunk-next))))))
1217 (defun diff-test-hunk (&optional reverse)
1218 "See whether it's possible to apply the current hunk.
1219 With a prefix argument, try to REVERSE the hunk."
1220 (interactive "P")
1221 (destructuring-bind (buf line-offset pos src dst &optional switched)
1222 ;; If REVERSE go to the new file, otherwise go to the old.
1223 (diff-find-source-location (not reverse) reverse)
1224 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1225 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1228 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1230 (defun diff-goto-source (&optional other-file event)
1231 "Jump to the corresponding source line.
1232 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1233 is given) determines whether to jump to the old or the new file.
1234 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1235 then `diff-jump-to-old-file' is also set, for the next invocations."
1236 (interactive (list current-prefix-arg last-input-event))
1237 ;; When pointing at a removal line, we probably want to jump to
1238 ;; the old location, and else to the new (i.e. as if reverting).
1239 ;; This is a convenient detail when using smerge-diff.
1240 (if event (posn-set-point (event-end event)))
1241 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1242 (destructuring-bind (buf line-offset pos src dst &optional switched)
1243 (diff-find-source-location other-file rev)
1244 (pop-to-buffer buf)
1245 (goto-char (+ (car pos) (cdr src)))
1246 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1249 (defun diff-current-defun ()
1250 "Find the name of function at point.
1251 For use in `add-log-current-defun-function'."
1252 (save-excursion
1253 (when (looking-at diff-hunk-header-re)
1254 (forward-line 1)
1255 (while (and (looking-at " ") (not (zerop (forward-line 1))))))
1256 (destructuring-bind (buf line-offset pos src dst &optional switched)
1257 (diff-find-source-location)
1258 (beginning-of-line)
1259 (or (when (memq (char-after) '(?< ?-))
1260 ;; Cursor is pointing at removed text. This could be a removed
1261 ;; function, in which case, going to the source buffer will
1262 ;; not help since the function is now removed. Instead,
1263 ;; try to figure out the function name just from the code-fragment.
1264 (let ((old (if switched dst src)))
1265 (with-temp-buffer
1266 (insert (car old))
1267 (funcall (with-current-buffer buf major-mode))
1268 (goto-char (+ (point-min) (cdr old)))
1269 (add-log-current-defun))))
1270 (with-current-buffer buf
1271 (goto-char (+ (car pos) (cdr src)))
1272 (add-log-current-defun))))))
1274 (defun diff-refine-hunk ()
1275 "Refine the current hunk by ignoring space differences."
1276 (interactive)
1277 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1278 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1279 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1280 (error "Can't find line number"))
1281 (string-to-number (match-string 1))))
1282 (hunk (delete-and-extract-region
1283 (point) (save-excursion (diff-end-of-hunk) (point))))
1284 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1285 (file1 (make-temp-file "diff1"))
1286 (file2 (make-temp-file "diff2"))
1287 (coding-system-for-read buffer-file-coding-system)
1288 old new)
1289 (unwind-protect
1290 (save-excursion
1291 (setq old (diff-hunk-text hunk nil char-offset))
1292 (setq new (diff-hunk-text hunk t char-offset))
1293 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1294 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1295 (with-temp-buffer
1296 (let ((status
1297 (call-process diff-command nil t nil
1298 opts file1 file2)))
1299 (case status
1300 (0 nil) ;Nothing to reformat.
1301 (1 (goto-char (point-min))
1302 ;; Remove the file-header.
1303 (when (re-search-forward diff-hunk-header-re nil t)
1304 (delete-region (point-min) (match-beginning 0))))
1305 (t (goto-char (point-max))
1306 (unless (bolp) (insert "\n"))
1307 (insert hunk)))
1308 (setq hunk (buffer-string))
1309 (unless (memq status '(0 1))
1310 (error "Diff returned: %s" status)))))
1311 ;; Whatever happens, put back some equivalent text: either the new
1312 ;; one or the original one in case some error happened.
1313 (insert hunk)
1314 (delete-file file1)
1315 (delete-file file2))))
1317 ;; provide the package
1318 (provide 'diff-mode)
1320 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1321 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1322 ;; (diff-mode-load-hook): dropped.
1323 ;; (auto-mode-alist): also catch *.diffs.
1324 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1325 ;; for *.rej files (that lack any file name indication).
1327 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1328 ;; added support for "\ No newline at end of file".
1330 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1331 ;; - added basic `compile' support.
1332 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1333 ;; - diff-kill-file now tries to kill the leading garbage as well.
1335 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1336 ;; - don't use CL in the autoloaded code
1337 ;; - accept diffs using -T
1339 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1340 ;; interface to ediff-patch
1342 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1343 ;; (ediff=patch-file): add bindings to call ediff-patch.
1344 ;; (diff-find-file-name): taken out of diff-goto-source.
1345 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1346 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1348 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1349 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1351 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1352 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1355 ;;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1356 ;;; diff-mode.el ends here