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