(diff-unified->context, diff-reverse-direction, diff-fixup-modifs):
[emacs.git] / lisp / diff-mode.el
blobe0aee67a62b0f59b7da1744361028217e6602ba7
1 ;;; diff-mode.el --- a mode for viewing/editing context diffs
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007 Free Software Foundation, Inc.
6 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; Keywords: convenience patch diff
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 3, or (at your option)
14 ;; any later version.
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.
26 ;;; Commentary:
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
36 ;; Bugs:
38 ;; - Reverse doesn't work with normal diffs.
40 ;; Todo:
42 ;; - Add a `delete-after-apply' so C-c C-a automatically deletes hunks.
43 ;; Also allow C-c C-a to delete already-applied hunks.
45 ;; - Try `diff <file> <hunk>' to try and fuzzily discover the source location
46 ;; of a hunk. Show then the changes between <file> and <hunk> and make it
47 ;; possible to apply them to <file>, <hunk-src>, or <hunk-dst>.
48 ;; Or maybe just make it into a ".rej to diff3-markers converter".
49 ;; Maybe just use `wiggle' (by Neil Brown) to do it for us.
51 ;; - Refine hunk on a word-by-word basis.
52 ;;
53 ;; - in diff-apply-hunk, strip context in replace-match to better
54 ;; preserve markers and spacing.
55 ;; - Handle `diff -b' output in context->unified.
57 ;;; Code:
58 (eval-when-compile (require 'cl))
60 (defvar add-log-buffer-file-name-function)
63 (defgroup diff-mode ()
64 "Major mode for viewing/editing diffs."
65 :version "21.1"
66 :group 'tools
67 :group 'diff)
69 (defcustom diff-default-read-only nil
70 "If non-nil, `diff-mode' buffers default to being read-only."
71 :type 'boolean
72 :group 'diff-mode)
74 (defcustom diff-jump-to-old-file nil
75 "*Non-nil means `diff-goto-source' jumps to the old file.
76 Else, it jumps to the new file."
77 :type 'boolean
78 :group 'diff-mode)
80 (defcustom diff-update-on-the-fly t
81 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
82 When editing a diff file, the line numbers in the hunk headers
83 need to be kept consistent with the actual diff. This can
84 either be done on the fly (but this sometimes interacts poorly with the
85 undo mechanism) or whenever the file is written (can be slow
86 when editing big diffs)."
87 :type 'boolean
88 :group 'diff-mode)
90 (defcustom diff-advance-after-apply-hunk t
91 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
92 :type 'boolean
93 :group 'diff-mode)
96 (defcustom diff-mode-hook nil
97 "Run after setting up the `diff-mode' major mode."
98 :type 'hook
99 :options '(diff-delete-empty-files diff-make-unified)
100 :group 'diff-mode)
102 (defvar diff-outline-regexp
103 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
105 ;;;;
106 ;;;; keymap, menu, ...
107 ;;;;
109 (easy-mmode-defmap diff-mode-shared-map
110 '(;; From Pavel Machek's patch-mode.
111 ("n" . diff-hunk-next)
112 ("N" . diff-file-next)
113 ("p" . diff-hunk-prev)
114 ("P" . diff-file-prev)
115 ("k" . diff-hunk-kill)
116 ("K" . diff-file-kill)
117 ;; From compilation-minor-mode.
118 ("}" . diff-file-next)
119 ("{" . diff-file-prev)
120 ("\C-m" . diff-goto-source)
121 ([mouse-2] . diff-goto-source)
122 ;; From XEmacs' diff-mode.
123 ;; Standard M-w is useful, so don't change M-W.
124 ;;("W" . widen)
125 ;;("." . diff-goto-source) ;display-buffer
126 ;;("f" . diff-goto-source) ;find-file
127 ("o" . diff-goto-source) ;other-window
128 ;;("w" . diff-goto-source) ;other-frame
129 ;;("N" . diff-narrow)
130 ;;("h" . diff-show-header)
131 ;;("j" . diff-show-difference) ;jump to Nth diff
132 ;;("q" . diff-quit)
133 ;; Not useful if you have to metafy them.
134 ;;(" " . scroll-up)
135 ;;("\177" . scroll-down)
136 ;; Standard M-a is useful, so don't change M-A.
137 ;;("A" . diff-ediff-patch)
138 ;; Standard M-r is useful, so don't change M-r or M-R.
139 ;;("r" . diff-restrict-view)
140 ;;("R" . diff-reverse-direction)
141 ("q" . quit-window))
142 "Basic keymap for `diff-mode', bound to various prefix keys.")
144 (easy-mmode-defmap diff-mode-map
145 `(("\e" . ,diff-mode-shared-map)
146 ;; From compilation-minor-mode.
147 ("\C-c\C-c" . diff-goto-source)
148 ;; Misc operations.
149 ("\C-c\C-a" . diff-apply-hunk)
150 ("\C-c\C-e" . diff-ediff-patch)
151 ("\C-c\C-n" . diff-restrict-view)
152 ("\C-c\C-r" . diff-reverse-direction)
153 ("\C-c\C-s" . diff-split-hunk)
154 ("\C-c\C-t" . diff-test-hunk)
155 ("\C-c\C-u" . diff-context->unified)
156 ;; `d' because it duplicates the context :-( --Stef
157 ("\C-c\C-d" . diff-unified->context)
158 ("\C-c\C-w" . diff-refine-hunk)
159 ("\C-c\C-f" . next-error-follow-minor-mode))
160 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
162 (easy-menu-define diff-mode-menu diff-mode-map
163 "Menu for `diff-mode'."
164 '("Diff"
165 ["Jump to Source" diff-goto-source t]
166 ["Apply hunk" diff-apply-hunk t]
167 ["Test applying hunk" diff-test-hunk t]
168 ["Apply diff with Ediff" diff-ediff-patch t]
169 "-----"
170 ["Reverse direction" diff-reverse-direction t]
171 ["Context -> Unified" diff-context->unified t]
172 ["Unified -> Context" diff-unified->context t]
173 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
174 "-----"
175 ["Split hunk" diff-split-hunk t]
176 ["Refine hunk" diff-refine-hunk t]
177 ["Kill current hunk" diff-hunk-kill t]
178 ["Kill current file's hunks" diff-file-kill t]
179 "-----"
180 ["Previous Hunk" diff-hunk-prev t]
181 ["Next Hunk" diff-hunk-next t]
182 ["Previous File" diff-file-prev t]
183 ["Next File" diff-file-next t]
186 (defcustom diff-minor-mode-prefix "\C-c="
187 "Prefix key for `diff-minor-mode' commands."
188 :type '(choice (string "\e") (string "C-c=") string)
189 :group 'diff-mode)
191 (easy-mmode-defmap diff-minor-mode-map
192 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
193 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
196 ;;;;
197 ;;;; font-lock support
198 ;;;;
200 (defface diff-header
201 '((((class color) (min-colors 88) (background light))
202 :background "grey85")
203 (((class color) (min-colors 88) (background dark))
204 :background "grey45")
205 (((class color) (background light))
206 :foreground "blue1" :weight bold)
207 (((class color) (background dark))
208 :foreground "green" :weight bold)
209 (t :weight bold))
210 "`diff-mode' face inherited by hunk and index header faces."
211 :group 'diff-mode)
212 ;; backward-compatibility alias
213 (put 'diff-header-face 'face-alias 'diff-header)
214 (defvar diff-header-face 'diff-header)
216 (defface diff-file-header
217 '((((class color) (min-colors 88) (background light))
218 :background "grey70" :weight bold)
219 (((class color) (min-colors 88) (background dark))
220 :background "grey60" :weight bold)
221 (((class color) (background light))
222 :foreground "green" :weight bold)
223 (((class color) (background dark))
224 :foreground "cyan" :weight bold)
225 (t :weight bold)) ; :height 1.3
226 "`diff-mode' face used to highlight file header lines."
227 :group 'diff-mode)
228 ;; backward-compatibility alias
229 (put 'diff-file-header-face 'face-alias 'diff-file-header)
230 (defvar diff-file-header-face 'diff-file-header)
232 (defface diff-index
233 '((t :inherit diff-file-header))
234 "`diff-mode' face used to highlight index header lines."
235 :group 'diff-mode)
236 ;; backward-compatibility alias
237 (put 'diff-index-face 'face-alias 'diff-index)
238 (defvar diff-index-face 'diff-index)
240 (defface diff-hunk-header
241 '((t :inherit diff-header))
242 "`diff-mode' face used to highlight hunk header lines."
243 :group 'diff-mode)
244 ;; backward-compatibility alias
245 (put 'diff-hunk-header-face 'face-alias 'diff-hunk-header)
246 (defvar diff-hunk-header-face 'diff-hunk-header)
248 (defface diff-removed
249 '((t :inherit diff-changed))
250 "`diff-mode' face used to highlight removed lines."
251 :group 'diff-mode)
252 ;; backward-compatibility alias
253 (put 'diff-removed-face 'face-alias 'diff-removed)
254 (defvar diff-removed-face 'diff-removed)
256 (defface diff-added
257 '((t :inherit diff-changed))
258 "`diff-mode' face used to highlight added lines."
259 :group 'diff-mode)
260 ;; backward-compatibility alias
261 (put 'diff-added-face 'face-alias 'diff-added)
262 (defvar diff-added-face 'diff-added)
264 (defface diff-changed
265 '((((type tty pc) (class color) (background light))
266 :foreground "magenta" :weight bold :slant italic)
267 (((type tty pc) (class color) (background dark))
268 :foreground "yellow" :weight bold :slant italic))
269 "`diff-mode' face used to highlight changed lines."
270 :group 'diff-mode)
271 ;; backward-compatibility alias
272 (put 'diff-changed-face 'face-alias 'diff-changed)
273 (defvar diff-changed-face 'diff-changed)
275 (defface diff-indicator-removed
276 '((t :inherit diff-removed))
277 "`diff-mode' face used to highlight indicator of removed lines (-, <)."
278 :group 'diff-mode
279 :version "22.1")
280 (defvar diff-indicator-removed-face 'diff-indicator-removed)
282 (defface diff-indicator-added
283 '((t :inherit diff-added))
284 "`diff-mode' face used to highlight indicator of added lines (+, >)."
285 :group 'diff-mode
286 :version "22.1")
287 (defvar diff-indicator-added-face 'diff-indicator-added)
289 (defface diff-indicator-changed
290 '((t :inherit diff-changed))
291 "`diff-mode' face used to highlight indicator of changed lines."
292 :group 'diff-mode
293 :version "22.1")
294 (defvar diff-indicator-changed-face 'diff-indicator-changed)
296 (defface diff-function
297 '((t :inherit diff-header))
298 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
299 :group 'diff-mode)
300 ;; backward-compatibility alias
301 (put 'diff-function-face 'face-alias 'diff-function)
302 (defvar diff-function-face 'diff-function)
304 (defface diff-context
305 '((((class color grayscale) (min-colors 88)) :inherit shadow))
306 "`diff-mode' face used to highlight context and other side-information."
307 :group 'diff-mode)
308 ;; backward-compatibility alias
309 (put 'diff-context-face 'face-alias 'diff-context)
310 (defvar diff-context-face 'diff-context)
312 (defface diff-nonexistent
313 '((t :inherit diff-file-header))
314 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
315 :group 'diff-mode)
316 ;; backward-compatibility alias
317 (put 'diff-nonexistent-face 'face-alias 'diff-nonexistent)
318 (defvar diff-nonexistent-face 'diff-nonexistent)
320 (defconst diff-yank-handler '(diff-yank-function))
321 (defun diff-yank-function (text)
322 ;; FIXME: the yank-handler is now called separately on each piece of text
323 ;; with a yank-handler property, so the next-single-property-change call
324 ;; below will always return nil :-( --stef
325 (let ((mixed (next-single-property-change 0 'yank-handler text))
326 (start (point)))
327 ;; First insert the text.
328 (insert text)
329 ;; If the text does not include any diff markers and if we're not
330 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
331 (unless (or mixed (derived-mode-p 'diff-mode))
332 (undo-boundary) ; Just in case the user wanted the prefixes.
333 (let ((re (save-excursion
334 (if (re-search-backward "^[><!][ \t]" start t)
335 (if (eq (char-after) ?!)
336 "^[!+- ][ \t]" "^[<>][ \t]")
337 "^[ <>!+-]"))))
338 (save-excursion
339 (while (re-search-backward re start t)
340 (replace-match "" t t)))))))
343 (defvar diff-font-lock-keywords
344 `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
345 (1 diff-hunk-header-face) (2 diff-function-face))
346 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
347 (1 diff-hunk-header-face) (2 diff-function-face))
348 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
349 ("^--- .+ ----$" . diff-hunk-header-face) ;context
350 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face) ;normal
351 ("^---$" . diff-hunk-header-face) ;normal
352 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
353 (0 diff-header-face) (2 diff-file-header-face prepend))
354 ("^\\([-<]\\)\\(.*\n\\)"
355 (1 diff-indicator-removed-face) (2 diff-removed-face))
356 ("^\\([+>]\\)\\(.*\n\\)"
357 (1 diff-indicator-added-face) (2 diff-added-face))
358 ("^\\(!\\)\\(.*\n\\)"
359 (1 diff-indicator-changed-face) (2 diff-changed-face))
360 ("^Index: \\(.+\\).*\n"
361 (0 diff-header-face) (1 diff-index-face prepend))
362 ("^Only in .*\n" . diff-nonexistent-face)
363 ("^\\(#\\)\\(.*\\)"
364 (1 font-lock-comment-delimiter-face)
365 (2 font-lock-comment-face))
366 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
368 (defconst diff-font-lock-defaults
369 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
371 (defvar diff-imenu-generic-expression
372 ;; Prefer second name as first is most likely to be a backup or
373 ;; version-control name. The [\t\n] at the end of the unidiff pattern
374 ;; catches Debian source diff files (which lack the trailing date).
375 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
376 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
378 ;;;;
379 ;;;; Movement
380 ;;;;
382 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
383 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
384 (defvar diff-narrowed-to nil)
386 (defun diff-end-of-hunk (&optional style)
387 (when (looking-at diff-hunk-header-re)
388 (unless style
389 ;; Especially important for unified (because headers are ambiguous).
390 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context))))))
391 (goto-char (match-end 0)))
392 (let ((end (and (re-search-forward (case style
393 ;; A `unified' header is ambiguous.
394 (unified (concat "^[^-+# \\]\\|"
395 diff-file-header-re))
396 (context "^[^-+#! \\]")
397 (normal "^[^<>#\\]")
398 (t "^[^-+#!<> \\]"))
399 nil t)
400 (match-beginning 0))))
401 ;; The return value is used by easy-mmode-define-navigation.
402 (goto-char (or end (point-max)))))
404 (defun diff-beginning-of-hunk (&optional try-harder)
405 "Move back to beginning of hunk.
406 If TRY-HARDER is non-nil, try to cater to the case where we're not in a hunk
407 but in the file header instead, in which case move forward to the first hunk."
408 (beginning-of-line)
409 (unless (looking-at diff-hunk-header-re)
410 (forward-line 1)
411 (condition-case ()
412 (re-search-backward diff-hunk-header-re)
413 (error
414 (if (not try-harder)
415 (error "Can't find the beginning of the hunk")
416 (diff-beginning-of-file-and-junk)
417 (diff-hunk-next))))))
419 (defun diff-beginning-of-file ()
420 (beginning-of-line)
421 (unless (looking-at diff-file-header-re)
422 (forward-line 2)
423 (condition-case ()
424 (re-search-backward diff-file-header-re)
425 (error (error "Can't find the beginning of the file")))))
427 (defun diff-end-of-file ()
428 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
429 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
430 nil 'move)
431 (if (match-beginning 1)
432 (goto-char (match-beginning 1))
433 (beginning-of-line)))
435 ;; Define diff-{hunk,file}-{prev,next}
436 (easy-mmode-define-navigation
437 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
438 (easy-mmode-define-navigation
439 diff-file diff-file-header-re "file" diff-end-of-hunk)
441 (defun diff-restrict-view (&optional arg)
442 "Restrict the view to the current hunk.
443 If the prefix ARG is given, restrict the view to the current file instead."
444 (interactive "P")
445 (save-excursion
446 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk 'try-harder))
447 (narrow-to-region (point)
448 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
449 (point)))
450 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
453 (defun diff-hunk-kill ()
454 "Kill current hunk."
455 (interactive)
456 (diff-beginning-of-hunk)
457 (let* ((start (point))
458 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
459 (match-beginning 0)))
460 (firsthunk (ignore-errors
461 (goto-char start)
462 (diff-beginning-of-file) (diff-hunk-next) (point)))
463 (nextfile (ignore-errors (diff-file-next) (point)))
464 (inhibit-read-only t))
465 (goto-char start)
466 (if (and firsthunk (= firsthunk start)
467 (or (null nexthunk)
468 (and nextfile (> nexthunk nextfile))))
469 ;; It's the only hunk for this file, so kill the file.
470 (diff-file-kill)
471 (diff-end-of-hunk)
472 (kill-region start (point)))))
474 (defun diff-beginning-of-file-and-junk ()
475 "Go to the beginning of file-related diff-info.
476 This is like `diff-beginning-of-file' except it tries to skip back over leading
477 data such as \"Index: ...\" and such."
478 (let ((start (point))
479 (file (condition-case err (progn (diff-beginning-of-file) (point))
480 (error err)))
481 ;; prevhunk is one of the limits.
482 (prevhunk (save-excursion (ignore-errors (diff-hunk-prev) (point))))
483 err)
484 (when (consp file)
485 ;; Presumably, we started before the file header, in the leading junk.
486 (setq err file)
487 (diff-file-next)
488 (setq file (point)))
489 (let ((index (save-excursion
490 (re-search-backward "^Index: " prevhunk t))))
491 (when index (setq file index))
492 (if (<= file start)
493 (goto-char file)
494 ;; File starts *after* the starting point: we really weren't in
495 ;; a file diff but elsewhere.
496 (goto-char start)
497 (signal (car err) (cdr err))))))
499 (defun diff-file-kill ()
500 "Kill current file's hunks."
501 (interactive)
502 (diff-beginning-of-file-and-junk)
503 (let* ((start (point))
504 (inhibit-read-only t))
505 (diff-end-of-file)
506 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
507 (kill-region start (point))))
509 (defun diff-kill-junk ()
510 "Kill spurious empty diffs."
511 (interactive)
512 (save-excursion
513 (let ((inhibit-read-only t))
514 (goto-char (point-min))
515 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
516 "\\([^-+!* <>].*\n\\)*?"
517 "\\(\\(Index:\\) \\|"
518 diff-file-header-re "\\)")
519 nil t)
520 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
521 (match-beginning 3))
522 (beginning-of-line)))))
524 (defun diff-count-matches (re start end)
525 (save-excursion
526 (let ((n 0))
527 (goto-char start)
528 (while (re-search-forward re end t) (incf n))
529 n)))
531 (defun diff-split-hunk ()
532 "Split the current (unified diff) hunk at point into two hunks."
533 (interactive)
534 (beginning-of-line)
535 (let ((pos (point))
536 (start (progn (diff-beginning-of-hunk) (point))))
537 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
538 (error "diff-split-hunk only works on unified context diffs"))
539 (forward-line 1)
540 (let* ((start1 (string-to-number (match-string 1)))
541 (start2 (string-to-number (match-string 2)))
542 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
543 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
544 (inhibit-read-only t))
545 (goto-char pos)
546 ;; Hopefully the after-change-function will not screw us over.
547 (insert "@@ -" (number-to-string newstart1) ",1 +"
548 (number-to-string newstart2) ",1 @@\n")
549 ;; Fix the original hunk-header.
550 (diff-fixup-modifs start pos))))
553 ;;;;
554 ;;;; jump to other buffers
555 ;;;;
557 (defvar diff-remembered-files-alist nil)
559 (defun diff-filename-drop-dir (file)
560 (when (string-match "/" file) (substring file (match-end 0))))
562 (defun diff-merge-strings (ancestor from to)
563 "Merge the diff between ANCESTOR and FROM into TO.
564 Returns the merged string if successful or nil otherwise.
565 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
566 If ANCESTOR = FROM, returns TO.
567 If ANCESTOR = TO, returns FROM.
568 The heuristic is simplistic and only really works for cases
569 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
570 ;; Ideally, we want:
571 ;; AMB ANB CMD -> CND
572 ;; but that's ambiguous if `foo' or `bar' is empty:
573 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
574 (let ((str (concat ancestor "\n" from "\n" to)))
575 (when (and (string-match (concat
576 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
577 "\\1\\(.*\\)\\3\n"
578 "\\(.*\\(\\2\\).*\\)\\'") str)
579 (equal to (match-string 5 str)))
580 (concat (substring str (match-beginning 5) (match-beginning 6))
581 (match-string 4 str)
582 (substring str (match-end 6) (match-end 5))))))
584 (defun diff-tell-file-name (old name)
585 "Tell Emacs where the find the source file of the current hunk.
586 If the OLD prefix arg is passed, tell the file NAME of the old file."
587 (interactive
588 (let* ((old current-prefix-arg)
589 (fs (diff-hunk-file-names current-prefix-arg)))
590 (unless fs (error "No file name to look for"))
591 (list old (read-file-name (format "File for %s: " (car fs))
592 nil (diff-find-file-name old) t))))
593 (let ((fs (diff-hunk-file-names old)))
594 (unless fs (error "No file name to look for"))
595 (push (cons fs name) diff-remembered-files-alist)))
597 (defun diff-hunk-file-names (&optional old)
598 "Give the list of file names textually mentioned for the current hunk."
599 (save-excursion
600 (unless (looking-at diff-file-header-re)
601 (or (ignore-errors (diff-beginning-of-file))
602 (re-search-forward diff-file-header-re nil t)))
603 (let ((limit (save-excursion
604 (condition-case ()
605 (progn (diff-hunk-prev) (point))
606 (error (point-min)))))
607 (header-files
608 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
609 (list (if old (match-string 1) (match-string 3))
610 (if old (match-string 3) (match-string 1)))
611 (forward-line 1) nil)))
612 (delq nil
613 (append
614 (when (and (not old)
615 (save-excursion
616 (re-search-backward "^Index: \\(.+\\)" limit t)))
617 (list (match-string 1)))
618 header-files
619 (when (re-search-backward
620 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
621 nil t)
622 (list (if old (match-string 2) (match-string 4))
623 (if old (match-string 4) (match-string 2)))))))))
625 (defun diff-find-file-name (&optional old prefix)
626 "Return the file corresponding to the current patch.
627 Non-nil OLD means that we want the old file.
628 PREFIX is only used internally: don't use it."
629 (save-excursion
630 (unless (looking-at diff-file-header-re)
631 (or (ignore-errors (diff-beginning-of-file))
632 (re-search-forward diff-file-header-re nil t)))
633 (let ((fs (diff-hunk-file-names old)))
634 (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
636 ;; use any previously used preference
637 (cdr (assoc fs diff-remembered-files-alist))
638 ;; try to be clever and use previous choices as an inspiration
639 (dolist (rf diff-remembered-files-alist)
640 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
641 (if (and newfile (file-exists-p newfile)) (return newfile))))
642 ;; look for each file in turn. If none found, try again but
643 ;; ignoring the first level of directory, ...
644 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
645 (file nil nil))
646 ((or (null files)
647 (setq file (do* ((files files (cdr files))
648 (file (car files) (car files)))
649 ((or (null file) (file-exists-p file))
650 file))))
651 file))
652 ;; <foo>.rej patches implicitly apply to <foo>
653 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
654 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
655 (when (file-exists-p file) file)))
656 ;; If we haven't found the file, maybe it's because we haven't paid
657 ;; attention to the PCL-CVS hint.
658 (and (not prefix)
659 (boundp 'cvs-pcl-cvs-dirchange-re)
660 (save-excursion
661 (re-search-backward cvs-pcl-cvs-dirchange-re nil t))
662 (diff-find-file-name old (match-string 1)))
663 ;; if all else fails, ask the user
664 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
665 nil (first fs) t (first fs))))
666 (set (make-local-variable 'diff-remembered-files-alist)
667 (cons (cons fs file) diff-remembered-files-alist))
668 file)))))
671 (defun diff-ediff-patch ()
672 "Call `ediff-patch-file' on the current buffer."
673 (interactive)
674 (condition-case err
675 (ediff-patch-file nil (current-buffer))
676 (wrong-number-of-arguments (ediff-patch-file))))
678 ;;;;
679 ;;;; Conversion functions
680 ;;;;
682 ;;(defvar diff-inhibit-after-change nil
683 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
685 (defun diff-unified->context (start end)
686 "Convert unified diffs to context diffs.
687 START and END are either taken from the region (if a prefix arg is given) or
688 else cover the whole buffer."
689 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
690 (list (region-beginning) (region-end))
691 (list (point-min) (point-max))))
692 (unless (markerp end) (setq end (copy-marker end t)))
693 (let (;;(diff-inhibit-after-change t)
694 (inhibit-read-only t))
695 (save-excursion
696 (goto-char start)
697 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
698 (< (point) end))
699 (combine-after-change-calls
700 (if (match-beginning 2)
701 ;; we matched a file header
702 (progn
703 ;; use reverse order to make sure the indices are kept valid
704 (replace-match "---" t t nil 3)
705 (replace-match "***" t t nil 2))
706 ;; we matched a hunk header
707 (let ((line1 (match-string 4))
708 (lines1 (match-string 5))
709 (line2 (match-string 6))
710 (lines2 (match-string 7)))
711 (replace-match
712 (concat "***************\n*** " line1 ","
713 (number-to-string (+ (string-to-number line1)
714 (string-to-number lines1)
715 -1)) " ****"))
716 (forward-line 1)
717 (save-restriction
718 (narrow-to-region (point)
719 (progn (diff-end-of-hunk 'unified) (point)))
720 (let ((hunk (buffer-string)))
721 (goto-char (point-min))
722 (if (not (save-excursion (re-search-forward "^-" nil t)))
723 (delete-region (point) (point-max))
724 (goto-char (point-max))
725 (let ((modif nil) last-pt)
726 (while (progn (setq last-pt (point))
727 (= (forward-line -1) 0))
728 (case (char-after)
729 (?\s (insert " ") (setq modif nil) (backward-char 1))
730 (?+ (delete-region (point) last-pt) (setq modif t))
731 (?- (if (not modif)
732 (progn (forward-char 1)
733 (insert " "))
734 (delete-char 1)
735 (insert "! "))
736 (backward-char 2))
737 (?\\ (when (save-excursion (forward-line -1)
738 (= (char-after) ?+))
739 (delete-region (point) last-pt) (setq modif t)))
740 (t (setq modif nil))))))
741 (goto-char (point-max))
742 (save-excursion
743 (insert "--- " line2 ","
744 (number-to-string (+ (string-to-number line2)
745 (string-to-number lines2)
746 -1)) " ----\n" hunk))
747 ;;(goto-char (point-min))
748 (forward-line 1)
749 (if (not (save-excursion (re-search-forward "^+" nil t)))
750 (delete-region (point) (point-max))
751 (let ((modif nil) (delete nil))
752 (while (not (eobp))
753 (case (char-after)
754 (?\s (insert " ") (setq modif nil) (backward-char 1))
755 (?- (setq delete t) (setq modif t))
756 (?+ (if (not modif)
757 (progn (forward-char 1)
758 (insert " "))
759 (delete-char 1)
760 (insert "! "))
761 (backward-char 2))
762 (?\\ (when (save-excursion (forward-line 1)
763 (not (eobp)))
764 (setq delete t) (setq modif t)))
765 (t (setq modif nil)))
766 (let ((last-pt (point)))
767 (forward-line 1)
768 (when delete
769 (delete-region last-pt (point))
770 (setq delete nil)))))))))))))))
772 (defun diff-context->unified (start end &optional to-context)
773 "Convert context diffs to unified diffs.
774 START and END are either taken from the region
775 \(when it is highlighted) or else cover the whole buffer.
776 With a prefix argument, convert unified format to context format."
777 (interactive (if (and transient-mark-mode mark-active)
778 (list (region-beginning) (region-end) current-prefix-arg)
779 (list (point-min) (point-max) current-prefix-arg)))
780 (if to-context
781 (diff-unified->context start end)
782 (unless (markerp end) (setq end (copy-marker end t)))
783 (let ( ;;(diff-inhibit-after-change t)
784 (inhibit-read-only t))
785 (save-excursion
786 (goto-char start)
787 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
788 (< (point) end))
789 (combine-after-change-calls
790 (if (match-beginning 2)
791 ;; we matched a file header
792 (progn
793 ;; use reverse order to make sure the indices are kept valid
794 (replace-match "+++" t t nil 3)
795 (replace-match "---" t t nil 2))
796 ;; we matched a hunk header
797 (let ((line1s (match-string 4))
798 (line1e (match-string 5))
799 (pt1 (match-beginning 0)))
800 (replace-match "")
801 (unless (re-search-forward
802 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
803 (error "Can't find matching `--- n1,n2 ----' line"))
804 (let ((line2s (match-string 1))
805 (line2e (match-string 2))
806 (pt2 (progn
807 (delete-region (progn (beginning-of-line) (point))
808 (progn (forward-line 1) (point)))
809 (point-marker))))
810 (goto-char pt1)
811 (forward-line 1)
812 (while (< (point) pt2)
813 (case (char-after)
814 ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
815 (?\s ;merge with the other half of the chunk
816 (let* ((endline2
817 (save-excursion
818 (goto-char pt2) (forward-line 1) (point)))
819 (c (char-after pt2)))
820 (case c
821 ((?! ?+)
822 (insert "+"
823 (prog1 (buffer-substring (+ pt2 2) endline2)
824 (delete-region pt2 endline2))))
825 (?\s ;FIXME: check consistency
826 (delete-region pt2 endline2)
827 (delete-char 1)
828 (forward-line 1))
829 (?\\ (forward-line 1))
830 (t (delete-char 1) (forward-line 1)))))
831 (t (forward-line 1))))
832 (while (looking-at "[+! ] ")
833 (if (/= (char-after) ?!) (forward-char 1)
834 (delete-char 1) (insert "+"))
835 (delete-char 1) (forward-line 1))
836 (save-excursion
837 (goto-char pt1)
838 (insert "@@ -" line1s ","
839 (number-to-string (- (string-to-number line1e)
840 (string-to-number line1s)
841 -1))
842 " +" line2s ","
843 (number-to-string (- (string-to-number line2e)
844 (string-to-number line2s)
845 -1)) " @@")))))))))))
847 (defun diff-reverse-direction (start end)
848 "Reverse the direction of the diffs.
849 START and END are either taken from the region (if a prefix arg is given) or
850 else cover the whole buffer."
851 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
852 (list (region-beginning) (region-end))
853 (list (point-min) (point-max))))
854 (unless (markerp end) (setq end (copy-marker end t)))
855 (let (;;(diff-inhibit-after-change t)
856 (inhibit-read-only t))
857 (save-excursion
858 (goto-char start)
859 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
860 (< (point) end))
861 (combine-after-change-calls
862 (cond
863 ;; a file header
864 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
865 ;; a context-diff hunk header
866 ((match-beginning 6)
867 (let ((pt-lines1 (match-beginning 6))
868 (lines1 (match-string 6)))
869 (replace-match "" nil nil nil 6)
870 (forward-line 1)
871 (let ((half1s (point)))
872 (while (looking-at "[-! \\][ \t]\\|#")
873 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
874 (forward-line 1))
875 (let ((half1 (delete-and-extract-region half1s (point))))
876 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
877 (insert half1)
878 (error "Can't find matching `--- n1,n2 ----' line"))
879 (let ((str1 (match-string 1)))
880 (replace-match lines1 nil nil nil 1)
881 (forward-line 1)
882 (let ((half2s (point)))
883 (while (looking-at "[!+ \\][ \t]\\|#")
884 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
885 (forward-line 1))
886 (let ((half2 (delete-and-extract-region half2s (point))))
887 (insert (or half1 ""))
888 (goto-char half1s)
889 (insert (or half2 ""))))
890 (goto-char pt-lines1)
891 (insert str1))))))
892 ;; a unified-diff hunk header
893 ((match-beginning 7)
894 (replace-match "@@ -\\8 +\\7 @@" nil)
895 (forward-line 1)
896 (let ((c (char-after)) first last)
897 (while (case (setq c (char-after))
898 (?- (setq first (or first (point)))
899 (delete-char 1) (insert "+") t)
900 (?+ (setq last (or last (point)))
901 (delete-char 1) (insert "-") t)
902 ((?\\ ?#) t)
903 (t (when (and first last (< first last))
904 (insert (delete-and-extract-region first last)))
905 (setq first nil last nil)
906 (equal ?\s c)))
907 (forward-line 1))))))))))
909 (defun diff-fixup-modifs (start end)
910 "Fixup the hunk headers (in case the buffer was modified).
911 START and END are either taken from the region (if a prefix arg is given) or
912 else cover the whole buffer."
913 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
914 (list (region-beginning) (region-end))
915 (list (point-min) (point-max))))
916 (let ((inhibit-read-only t))
917 (save-excursion
918 (goto-char end) (diff-end-of-hunk)
919 (let ((plus 0) (minus 0) (space 0) (bang 0))
920 (while (and (= (forward-line -1) 0) (<= start (point)))
921 (if (not (looking-at
922 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
923 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
924 "\\|--- .+\n\\+\\+\\+ ")))
925 (case (char-after)
926 (?\s (incf space))
927 (?+ (incf plus))
928 (?- (incf minus))
929 (?! (incf bang))
930 ((?\\ ?#) nil)
931 (t (setq space 0 plus 0 minus 0 bang 0)))
932 (cond
933 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
934 (let* ((old1 (match-string 1))
935 (old2 (match-string 2))
936 (new1 (number-to-string (+ space minus)))
937 (new2 (number-to-string (+ space plus))))
938 (unless (string= new2 old2) (replace-match new2 t t nil 2))
939 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
940 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
941 (when (> (+ space bang plus) 0)
942 (let* ((old1 (match-string 1))
943 (old2 (match-string 2))
944 (new (number-to-string
945 (+ space bang plus -1 (string-to-number old1)))))
946 (unless (string= new old2) (replace-match new t t nil 2)))))
947 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
948 (when (> (+ space bang minus) 0)
949 (let* ((old (match-string 1))
950 (new (format
951 (concat "%0" (number-to-string (length old)) "d")
952 (+ space bang minus -1 (string-to-number old)))))
953 (unless (string= new old) (replace-match new t t nil 2))))))
954 (setq space 0 plus 0 minus 0 bang 0)))))))
956 ;;;;
957 ;;;; Hooks
958 ;;;;
960 (defun diff-write-contents-hooks ()
961 "Fixup hunk headers if necessary."
962 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
963 nil)
965 ;; It turns out that making changes in the buffer from within an
966 ;; *-change-function is asking for trouble, whereas making them
967 ;; from a post-command-hook doesn't pose much problems
968 (defvar diff-unhandled-changes nil)
969 (defun diff-after-change-function (beg end len)
970 "Remember to fixup the hunk header.
971 See `after-change-functions' for the meaning of BEG, END and LEN."
972 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
973 ;; incorrect, but it turns out that inhibit-read-only is normally not set
974 ;; inside editing commands, while it tends to be set when the buffer gets
975 ;; updated by an async process or by a conversion function, both of which
976 ;; would rather not be uselessly slowed down by this hook.
977 (when (and (not undo-in-progress) (not inhibit-read-only))
978 (if diff-unhandled-changes
979 (setq diff-unhandled-changes
980 (cons (min beg (car diff-unhandled-changes))
981 (max end (cdr diff-unhandled-changes))))
982 (setq diff-unhandled-changes (cons beg end)))))
984 (defun diff-post-command-hook ()
985 "Fixup hunk headers if necessary."
986 (when (consp diff-unhandled-changes)
987 (ignore-errors
988 (save-excursion
989 (goto-char (car diff-unhandled-changes))
990 ;; Maybe we've cut the end of the hunk before point.
991 (if (and (bolp) (not (bobp))) (backward-char 1))
992 ;; We used to fixup modifs on all the changes, but it turns out
993 ;; that it's safer not to do it on big changes, for example
994 ;; when yanking a big diff, since we might then screw up perfectly
995 ;; correct values. -stef
996 ;; (unless (ignore-errors
997 ;; (diff-beginning-of-hunk)
998 ;; (save-excursion
999 ;; (diff-end-of-hunk)
1000 ;; (> (point) (car diff-unhandled-changes))))
1001 ;; (goto-char (car diff-unhandled-changes))
1002 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
1003 ;; (diff-beginning-of-hunk))
1004 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
1005 (diff-beginning-of-hunk)
1006 (when (save-excursion
1007 (diff-end-of-hunk)
1008 (>= (point) (cdr diff-unhandled-changes)))
1009 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
1010 (setq diff-unhandled-changes nil)))
1012 (defun diff-next-error (arg reset)
1013 ;; Select a window that displays the current buffer so that point
1014 ;; movements are reflected in that window. Otherwise, the user might
1015 ;; never see the hunk corresponding to the source she's jumping to.
1016 (pop-to-buffer (current-buffer))
1017 (if reset (goto-char (point-min)))
1018 (diff-hunk-next arg)
1019 (diff-goto-source))
1021 ;;;###autoload
1022 (define-derived-mode diff-mode fundamental-mode "Diff"
1023 "Major mode for viewing/editing context diffs.
1024 Supports unified and context diffs as well as (to a lesser extent)
1025 normal diffs.
1027 When the buffer is read-only, the ESC prefix is not necessary.
1028 If you edit the buffer manually, diff-mode will try to update the hunk
1029 headers for you on-the-fly.
1031 You can also switch between context diff and unified diff with \\[diff-context->unified],
1032 or vice versa with \\[diff-unified->context] and you can also reverse the direction of
1033 a diff with \\[diff-reverse-direction].
1035 \\{diff-mode-map}"
1037 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
1038 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
1039 (set (make-local-variable 'imenu-generic-expression)
1040 diff-imenu-generic-expression)
1041 ;; These are not perfect. They would be better done separately for
1042 ;; context diffs and unidiffs.
1043 ;; (set (make-local-variable 'paragraph-start)
1044 ;; (concat "@@ " ; unidiff hunk
1045 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1046 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1047 ;; ; start (first or second line)
1048 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1049 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1050 ;; compile support
1051 (set (make-local-variable 'next-error-function) 'diff-next-error)
1053 (setq buffer-read-only diff-default-read-only)
1054 ;; setup change hooks
1055 (if (not diff-update-on-the-fly)
1056 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1057 (make-local-variable 'diff-unhandled-changes)
1058 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1059 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
1060 ;; Neat trick from Dave Love to add more bindings in read-only mode:
1061 (lexical-let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
1062 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1063 ;; Turn off this little trick in case the buffer is put in view-mode.
1064 (add-hook 'view-mode-hook
1065 (lambda ()
1066 (setq minor-mode-overriding-map-alist
1067 (delq ro-bind minor-mode-overriding-map-alist)))
1068 nil t))
1069 ;; add-log support
1070 (set (make-local-variable 'add-log-current-defun-function)
1071 'diff-current-defun)
1072 (set (make-local-variable 'add-log-buffer-file-name-function)
1073 'diff-find-file-name))
1075 ;;;###autoload
1076 (define-minor-mode diff-minor-mode
1077 "Minor mode for viewing/editing context diffs.
1078 \\{diff-minor-mode-map}"
1079 :group 'diff-mode :lighter " Diff"
1080 ;; FIXME: setup font-lock
1081 ;; setup change hooks
1082 (if (not diff-update-on-the-fly)
1083 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1084 (make-local-variable 'diff-unhandled-changes)
1085 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1086 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
1088 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1090 (defun diff-delete-if-empty ()
1091 ;; An empty diff file means there's no more diffs to integrate, so we
1092 ;; can just remove the file altogether. Very handy for .rej files if we
1093 ;; remove hunks as we apply them.
1094 (when (and buffer-file-name
1095 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1096 (delete-file buffer-file-name)))
1098 (defun diff-delete-empty-files ()
1099 "Arrange for empty diff files to be removed."
1100 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1102 (defun diff-make-unified ()
1103 "Turn context diffs into unified diffs if applicable."
1104 (if (save-excursion
1105 (goto-char (point-min))
1106 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
1107 (let ((mod (buffer-modified-p)))
1108 (unwind-protect
1109 (diff-context->unified (point-min) (point-max))
1110 (restore-buffer-modified-p mod)))))
1113 ;;; Misc operations that have proved useful at some point.
1116 (defun diff-next-complex-hunk ()
1117 "Jump to the next \"complex\" hunk.
1118 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1119 Only works for unified diffs."
1120 (interactive)
1121 (while
1122 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1123 nil t)
1124 (equal (match-string 1) (match-string 2)))))
1126 (defun diff-sanity-check-context-hunk-half (lines)
1127 (let ((count lines))
1128 (while
1129 (cond
1130 ((and (memq (char-after) '(?\s ?! ?+ ?-))
1131 (memq (char-after (1+ (point))) '(?\s ?\t)))
1132 (decf count) t)
1133 ((or (zerop count) (= count lines)) nil)
1134 ((memq (char-after) '(?! ?+ ?-))
1135 (if (not (and (eq (char-after (1+ (point))) ?\n)
1136 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1137 (error "End of hunk ambiguously marked")
1138 (forward-char 1) (insert " ") (forward-line -1) t))
1139 ((< lines 0)
1140 (error "End of hunk ambiguously marked"))
1141 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1142 (error "Abort!"))
1143 ((eolp) (insert " ") (forward-line -1) t)
1144 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1145 (forward-line))))
1147 (defun diff-sanity-check-hunk ()
1148 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1149 ;; OK to override a read-only setting.
1150 (inhibit-read-only t))
1151 (save-excursion
1152 (cond
1153 ((not (looking-at diff-hunk-header-re))
1154 (error "Not recognizable hunk header"))
1156 ;; A context diff.
1157 ((eq (char-after) ?*)
1158 (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\),\\([0-9]+\\) \\*\\*\\*\\*"))
1159 (error "Unrecognized context diff first hunk header format")
1160 (forward-line 2)
1161 (diff-sanity-check-context-hunk-half
1162 (1+ (- (string-to-number (match-string 2))
1163 (string-to-number (match-string 1)))))
1164 (if (not (looking-at "--- \\([0-9]+\\),\\([0-9]+\\) ----$"))
1165 (error "Unrecognized context diff second hunk header format")
1166 (forward-line)
1167 (diff-sanity-check-context-hunk-half
1168 (1+ (- (string-to-number (match-string 2))
1169 (string-to-number (match-string 1))))))))
1171 ;; A unified diff.
1172 ((eq (char-after) ?@)
1173 (if (not (looking-at
1174 "@@ -[0-9]+,\\([0-9]+\\) \\+[0-9]+,\\([0-9]+\\) @@"))
1175 (error "Unrecognized unified diff hunk header format")
1176 (let ((before (string-to-number (match-string 1)))
1177 (after (string-to-number (match-string 2))))
1178 (forward-line)
1179 (while
1180 (case (char-after)
1181 (?\s (decf before) (decf after) t)
1182 (?- (decf before) t)
1183 (?+ (decf after) t)
1185 (cond
1186 ((and (zerop before) (zerop after)) nil)
1187 ((or (< before 0) (< after 0))
1188 (error (if (or (zerop before) (zerop after))
1189 "End of hunk ambiguously marked"
1190 "Hunk seriously messed up")))
1191 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1192 (error "Abort!"))
1193 ((eolp) (insert " ") (forward-line -1) t)
1194 (t (insert " ")
1195 (delete-region (- (point) 2) (- (point) 1)) t))))
1196 (forward-line)))))
1198 ;; A plain diff.
1200 ;; TODO.
1201 )))))
1203 (defun diff-hunk-text (hunk destp char-offset)
1204 "Return the literal source text from HUNK as (TEXT . OFFSET).
1205 If DESTP is nil, TEXT is the source, otherwise the destination text.
1206 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1207 char-offset in TEXT."
1208 (with-temp-buffer
1209 (insert hunk)
1210 (goto-char (point-min))
1211 (let ((src-pos nil)
1212 (dst-pos nil)
1213 (divider-pos nil)
1214 (num-pfx-chars 2))
1215 ;; Set the following variables:
1216 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1217 ;; DST-POS buffer pos of the destination part of the hunk or nil
1218 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1219 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1220 (cond ((looking-at "^@@")
1221 ;; unified diff
1222 (setq num-pfx-chars 1)
1223 (forward-line 1)
1224 (setq src-pos (point) dst-pos (point)))
1225 ((looking-at "^\\*\\*")
1226 ;; context diff
1227 (forward-line 2)
1228 (setq src-pos (point))
1229 (re-search-forward "^--- " nil t)
1230 (forward-line 0)
1231 (setq divider-pos (point))
1232 (forward-line 1)
1233 (setq dst-pos (point)))
1234 ((looking-at "^[0-9]+a[0-9,]+$")
1235 ;; normal diff, insert
1236 (forward-line 1)
1237 (setq dst-pos (point)))
1238 ((looking-at "^[0-9,]+d[0-9]+$")
1239 ;; normal diff, delete
1240 (forward-line 1)
1241 (setq src-pos (point)))
1242 ((looking-at "^[0-9,]+c[0-9,]+$")
1243 ;; normal diff, change
1244 (forward-line 1)
1245 (setq src-pos (point))
1246 (re-search-forward "^---$" nil t)
1247 (forward-line 0)
1248 (setq divider-pos (point))
1249 (forward-line 1)
1250 (setq dst-pos (point)))
1252 (error "Unknown diff hunk type")))
1254 (if (if destp (null dst-pos) (null src-pos))
1255 ;; Implied empty text
1256 (if char-offset '("" . 0) "")
1258 ;; For context diffs, either side can be empty, (if there's only
1259 ;; added or only removed text). We should then use the other side.
1260 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1261 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1263 (when char-offset (goto-char (+ (point-min) char-offset)))
1265 ;; Get rid of anything except the desired text.
1266 (save-excursion
1267 ;; Delete unused text region
1268 (let ((keep (if destp dst-pos src-pos)))
1269 (when (and divider-pos (> divider-pos keep))
1270 (delete-region divider-pos (point-max)))
1271 (delete-region (point-min) keep))
1272 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1273 (let ((kill-char (if destp ?- ?+)))
1274 (goto-char (point-min))
1275 (while (not (eobp))
1276 (if (eq (char-after) kill-char)
1277 (delete-region (point) (progn (forward-line 1) (point)))
1278 (delete-char num-pfx-chars)
1279 (forward-line 1)))))
1281 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1282 (if char-offset (cons text (- (point) (point-min))) text))))))
1285 (defun diff-find-text (text)
1286 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1287 If TEXT isn't found, nil is returned."
1288 (let* ((orig (point))
1289 (forw (and (search-forward text nil t)
1290 (cons (match-beginning 0) (match-end 0))))
1291 (back (and (goto-char (+ orig (length text)))
1292 (search-backward text nil t)
1293 (cons (match-beginning 0) (match-end 0)))))
1294 ;; Choose the closest match.
1295 (if (and forw back)
1296 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1297 (or back forw))))
1299 (defun diff-find-approx-text (text)
1300 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1301 Whitespace differences are ignored."
1302 (let* ((orig (point))
1303 (re (concat "^[ \t\n\f]*"
1304 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1305 "[ \t\n\f]*\n"))
1306 (forw (and (re-search-forward re nil t)
1307 (cons (match-beginning 0) (match-end 0))))
1308 (back (and (goto-char (+ orig (length text)))
1309 (re-search-backward re nil t)
1310 (cons (match-beginning 0) (match-end 0)))))
1311 ;; Choose the closest match.
1312 (if (and forw back)
1313 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1314 (or back forw))))
1316 (defsubst diff-xor (a b) (if a (not b) b))
1318 (defun diff-find-source-location (&optional other-file reverse)
1319 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1320 BUF is the buffer corresponding to the source file.
1321 LINE-OFFSET is the offset between the expected and actual positions
1322 of the text of the hunk or nil if the text was not found.
1323 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1324 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1325 SRC is the variant that was found in the buffer.
1326 SWITCHED is non-nil if the patch is already applied."
1327 (save-excursion
1328 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1329 (char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1330 (point))))
1331 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1332 ;; the user may disagree on what constitutes the hunk
1333 ;; (e.g. because an empty line truncates the hunk mid-course),
1334 ;; leading to potentially nasty surprises for the user.
1335 (_ (diff-sanity-check-hunk))
1336 (hunk (buffer-substring (point)
1337 (save-excursion (diff-end-of-hunk) (point))))
1338 (old (diff-hunk-text hunk reverse char-offset))
1339 (new (diff-hunk-text hunk (not reverse) char-offset))
1340 ;; Find the location specification.
1341 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1342 (error "Can't find the hunk header")
1343 (if other (match-string 1)
1344 (if (match-end 3) (match-string 3)
1345 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1346 (error "Can't find the hunk separator"))
1347 (match-string 1)))))
1348 (file (or (diff-find-file-name other) (error "Can't find the file")))
1349 (buf (find-file-noselect file)))
1350 ;; Update the user preference if he so wished.
1351 (when (> (prefix-numeric-value other-file) 8)
1352 (setq diff-jump-to-old-file other))
1353 (with-current-buffer buf
1354 (goto-line (string-to-number line))
1355 (let* ((orig-pos (point))
1356 (switched nil)
1357 ;; FIXME: Check for case where both OLD and NEW are found.
1358 (pos (or (diff-find-text (car old))
1359 (progn (setq switched t) (diff-find-text (car new)))
1360 (progn (setq switched nil)
1361 (condition-case nil
1362 (diff-find-approx-text (car old))
1363 (invalid-regexp nil))) ;Regex too big.
1364 (progn (setq switched t)
1365 (condition-case nil
1366 (diff-find-approx-text (car new))
1367 (invalid-regexp nil))) ;Regex too big.
1368 (progn (setq switched nil) nil))))
1369 (nconc
1370 (list buf)
1371 (if pos
1372 (list (count-lines orig-pos (car pos)) pos)
1373 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1374 (if switched (list new old t) (list old new))))))))
1377 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1378 (let ((msg (if dry-run
1379 (if reversed "already applied" "not yet applied")
1380 (if reversed "undone" "applied"))))
1381 (message (cond ((null line-offset) "Hunk text not found")
1382 ((= line-offset 0) "Hunk %s")
1383 ((= line-offset 1) "Hunk %s at offset %d line")
1384 (t "Hunk %s at offset %d lines"))
1385 msg line-offset)))
1387 (defvar diff-apply-hunk-to-backup-file nil)
1389 (defun diff-apply-hunk (&optional reverse)
1390 "Apply the current hunk to the source file and go to the next.
1391 By default, the new source file is patched, but if the variable
1392 `diff-jump-to-old-file' is non-nil, then the old source file is
1393 patched instead (some commands, such as `diff-goto-source' can change
1394 the value of this variable when given an appropriate prefix argument).
1396 With a prefix argument, REVERSE the hunk."
1397 (interactive "P")
1398 (destructuring-bind (buf line-offset pos old new &optional switched)
1399 ;; If REVERSE go to the new file, otherwise go to the old.
1400 (diff-find-source-location (not reverse) reverse)
1401 (cond
1402 ((null line-offset)
1403 (error "Can't find the text to patch"))
1404 ((with-current-buffer buf
1405 (and buffer-file-name
1406 (backup-file-name-p buffer-file-name)
1407 (not diff-apply-hunk-to-backup-file)
1408 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1409 (yes-or-no-p (format "Really apply this hunk to %s? "
1410 (file-name-nondirectory
1411 buffer-file-name)))))))
1412 (error "%s"
1413 (substitute-command-keys
1414 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1415 (if (not reverse) "\\[universal-argument] ")))))
1416 ((and switched
1417 ;; A reversed patch was detected, perhaps apply it in reverse.
1418 (not (save-window-excursion
1419 (pop-to-buffer buf)
1420 (goto-char (+ (car pos) (cdr old)))
1421 (y-or-n-p
1422 (if reverse
1423 "Hunk hasn't been applied yet; apply it now? "
1424 "Hunk has already been applied; undo it? ")))))
1425 (message "(Nothing done)"))
1427 ;; Apply the hunk
1428 (with-current-buffer buf
1429 (goto-char (car pos))
1430 (delete-region (car pos) (cdr pos))
1431 (insert (car new)))
1432 ;; Display BUF in a window
1433 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1434 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1435 (when diff-advance-after-apply-hunk
1436 (diff-hunk-next))))))
1439 (defun diff-test-hunk (&optional reverse)
1440 "See whether it's possible to apply the current hunk.
1441 With a prefix argument, try to REVERSE the hunk."
1442 (interactive "P")
1443 (destructuring-bind (buf line-offset pos src dst &optional switched)
1444 ;; If REVERSE go to the new file, otherwise go to the old.
1445 (diff-find-source-location (not reverse) reverse)
1446 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1447 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1450 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1452 (defun diff-goto-source (&optional other-file event)
1453 "Jump to the corresponding source line.
1454 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1455 is given) determines whether to jump to the old or the new file.
1456 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1457 then `diff-jump-to-old-file' is also set, for the next invocations."
1458 (interactive (list current-prefix-arg last-input-event))
1459 ;; When pointing at a removal line, we probably want to jump to
1460 ;; the old location, and else to the new (i.e. as if reverting).
1461 ;; This is a convenient detail when using smerge-diff.
1462 (if event (posn-set-point (event-end event)))
1463 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1464 (destructuring-bind (buf line-offset pos src dst &optional switched)
1465 (diff-find-source-location other-file rev)
1466 (pop-to-buffer buf)
1467 (goto-char (+ (car pos) (cdr src)))
1468 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1471 (defun diff-current-defun ()
1472 "Find the name of function at point.
1473 For use in `add-log-current-defun-function'."
1474 (save-excursion
1475 (when (looking-at diff-hunk-header-re)
1476 (forward-line 1)
1477 (re-search-forward "^[^ ]" nil t))
1478 (destructuring-bind (buf line-offset pos src dst &optional switched)
1479 (diff-find-source-location)
1480 (beginning-of-line)
1481 (or (when (memq (char-after) '(?< ?-))
1482 ;; Cursor is pointing at removed text. This could be a removed
1483 ;; function, in which case, going to the source buffer will
1484 ;; not help since the function is now removed. Instead,
1485 ;; try to figure out the function name just from the code-fragment.
1486 (let ((old (if switched dst src)))
1487 (with-temp-buffer
1488 (insert (car old))
1489 (funcall (with-current-buffer buf major-mode))
1490 (goto-char (+ (point-min) (cdr old)))
1491 (add-log-current-defun))))
1492 (with-current-buffer buf
1493 (goto-char (+ (car pos) (cdr src)))
1494 (add-log-current-defun))))))
1496 (defun diff-refine-hunk ()
1497 "Refine the current hunk by ignoring space differences."
1498 (interactive)
1499 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1500 (point))))
1501 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1502 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1503 (error "Can't find line number"))
1504 (string-to-number (match-string 1))))
1505 (hunk (delete-and-extract-region
1506 (point) (save-excursion (diff-end-of-hunk) (point))))
1507 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1508 (file1 (make-temp-file "diff1"))
1509 (file2 (make-temp-file "diff2"))
1510 (coding-system-for-read buffer-file-coding-system)
1511 (inhibit-read-only t)
1512 old new)
1513 (unwind-protect
1514 (save-excursion
1515 (setq old (diff-hunk-text hunk nil char-offset))
1516 (setq new (diff-hunk-text hunk t char-offset))
1517 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1518 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1519 (with-temp-buffer
1520 (let ((status
1521 (call-process diff-command nil t nil
1522 opts file1 file2)))
1523 (case status
1524 (0 nil) ;Nothing to reformat.
1525 (1 (goto-char (point-min))
1526 ;; Remove the file-header.
1527 (when (re-search-forward diff-hunk-header-re nil t)
1528 (delete-region (point-min) (match-beginning 0))))
1529 (t (goto-char (point-max))
1530 (unless (bolp) (insert "\n"))
1531 (insert hunk)))
1532 (setq hunk (buffer-string))
1533 (unless (memq status '(0 1))
1534 (error "Diff returned: %s" status)))))
1535 ;; Whatever happens, put back some equivalent text: either the new
1536 ;; one or the original one in case some error happened.
1537 (insert hunk)
1538 (delete-file file1)
1539 (delete-file file2))))
1541 ;; provide the package
1542 (provide 'diff-mode)
1544 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1545 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1546 ;; (diff-mode-load-hook): dropped.
1547 ;; (auto-mode-alist): also catch *.diffs.
1548 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1549 ;; for *.rej files (that lack any file name indication).
1551 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1552 ;; added support for "\ No newline at end of file".
1554 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1555 ;; - added basic `compile' support.
1556 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1557 ;; - diff-kill-file now tries to kill the leading garbage as well.
1559 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1560 ;; - don't use CL in the autoloaded code
1561 ;; - accept diffs using -T
1563 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1564 ;; interface to ediff-patch
1566 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1567 ;; (ediff=patch-file): add bindings to call ediff-patch.
1568 ;; (diff-find-file-name): taken out of diff-goto-source.
1569 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1570 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1572 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1573 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1575 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1576 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1579 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1580 ;;; diff-mode.el ends here