(Limitations and Known Bugs): State that the number of parens/brackets in
[emacs.git] / lisp / diff-mode.el
blobafd9399d1e56f42394fbc5bd317fa9fbf15c85ee
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, 2008 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 ;; - Improve `diff-add-change-log-entries-other-window',
43 ;; it is very simplistic now.
44 ;;
45 ;; - Add a `delete-after-apply' so C-c C-a automatically deletes hunks.
46 ;; Also allow C-c C-a to delete already-applied hunks.
48 ;; - Try `diff <file> <hunk>' to try and fuzzily discover the source location
49 ;; of a hunk. Show then the changes between <file> and <hunk> and make it
50 ;; possible to apply them to <file>, <hunk-src>, or <hunk-dst>.
51 ;; Or maybe just make it into a ".rej to diff3-markers converter".
52 ;; Maybe just use `wiggle' (by Neil Brown) to do it for us.
54 ;; - in diff-apply-hunk, strip context in replace-match to better
55 ;; preserve markers and spacing.
56 ;; - Handle `diff -b' output in context->unified.
58 ;;; Code:
59 (eval-when-compile (require 'cl))
61 (defvar add-log-buffer-file-name-function)
64 (defgroup diff-mode ()
65 "Major mode for viewing/editing diffs."
66 :version "21.1"
67 :group 'tools
68 :group 'diff)
70 (defcustom diff-default-read-only nil
71 "If non-nil, `diff-mode' buffers default to being read-only."
72 :type 'boolean
73 :group 'diff-mode)
75 (defcustom diff-jump-to-old-file nil
76 "Non-nil means `diff-goto-source' jumps to the old file.
77 Else, it jumps to the new file."
78 :type 'boolean
79 :group 'diff-mode)
81 (defcustom diff-update-on-the-fly t
82 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
83 When editing a diff file, the line numbers in the hunk headers
84 need to be kept consistent with the actual diff. This can
85 either be done on the fly (but this sometimes interacts poorly with the
86 undo mechanism) or whenever the file is written (can be slow
87 when editing big diffs)."
88 :type 'boolean
89 :group 'diff-mode)
91 (defcustom diff-advance-after-apply-hunk t
92 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
93 :type 'boolean
94 :group 'diff-mode)
96 (defcustom diff-auto-refine t
97 "Automatically highlight changes in detail as the user visits hunks."
98 :type 'boolean
99 :group 'diff-mode)
101 (defcustom diff-mode-hook nil
102 "Run after setting up the `diff-mode' major mode."
103 :type 'hook
104 :options '(diff-delete-empty-files diff-make-unified)
105 :group 'diff-mode)
107 (defvar diff-outline-regexp
108 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
110 ;;;;
111 ;;;; keymap, menu, ...
112 ;;;;
114 (easy-mmode-defmap diff-mode-shared-map
115 '(;; From Pavel Machek's patch-mode.
116 ("n" . diff-hunk-next)
117 ("N" . diff-file-next)
118 ("p" . diff-hunk-prev)
119 ("P" . diff-file-prev)
120 ("\t" . diff-hunk-next)
121 ([backtab] . diff-hunk-prev)
122 ("k" . diff-hunk-kill)
123 ("K" . diff-file-kill)
124 ;; From compilation-minor-mode.
125 ("}" . diff-file-next)
126 ("{" . diff-file-prev)
127 ("\C-m" . diff-goto-source)
128 ([mouse-2] . diff-goto-source)
129 ;; From XEmacs' diff-mode.
130 ;; Standard M-w is useful, so don't change M-W.
131 ;;("W" . widen)
132 ;;("." . diff-goto-source) ;display-buffer
133 ;;("f" . diff-goto-source) ;find-file
134 ("o" . diff-goto-source) ;other-window
135 ;;("w" . diff-goto-source) ;other-frame
136 ;;("N" . diff-narrow)
137 ;;("h" . diff-show-header)
138 ;;("j" . diff-show-difference) ;jump to Nth diff
139 ;;("q" . diff-quit)
140 ;; Not useful if you have to metafy them.
141 ;;(" " . scroll-up)
142 ;;("\177" . scroll-down)
143 ;; Standard M-a is useful, so don't change M-A.
144 ;;("A" . diff-ediff-patch)
145 ;; Standard M-r is useful, so don't change M-r or M-R.
146 ;;("r" . diff-restrict-view)
147 ;;("R" . diff-reverse-direction)
148 ("q" . quit-window))
149 "Basic keymap for `diff-mode', bound to various prefix keys.")
151 (easy-mmode-defmap diff-mode-map
152 `(("\e" . ,diff-mode-shared-map)
153 ;; From compilation-minor-mode.
154 ("\C-c\C-c" . diff-goto-source)
155 ;; By analogy with the global C-x 4 a binding.
156 ("\C-x4A" . diff-add-change-log-entries-other-window)
157 ;; Misc operations.
158 ("\C-c\C-a" . diff-apply-hunk)
159 ("\C-c\C-e" . diff-ediff-patch)
160 ("\C-c\C-n" . diff-restrict-view)
161 ("\C-c\C-s" . diff-split-hunk)
162 ("\C-c\C-t" . diff-test-hunk)
163 ("\C-c\C-r" . diff-reverse-direction)
164 ("\C-c\C-u" . diff-context->unified)
165 ;; `d' because it duplicates the context :-( --Stef
166 ("\C-c\C-d" . diff-unified->context)
167 ("\C-c\C-w" . diff-ignore-whitespace-hunk)
168 ("\C-c\C-b" . diff-refine-hunk) ;No reason for `b' :-(
169 ("\C-c\C-f" . next-error-follow-minor-mode))
170 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
172 (easy-menu-define diff-mode-menu diff-mode-map
173 "Menu for `diff-mode'."
174 '("Diff"
175 ["Jump to Source" diff-goto-source t]
176 ["Apply hunk" diff-apply-hunk t]
177 ["Test applying hunk" diff-test-hunk t]
178 ["Apply diff with Ediff" diff-ediff-patch t]
179 ["Create Change Log entries" diff-add-change-log-entries-other-window
180 :help "Create ChangeLog entries for the changes in the diff buffer"]
181 "-----"
182 ["Reverse direction" diff-reverse-direction t]
183 ["Context -> Unified" diff-context->unified t]
184 ["Unified -> Context" diff-unified->context t]
185 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
186 "-----"
187 ["Split hunk" diff-split-hunk (diff-splittable-p)]
188 ["Ignore whitespace changes" diff-ignore-whitespace-hunk t]
189 ["Highlight fine changes" diff-refine-hunk t]
190 ["Kill current hunk" diff-hunk-kill t]
191 ["Kill current file's hunks" diff-file-kill t]
192 "-----"
193 ["Previous Hunk" diff-hunk-prev t]
194 ["Next Hunk" diff-hunk-next t]
195 ["Previous File" diff-file-prev t]
196 ["Next File" diff-file-next t]
199 (defcustom diff-minor-mode-prefix "\C-c="
200 "Prefix key for `diff-minor-mode' commands."
201 :type '(choice (string "\e") (string "C-c=") string)
202 :group 'diff-mode)
204 (easy-mmode-defmap diff-minor-mode-map
205 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
206 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
209 ;;;;
210 ;;;; font-lock support
211 ;;;;
213 (defface diff-header
214 '((((class color) (min-colors 88) (background light))
215 :background "grey85")
216 (((class color) (min-colors 88) (background dark))
217 :background "grey45")
218 (((class color) (background light))
219 :foreground "blue1" :weight bold)
220 (((class color) (background dark))
221 :foreground "green" :weight bold)
222 (t :weight bold))
223 "`diff-mode' face inherited by hunk and index header faces."
224 :group 'diff-mode)
225 ;; backward-compatibility alias
226 (put 'diff-header-face 'face-alias 'diff-header)
227 (defvar diff-header-face 'diff-header)
229 (defface diff-file-header
230 '((((class color) (min-colors 88) (background light))
231 :background "grey70" :weight bold)
232 (((class color) (min-colors 88) (background dark))
233 :background "grey60" :weight bold)
234 (((class color) (background light))
235 :foreground "green" :weight bold)
236 (((class color) (background dark))
237 :foreground "cyan" :weight bold)
238 (t :weight bold)) ; :height 1.3
239 "`diff-mode' face used to highlight file header lines."
240 :group 'diff-mode)
241 ;; backward-compatibility alias
242 (put 'diff-file-header-face 'face-alias 'diff-file-header)
243 (defvar diff-file-header-face 'diff-file-header)
245 (defface diff-index
246 '((t :inherit diff-file-header))
247 "`diff-mode' face used to highlight index header lines."
248 :group 'diff-mode)
249 ;; backward-compatibility alias
250 (put 'diff-index-face 'face-alias 'diff-index)
251 (defvar diff-index-face 'diff-index)
253 (defface diff-hunk-header
254 '((t :inherit diff-header))
255 "`diff-mode' face used to highlight hunk header lines."
256 :group 'diff-mode)
257 ;; backward-compatibility alias
258 (put 'diff-hunk-header-face 'face-alias 'diff-hunk-header)
259 (defvar diff-hunk-header-face 'diff-hunk-header)
261 (defface diff-removed
262 '((t :inherit diff-changed))
263 "`diff-mode' face used to highlight removed lines."
264 :group 'diff-mode)
265 ;; backward-compatibility alias
266 (put 'diff-removed-face 'face-alias 'diff-removed)
267 (defvar diff-removed-face 'diff-removed)
269 (defface diff-added
270 '((t :inherit diff-changed))
271 "`diff-mode' face used to highlight added lines."
272 :group 'diff-mode)
273 ;; backward-compatibility alias
274 (put 'diff-added-face 'face-alias 'diff-added)
275 (defvar diff-added-face 'diff-added)
277 (defface diff-changed
278 '((((type tty pc) (class color) (background light))
279 :foreground "magenta" :weight bold :slant italic)
280 (((type tty pc) (class color) (background dark))
281 :foreground "yellow" :weight bold :slant italic))
282 "`diff-mode' face used to highlight changed lines."
283 :group 'diff-mode)
284 ;; backward-compatibility alias
285 (put 'diff-changed-face 'face-alias 'diff-changed)
286 (defvar diff-changed-face 'diff-changed)
288 (defface diff-indicator-removed
289 '((t :inherit diff-removed))
290 "`diff-mode' face used to highlight indicator of removed lines (-, <)."
291 :group 'diff-mode
292 :version "22.1")
293 (defvar diff-indicator-removed-face 'diff-indicator-removed)
295 (defface diff-indicator-added
296 '((t :inherit diff-added))
297 "`diff-mode' face used to highlight indicator of added lines (+, >)."
298 :group 'diff-mode
299 :version "22.1")
300 (defvar diff-indicator-added-face 'diff-indicator-added)
302 (defface diff-indicator-changed
303 '((t :inherit diff-changed))
304 "`diff-mode' face used to highlight indicator of changed lines."
305 :group 'diff-mode
306 :version "22.1")
307 (defvar diff-indicator-changed-face 'diff-indicator-changed)
309 (defface diff-function
310 '((t :inherit diff-header))
311 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
312 :group 'diff-mode)
313 ;; backward-compatibility alias
314 (put 'diff-function-face 'face-alias 'diff-function)
315 (defvar diff-function-face 'diff-function)
317 (defface diff-context
318 '((((class color grayscale) (min-colors 88)) :inherit shadow))
319 "`diff-mode' face used to highlight context and other side-information."
320 :group 'diff-mode)
321 ;; backward-compatibility alias
322 (put 'diff-context-face 'face-alias 'diff-context)
323 (defvar diff-context-face 'diff-context)
325 (defface diff-nonexistent
326 '((t :inherit diff-file-header))
327 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
328 :group 'diff-mode)
329 ;; backward-compatibility alias
330 (put 'diff-nonexistent-face 'face-alias 'diff-nonexistent)
331 (defvar diff-nonexistent-face 'diff-nonexistent)
333 (defconst diff-yank-handler '(diff-yank-function))
334 (defun diff-yank-function (text)
335 ;; FIXME: the yank-handler is now called separately on each piece of text
336 ;; with a yank-handler property, so the next-single-property-change call
337 ;; below will always return nil :-( --stef
338 (let ((mixed (next-single-property-change 0 'yank-handler text))
339 (start (point)))
340 ;; First insert the text.
341 (insert text)
342 ;; If the text does not include any diff markers and if we're not
343 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
344 (unless (or mixed (derived-mode-p 'diff-mode))
345 (undo-boundary) ; Just in case the user wanted the prefixes.
346 (let ((re (save-excursion
347 (if (re-search-backward "^[><!][ \t]" start t)
348 (if (eq (char-after) ?!)
349 "^[!+- ][ \t]" "^[<>][ \t]")
350 "^[ <>!+-]"))))
351 (save-excursion
352 (while (re-search-backward re start t)
353 (replace-match "" t t)))))))
355 (defconst diff-hunk-header-re-unified
356 "^@@ -\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? \\+\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\) @@")
358 (defvar diff-font-lock-keywords
359 `((,(concat "\\(" diff-hunk-header-re-unified "\\)\\(.*\\)$")
360 (1 diff-hunk-header-face) (6 diff-function-face))
361 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
362 (1 diff-hunk-header-face) (2 diff-function-face))
363 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
364 ("^--- .+ ----$" . diff-hunk-header-face) ;context
365 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face) ;normal
366 ("^---$" . diff-hunk-header-face) ;normal
367 ;; For file headers, accept files with spaces, but be careful to rule
368 ;; out false-positives when matching hunk headers.
369 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\([^\t\n]+?\\)\\(?:\t.*\\| \\(\\*\\*\\*\\*\\|----\\)\\)?\n"
370 (0 diff-header-face)
371 (2 (if (not (match-end 3)) diff-file-header-face) prepend))
372 ("^\\([-<]\\)\\(.*\n\\)"
373 (1 diff-indicator-removed-face) (2 diff-removed-face))
374 ("^\\([+>]\\)\\(.*\n\\)"
375 (1 diff-indicator-added-face) (2 diff-added-face))
376 ("^\\(!\\)\\(.*\n\\)"
377 (1 diff-indicator-changed-face) (2 diff-changed-face))
378 ("^Index: \\(.+\\).*\n"
379 (0 diff-header-face) (1 diff-index-face prepend))
380 ("^Only in .*\n" . diff-nonexistent-face)
381 ("^\\(#\\)\\(.*\\)"
382 (1 font-lock-comment-delimiter-face)
383 (2 font-lock-comment-face))
384 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
386 (defconst diff-font-lock-defaults
387 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
389 (defvar diff-imenu-generic-expression
390 ;; Prefer second name as first is most likely to be a backup or
391 ;; version-control name. The [\t\n] at the end of the unidiff pattern
392 ;; catches Debian source diff files (which lack the trailing date).
393 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
394 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
396 ;;;;
397 ;;;; Movement
398 ;;;;
400 (defvar diff-valid-unified-empty-line t
401 "If non-nil, empty lines are valid in unified diffs.
402 Some versions of diff replace all-blank context lines in unified format with
403 empty lines. This makes the format less robust, but is tolerated.
404 See http://lists.gnu.org/archive/html/emacs-devel/2007-11/msg01990.html")
406 (defconst diff-hunk-header-re
407 (concat "^\\(?:" diff-hunk-header-re-unified ".*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$"))
408 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
409 (defvar diff-narrowed-to nil)
411 (defun diff-hunk-style (&optional style)
412 (when (looking-at diff-hunk-header-re)
413 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context)))))
414 (goto-char (match-end 0)))
415 style)
417 (defun diff-end-of-hunk (&optional style donttrustheader)
418 (let (end)
419 (when (looking-at diff-hunk-header-re)
420 ;; Especially important for unified (because headers are ambiguous).
421 (setq style (diff-hunk-style style))
422 (goto-char (match-end 0))
423 (when (and (not donttrustheader) (match-end 2))
424 (save-excursion
425 (re-search-forward (if diff-valid-unified-empty-line
426 "^[- \n]" "^[- ]")
427 nil t
428 (string-to-number (match-string 2)))
429 (setq end (line-beginning-position 2)))))
430 ;; We may have a first evaluation of `end' thanks to the hunk header.
431 (unless end
432 (setq end (and (re-search-forward
433 (case style
434 (unified (concat (if diff-valid-unified-empty-line
435 "^[^-+# \\\n]\\|" "^[^-+# \\]\\|")
436 ;; A `unified' header is ambiguous.
437 diff-file-header-re))
438 (context "^[^-+#! \\]")
439 (normal "^[^<>#\\]")
440 (t "^[^-+#!<> \\]"))
441 nil t)
442 (match-beginning 0)))
443 (when diff-valid-unified-empty-line
444 ;; While empty lines may be valid inside hunks, they are also likely
445 ;; to be unrelated to the hunk.
446 (goto-char (or end (point-max)))
447 (while (eq ?\n (char-before (1- (point))))
448 (forward-char -1)
449 (setq end (point)))))
450 ;; The return value is used by easy-mmode-define-navigation.
451 (goto-char (or end (point-max)))))
453 (defun diff-beginning-of-hunk (&optional try-harder)
454 "Move back to beginning of hunk.
455 If TRY-HARDER is non-nil, try to cater to the case where we're not in a hunk
456 but in the file header instead, in which case move forward to the first hunk."
457 (beginning-of-line)
458 (unless (looking-at diff-hunk-header-re)
459 (forward-line 1)
460 (condition-case ()
461 (re-search-backward diff-hunk-header-re)
462 (error
463 (if (not try-harder)
464 (error "Can't find the beginning of the hunk")
465 (diff-beginning-of-file-and-junk)
466 (diff-hunk-next))))))
468 (defun diff-unified-hunk-p ()
469 (save-excursion
470 (ignore-errors
471 (diff-beginning-of-hunk)
472 (looking-at "^@@"))))
474 (defun diff-beginning-of-file ()
475 (beginning-of-line)
476 (unless (looking-at diff-file-header-re)
477 (let ((start (point))
478 res)
479 ;; diff-file-header-re may need to match up to 4 lines, so in case
480 ;; we're inside the header, we need to move up to 3 lines forward.
481 (forward-line 3)
482 (if (and (setq res (re-search-backward diff-file-header-re nil t))
483 ;; Maybe the 3 lines forward were too much and we matched
484 ;; a file header after our starting point :-(
485 (or (<= (point) start)
486 (setq res (re-search-backward diff-file-header-re nil t))))
488 (goto-char start)
489 (error "Can't find the beginning of the file")))))
492 (defun diff-end-of-file ()
493 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
494 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
495 nil 'move)
496 (if (match-beginning 1)
497 (goto-char (match-beginning 1))
498 (beginning-of-line)))
500 ;; Define diff-{hunk,file}-{prev,next}
501 (easy-mmode-define-navigation
502 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view
503 (if diff-auto-refine
504 (condition-case-no-debug nil (diff-refine-hunk) (error nil))))
506 (easy-mmode-define-navigation
507 diff-file diff-file-header-re "file" diff-end-of-hunk)
509 (defun diff-restrict-view (&optional arg)
510 "Restrict the view to the current hunk.
511 If the prefix ARG is given, restrict the view to the current file instead."
512 (interactive "P")
513 (save-excursion
514 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk 'try-harder))
515 (narrow-to-region (point)
516 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
517 (point)))
518 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
521 (defun diff-hunk-kill ()
522 "Kill current hunk."
523 (interactive)
524 (diff-beginning-of-hunk)
525 (let* ((start (point))
526 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
527 (match-beginning 0)))
528 (firsthunk (ignore-errors
529 (goto-char start)
530 (diff-beginning-of-file) (diff-hunk-next) (point)))
531 (nextfile (ignore-errors (diff-file-next) (point)))
532 (inhibit-read-only t))
533 (goto-char start)
534 (if (and firsthunk (= firsthunk start)
535 (or (null nexthunk)
536 (and nextfile (> nexthunk nextfile))))
537 ;; It's the only hunk for this file, so kill the file.
538 (diff-file-kill)
539 (diff-end-of-hunk)
540 (kill-region start (point)))))
542 (defconst diff-file-junk-re "diff \\|index ") ; "index " is output by git-diff.
544 (defun diff-beginning-of-file-and-junk ()
545 "Go to the beginning of file-related diff-info.
546 This is like `diff-beginning-of-file' except it tries to skip back over leading
547 data such as \"Index: ...\" and such."
548 (let* ((orig (point))
549 ;; Skip forward over what might be "leading junk" so as to get
550 ;; closer to the actual diff.
551 (_ (progn (beginning-of-line)
552 (while (looking-at diff-file-junk-re)
553 (forward-line 1))))
554 (start (point))
555 (prevfile (condition-case err
556 (save-excursion (diff-beginning-of-file) (point))
557 (error err)))
558 (err (if (consp prevfile) prevfile))
559 (nextfile (ignore-errors
560 (save-excursion
561 (goto-char start) (diff-file-next) (point))))
562 ;; prevhunk is one of the limits.
563 (prevhunk (save-excursion
564 (ignore-errors
565 (if (numberp prevfile) (goto-char prevfile))
566 (diff-hunk-prev) (point))))
567 (previndex (save-excursion
568 (forward-line 1) ;In case we're looking at "Index:".
569 (re-search-backward "^Index: " prevhunk t))))
570 ;; If we're in the junk, we should use nextfile instead of prevfile.
571 (if (and (numberp nextfile)
572 (or (not (numberp prevfile))
573 (and previndex (> previndex prevfile))))
574 (setq prevfile nextfile))
575 (if (and previndex (numberp prevfile) (< previndex prevfile))
576 (setq prevfile previndex))
577 (if (and (numberp prevfile) (<= prevfile start))
578 (progn
579 (goto-char prevfile)
580 ;; Now skip backward over the leading junk we may have before the
581 ;; diff itself.
582 (while (save-excursion
583 (and (zerop (forward-line -1))
584 (looking-at diff-file-junk-re)))
585 (forward-line -1)))
586 ;; File starts *after* the starting point: we really weren't in
587 ;; a file diff but elsewhere.
588 (goto-char orig)
589 (signal (car err) (cdr err)))))
591 (defun diff-file-kill ()
592 "Kill current file's hunks."
593 (interactive)
594 (let ((orig (point))
595 (start (progn (diff-beginning-of-file-and-junk) (point)))
596 (inhibit-read-only t))
597 (diff-end-of-file)
598 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
599 (if (> orig (point)) (error "Not inside a file diff"))
600 (kill-region start (point))))
602 (defun diff-kill-junk ()
603 "Kill spurious empty diffs."
604 (interactive)
605 (save-excursion
606 (let ((inhibit-read-only t))
607 (goto-char (point-min))
608 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
609 "\\([^-+!* <>].*\n\\)*?"
610 "\\(\\(Index:\\) \\|"
611 diff-file-header-re "\\)")
612 nil t)
613 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
614 (match-beginning 3))
615 (beginning-of-line)))))
617 (defun diff-count-matches (re start end)
618 (save-excursion
619 (let ((n 0))
620 (goto-char start)
621 (while (re-search-forward re end t) (incf n))
622 n)))
624 (defun diff-splittable-p ()
625 (save-excursion
626 (beginning-of-line)
627 (and (looking-at "^[-+ ]")
628 (progn (forward-line -1) (looking-at "^[-+ ]"))
629 (diff-unified-hunk-p))))
631 (defun diff-split-hunk ()
632 "Split the current (unified diff) hunk at point into two hunks."
633 (interactive)
634 (beginning-of-line)
635 (let ((pos (point))
636 (start (progn (diff-beginning-of-hunk) (point))))
637 (unless (looking-at diff-hunk-header-re-unified)
638 (error "diff-split-hunk only works on unified context diffs"))
639 (forward-line 1)
640 (let* ((start1 (string-to-number (match-string 1)))
641 (start2 (string-to-number (match-string 3)))
642 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
643 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
644 (inhibit-read-only t))
645 (goto-char pos)
646 ;; Hopefully the after-change-function will not screw us over.
647 (insert "@@ -" (number-to-string newstart1) ",1 +"
648 (number-to-string newstart2) ",1 @@\n")
649 ;; Fix the original hunk-header.
650 (diff-fixup-modifs start pos))))
653 ;;;;
654 ;;;; jump to other buffers
655 ;;;;
657 (defvar diff-remembered-files-alist nil)
659 (defun diff-filename-drop-dir (file)
660 (when (string-match "/" file) (substring file (match-end 0))))
662 (defun diff-merge-strings (ancestor from to)
663 "Merge the diff between ANCESTOR and FROM into TO.
664 Returns the merged string if successful or nil otherwise.
665 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
666 If ANCESTOR = FROM, returns TO.
667 If ANCESTOR = TO, returns FROM.
668 The heuristic is simplistic and only really works for cases
669 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
670 ;; Ideally, we want:
671 ;; AMB ANB CMD -> CND
672 ;; but that's ambiguous if `foo' or `bar' is empty:
673 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
674 (let ((str (concat ancestor "\n" from "\n" to)))
675 (when (and (string-match (concat
676 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
677 "\\1\\(.*\\)\\3\n"
678 "\\(.*\\(\\2\\).*\\)\\'") str)
679 (equal to (match-string 5 str)))
680 (concat (substring str (match-beginning 5) (match-beginning 6))
681 (match-string 4 str)
682 (substring str (match-end 6) (match-end 5))))))
684 (defun diff-tell-file-name (old name)
685 "Tell Emacs where the find the source file of the current hunk.
686 If the OLD prefix arg is passed, tell the file NAME of the old file."
687 (interactive
688 (let* ((old current-prefix-arg)
689 (fs (diff-hunk-file-names current-prefix-arg)))
690 (unless fs (error "No file name to look for"))
691 (list old (read-file-name (format "File for %s: " (car fs))
692 nil (diff-find-file-name old) t))))
693 (let ((fs (diff-hunk-file-names old)))
694 (unless fs (error "No file name to look for"))
695 (push (cons fs name) diff-remembered-files-alist)))
697 (defun diff-hunk-file-names (&optional old)
698 "Give the list of file names textually mentioned for the current hunk."
699 (save-excursion
700 (unless (looking-at diff-file-header-re)
701 (or (ignore-errors (diff-beginning-of-file))
702 (re-search-forward diff-file-header-re nil t)))
703 (let ((limit (save-excursion
704 (condition-case ()
705 (progn (diff-hunk-prev) (point))
706 (error (point-min)))))
707 (header-files
708 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
709 (list (if old (match-string 1) (match-string 3))
710 (if old (match-string 3) (match-string 1)))
711 (forward-line 1) nil)))
712 (delq nil
713 (append
714 (when (and (not old)
715 (save-excursion
716 (re-search-backward "^Index: \\(.+\\)" limit t)))
717 (list (match-string 1)))
718 header-files
719 (when (re-search-backward
720 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
721 nil t)
722 (list (if old (match-string 2) (match-string 4))
723 (if old (match-string 4) (match-string 2)))))))))
725 (defun diff-find-file-name (&optional old batch prefix)
726 "Return the file corresponding to the current patch.
727 Non-nil OLD means that we want the old file.
728 Non-nil BATCH means to prefer returning an incorrect answer than to prompt
729 the user.
730 PREFIX is only used internally: don't use it."
731 (save-excursion
732 (unless (looking-at diff-file-header-re)
733 (or (ignore-errors (diff-beginning-of-file))
734 (re-search-forward diff-file-header-re nil t)))
735 (let ((fs (diff-hunk-file-names old)))
736 (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
738 ;; use any previously used preference
739 (cdr (assoc fs diff-remembered-files-alist))
740 ;; try to be clever and use previous choices as an inspiration
741 (dolist (rf diff-remembered-files-alist)
742 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
743 (if (and newfile (file-exists-p newfile)) (return newfile))))
744 ;; look for each file in turn. If none found, try again but
745 ;; ignoring the first level of directory, ...
746 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
747 (file nil nil))
748 ((or (null files)
749 (setq file (do* ((files files (cdr files))
750 (file (car files) (car files)))
751 ;; Use file-regular-p to avoid
752 ;; /dev/null, directories, etc.
753 ((or (null file) (file-regular-p file))
754 file))))
755 file))
756 ;; <foo>.rej patches implicitly apply to <foo>
757 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
758 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
759 (when (file-exists-p file) file)))
760 ;; If we haven't found the file, maybe it's because we haven't paid
761 ;; attention to the PCL-CVS hint.
762 (and (not prefix)
763 (boundp 'cvs-pcl-cvs-dirchange-re)
764 (save-excursion
765 (re-search-backward cvs-pcl-cvs-dirchange-re nil t))
766 (diff-find-file-name old batch (match-string 1)))
767 ;; Invent something, if necessary.
768 (when batch
769 (or (car fs) default-directory))
770 ;; if all else fails, ask the user
771 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
772 nil (first fs) t (first fs))))
773 (set (make-local-variable 'diff-remembered-files-alist)
774 (cons (cons fs file) diff-remembered-files-alist))
775 file)))))
778 (defun diff-ediff-patch ()
779 "Call `ediff-patch-file' on the current buffer."
780 (interactive)
781 (condition-case err
782 (ediff-patch-file nil (current-buffer))
783 (wrong-number-of-arguments (ediff-patch-file))))
785 ;;;;
786 ;;;; Conversion functions
787 ;;;;
789 ;;(defvar diff-inhibit-after-change nil
790 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
792 (defun diff-unified->context (start end)
793 "Convert unified diffs to context diffs.
794 START and END are either taken from the region (if a prefix arg is given) or
795 else cover the whole buffer."
796 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
797 (list (region-beginning) (region-end))
798 (list (point-min) (point-max))))
799 (unless (markerp end) (setq end (copy-marker end t)))
800 (let (;;(diff-inhibit-after-change t)
801 (inhibit-read-only t))
802 (save-excursion
803 (goto-char start)
804 (while (and (re-search-forward
805 (concat "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|"
806 diff-hunk-header-re-unified ".*\\)$")
807 nil t)
808 (< (point) end))
809 (combine-after-change-calls
810 (if (match-beginning 2)
811 ;; we matched a file header
812 (progn
813 ;; use reverse order to make sure the indices are kept valid
814 (replace-match "---" t t nil 3)
815 (replace-match "***" t t nil 2))
816 ;; we matched a hunk header
817 (let ((line1 (match-string 4))
818 (lines1 (if (match-end 5)
819 (string-to-number (match-string 5)) 1))
820 (line2 (match-string 6))
821 (lines2 (if (match-end 7)
822 (string-to-number (match-string 7)) 1))
823 ;; Variables to use the special undo function.
824 (old-undo buffer-undo-list)
825 (old-end (marker-position end))
826 (start (match-beginning 0))
827 (reversible t))
828 (replace-match
829 (concat "***************\n*** " line1 ","
830 (number-to-string (+ (string-to-number line1)
831 lines1 -1)) " ****"))
832 (save-restriction
833 (narrow-to-region (line-beginning-position 2)
834 ;; Call diff-end-of-hunk from just before
835 ;; the hunk header so it can use the hunk
836 ;; header info.
837 (progn (diff-end-of-hunk 'unified) (point)))
838 (let ((hunk (buffer-string)))
839 (goto-char (point-min))
840 (if (not (save-excursion (re-search-forward "^-" nil t)))
841 (delete-region (point) (point-max))
842 (goto-char (point-max))
843 (let ((modif nil) last-pt)
844 (while (progn (setq last-pt (point))
845 (= (forward-line -1) 0))
846 (case (char-after)
847 (?\s (insert " ") (setq modif nil) (backward-char 1))
848 (?+ (delete-region (point) last-pt) (setq modif t))
849 (?- (if (not modif)
850 (progn (forward-char 1)
851 (insert " "))
852 (delete-char 1)
853 (insert "! "))
854 (backward-char 2))
855 (?\\ (when (save-excursion (forward-line -1)
856 (= (char-after) ?+))
857 (delete-region (point) last-pt) (setq modif t)))
858 ;; diff-valid-unified-empty-line.
859 (?\n (insert " ") (setq modif nil) (backward-char 2))
860 (t (setq modif nil))))))
861 (goto-char (point-max))
862 (save-excursion
863 (insert "--- " line2 ","
864 (number-to-string (+ (string-to-number line2)
865 lines2 -1))
866 " ----\n" hunk))
867 ;;(goto-char (point-min))
868 (forward-line 1)
869 (if (not (save-excursion (re-search-forward "^+" nil t)))
870 (delete-region (point) (point-max))
871 (let ((modif nil) (delete nil))
872 (if (save-excursion (re-search-forward "^\\+.*\n-" nil t))
873 ;; Normally, lines in a substitution come with
874 ;; first the removals and then the additions, and
875 ;; the context->unified function follows this
876 ;; convention, of course. Yet, other alternatives
877 ;; are valid as well, but they preclude the use of
878 ;; context->unified as an undo command.
879 (setq reversible nil))
880 (while (not (eobp))
881 (case (char-after)
882 (?\s (insert " ") (setq modif nil) (backward-char 1))
883 (?- (setq delete t) (setq modif t))
884 (?+ (if (not modif)
885 (progn (forward-char 1)
886 (insert " "))
887 (delete-char 1)
888 (insert "! "))
889 (backward-char 2))
890 (?\\ (when (save-excursion (forward-line 1)
891 (not (eobp)))
892 (setq delete t) (setq modif t)))
893 ;; diff-valid-unified-empty-line.
894 (?\n (insert " ") (setq modif nil) (backward-char 2)
895 (setq reversible nil))
896 (t (setq modif nil)))
897 (let ((last-pt (point)))
898 (forward-line 1)
899 (when delete
900 (delete-region last-pt (point))
901 (setq delete nil)))))))
902 (unless (or (not reversible) (eq buffer-undo-list t))
903 ;; Drop the many undo entries and replace them with
904 ;; a single entry that uses diff-context->unified to do
905 ;; the work.
906 (setq buffer-undo-list
907 (cons (list 'apply (- old-end end) start (point-max)
908 'diff-context->unified start (point-max))
909 old-undo)))))))))))
911 (defun diff-context->unified (start end &optional to-context)
912 "Convert context diffs to unified diffs.
913 START and END are either taken from the region
914 \(when it is highlighted) or else cover the whole buffer.
915 With a prefix argument, convert unified format to context format."
916 (interactive (if (and transient-mark-mode mark-active)
917 (list (region-beginning) (region-end) current-prefix-arg)
918 (list (point-min) (point-max) current-prefix-arg)))
919 (if to-context
920 (diff-unified->context start end)
921 (unless (markerp end) (setq end (copy-marker end t)))
922 (let ( ;;(diff-inhibit-after-change t)
923 (inhibit-read-only t))
924 (save-excursion
925 (goto-char start)
926 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
927 (< (point) end))
928 (combine-after-change-calls
929 (if (match-beginning 2)
930 ;; we matched a file header
931 (progn
932 ;; use reverse order to make sure the indices are kept valid
933 (replace-match "+++" t t nil 3)
934 (replace-match "---" t t nil 2))
935 ;; we matched a hunk header
936 (let ((line1s (match-string 4))
937 (line1e (match-string 5))
938 (pt1 (match-beginning 0))
939 ;; Variables to use the special undo function.
940 (old-undo buffer-undo-list)
941 (old-end (marker-position end))
942 (reversible t))
943 (replace-match "")
944 (unless (re-search-forward
945 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
946 (error "Can't find matching `--- n1,n2 ----' line"))
947 (let ((line2s (match-string 1))
948 (line2e (match-string 2))
949 (pt2 (progn
950 (delete-region (progn (beginning-of-line) (point))
951 (progn (forward-line 1) (point)))
952 (point-marker))))
953 (goto-char pt1)
954 (forward-line 1)
955 (while (< (point) pt2)
956 (case (char-after)
957 (?! (delete-char 2) (insert "-") (forward-line 1))
958 (?- (forward-char 1) (delete-char 1) (forward-line 1))
959 (?\s ;merge with the other half of the chunk
960 (let* ((endline2
961 (save-excursion
962 (goto-char pt2) (forward-line 1) (point))))
963 (case (char-after pt2)
964 ((?! ?+)
965 (insert "+"
966 (prog1 (buffer-substring (+ pt2 2) endline2)
967 (delete-region pt2 endline2))))
968 (?\s
969 (unless (= (- endline2 pt2)
970 (- (line-beginning-position 2) (point)))
971 ;; If the two lines we're merging don't have the
972 ;; same length (can happen with "diff -b"), then
973 ;; diff-unified->context will not properly undo
974 ;; this operation.
975 (setq reversible nil))
976 (delete-region pt2 endline2)
977 (delete-char 1)
978 (forward-line 1))
979 (?\\ (forward-line 1))
980 (t (setq reversible nil)
981 (delete-char 1) (forward-line 1)))))
982 (t (setq reversible nil) (forward-line 1))))
983 (while (looking-at "[+! ] ")
984 (if (/= (char-after) ?!) (forward-char 1)
985 (delete-char 1) (insert "+"))
986 (delete-char 1) (forward-line 1))
987 (save-excursion
988 (goto-char pt1)
989 (insert "@@ -" line1s ","
990 (number-to-string (- (string-to-number line1e)
991 (string-to-number line1s)
992 -1))
993 " +" line2s ","
994 (number-to-string (- (string-to-number line2e)
995 (string-to-number line2s)
996 -1)) " @@"))
997 (set-marker pt2 nil)
998 ;; The whole procedure succeeded, let's replace the myriad
999 ;; of undo elements with just a single special one.
1000 (unless (or (not reversible) (eq buffer-undo-list t))
1001 (setq buffer-undo-list
1002 (cons (list 'apply (- old-end end) pt1 (point)
1003 'diff-unified->context pt1 (point))
1004 old-undo)))
1005 )))))))))
1007 (defun diff-reverse-direction (start end)
1008 "Reverse the direction of the diffs.
1009 START and END are either taken from the region (if a prefix arg is given) or
1010 else cover the whole buffer."
1011 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
1012 (list (region-beginning) (region-end))
1013 (list (point-min) (point-max))))
1014 (unless (markerp end) (setq end (copy-marker end t)))
1015 (let (;;(diff-inhibit-after-change t)
1016 (inhibit-read-only t))
1017 (save-excursion
1018 (goto-char start)
1019 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
1020 (< (point) end))
1021 (combine-after-change-calls
1022 (cond
1023 ;; a file header
1024 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
1025 ;; a context-diff hunk header
1026 ((match-beginning 6)
1027 (let ((pt-lines1 (match-beginning 6))
1028 (lines1 (match-string 6)))
1029 (replace-match "" nil nil nil 6)
1030 (forward-line 1)
1031 (let ((half1s (point)))
1032 (while (looking-at "[-! \\][ \t]\\|#")
1033 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
1034 (forward-line 1))
1035 (let ((half1 (delete-and-extract-region half1s (point))))
1036 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
1037 (insert half1)
1038 (error "Can't find matching `--- n1,n2 ----' line"))
1039 (let ((str1 (match-string 1)))
1040 (replace-match lines1 nil nil nil 1)
1041 (forward-line 1)
1042 (let ((half2s (point)))
1043 (while (looking-at "[!+ \\][ \t]\\|#")
1044 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
1045 (forward-line 1))
1046 (let ((half2 (delete-and-extract-region half2s (point))))
1047 (insert (or half1 ""))
1048 (goto-char half1s)
1049 (insert (or half2 ""))))
1050 (goto-char pt-lines1)
1051 (insert str1))))))
1052 ;; a unified-diff hunk header
1053 ((match-beginning 7)
1054 (replace-match "@@ -\\8 +\\7 @@" nil)
1055 (forward-line 1)
1056 (let ((c (char-after)) first last)
1057 (while (case (setq c (char-after))
1058 (?- (setq first (or first (point)))
1059 (delete-char 1) (insert "+") t)
1060 (?+ (setq last (or last (point)))
1061 (delete-char 1) (insert "-") t)
1062 ((?\\ ?#) t)
1063 (t (when (and first last (< first last))
1064 (insert (delete-and-extract-region first last)))
1065 (setq first nil last nil)
1066 (memq c (if diff-valid-unified-empty-line
1067 '(?\s ?\n) '(?\s)))))
1068 (forward-line 1))))))))))
1070 (defun diff-fixup-modifs (start end)
1071 "Fixup the hunk headers (in case the buffer was modified).
1072 START and END are either taken from the region (if a prefix arg is given) or
1073 else cover the whole buffer."
1074 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
1075 (list (region-beginning) (region-end))
1076 (list (point-min) (point-max))))
1077 (let ((inhibit-read-only t))
1078 (save-excursion
1079 (goto-char end) (diff-end-of-hunk nil 'donttrustheader)
1080 (let ((plus 0) (minus 0) (space 0) (bang 0))
1081 (while (and (= (forward-line -1) 0) (<= start (point)))
1082 (if (not (looking-at
1083 (concat diff-hunk-header-re-unified
1084 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
1085 "\\|--- .+\n\\+\\+\\+ ")))
1086 (case (char-after)
1087 (?\s (incf space))
1088 (?+ (incf plus))
1089 (?- (incf minus))
1090 (?! (incf bang))
1091 ((?\\ ?#) nil)
1092 (t (setq space 0 plus 0 minus 0 bang 0)))
1093 (cond
1094 ((looking-at diff-hunk-header-re-unified)
1095 (let* ((old1 (match-string 2))
1096 (old2 (match-string 4))
1097 (new1 (number-to-string (+ space minus)))
1098 (new2 (number-to-string (+ space plus))))
1099 (if old2
1100 (unless (string= new2 old2) (replace-match new2 t t nil 4))
1101 (goto-char (match-end 4)) (insert "," new2))
1102 (if old1
1103 (unless (string= new1 old1) (replace-match new1 t t nil 2))
1104 (goto-char (match-end 2)) (insert "," new1))))
1105 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
1106 (when (> (+ space bang plus) 0)
1107 (let* ((old1 (match-string 1))
1108 (old2 (match-string 2))
1109 (new (number-to-string
1110 (+ space bang plus -1 (string-to-number old1)))))
1111 (unless (string= new old2) (replace-match new t t nil 2)))))
1112 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
1113 (when (> (+ space bang minus) 0)
1114 (let* ((old (match-string 1))
1115 (new (format
1116 (concat "%0" (number-to-string (length old)) "d")
1117 (+ space bang minus -1 (string-to-number old)))))
1118 (unless (string= new old) (replace-match new t t nil 2))))))
1119 (setq space 0 plus 0 minus 0 bang 0)))))))
1121 ;;;;
1122 ;;;; Hooks
1123 ;;;;
1125 (defun diff-write-contents-hooks ()
1126 "Fixup hunk headers if necessary."
1127 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
1128 nil)
1130 ;; It turns out that making changes in the buffer from within an
1131 ;; *-change-function is asking for trouble, whereas making them
1132 ;; from a post-command-hook doesn't pose much problems
1133 (defvar diff-unhandled-changes nil)
1134 (defun diff-after-change-function (beg end len)
1135 "Remember to fixup the hunk header.
1136 See `after-change-functions' for the meaning of BEG, END and LEN."
1137 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
1138 ;; incorrect, but it turns out that inhibit-read-only is normally not set
1139 ;; inside editing commands, while it tends to be set when the buffer gets
1140 ;; updated by an async process or by a conversion function, both of which
1141 ;; would rather not be uselessly slowed down by this hook.
1142 (when (and (not undo-in-progress) (not inhibit-read-only))
1143 (if diff-unhandled-changes
1144 (setq diff-unhandled-changes
1145 (cons (min beg (car diff-unhandled-changes))
1146 (max end (cdr diff-unhandled-changes))))
1147 (setq diff-unhandled-changes (cons beg end)))))
1149 (defun diff-post-command-hook ()
1150 "Fixup hunk headers if necessary."
1151 (when (consp diff-unhandled-changes)
1152 (ignore-errors
1153 (save-excursion
1154 (goto-char (car diff-unhandled-changes))
1155 ;; Maybe we've cut the end of the hunk before point.
1156 (if (and (bolp) (not (bobp))) (backward-char 1))
1157 ;; We used to fixup modifs on all the changes, but it turns out
1158 ;; that it's safer not to do it on big changes, for example
1159 ;; when yanking a big diff, since we might then screw up perfectly
1160 ;; correct values. -stef
1161 ;; (unless (ignore-errors
1162 ;; (diff-beginning-of-hunk)
1163 ;; (save-excursion
1164 ;; (diff-end-of-hunk)
1165 ;; (> (point) (car diff-unhandled-changes))))
1166 ;; (goto-char (car diff-unhandled-changes))
1167 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
1168 ;; (diff-beginning-of-hunk))
1169 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
1170 (diff-beginning-of-hunk)
1171 (when (save-excursion
1172 (diff-end-of-hunk nil 'donttrustheader)
1173 (>= (point) (cdr diff-unhandled-changes)))
1174 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
1175 (setq diff-unhandled-changes nil)))
1177 (defun diff-next-error (arg reset)
1178 ;; Select a window that displays the current buffer so that point
1179 ;; movements are reflected in that window. Otherwise, the user might
1180 ;; never see the hunk corresponding to the source she's jumping to.
1181 (pop-to-buffer (current-buffer))
1182 (if reset (goto-char (point-min)))
1183 (diff-hunk-next arg)
1184 (diff-goto-source))
1186 ;;;###autoload
1187 (define-derived-mode diff-mode fundamental-mode "Diff"
1188 "Major mode for viewing/editing context diffs.
1189 Supports unified and context diffs as well as (to a lesser extent)
1190 normal diffs.
1192 When the buffer is read-only, the ESC prefix is not necessary.
1193 If you edit the buffer manually, diff-mode will try to update the hunk
1194 headers for you on-the-fly.
1196 You can also switch between context diff and unified diff with \\[diff-context->unified],
1197 or vice versa with \\[diff-unified->context] and you can also reverse the direction of
1198 a diff with \\[diff-reverse-direction].
1200 \\{diff-mode-map}"
1202 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
1203 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
1204 (set (make-local-variable 'imenu-generic-expression)
1205 diff-imenu-generic-expression)
1206 ;; These are not perfect. They would be better done separately for
1207 ;; context diffs and unidiffs.
1208 ;; (set (make-local-variable 'paragraph-start)
1209 ;; (concat "@@ " ; unidiff hunk
1210 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1211 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1212 ;; ; start (first or second line)
1213 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1214 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1215 ;; compile support
1216 (set (make-local-variable 'next-error-function) 'diff-next-error)
1218 (setq buffer-read-only diff-default-read-only)
1219 ;; setup change hooks
1220 (if (not diff-update-on-the-fly)
1221 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1222 (make-local-variable 'diff-unhandled-changes)
1223 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1224 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
1225 ;; Neat trick from Dave Love to add more bindings in read-only mode:
1226 (lexical-let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
1227 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1228 ;; Turn off this little trick in case the buffer is put in view-mode.
1229 (add-hook 'view-mode-hook
1230 (lambda ()
1231 (setq minor-mode-overriding-map-alist
1232 (delq ro-bind minor-mode-overriding-map-alist)))
1233 nil t))
1234 ;; add-log support
1235 (set (make-local-variable 'add-log-current-defun-function)
1236 'diff-current-defun)
1237 (set (make-local-variable 'add-log-buffer-file-name-function)
1238 'diff-find-file-name))
1240 ;;;###autoload
1241 (define-minor-mode diff-minor-mode
1242 "Minor mode for viewing/editing context diffs.
1243 \\{diff-minor-mode-map}"
1244 :group 'diff-mode :lighter " Diff"
1245 ;; FIXME: setup font-lock
1246 ;; setup change hooks
1247 (if (not diff-update-on-the-fly)
1248 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1249 (make-local-variable 'diff-unhandled-changes)
1250 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1251 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
1253 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1255 (defun diff-delete-if-empty ()
1256 ;; An empty diff file means there's no more diffs to integrate, so we
1257 ;; can just remove the file altogether. Very handy for .rej files if we
1258 ;; remove hunks as we apply them.
1259 (when (and buffer-file-name
1260 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1261 (delete-file buffer-file-name)))
1263 (defun diff-delete-empty-files ()
1264 "Arrange for empty diff files to be removed."
1265 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1267 (defun diff-make-unified ()
1268 "Turn context diffs into unified diffs if applicable."
1269 (if (save-excursion
1270 (goto-char (point-min))
1271 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
1272 (let ((mod (buffer-modified-p)))
1273 (unwind-protect
1274 (diff-context->unified (point-min) (point-max))
1275 (restore-buffer-modified-p mod)))))
1278 ;;; Misc operations that have proved useful at some point.
1281 (defun diff-next-complex-hunk ()
1282 "Jump to the next \"complex\" hunk.
1283 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1284 Only works for unified diffs."
1285 (interactive)
1286 (while
1287 (and (re-search-forward diff-hunk-header-re-unified nil t)
1288 (equal (match-string 2) (match-string 4)))))
1290 (defun diff-sanity-check-context-hunk-half (lines)
1291 (let ((count lines))
1292 (while
1293 (cond
1294 ((and (memq (char-after) '(?\s ?! ?+ ?-))
1295 (memq (char-after (1+ (point))) '(?\s ?\t)))
1296 (decf count) t)
1297 ((or (zerop count) (= count lines)) nil)
1298 ((memq (char-after) '(?! ?+ ?-))
1299 (if (not (and (eq (char-after (1+ (point))) ?\n)
1300 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1301 (error "End of hunk ambiguously marked")
1302 (forward-char 1) (insert " ") (forward-line -1) t))
1303 ((< lines 0)
1304 (error "End of hunk ambiguously marked"))
1305 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1306 (error "Abort!"))
1307 ((eolp) (insert " ") (forward-line -1) t)
1308 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1309 (forward-line))))
1311 (defun diff-sanity-check-hunk ()
1312 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1313 ;; OK to override a read-only setting.
1314 (inhibit-read-only t))
1315 (save-excursion
1316 (cond
1317 ((not (looking-at diff-hunk-header-re))
1318 (error "Not recognizable hunk header"))
1320 ;; A context diff.
1321 ((eq (char-after) ?*)
1322 (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? \\*\\*\\*\\*"))
1323 (error "Unrecognized context diff first hunk header format")
1324 (forward-line 2)
1325 (diff-sanity-check-context-hunk-half
1326 (if (match-end 2)
1327 (1+ (- (string-to-number (match-string 2))
1328 (string-to-number (match-string 1))))
1330 (if (not (looking-at "--- \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? ----$"))
1331 (error "Unrecognized context diff second hunk header format")
1332 (forward-line)
1333 (diff-sanity-check-context-hunk-half
1334 (if (match-end 2)
1335 (1+ (- (string-to-number (match-string 2))
1336 (string-to-number (match-string 1))))
1337 1)))))
1339 ;; A unified diff.
1340 ((eq (char-after) ?@)
1341 (if (not (looking-at diff-hunk-header-re-unified))
1342 (error "Unrecognized unified diff hunk header format")
1343 (let ((before (if (match-end 2)
1344 (string-to-number (match-string 2)) 1))
1345 (after (if (match-end 4)
1346 (string-to-number (match-string 4)) 1)))
1347 (forward-line)
1348 (while
1349 (case (char-after)
1350 (?\s (decf before) (decf after) t)
1352 (if (and (looking-at diff-file-header-re)
1353 (zerop before) (zerop after))
1354 ;; No need to query: this is a case where two patches
1355 ;; are concatenated and only counting the lines will
1356 ;; give the right result. Let's just add an empty
1357 ;; line so that our code which doesn't count lines
1358 ;; will not get confused.
1359 (progn (save-excursion (insert "\n")) nil)
1360 (decf before) t))
1361 (?+ (decf after) t)
1363 (cond
1364 ((and diff-valid-unified-empty-line
1365 ;; Not just (eolp) so we don't infloop at eob.
1366 (eq (char-after) ?\n)
1367 (> before 0) (> after 0))
1368 (decf before) (decf after) t)
1369 ((and (zerop before) (zerop after)) nil)
1370 ((or (< before 0) (< after 0))
1371 (error (if (or (zerop before) (zerop after))
1372 "End of hunk ambiguously marked"
1373 "Hunk seriously messed up")))
1374 ((not (y-or-n-p (concat "Try to auto-fix " (if (eolp) "whitespace loss" "word-wrap damage") "? ")))
1375 (error "Abort!"))
1376 ((eolp) (insert " ") (forward-line -1) t)
1377 (t (insert " ")
1378 (delete-region (- (point) 2) (- (point) 1)) t))))
1379 (forward-line)))))
1381 ;; A plain diff.
1383 ;; TODO.
1384 )))))
1386 (defun diff-hunk-text (hunk destp char-offset)
1387 "Return the literal source text from HUNK as (TEXT . OFFSET).
1388 If DESTP is nil, TEXT is the source, otherwise the destination text.
1389 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1390 char-offset in TEXT."
1391 (with-temp-buffer
1392 (insert hunk)
1393 (goto-char (point-min))
1394 (let ((src-pos nil)
1395 (dst-pos nil)
1396 (divider-pos nil)
1397 (num-pfx-chars 2))
1398 ;; Set the following variables:
1399 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1400 ;; DST-POS buffer pos of the destination part of the hunk or nil
1401 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1402 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1403 (cond ((looking-at "^@@")
1404 ;; unified diff
1405 (setq num-pfx-chars 1)
1406 (forward-line 1)
1407 (setq src-pos (point) dst-pos (point)))
1408 ((looking-at "^\\*\\*")
1409 ;; context diff
1410 (forward-line 2)
1411 (setq src-pos (point))
1412 (re-search-forward "^--- " nil t)
1413 (forward-line 0)
1414 (setq divider-pos (point))
1415 (forward-line 1)
1416 (setq dst-pos (point)))
1417 ((looking-at "^[0-9]+a[0-9,]+$")
1418 ;; normal diff, insert
1419 (forward-line 1)
1420 (setq dst-pos (point)))
1421 ((looking-at "^[0-9,]+d[0-9]+$")
1422 ;; normal diff, delete
1423 (forward-line 1)
1424 (setq src-pos (point)))
1425 ((looking-at "^[0-9,]+c[0-9,]+$")
1426 ;; normal diff, change
1427 (forward-line 1)
1428 (setq src-pos (point))
1429 (re-search-forward "^---$" nil t)
1430 (forward-line 0)
1431 (setq divider-pos (point))
1432 (forward-line 1)
1433 (setq dst-pos (point)))
1435 (error "Unknown diff hunk type")))
1437 (if (if destp (null dst-pos) (null src-pos))
1438 ;; Implied empty text
1439 (if char-offset '("" . 0) "")
1441 ;; For context diffs, either side can be empty, (if there's only
1442 ;; added or only removed text). We should then use the other side.
1443 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1444 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1446 (when char-offset (goto-char (+ (point-min) char-offset)))
1448 ;; Get rid of anything except the desired text.
1449 (save-excursion
1450 ;; Delete unused text region
1451 (let ((keep (if destp dst-pos src-pos)))
1452 (when (and divider-pos (> divider-pos keep))
1453 (delete-region divider-pos (point-max)))
1454 (delete-region (point-min) keep))
1455 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1456 (let ((kill-char (if destp ?- ?+)))
1457 (goto-char (point-min))
1458 (while (not (eobp))
1459 (if (eq (char-after) kill-char)
1460 (delete-region (point) (progn (forward-line 1) (point)))
1461 (delete-char num-pfx-chars)
1462 (forward-line 1)))))
1464 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1465 (if char-offset (cons text (- (point) (point-min))) text))))))
1468 (defun diff-find-text (text)
1469 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1470 If TEXT isn't found, nil is returned."
1471 (let* ((orig (point))
1472 (forw (and (search-forward text nil t)
1473 (cons (match-beginning 0) (match-end 0))))
1474 (back (and (goto-char (+ orig (length text)))
1475 (search-backward text nil t)
1476 (cons (match-beginning 0) (match-end 0)))))
1477 ;; Choose the closest match.
1478 (if (and forw back)
1479 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1480 (or back forw))))
1482 (defun diff-find-approx-text (text)
1483 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1484 Whitespace differences are ignored."
1485 (let* ((orig (point))
1486 (re (concat "^[ \t\n\f]*"
1487 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1488 "[ \t\n\f]*\n"))
1489 (forw (and (re-search-forward re nil t)
1490 (cons (match-beginning 0) (match-end 0))))
1491 (back (and (goto-char (+ orig (length text)))
1492 (re-search-backward re nil t)
1493 (cons (match-beginning 0) (match-end 0)))))
1494 ;; Choose the closest match.
1495 (if (and forw back)
1496 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1497 (or back forw))))
1499 (defsubst diff-xor (a b) (if a (if (not b) a) b))
1501 (defun diff-find-source-location (&optional other-file reverse)
1502 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1503 BUF is the buffer corresponding to the source file.
1504 LINE-OFFSET is the offset between the expected and actual positions
1505 of the text of the hunk or nil if the text was not found.
1506 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1507 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1508 SRC is the variant that was found in the buffer.
1509 SWITCHED is non-nil if the patch is already applied."
1510 (save-excursion
1511 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1512 (char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1513 (point))))
1514 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1515 ;; the user may disagree on what constitutes the hunk
1516 ;; (e.g. because an empty line truncates the hunk mid-course),
1517 ;; leading to potentially nasty surprises for the user.
1518 (_ (diff-sanity-check-hunk))
1519 (hunk (buffer-substring (point)
1520 (save-excursion (diff-end-of-hunk) (point))))
1521 (old (diff-hunk-text hunk reverse char-offset))
1522 (new (diff-hunk-text hunk (not reverse) char-offset))
1523 ;; Find the location specification.
1524 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1525 (error "Can't find the hunk header")
1526 (if other (match-string 1)
1527 (if (match-end 3) (match-string 3)
1528 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1529 (error "Can't find the hunk separator"))
1530 (match-string 1)))))
1531 (file (or (diff-find-file-name other) (error "Can't find the file")))
1532 (buf (find-file-noselect file)))
1533 ;; Update the user preference if he so wished.
1534 (when (> (prefix-numeric-value other-file) 8)
1535 (setq diff-jump-to-old-file other))
1536 (with-current-buffer buf
1537 (goto-line (string-to-number line))
1538 (let* ((orig-pos (point))
1539 (switched nil)
1540 ;; FIXME: Check for case where both OLD and NEW are found.
1541 (pos (or (diff-find-text (car old))
1542 (progn (setq switched t) (diff-find-text (car new)))
1543 (progn (setq switched nil)
1544 (condition-case nil
1545 (diff-find-approx-text (car old))
1546 (invalid-regexp nil))) ;Regex too big.
1547 (progn (setq switched t)
1548 (condition-case nil
1549 (diff-find-approx-text (car new))
1550 (invalid-regexp nil))) ;Regex too big.
1551 (progn (setq switched nil) nil))))
1552 (nconc
1553 (list buf)
1554 (if pos
1555 (list (count-lines orig-pos (car pos)) pos)
1556 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1557 (if switched (list new old t) (list old new))))))))
1560 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1561 (let ((msg (if dry-run
1562 (if reversed "already applied" "not yet applied")
1563 (if reversed "undone" "applied"))))
1564 (message (cond ((null line-offset) "Hunk text not found")
1565 ((= line-offset 0) "Hunk %s")
1566 ((= line-offset 1) "Hunk %s at offset %d line")
1567 (t "Hunk %s at offset %d lines"))
1568 msg line-offset)))
1570 (defvar diff-apply-hunk-to-backup-file nil)
1572 (defun diff-apply-hunk (&optional reverse)
1573 "Apply the current hunk to the source file and go to the next.
1574 By default, the new source file is patched, but if the variable
1575 `diff-jump-to-old-file' is non-nil, then the old source file is
1576 patched instead (some commands, such as `diff-goto-source' can change
1577 the value of this variable when given an appropriate prefix argument).
1579 With a prefix argument, REVERSE the hunk."
1580 (interactive "P")
1581 (destructuring-bind (buf line-offset pos old new &optional switched)
1582 ;; Sometimes we'd like to have the following behavior: if REVERSE go
1583 ;; to the new file, otherwise go to the old. But that means that by
1584 ;; default we use the old file, which is the opposite of the default
1585 ;; for diff-goto-source, and is thus confusing. Also when you don't
1586 ;; know about it it's pretty surprising.
1587 ;; TODO: make it possible to ask explicitly for this behavior.
1589 ;; This is duplicated in diff-test-hunk.
1590 (diff-find-source-location nil reverse)
1591 (cond
1592 ((null line-offset)
1593 (error "Can't find the text to patch"))
1594 ((with-current-buffer buf
1595 (and buffer-file-name
1596 (backup-file-name-p buffer-file-name)
1597 (not diff-apply-hunk-to-backup-file)
1598 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1599 (yes-or-no-p (format "Really apply this hunk to %s? "
1600 (file-name-nondirectory
1601 buffer-file-name)))))))
1602 (error "%s"
1603 (substitute-command-keys
1604 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1605 (if (not reverse) "\\[universal-argument] ")))))
1606 ((and switched
1607 ;; A reversed patch was detected, perhaps apply it in reverse.
1608 (not (save-window-excursion
1609 (pop-to-buffer buf)
1610 (goto-char (+ (car pos) (cdr old)))
1611 (y-or-n-p
1612 (if reverse
1613 "Hunk hasn't been applied yet; apply it now? "
1614 "Hunk has already been applied; undo it? ")))))
1615 (message "(Nothing done)"))
1617 ;; Apply the hunk
1618 (with-current-buffer buf
1619 (goto-char (car pos))
1620 (delete-region (car pos) (cdr pos))
1621 (insert (car new)))
1622 ;; Display BUF in a window
1623 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1624 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1625 (when diff-advance-after-apply-hunk
1626 (diff-hunk-next))))))
1629 (defun diff-test-hunk (&optional reverse)
1630 "See whether it's possible to apply the current hunk.
1631 With a prefix argument, try to REVERSE the hunk."
1632 (interactive "P")
1633 (destructuring-bind (buf line-offset pos src dst &optional switched)
1634 (diff-find-source-location nil reverse)
1635 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1636 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1639 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1641 (defun diff-goto-source (&optional other-file event)
1642 "Jump to the corresponding source line.
1643 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1644 is given) determines whether to jump to the old or the new file.
1645 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1646 then `diff-jump-to-old-file' is also set, for the next invocations."
1647 (interactive (list current-prefix-arg last-input-event))
1648 ;; When pointing at a removal line, we probably want to jump to
1649 ;; the old location, and else to the new (i.e. as if reverting).
1650 ;; This is a convenient detail when using smerge-diff.
1651 (if event (posn-set-point (event-end event)))
1652 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1653 (destructuring-bind (buf line-offset pos src dst &optional switched)
1654 (diff-find-source-location other-file rev)
1655 (pop-to-buffer buf)
1656 (goto-char (+ (car pos) (cdr src)))
1657 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1660 (defun diff-current-defun ()
1661 "Find the name of function at point.
1662 For use in `add-log-current-defun-function'."
1663 ;; Kill change-log-default-name so it gets recomputed each time, since
1664 ;; each hunk may belong to another file which may belong to another
1665 ;; directory and hence have a different ChangeLog file.
1666 (kill-local-variable 'change-log-default-name)
1667 (save-excursion
1668 (when (looking-at diff-hunk-header-re)
1669 (forward-line 1)
1670 (re-search-forward "^[^ ]" nil t))
1671 (destructuring-bind (buf line-offset pos src dst &optional switched)
1672 (diff-find-source-location)
1673 (beginning-of-line)
1674 (or (when (memq (char-after) '(?< ?-))
1675 ;; Cursor is pointing at removed text. This could be a removed
1676 ;; function, in which case, going to the source buffer will
1677 ;; not help since the function is now removed. Instead,
1678 ;; try to figure out the function name just from the code-fragment.
1679 (let ((old (if switched dst src)))
1680 (with-temp-buffer
1681 (insert (car old))
1682 (funcall (with-current-buffer buf major-mode))
1683 (goto-char (+ (point-min) (cdr old)))
1684 (add-log-current-defun))))
1685 (with-current-buffer buf
1686 (goto-char (+ (car pos) (cdr src)))
1687 (add-log-current-defun))))))
1689 (defun diff-ignore-whitespace-hunk ()
1690 "Re-diff the current hunk, ignoring whitespace differences."
1691 (interactive)
1692 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1693 (point))))
1694 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1695 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1696 (error "Can't find line number"))
1697 (string-to-number (match-string 1))))
1698 (hunk (delete-and-extract-region
1699 (point) (save-excursion (diff-end-of-hunk) (point))))
1700 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1701 (file1 (make-temp-file "diff1"))
1702 (file2 (make-temp-file "diff2"))
1703 (coding-system-for-read buffer-file-coding-system)
1704 (inhibit-read-only t)
1705 old new)
1706 (unwind-protect
1707 (save-excursion
1708 (setq old (diff-hunk-text hunk nil char-offset))
1709 (setq new (diff-hunk-text hunk t char-offset))
1710 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1711 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1712 (with-temp-buffer
1713 (let ((status
1714 (call-process diff-command nil t nil
1715 opts file1 file2)))
1716 (case status
1717 (0 nil) ;Nothing to reformat.
1718 (1 (goto-char (point-min))
1719 ;; Remove the file-header.
1720 (when (re-search-forward diff-hunk-header-re nil t)
1721 (delete-region (point-min) (match-beginning 0))))
1722 (t (goto-char (point-max))
1723 (unless (bolp) (insert "\n"))
1724 (insert hunk)))
1725 (setq hunk (buffer-string))
1726 (unless (memq status '(0 1))
1727 (error "Diff returned: %s" status)))))
1728 ;; Whatever happens, put back some equivalent text: either the new
1729 ;; one or the original one in case some error happened.
1730 (insert hunk)
1731 (delete-file file1)
1732 (delete-file file2))))
1734 ;;; Fine change highlighting.
1736 (defface diff-refine-change
1737 '((((class color) (min-colors 88) (background light))
1738 :background "grey90")
1739 (((class color) (min-colors 88) (background dark))
1740 :background "grey40")
1741 (((class color) (background light))
1742 :background "yellow")
1743 (((class color) (background dark))
1744 :background "green")
1745 (t :weight bold))
1746 "Face used for char-based changes shown by `diff-refine-hunk'."
1747 :group 'diff-mode)
1749 (defun diff-refine-preproc ()
1750 (while (re-search-forward "^[+>]" nil t)
1751 ;; Remove spurious changes due to the fact that one side of the hunk is
1752 ;; marked with leading + or > and the other with leading - or <.
1753 ;; We used to replace all the prefix chars with " " but this only worked
1754 ;; when we did char-based refinement (or when using
1755 ;; smerge-refine-weight-hack) since otherwise, the `forward' motion done
1756 ;; in chopup do not necessarily do the same as the ones in highlight
1757 ;; since the "_" is not treated the same as " ".
1758 (replace-match (cdr (assq (char-before) '((?+ . "-") (?> . "<"))))))
1761 (defun diff-refine-hunk ()
1762 "Highlight changes of hunk at point at a finer granularity."
1763 (interactive)
1764 (eval-and-compile (require 'smerge-mode))
1765 (save-excursion
1766 (diff-beginning-of-hunk 'try-harder)
1767 (let* ((style (diff-hunk-style)) ;Skips the hunk header as well.
1768 (beg (point))
1769 (props '((diff-mode . fine) (face diff-refine-change)))
1770 (end (progn (diff-end-of-hunk) (point))))
1772 (remove-overlays beg end 'diff-mode 'fine)
1774 (goto-char beg)
1775 (case style
1776 (unified
1777 (while (re-search-forward "^\\(?:-.*\n\\)+\\(\\)\\(?:\\+.*\n\\)+"
1778 end t)
1779 (smerge-refine-subst (match-beginning 0) (match-end 1)
1780 (match-end 1) (match-end 0)
1781 props 'diff-refine-preproc)))
1782 (context
1783 (let* ((middle (save-excursion (re-search-forward "^---")))
1784 (other middle))
1785 (while (re-search-forward "^\\(?:!.*\n\\)+" middle t)
1786 (smerge-refine-subst (match-beginning 0) (match-end 0)
1787 (save-excursion
1788 (goto-char other)
1789 (re-search-forward "^\\(?:!.*\n\\)+" end)
1790 (setq other (match-end 0))
1791 (match-beginning 0))
1792 other
1793 props 'diff-refine-preproc))))
1794 (t ;; Normal diffs.
1795 (let ((beg1 (1+ (point))))
1796 (when (re-search-forward "^---.*\n" end t)
1797 ;; It's a combined add&remove, so there's something to do.
1798 (smerge-refine-subst beg1 (match-beginning 0)
1799 (match-end 0) end
1800 props 'diff-refine-preproc))))))))
1803 (defun diff-add-change-log-entries-other-window ()
1804 "Iterate through the current diff and create ChangeLog entries.
1805 I.e. like `add-change-log-entry-other-window' but applied to all hunks."
1806 (interactive)
1807 ;; XXX: Currently add-change-log-entry-other-window is only called
1808 ;; once per hunk. Some hunks have multiple changes, it would be
1809 ;; good to call it for each change.
1810 (save-excursion
1811 (goto-char (point-min))
1812 (let ((orig-buffer (current-buffer)))
1813 (condition-case nil
1814 ;; Call add-change-log-entry-other-window for each hunk in
1815 ;; the diff buffer.
1816 (while (progn
1817 (diff-hunk-next)
1818 ;; Move to where the changes are,
1819 ;; `add-change-log-entry-other-window' works better in
1820 ;; that case.
1821 (re-search-forward
1822 (concat "\n[!+-<>]"
1823 ;; If the hunk is a context hunk with an empty first
1824 ;; half, recognize the "--- NNN,MMM ----" line
1825 "\\(-- [0-9]+\\(,[0-9]+\\)? ----\n"
1826 ;; and skip to the next non-context line.
1827 "\\( .*\n\\)*[+]\\)?")
1828 nil t))
1829 (save-excursion
1830 (add-change-log-entry nil nil t t)))
1831 ;; When there's no more hunks, diff-hunk-next signals an error.
1832 (error nil)))))
1834 ;; provide the package
1835 (provide 'diff-mode)
1837 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1838 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1839 ;; (diff-mode-load-hook): dropped.
1840 ;; (auto-mode-alist): also catch *.diffs.
1841 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1842 ;; for *.rej files (that lack any file name indication).
1844 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1845 ;; added support for "\ No newline at end of file".
1847 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1848 ;; - added basic `compile' support.
1849 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1850 ;; - diff-kill-file now tries to kill the leading garbage as well.
1852 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1853 ;; - don't use CL in the autoloaded code
1854 ;; - accept diffs using -T
1856 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1857 ;; interface to ediff-patch
1859 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1860 ;; (ediff=patch-file): add bindings to call ediff-patch.
1861 ;; (diff-find-file-name): taken out of diff-goto-source.
1862 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1863 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1865 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1866 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1868 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1869 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1872 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1873 ;;; diff-mode.el ends here