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