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