(diff-hunk-style): New fun.
[emacs.git] / lisp / diff-mode.el
blob706a532938dab1bd69ec615ee18999154dd65a50
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-ignore-spaces-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 (diff-splittable-p)]
176 ["Refine hunk" diff-refine-ignore-spaces-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 ;; For file headers, accept files with spaces, but be careful to rule
353 ;; out false-positives when matching hunk headers.
354 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\([^\t\n]+?\\)\\(?:\t.*\\| \\(\\*\\*\\*\\*\\|----\\)\\)?\n"
355 (0 diff-header-face)
356 (2 (if (not (match-end 3)) diff-file-header-face) prepend))
357 ("^\\([-<]\\)\\(.*\n\\)"
358 (1 diff-indicator-removed-face) (2 diff-removed-face))
359 ("^\\([+>]\\)\\(.*\n\\)"
360 (1 diff-indicator-added-face) (2 diff-added-face))
361 ("^\\(!\\)\\(.*\n\\)"
362 (1 diff-indicator-changed-face) (2 diff-changed-face))
363 ("^Index: \\(.+\\).*\n"
364 (0 diff-header-face) (1 diff-index-face prepend))
365 ("^Only in .*\n" . diff-nonexistent-face)
366 ("^\\(#\\)\\(.*\\)"
367 (1 font-lock-comment-delimiter-face)
368 (2 font-lock-comment-face))
369 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
371 (defconst diff-font-lock-defaults
372 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
374 (defvar diff-imenu-generic-expression
375 ;; Prefer second name as first is most likely to be a backup or
376 ;; version-control name. The [\t\n] at the end of the unidiff pattern
377 ;; catches Debian source diff files (which lack the trailing date).
378 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
379 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
381 ;;;;
382 ;;;; Movement
383 ;;;;
385 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
386 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
387 (defvar diff-narrowed-to nil)
389 (defun diff-hunk-style (&optional style)
390 (when (looking-at diff-hunk-header-re)
391 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context)))))
392 (goto-char (match-end 0)))
393 style)
395 (defun diff-end-of-hunk (&optional style)
396 ;; Especially important for unified (because headers are ambiguous).
397 (setq style (diff-hunk-style style))
398 (let ((end (and (re-search-forward (case style
399 ;; A `unified' header is ambiguous.
400 (unified (concat "^[^-+# \\]\\|"
401 diff-file-header-re))
402 (context "^[^-+#! \\]")
403 (normal "^[^<>#\\]")
404 (t "^[^-+#!<> \\]"))
405 nil t)
406 (match-beginning 0))))
407 ;; The return value is used by easy-mmode-define-navigation.
408 (goto-char (or end (point-max)))))
410 (defun diff-beginning-of-hunk (&optional try-harder)
411 "Move back to beginning of hunk.
412 If TRY-HARDER is non-nil, try to cater to the case where we're not in a hunk
413 but in the file header instead, in which case move forward to the first hunk."
414 (beginning-of-line)
415 (unless (looking-at diff-hunk-header-re)
416 (forward-line 1)
417 (condition-case ()
418 (re-search-backward diff-hunk-header-re)
419 (error
420 (if (not try-harder)
421 (error "Can't find the beginning of the hunk")
422 (diff-beginning-of-file-and-junk)
423 (diff-hunk-next))))))
425 (defun diff-unified-hunk-p ()
426 (save-excursion
427 (ignore-errors
428 (diff-beginning-of-hunk)
429 (looking-at "^@@"))))
431 (defun diff-beginning-of-file ()
432 (beginning-of-line)
433 (unless (looking-at diff-file-header-re)
434 (let ((start (point))
435 res)
436 ;; diff-file-header-re may need to match up to 4 lines, so in case
437 ;; we're inside the header, we need to move up to 3 lines forward.
438 (forward-line 3)
439 (if (and (setq res (re-search-backward diff-file-header-re nil t))
440 ;; Maybe the 3 lines forward were too much and we matched
441 ;; a file header after our starting point :-(
442 (or (<= (point) start)
443 (setq res (re-search-backward diff-file-header-re nil t))))
445 (goto-char start)
446 (error "Can't find the beginning of the file")))))
449 (defun diff-end-of-file ()
450 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
451 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
452 nil 'move)
453 (if (match-beginning 1)
454 (goto-char (match-beginning 1))
455 (beginning-of-line)))
457 ;; Define diff-{hunk,file}-{prev,next}
458 (easy-mmode-define-navigation
459 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
460 (easy-mmode-define-navigation
461 diff-file diff-file-header-re "file" diff-end-of-hunk)
463 (defun diff-restrict-view (&optional arg)
464 "Restrict the view to the current hunk.
465 If the prefix ARG is given, restrict the view to the current file instead."
466 (interactive "P")
467 (save-excursion
468 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk 'try-harder))
469 (narrow-to-region (point)
470 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
471 (point)))
472 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
475 (defun diff-hunk-kill ()
476 "Kill current hunk."
477 (interactive)
478 (diff-beginning-of-hunk)
479 (let* ((start (point))
480 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
481 (match-beginning 0)))
482 (firsthunk (ignore-errors
483 (goto-char start)
484 (diff-beginning-of-file) (diff-hunk-next) (point)))
485 (nextfile (ignore-errors (diff-file-next) (point)))
486 (inhibit-read-only t))
487 (goto-char start)
488 (if (and firsthunk (= firsthunk start)
489 (or (null nexthunk)
490 (and nextfile (> nexthunk nextfile))))
491 ;; It's the only hunk for this file, so kill the file.
492 (diff-file-kill)
493 (diff-end-of-hunk)
494 (kill-region start (point)))))
496 (defun diff-beginning-of-file-and-junk ()
497 "Go to the beginning of file-related diff-info.
498 This is like `diff-beginning-of-file' except it tries to skip back over leading
499 data such as \"Index: ...\" and such."
500 (let* ((start (point))
501 (prevfile (condition-case err
502 (save-excursion (diff-beginning-of-file) (point))
503 (error err)))
504 (err (if (consp prevfile) prevfile))
505 (nextfile (ignore-errors
506 (save-excursion
507 (goto-char start) (diff-file-next) (point))))
508 ;; prevhunk is one of the limits.
509 (prevhunk (save-excursion
510 (ignore-errors
511 (if (numberp prevfile) (goto-char prevfile))
512 (diff-hunk-prev) (point))))
513 (previndex (save-excursion
514 (re-search-backward "^Index: " prevhunk t))))
515 ;; If we're in the junk, we should use nextfile instead of prevfile.
516 (if (and (numberp nextfile)
517 (or (not (numberp prevfile))
518 (and previndex (> previndex prevfile))))
519 (setq prevfile nextfile))
520 (if (and previndex (numberp prevfile) (< previndex prevfile))
521 (setq prevfile previndex))
522 (if (and (numberp prevfile) (<= prevfile start))
523 (goto-char prevfile)
524 ;; File starts *after* the starting point: we really weren't in
525 ;; a file diff but elsewhere.
526 (goto-char start)
527 (signal (car err) (cdr err)))))
529 (defun diff-file-kill ()
530 "Kill current file's hunks."
531 (interactive)
532 (diff-beginning-of-file-and-junk)
533 (let* ((start (point))
534 (inhibit-read-only t))
535 (diff-end-of-file)
536 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
537 (kill-region start (point))))
539 (defun diff-kill-junk ()
540 "Kill spurious empty diffs."
541 (interactive)
542 (save-excursion
543 (let ((inhibit-read-only t))
544 (goto-char (point-min))
545 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
546 "\\([^-+!* <>].*\n\\)*?"
547 "\\(\\(Index:\\) \\|"
548 diff-file-header-re "\\)")
549 nil t)
550 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
551 (match-beginning 3))
552 (beginning-of-line)))))
554 (defun diff-count-matches (re start end)
555 (save-excursion
556 (let ((n 0))
557 (goto-char start)
558 (while (re-search-forward re end t) (incf n))
559 n)))
561 (defun diff-splittable-p ()
562 (save-excursion
563 (beginning-of-line)
564 (and (looking-at "^[-+ ]")
565 (progn (forward-line -1) (looking-at "^[-+ ]"))
566 (diff-unified-hunk-p))))
568 (defun diff-split-hunk ()
569 "Split the current (unified diff) hunk at point into two hunks."
570 (interactive)
571 (beginning-of-line)
572 (let ((pos (point))
573 (start (progn (diff-beginning-of-hunk) (point))))
574 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
575 (error "diff-split-hunk only works on unified context diffs"))
576 (forward-line 1)
577 (let* ((start1 (string-to-number (match-string 1)))
578 (start2 (string-to-number (match-string 2)))
579 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
580 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
581 (inhibit-read-only t))
582 (goto-char pos)
583 ;; Hopefully the after-change-function will not screw us over.
584 (insert "@@ -" (number-to-string newstart1) ",1 +"
585 (number-to-string newstart2) ",1 @@\n")
586 ;; Fix the original hunk-header.
587 (diff-fixup-modifs start pos))))
590 ;;;;
591 ;;;; jump to other buffers
592 ;;;;
594 (defvar diff-remembered-files-alist nil)
596 (defun diff-filename-drop-dir (file)
597 (when (string-match "/" file) (substring file (match-end 0))))
599 (defun diff-merge-strings (ancestor from to)
600 "Merge the diff between ANCESTOR and FROM into TO.
601 Returns the merged string if successful or nil otherwise.
602 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
603 If ANCESTOR = FROM, returns TO.
604 If ANCESTOR = TO, returns FROM.
605 The heuristic is simplistic and only really works for cases
606 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
607 ;; Ideally, we want:
608 ;; AMB ANB CMD -> CND
609 ;; but that's ambiguous if `foo' or `bar' is empty:
610 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
611 (let ((str (concat ancestor "\n" from "\n" to)))
612 (when (and (string-match (concat
613 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
614 "\\1\\(.*\\)\\3\n"
615 "\\(.*\\(\\2\\).*\\)\\'") str)
616 (equal to (match-string 5 str)))
617 (concat (substring str (match-beginning 5) (match-beginning 6))
618 (match-string 4 str)
619 (substring str (match-end 6) (match-end 5))))))
621 (defun diff-tell-file-name (old name)
622 "Tell Emacs where the find the source file of the current hunk.
623 If the OLD prefix arg is passed, tell the file NAME of the old file."
624 (interactive
625 (let* ((old current-prefix-arg)
626 (fs (diff-hunk-file-names current-prefix-arg)))
627 (unless fs (error "No file name to look for"))
628 (list old (read-file-name (format "File for %s: " (car fs))
629 nil (diff-find-file-name old) t))))
630 (let ((fs (diff-hunk-file-names old)))
631 (unless fs (error "No file name to look for"))
632 (push (cons fs name) diff-remembered-files-alist)))
634 (defun diff-hunk-file-names (&optional old)
635 "Give the list of file names textually mentioned for the current hunk."
636 (save-excursion
637 (unless (looking-at diff-file-header-re)
638 (or (ignore-errors (diff-beginning-of-file))
639 (re-search-forward diff-file-header-re nil t)))
640 (let ((limit (save-excursion
641 (condition-case ()
642 (progn (diff-hunk-prev) (point))
643 (error (point-min)))))
644 (header-files
645 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
646 (list (if old (match-string 1) (match-string 3))
647 (if old (match-string 3) (match-string 1)))
648 (forward-line 1) nil)))
649 (delq nil
650 (append
651 (when (and (not old)
652 (save-excursion
653 (re-search-backward "^Index: \\(.+\\)" limit t)))
654 (list (match-string 1)))
655 header-files
656 (when (re-search-backward
657 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
658 nil t)
659 (list (if old (match-string 2) (match-string 4))
660 (if old (match-string 4) (match-string 2)))))))))
662 (defun diff-find-file-name (&optional old batch prefix)
663 "Return the file corresponding to the current patch.
664 Non-nil OLD means that we want the old file.
665 Non-nil BATCH means to prefer returning an incorrect answer than to prompt
666 the user.
667 PREFIX is only used internally: don't use it."
668 (save-excursion
669 (unless (looking-at diff-file-header-re)
670 (or (ignore-errors (diff-beginning-of-file))
671 (re-search-forward diff-file-header-re nil t)))
672 (let ((fs (diff-hunk-file-names old)))
673 (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
675 ;; use any previously used preference
676 (cdr (assoc fs diff-remembered-files-alist))
677 ;; try to be clever and use previous choices as an inspiration
678 (dolist (rf diff-remembered-files-alist)
679 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
680 (if (and newfile (file-exists-p newfile)) (return newfile))))
681 ;; look for each file in turn. If none found, try again but
682 ;; ignoring the first level of directory, ...
683 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
684 (file nil nil))
685 ((or (null files)
686 (setq file (do* ((files files (cdr files))
687 (file (car files) (car files)))
688 ;; Use file-regular-p to avoid
689 ;; /dev/null, directories, etc.
690 ((or (null file) (file-regular-p file))
691 file))))
692 file))
693 ;; <foo>.rej patches implicitly apply to <foo>
694 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
695 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
696 (when (file-exists-p file) file)))
697 ;; If we haven't found the file, maybe it's because we haven't paid
698 ;; attention to the PCL-CVS hint.
699 (and (not prefix)
700 (boundp 'cvs-pcl-cvs-dirchange-re)
701 (save-excursion
702 (re-search-backward cvs-pcl-cvs-dirchange-re nil t))
703 (diff-find-file-name old batch (match-string 1)))
704 ;; Invent something, if necessary.
705 (when batch
706 (or (car fs) default-directory))
707 ;; if all else fails, ask the user
708 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
709 nil (first fs) t (first fs))))
710 (set (make-local-variable 'diff-remembered-files-alist)
711 (cons (cons fs file) diff-remembered-files-alist))
712 file)))))
715 (defun diff-ediff-patch ()
716 "Call `ediff-patch-file' on the current buffer."
717 (interactive)
718 (condition-case err
719 (ediff-patch-file nil (current-buffer))
720 (wrong-number-of-arguments (ediff-patch-file))))
722 ;;;;
723 ;;;; Conversion functions
724 ;;;;
726 ;;(defvar diff-inhibit-after-change nil
727 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
729 (defun diff-unified->context (start end)
730 "Convert unified diffs to context diffs.
731 START and END are either taken from the region (if a prefix arg is given) or
732 else cover the whole buffer."
733 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
734 (list (region-beginning) (region-end))
735 (list (point-min) (point-max))))
736 (unless (markerp end) (setq end (copy-marker end t)))
737 (let (;;(diff-inhibit-after-change t)
738 (inhibit-read-only t))
739 (save-excursion
740 (goto-char start)
741 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
742 (< (point) end))
743 (combine-after-change-calls
744 (if (match-beginning 2)
745 ;; we matched a file header
746 (progn
747 ;; use reverse order to make sure the indices are kept valid
748 (replace-match "---" t t nil 3)
749 (replace-match "***" t t nil 2))
750 ;; we matched a hunk header
751 (let ((line1 (match-string 4))
752 (lines1 (match-string 5))
753 (line2 (match-string 6))
754 (lines2 (match-string 7))
755 ;; Variables to use the special undo function.
756 (old-undo buffer-undo-list)
757 (old-end (marker-position end))
758 (start (match-beginning 0))
759 (reversible t))
760 (replace-match
761 (concat "***************\n*** " line1 ","
762 (number-to-string (+ (string-to-number line1)
763 (string-to-number lines1)
764 -1)) " ****"))
765 (forward-line 1)
766 (save-restriction
767 (narrow-to-region (point)
768 (progn (diff-end-of-hunk 'unified) (point)))
769 (let ((hunk (buffer-string)))
770 (goto-char (point-min))
771 (if (not (save-excursion (re-search-forward "^-" nil t)))
772 (delete-region (point) (point-max))
773 (goto-char (point-max))
774 (let ((modif nil) last-pt)
775 (while (progn (setq last-pt (point))
776 (= (forward-line -1) 0))
777 (case (char-after)
778 (?\s (insert " ") (setq modif nil) (backward-char 1))
779 (?+ (delete-region (point) last-pt) (setq modif t))
780 (?- (if (not modif)
781 (progn (forward-char 1)
782 (insert " "))
783 (delete-char 1)
784 (insert "! "))
785 (backward-char 2))
786 (?\\ (when (save-excursion (forward-line -1)
787 (= (char-after) ?+))
788 (delete-region (point) last-pt) (setq modif t)))
789 (t (setq modif nil))))))
790 (goto-char (point-max))
791 (save-excursion
792 (insert "--- " line2 ","
793 (number-to-string (+ (string-to-number line2)
794 (string-to-number lines2)
795 -1)) " ----\n" hunk))
796 ;;(goto-char (point-min))
797 (forward-line 1)
798 (if (not (save-excursion (re-search-forward "^+" nil t)))
799 (delete-region (point) (point-max))
800 (let ((modif nil) (delete nil))
801 (if (save-excursion (re-search-forward "^\\+.*\n-" nil t))
802 ;; Normally, lines in a substitution come with
803 ;; first the removals and then the additions, and
804 ;; the context->unified function follows this
805 ;; convention, of course. Yet, other alternatives
806 ;; are valid as well, but they preclude the use of
807 ;; context->unified as an undo command.
808 (setq reversible nil))
809 (while (not (eobp))
810 (case (char-after)
811 (?\s (insert " ") (setq modif nil) (backward-char 1))
812 (?- (setq delete t) (setq modif t))
813 (?+ (if (not modif)
814 (progn (forward-char 1)
815 (insert " "))
816 (delete-char 1)
817 (insert "! "))
818 (backward-char 2))
819 (?\\ (when (save-excursion (forward-line 1)
820 (not (eobp)))
821 (setq delete t) (setq modif t)))
822 (t (setq modif nil)))
823 (let ((last-pt (point)))
824 (forward-line 1)
825 (when delete
826 (delete-region last-pt (point))
827 (setq delete nil)))))))
828 (unless (or (not reversible) (eq buffer-undo-list t))
829 ;; Drop the many undo entries and replace them with
830 ;; a single entry that uses diff-context->unified to do
831 ;; the work.
832 (setq buffer-undo-list
833 (cons (list 'apply (- old-end end) start (point-max)
834 'diff-context->unified start (point-max))
835 old-undo)))))))))))
837 (defun diff-context->unified (start end &optional to-context)
838 "Convert context diffs to unified diffs.
839 START and END are either taken from the region
840 \(when it is highlighted) or else cover the whole buffer.
841 With a prefix argument, convert unified format to context format."
842 (interactive (if (and transient-mark-mode mark-active)
843 (list (region-beginning) (region-end) current-prefix-arg)
844 (list (point-min) (point-max) current-prefix-arg)))
845 (if to-context
846 (diff-unified->context start end)
847 (unless (markerp end) (setq end (copy-marker end t)))
848 (let ( ;;(diff-inhibit-after-change t)
849 (inhibit-read-only t))
850 (save-excursion
851 (goto-char start)
852 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
853 (< (point) end))
854 (combine-after-change-calls
855 (if (match-beginning 2)
856 ;; we matched a file header
857 (progn
858 ;; use reverse order to make sure the indices are kept valid
859 (replace-match "+++" t t nil 3)
860 (replace-match "---" t t nil 2))
861 ;; we matched a hunk header
862 (let ((line1s (match-string 4))
863 (line1e (match-string 5))
864 (pt1 (match-beginning 0))
865 ;; Variables to use the special undo function.
866 (old-undo buffer-undo-list)
867 (old-end (marker-position end))
868 (reversible t))
869 (replace-match "")
870 (unless (re-search-forward
871 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
872 (error "Can't find matching `--- n1,n2 ----' line"))
873 (let ((line2s (match-string 1))
874 (line2e (match-string 2))
875 (pt2 (progn
876 (delete-region (progn (beginning-of-line) (point))
877 (progn (forward-line 1) (point)))
878 (point-marker))))
879 (goto-char pt1)
880 (forward-line 1)
881 (while (< (point) pt2)
882 (case (char-after)
883 (?! (delete-char 2) (insert "-") (forward-line 1))
884 (?- (forward-char 1) (delete-char 1) (forward-line 1))
885 (?\s ;merge with the other half of the chunk
886 (let* ((endline2
887 (save-excursion
888 (goto-char pt2) (forward-line 1) (point))))
889 (case (char-after pt2)
890 ((?! ?+)
891 (insert "+"
892 (prog1 (buffer-substring (+ pt2 2) endline2)
893 (delete-region pt2 endline2))))
894 (?\s
895 (unless (= (- endline2 pt2)
896 (- (line-beginning-position 2) (point)))
897 ;; If the two lines we're merging don't have the
898 ;; same length (can happen with "diff -b"), then
899 ;; diff-unified->context will not properly undo
900 ;; this operation.
901 (setq reversible nil))
902 (delete-region pt2 endline2)
903 (delete-char 1)
904 (forward-line 1))
905 (?\\ (forward-line 1))
906 (t (setq reversible nil)
907 (delete-char 1) (forward-line 1)))))
908 (t (setq reversible nil) (forward-line 1))))
909 (while (looking-at "[+! ] ")
910 (if (/= (char-after) ?!) (forward-char 1)
911 (delete-char 1) (insert "+"))
912 (delete-char 1) (forward-line 1))
913 (save-excursion
914 (goto-char pt1)
915 (insert "@@ -" line1s ","
916 (number-to-string (- (string-to-number line1e)
917 (string-to-number line1s)
918 -1))
919 " +" line2s ","
920 (number-to-string (- (string-to-number line2e)
921 (string-to-number line2s)
922 -1)) " @@"))
923 (set-marker pt2 nil)
924 ;; The whole procedure succeeded, let's replace the myriad
925 ;; of undo elements with just a single special one.
926 (unless (or (not reversible) (eq buffer-undo-list t))
927 (setq buffer-undo-list
928 (cons (list 'apply (- old-end end) pt1 (point)
929 'diff-unified->context pt1 (point))
930 old-undo)))
931 )))))))))
933 (defun diff-reverse-direction (start end)
934 "Reverse the direction of the diffs.
935 START and END are either taken from the region (if a prefix arg is given) or
936 else cover the whole buffer."
937 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
938 (list (region-beginning) (region-end))
939 (list (point-min) (point-max))))
940 (unless (markerp end) (setq end (copy-marker end t)))
941 (let (;;(diff-inhibit-after-change t)
942 (inhibit-read-only t))
943 (save-excursion
944 (goto-char start)
945 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
946 (< (point) end))
947 (combine-after-change-calls
948 (cond
949 ;; a file header
950 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
951 ;; a context-diff hunk header
952 ((match-beginning 6)
953 (let ((pt-lines1 (match-beginning 6))
954 (lines1 (match-string 6)))
955 (replace-match "" nil nil nil 6)
956 (forward-line 1)
957 (let ((half1s (point)))
958 (while (looking-at "[-! \\][ \t]\\|#")
959 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
960 (forward-line 1))
961 (let ((half1 (delete-and-extract-region half1s (point))))
962 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
963 (insert half1)
964 (error "Can't find matching `--- n1,n2 ----' line"))
965 (let ((str1 (match-string 1)))
966 (replace-match lines1 nil nil nil 1)
967 (forward-line 1)
968 (let ((half2s (point)))
969 (while (looking-at "[!+ \\][ \t]\\|#")
970 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
971 (forward-line 1))
972 (let ((half2 (delete-and-extract-region half2s (point))))
973 (insert (or half1 ""))
974 (goto-char half1s)
975 (insert (or half2 ""))))
976 (goto-char pt-lines1)
977 (insert str1))))))
978 ;; a unified-diff hunk header
979 ((match-beginning 7)
980 (replace-match "@@ -\\8 +\\7 @@" nil)
981 (forward-line 1)
982 (let ((c (char-after)) first last)
983 (while (case (setq c (char-after))
984 (?- (setq first (or first (point)))
985 (delete-char 1) (insert "+") t)
986 (?+ (setq last (or last (point)))
987 (delete-char 1) (insert "-") t)
988 ((?\\ ?#) t)
989 (t (when (and first last (< first last))
990 (insert (delete-and-extract-region first last)))
991 (setq first nil last nil)
992 (equal ?\s c)))
993 (forward-line 1))))))))))
995 (defun diff-fixup-modifs (start end)
996 "Fixup the hunk headers (in case the buffer was modified).
997 START and END are either taken from the region (if a prefix arg is given) or
998 else cover the whole buffer."
999 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
1000 (list (region-beginning) (region-end))
1001 (list (point-min) (point-max))))
1002 (let ((inhibit-read-only t))
1003 (save-excursion
1004 (goto-char end) (diff-end-of-hunk)
1005 (let ((plus 0) (minus 0) (space 0) (bang 0))
1006 (while (and (= (forward-line -1) 0) (<= start (point)))
1007 (if (not (looking-at
1008 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
1009 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
1010 "\\|--- .+\n\\+\\+\\+ ")))
1011 (case (char-after)
1012 (?\s (incf space))
1013 (?+ (incf plus))
1014 (?- (incf minus))
1015 (?! (incf bang))
1016 ((?\\ ?#) nil)
1017 (t (setq space 0 plus 0 minus 0 bang 0)))
1018 (cond
1019 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
1020 (let* ((old1 (match-string 1))
1021 (old2 (match-string 2))
1022 (new1 (number-to-string (+ space minus)))
1023 (new2 (number-to-string (+ space plus))))
1024 (unless (string= new2 old2) (replace-match new2 t t nil 2))
1025 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
1026 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
1027 (when (> (+ space bang plus) 0)
1028 (let* ((old1 (match-string 1))
1029 (old2 (match-string 2))
1030 (new (number-to-string
1031 (+ space bang plus -1 (string-to-number old1)))))
1032 (unless (string= new old2) (replace-match new t t nil 2)))))
1033 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
1034 (when (> (+ space bang minus) 0)
1035 (let* ((old (match-string 1))
1036 (new (format
1037 (concat "%0" (number-to-string (length old)) "d")
1038 (+ space bang minus -1 (string-to-number old)))))
1039 (unless (string= new old) (replace-match new t t nil 2))))))
1040 (setq space 0 plus 0 minus 0 bang 0)))))))
1042 ;;;;
1043 ;;;; Hooks
1044 ;;;;
1046 (defun diff-write-contents-hooks ()
1047 "Fixup hunk headers if necessary."
1048 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
1049 nil)
1051 ;; It turns out that making changes in the buffer from within an
1052 ;; *-change-function is asking for trouble, whereas making them
1053 ;; from a post-command-hook doesn't pose much problems
1054 (defvar diff-unhandled-changes nil)
1055 (defun diff-after-change-function (beg end len)
1056 "Remember to fixup the hunk header.
1057 See `after-change-functions' for the meaning of BEG, END and LEN."
1058 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
1059 ;; incorrect, but it turns out that inhibit-read-only is normally not set
1060 ;; inside editing commands, while it tends to be set when the buffer gets
1061 ;; updated by an async process or by a conversion function, both of which
1062 ;; would rather not be uselessly slowed down by this hook.
1063 (when (and (not undo-in-progress) (not inhibit-read-only))
1064 (if diff-unhandled-changes
1065 (setq diff-unhandled-changes
1066 (cons (min beg (car diff-unhandled-changes))
1067 (max end (cdr diff-unhandled-changes))))
1068 (setq diff-unhandled-changes (cons beg end)))))
1070 (defun diff-post-command-hook ()
1071 "Fixup hunk headers if necessary."
1072 (when (consp diff-unhandled-changes)
1073 (ignore-errors
1074 (save-excursion
1075 (goto-char (car diff-unhandled-changes))
1076 ;; Maybe we've cut the end of the hunk before point.
1077 (if (and (bolp) (not (bobp))) (backward-char 1))
1078 ;; We used to fixup modifs on all the changes, but it turns out
1079 ;; that it's safer not to do it on big changes, for example
1080 ;; when yanking a big diff, since we might then screw up perfectly
1081 ;; correct values. -stef
1082 ;; (unless (ignore-errors
1083 ;; (diff-beginning-of-hunk)
1084 ;; (save-excursion
1085 ;; (diff-end-of-hunk)
1086 ;; (> (point) (car diff-unhandled-changes))))
1087 ;; (goto-char (car diff-unhandled-changes))
1088 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
1089 ;; (diff-beginning-of-hunk))
1090 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
1091 (diff-beginning-of-hunk)
1092 (when (save-excursion
1093 (diff-end-of-hunk)
1094 (>= (point) (cdr diff-unhandled-changes)))
1095 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
1096 (setq diff-unhandled-changes nil)))
1098 (defun diff-next-error (arg reset)
1099 ;; Select a window that displays the current buffer so that point
1100 ;; movements are reflected in that window. Otherwise, the user might
1101 ;; never see the hunk corresponding to the source she's jumping to.
1102 (pop-to-buffer (current-buffer))
1103 (if reset (goto-char (point-min)))
1104 (diff-hunk-next arg)
1105 (diff-goto-source))
1107 ;;;###autoload
1108 (define-derived-mode diff-mode fundamental-mode "Diff"
1109 "Major mode for viewing/editing context diffs.
1110 Supports unified and context diffs as well as (to a lesser extent)
1111 normal diffs.
1113 When the buffer is read-only, the ESC prefix is not necessary.
1114 If you edit the buffer manually, diff-mode will try to update the hunk
1115 headers for you on-the-fly.
1117 You can also switch between context diff and unified diff with \\[diff-context->unified],
1118 or vice versa with \\[diff-unified->context] and you can also reverse the direction of
1119 a diff with \\[diff-reverse-direction].
1121 \\{diff-mode-map}"
1123 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
1124 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
1125 (set (make-local-variable 'imenu-generic-expression)
1126 diff-imenu-generic-expression)
1127 ;; These are not perfect. They would be better done separately for
1128 ;; context diffs and unidiffs.
1129 ;; (set (make-local-variable 'paragraph-start)
1130 ;; (concat "@@ " ; unidiff hunk
1131 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1132 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1133 ;; ; start (first or second line)
1134 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1135 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1136 ;; compile support
1137 (set (make-local-variable 'next-error-function) 'diff-next-error)
1139 (setq buffer-read-only diff-default-read-only)
1140 ;; setup change hooks
1141 (if (not diff-update-on-the-fly)
1142 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1143 (make-local-variable 'diff-unhandled-changes)
1144 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1145 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
1146 ;; Neat trick from Dave Love to add more bindings in read-only mode:
1147 (lexical-let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
1148 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1149 ;; Turn off this little trick in case the buffer is put in view-mode.
1150 (add-hook 'view-mode-hook
1151 (lambda ()
1152 (setq minor-mode-overriding-map-alist
1153 (delq ro-bind minor-mode-overriding-map-alist)))
1154 nil t))
1155 ;; add-log support
1156 (set (make-local-variable 'add-log-current-defun-function)
1157 'diff-current-defun)
1158 (set (make-local-variable 'add-log-buffer-file-name-function)
1159 'diff-find-file-name))
1161 ;;;###autoload
1162 (define-minor-mode diff-minor-mode
1163 "Minor mode for viewing/editing context diffs.
1164 \\{diff-minor-mode-map}"
1165 :group 'diff-mode :lighter " Diff"
1166 ;; FIXME: setup font-lock
1167 ;; setup change hooks
1168 (if (not diff-update-on-the-fly)
1169 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1170 (make-local-variable 'diff-unhandled-changes)
1171 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1172 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
1174 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1176 (defun diff-delete-if-empty ()
1177 ;; An empty diff file means there's no more diffs to integrate, so we
1178 ;; can just remove the file altogether. Very handy for .rej files if we
1179 ;; remove hunks as we apply them.
1180 (when (and buffer-file-name
1181 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1182 (delete-file buffer-file-name)))
1184 (defun diff-delete-empty-files ()
1185 "Arrange for empty diff files to be removed."
1186 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1188 (defun diff-make-unified ()
1189 "Turn context diffs into unified diffs if applicable."
1190 (if (save-excursion
1191 (goto-char (point-min))
1192 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
1193 (let ((mod (buffer-modified-p)))
1194 (unwind-protect
1195 (diff-context->unified (point-min) (point-max))
1196 (restore-buffer-modified-p mod)))))
1199 ;;; Misc operations that have proved useful at some point.
1202 (defun diff-next-complex-hunk ()
1203 "Jump to the next \"complex\" hunk.
1204 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1205 Only works for unified diffs."
1206 (interactive)
1207 (while
1208 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1209 nil t)
1210 (equal (match-string 1) (match-string 2)))))
1212 (defun diff-sanity-check-context-hunk-half (lines)
1213 (let ((count lines))
1214 (while
1215 (cond
1216 ((and (memq (char-after) '(?\s ?! ?+ ?-))
1217 (memq (char-after (1+ (point))) '(?\s ?\t)))
1218 (decf count) t)
1219 ((or (zerop count) (= count lines)) nil)
1220 ((memq (char-after) '(?! ?+ ?-))
1221 (if (not (and (eq (char-after (1+ (point))) ?\n)
1222 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1223 (error "End of hunk ambiguously marked")
1224 (forward-char 1) (insert " ") (forward-line -1) t))
1225 ((< lines 0)
1226 (error "End of hunk ambiguously marked"))
1227 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1228 (error "Abort!"))
1229 ((eolp) (insert " ") (forward-line -1) t)
1230 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1231 (forward-line))))
1233 (defun diff-sanity-check-hunk ()
1234 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1235 ;; OK to override a read-only setting.
1236 (inhibit-read-only t))
1237 (save-excursion
1238 (cond
1239 ((not (looking-at diff-hunk-header-re))
1240 (error "Not recognizable hunk header"))
1242 ;; A context diff.
1243 ((eq (char-after) ?*)
1244 (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? \\*\\*\\*\\*"))
1245 (error "Unrecognized context diff first hunk header format")
1246 (forward-line 2)
1247 (diff-sanity-check-context-hunk-half
1248 (if (match-string 2)
1249 (1+ (- (string-to-number (match-string 2))
1250 (string-to-number (match-string 1))))
1252 (if (not (looking-at "--- \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? ----$"))
1253 (error "Unrecognized context diff second hunk header format")
1254 (forward-line)
1255 (diff-sanity-check-context-hunk-half
1256 (if (match-string 2)
1257 (1+ (- (string-to-number (match-string 2))
1258 (string-to-number (match-string 1))))
1259 1)))))
1261 ;; A unified diff.
1262 ((eq (char-after) ?@)
1263 (if (not (looking-at
1264 "@@ -[0-9]+\\(?:,\\([0-9]+\\)\\)? \\+[0-9]+\\(?:,\\([0-9]+\\)\\)? @@"))
1265 (error "Unrecognized unified diff hunk header format")
1266 (let ((before (if (match-string 1) (string-to-number (match-string 1)) 1))
1267 (after (if (match-string 2) (string-to-number (match-string 2)) 1)))
1268 (forward-line)
1269 (while
1270 (case (char-after)
1271 (?\s (decf before) (decf after) t)
1272 (?- (decf before) t)
1273 (?+ (decf after) t)
1275 (cond
1276 ((and (zerop before) (zerop after)) nil)
1277 ((or (< before 0) (< after 0))
1278 (error (if (or (zerop before) (zerop after))
1279 "End of hunk ambiguously marked"
1280 "Hunk seriously messed up")))
1281 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1282 (error "Abort!"))
1283 ((eolp) (insert " ") (forward-line -1) t)
1284 (t (insert " ")
1285 (delete-region (- (point) 2) (- (point) 1)) t))))
1286 (forward-line)))))
1288 ;; A plain diff.
1290 ;; TODO.
1291 )))))
1293 (defun diff-hunk-text (hunk destp char-offset)
1294 "Return the literal source text from HUNK as (TEXT . OFFSET).
1295 If DESTP is nil, TEXT is the source, otherwise the destination text.
1296 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1297 char-offset in TEXT."
1298 (with-temp-buffer
1299 (insert hunk)
1300 (goto-char (point-min))
1301 (let ((src-pos nil)
1302 (dst-pos nil)
1303 (divider-pos nil)
1304 (num-pfx-chars 2))
1305 ;; Set the following variables:
1306 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1307 ;; DST-POS buffer pos of the destination part of the hunk or nil
1308 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1309 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1310 (cond ((looking-at "^@@")
1311 ;; unified diff
1312 (setq num-pfx-chars 1)
1313 (forward-line 1)
1314 (setq src-pos (point) dst-pos (point)))
1315 ((looking-at "^\\*\\*")
1316 ;; context diff
1317 (forward-line 2)
1318 (setq src-pos (point))
1319 (re-search-forward "^--- " nil t)
1320 (forward-line 0)
1321 (setq divider-pos (point))
1322 (forward-line 1)
1323 (setq dst-pos (point)))
1324 ((looking-at "^[0-9]+a[0-9,]+$")
1325 ;; normal diff, insert
1326 (forward-line 1)
1327 (setq dst-pos (point)))
1328 ((looking-at "^[0-9,]+d[0-9]+$")
1329 ;; normal diff, delete
1330 (forward-line 1)
1331 (setq src-pos (point)))
1332 ((looking-at "^[0-9,]+c[0-9,]+$")
1333 ;; normal diff, change
1334 (forward-line 1)
1335 (setq src-pos (point))
1336 (re-search-forward "^---$" nil t)
1337 (forward-line 0)
1338 (setq divider-pos (point))
1339 (forward-line 1)
1340 (setq dst-pos (point)))
1342 (error "Unknown diff hunk type")))
1344 (if (if destp (null dst-pos) (null src-pos))
1345 ;; Implied empty text
1346 (if char-offset '("" . 0) "")
1348 ;; For context diffs, either side can be empty, (if there's only
1349 ;; added or only removed text). We should then use the other side.
1350 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1351 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1353 (when char-offset (goto-char (+ (point-min) char-offset)))
1355 ;; Get rid of anything except the desired text.
1356 (save-excursion
1357 ;; Delete unused text region
1358 (let ((keep (if destp dst-pos src-pos)))
1359 (when (and divider-pos (> divider-pos keep))
1360 (delete-region divider-pos (point-max)))
1361 (delete-region (point-min) keep))
1362 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1363 (let ((kill-char (if destp ?- ?+)))
1364 (goto-char (point-min))
1365 (while (not (eobp))
1366 (if (eq (char-after) kill-char)
1367 (delete-region (point) (progn (forward-line 1) (point)))
1368 (delete-char num-pfx-chars)
1369 (forward-line 1)))))
1371 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1372 (if char-offset (cons text (- (point) (point-min))) text))))))
1375 (defun diff-find-text (text)
1376 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1377 If TEXT isn't found, nil is returned."
1378 (let* ((orig (point))
1379 (forw (and (search-forward text nil t)
1380 (cons (match-beginning 0) (match-end 0))))
1381 (back (and (goto-char (+ orig (length text)))
1382 (search-backward text nil t)
1383 (cons (match-beginning 0) (match-end 0)))))
1384 ;; Choose the closest match.
1385 (if (and forw back)
1386 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1387 (or back forw))))
1389 (defun diff-find-approx-text (text)
1390 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1391 Whitespace differences are ignored."
1392 (let* ((orig (point))
1393 (re (concat "^[ \t\n\f]*"
1394 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1395 "[ \t\n\f]*\n"))
1396 (forw (and (re-search-forward re nil t)
1397 (cons (match-beginning 0) (match-end 0))))
1398 (back (and (goto-char (+ orig (length text)))
1399 (re-search-backward re nil t)
1400 (cons (match-beginning 0) (match-end 0)))))
1401 ;; Choose the closest match.
1402 (if (and forw back)
1403 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1404 (or back forw))))
1406 (defsubst diff-xor (a b) (if a (if (not b) a) b))
1408 (defun diff-find-source-location (&optional other-file reverse)
1409 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1410 BUF is the buffer corresponding to the source file.
1411 LINE-OFFSET is the offset between the expected and actual positions
1412 of the text of the hunk or nil if the text was not found.
1413 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1414 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1415 SRC is the variant that was found in the buffer.
1416 SWITCHED is non-nil if the patch is already applied."
1417 (save-excursion
1418 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1419 (char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1420 (point))))
1421 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1422 ;; the user may disagree on what constitutes the hunk
1423 ;; (e.g. because an empty line truncates the hunk mid-course),
1424 ;; leading to potentially nasty surprises for the user.
1425 (_ (diff-sanity-check-hunk))
1426 (hunk (buffer-substring (point)
1427 (save-excursion (diff-end-of-hunk) (point))))
1428 (old (diff-hunk-text hunk reverse char-offset))
1429 (new (diff-hunk-text hunk (not reverse) char-offset))
1430 ;; Find the location specification.
1431 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1432 (error "Can't find the hunk header")
1433 (if other (match-string 1)
1434 (if (match-end 3) (match-string 3)
1435 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1436 (error "Can't find the hunk separator"))
1437 (match-string 1)))))
1438 (file (or (diff-find-file-name other) (error "Can't find the file")))
1439 (buf (find-file-noselect file)))
1440 ;; Update the user preference if he so wished.
1441 (when (> (prefix-numeric-value other-file) 8)
1442 (setq diff-jump-to-old-file other))
1443 (with-current-buffer buf
1444 (goto-line (string-to-number line))
1445 (let* ((orig-pos (point))
1446 (switched nil)
1447 ;; FIXME: Check for case where both OLD and NEW are found.
1448 (pos (or (diff-find-text (car old))
1449 (progn (setq switched t) (diff-find-text (car new)))
1450 (progn (setq switched nil)
1451 (condition-case nil
1452 (diff-find-approx-text (car old))
1453 (invalid-regexp nil))) ;Regex too big.
1454 (progn (setq switched t)
1455 (condition-case nil
1456 (diff-find-approx-text (car new))
1457 (invalid-regexp nil))) ;Regex too big.
1458 (progn (setq switched nil) nil))))
1459 (nconc
1460 (list buf)
1461 (if pos
1462 (list (count-lines orig-pos (car pos)) pos)
1463 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1464 (if switched (list new old t) (list old new))))))))
1467 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1468 (let ((msg (if dry-run
1469 (if reversed "already applied" "not yet applied")
1470 (if reversed "undone" "applied"))))
1471 (message (cond ((null line-offset) "Hunk text not found")
1472 ((= line-offset 0) "Hunk %s")
1473 ((= line-offset 1) "Hunk %s at offset %d line")
1474 (t "Hunk %s at offset %d lines"))
1475 msg line-offset)))
1477 (defvar diff-apply-hunk-to-backup-file nil)
1479 (defun diff-apply-hunk (&optional reverse)
1480 "Apply the current hunk to the source file and go to the next.
1481 By default, the new source file is patched, but if the variable
1482 `diff-jump-to-old-file' is non-nil, then the old source file is
1483 patched instead (some commands, such as `diff-goto-source' can change
1484 the value of this variable when given an appropriate prefix argument).
1486 With a prefix argument, REVERSE the hunk."
1487 (interactive "P")
1488 (destructuring-bind (buf line-offset pos old new &optional switched)
1489 ;; Sometimes we'd like to have the following behavior: if REVERSE go
1490 ;; to the new file, otherwise go to the old. But that means that by
1491 ;; default we use the old file, which is the opposite of the default
1492 ;; for diff-goto-source, and is thus confusing. Also when you don't
1493 ;; know about it it's pretty surprising.
1494 ;; TODO: make it possible to ask explicitly for this behavior.
1496 ;; This is duplicated in diff-test-hunk.
1497 (diff-find-source-location nil reverse)
1498 (cond
1499 ((null line-offset)
1500 (error "Can't find the text to patch"))
1501 ((with-current-buffer buf
1502 (and buffer-file-name
1503 (backup-file-name-p buffer-file-name)
1504 (not diff-apply-hunk-to-backup-file)
1505 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1506 (yes-or-no-p (format "Really apply this hunk to %s? "
1507 (file-name-nondirectory
1508 buffer-file-name)))))))
1509 (error "%s"
1510 (substitute-command-keys
1511 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1512 (if (not reverse) "\\[universal-argument] ")))))
1513 ((and switched
1514 ;; A reversed patch was detected, perhaps apply it in reverse.
1515 (not (save-window-excursion
1516 (pop-to-buffer buf)
1517 (goto-char (+ (car pos) (cdr old)))
1518 (y-or-n-p
1519 (if reverse
1520 "Hunk hasn't been applied yet; apply it now? "
1521 "Hunk has already been applied; undo it? ")))))
1522 (message "(Nothing done)"))
1524 ;; Apply the hunk
1525 (with-current-buffer buf
1526 (goto-char (car pos))
1527 (delete-region (car pos) (cdr pos))
1528 (insert (car new)))
1529 ;; Display BUF in a window
1530 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1531 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1532 (when diff-advance-after-apply-hunk
1533 (diff-hunk-next))))))
1536 (defun diff-test-hunk (&optional reverse)
1537 "See whether it's possible to apply the current hunk.
1538 With a prefix argument, try to REVERSE the hunk."
1539 (interactive "P")
1540 (destructuring-bind (buf line-offset pos src dst &optional switched)
1541 (diff-find-source-location nil reverse)
1542 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1543 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1546 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1548 (defun diff-goto-source (&optional other-file event)
1549 "Jump to the corresponding source line.
1550 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1551 is given) determines whether to jump to the old or the new file.
1552 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1553 then `diff-jump-to-old-file' is also set, for the next invocations."
1554 (interactive (list current-prefix-arg last-input-event))
1555 ;; When pointing at a removal line, we probably want to jump to
1556 ;; the old location, and else to the new (i.e. as if reverting).
1557 ;; This is a convenient detail when using smerge-diff.
1558 (if event (posn-set-point (event-end event)))
1559 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1560 (destructuring-bind (buf line-offset pos src dst &optional switched)
1561 (diff-find-source-location other-file rev)
1562 (pop-to-buffer buf)
1563 (goto-char (+ (car pos) (cdr src)))
1564 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1567 (defun diff-current-defun ()
1568 "Find the name of function at point.
1569 For use in `add-log-current-defun-function'."
1570 (save-excursion
1571 (when (looking-at diff-hunk-header-re)
1572 (forward-line 1)
1573 (re-search-forward "^[^ ]" nil t))
1574 (destructuring-bind (buf line-offset pos src dst &optional switched)
1575 (diff-find-source-location)
1576 (beginning-of-line)
1577 (or (when (memq (char-after) '(?< ?-))
1578 ;; Cursor is pointing at removed text. This could be a removed
1579 ;; function, in which case, going to the source buffer will
1580 ;; not help since the function is now removed. Instead,
1581 ;; try to figure out the function name just from the code-fragment.
1582 (let ((old (if switched dst src)))
1583 (with-temp-buffer
1584 (insert (car old))
1585 (funcall (with-current-buffer buf major-mode))
1586 (goto-char (+ (point-min) (cdr old)))
1587 (add-log-current-defun))))
1588 (with-current-buffer buf
1589 (goto-char (+ (car pos) (cdr src)))
1590 (add-log-current-defun))))))
1592 (defun diff-refine-ignore-spaces-hunk ()
1593 "Refine the current hunk by ignoring space differences."
1594 (interactive)
1595 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1596 (point))))
1597 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1598 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1599 (error "Can't find line number"))
1600 (string-to-number (match-string 1))))
1601 (hunk (delete-and-extract-region
1602 (point) (save-excursion (diff-end-of-hunk) (point))))
1603 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1604 (file1 (make-temp-file "diff1"))
1605 (file2 (make-temp-file "diff2"))
1606 (coding-system-for-read buffer-file-coding-system)
1607 (inhibit-read-only t)
1608 old new)
1609 (unwind-protect
1610 (save-excursion
1611 (setq old (diff-hunk-text hunk nil char-offset))
1612 (setq new (diff-hunk-text hunk t char-offset))
1613 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1614 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1615 (with-temp-buffer
1616 (let ((status
1617 (call-process diff-command nil t nil
1618 opts file1 file2)))
1619 (case status
1620 (0 nil) ;Nothing to reformat.
1621 (1 (goto-char (point-min))
1622 ;; Remove the file-header.
1623 (when (re-search-forward diff-hunk-header-re nil t)
1624 (delete-region (point-min) (match-beginning 0))))
1625 (t (goto-char (point-max))
1626 (unless (bolp) (insert "\n"))
1627 (insert hunk)))
1628 (setq hunk (buffer-string))
1629 (unless (memq status '(0 1))
1630 (error "Diff returned: %s" status)))))
1631 ;; Whatever happens, put back some equivalent text: either the new
1632 ;; one or the original one in case some error happened.
1633 (insert hunk)
1634 (delete-file file1)
1635 (delete-file file2))))
1637 ;;; Fine change highlighting.
1639 (defface diff-fine-change
1640 '((t :background "yellow"))
1641 "Face used for char-based changes shown by `diff-fine-highlight'.")
1643 (defun diff-fine-highlight-preproc ()
1644 (while (re-search-forward "^." nil t)
1645 ;; Replace the hunk's leading prefix (+, -, !, <, or >) on each line
1646 ;; with something constant, otherwise it'll be flagged as changes
1647 ;; (since it's typically "-" on one side and "+" on the other).
1648 ;; Note that we keep the same number of chars: we treat the prefix
1649 ;; as part of the texts-to-diff, so that finding the right char
1650 ;; afterwards will be easier. This only makes sense because we make
1651 ;; diffs at char-granularity.
1652 (replace-match " ")))
1654 (defun diff-fine-highlight ()
1655 "Highlight changes of hunk at point at a finer granularity."
1656 (interactive)
1657 (require 'smerge-mode)
1658 (diff-beginning-of-hunk 'try-harder)
1659 (let* ((style (diff-hunk-style)) ;Skips the hunk header as well.
1660 (beg (point))
1661 (props '((diff-mode . fine) (face diff-fine-change)))
1662 (end (progn (diff-end-of-hunk) (point))))
1664 (remove-overlays beg end 'diff-mode 'fine)
1666 (goto-char beg)
1667 (case style
1668 (unified
1669 (while (re-search-forward "^\\(?:-.*\n\\)+\\(\\)\\(?:\\+.*\n\\)+" end t)
1670 (smerge-refine-subst (match-beginning 0) (match-end 1)
1671 (match-end 1) (match-end 0)
1672 props 'diff-fine-highlight-preproc)))
1673 (context
1674 (let* ((middle (save-excursion (re-search-forward "^---")))
1675 (other middle))
1676 (while (re-search-forward "^\\(?:!.*\n\\)+" middle t)
1677 (smerge-refine-subst (match-beginning 0) (match-end 0)
1678 (save-excursion
1679 (goto-char other)
1680 (re-search-forward "^\\(?:!.*\n\\)+" end)
1681 (setq other (match-end 0))
1682 (match-beginning 0))
1683 other
1684 props 'diff-fine-highlight-preproc))))
1685 (t ;; Normal diffs.
1686 (let ((beg1 (1+ (point))))
1687 (when (re-search-forward "^---.*\n" end t)
1688 ;; It's a combined add&remove, so there's something to do.
1689 (smerge-refine-subst beg1 (match-beginning 0)
1690 (match-end 0) end
1691 props 'diff-fine-highlight-preproc)))))))
1694 ;; provide the package
1695 (provide 'diff-mode)
1697 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1698 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1699 ;; (diff-mode-load-hook): dropped.
1700 ;; (auto-mode-alist): also catch *.diffs.
1701 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1702 ;; for *.rej files (that lack any file name indication).
1704 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1705 ;; added support for "\ No newline at end of file".
1707 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1708 ;; - added basic `compile' support.
1709 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1710 ;; - diff-kill-file now tries to kill the leading garbage as well.
1712 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1713 ;; - don't use CL in the autoloaded code
1714 ;; - accept diffs using -T
1716 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1717 ;; interface to ediff-patch
1719 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1720 ;; (ediff=patch-file): add bindings to call ediff-patch.
1721 ;; (diff-find-file-name): taken out of diff-goto-source.
1722 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1723 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1725 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1726 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1728 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1729 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1732 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1733 ;;; diff-mode.el ends here