Specify missing group (and type, if simple) in defcustom.
[emacs.git] / lisp / diff-mode.el
blobc16738f6570974200ecf9e58f784aebe3b2cf50f
1 ;;; diff-mode.el --- a mode for viewing/editing context diffs
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
4 ;; Free Software Foundation, Inc.
6 ;; Author: Stefan Monnier <monnier@cs.yale.edu>
7 ;; Keywords: convenience patch diff
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
26 ;;; Commentary:
28 ;; Provides support for font-lock, outline, navigation
29 ;; commands, editing and various conversions as well as jumping
30 ;; to the corresponding source file.
32 ;; Inspired by Pavel Machek's patch-mode.el (<pavel@@atrey.karlin.mff.cuni.cz>)
33 ;; Some efforts were spent to have it somewhat compatible with XEmacs'
34 ;; diff-mode as well as with compilation-minor-mode
36 ;; Bugs:
38 ;; - Reverse doesn't work with normal diffs.
40 ;; Todo:
42 ;; - Add a `delete-after-apply' so C-c C-a automatically deletes hunks.
43 ;; Also allow C-c C-a to delete already-applied hunks.
45 ;; - Try `diff <file> <hunk>' to try and fuzzily discover the source location
46 ;; of a hunk. Show then the changes between <file> and <hunk> and make it
47 ;; possible to apply them to <file>, <hunk-src>, or <hunk-dst>.
48 ;; Or maybe just make it into a ".rej to diff3-markers converter".
50 ;; - Refine hunk on a word-by-word basis.
52 ;; - Handle `diff -b' output in context->unified.
54 ;;; Code:
56 (eval-when-compile (require 'cl))
59 (defgroup diff-mode ()
60 "Major mode for viewing/editing diffs"
61 :version "21.1"
62 :group 'tools
63 :group 'diff)
65 (defcustom diff-default-read-only nil
66 "If non-nil, `diff-mode' buffers default to being read-only."
67 :type 'boolean
68 :group 'diff-mode)
70 (defcustom diff-jump-to-old-file nil
71 "*Non-nil means `diff-goto-source' jumps to the old file.
72 Else, it jumps to the new file."
73 :type 'boolean
74 :group 'diff-mode)
76 (defcustom diff-update-on-the-fly t
77 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
78 When editing a diff file, the line numbers in the hunk headers
79 need to be kept consistent with the actual diff. This can
80 either be done on the fly (but this sometimes interacts poorly with the
81 undo mechanism) or whenever the file is written (can be slow
82 when editing big diffs)."
83 :type 'boolean
84 :group 'diff-mode)
86 (defcustom diff-advance-after-apply-hunk t
87 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
88 :type 'boolean
89 :group 'diff-mode)
92 (defcustom diff-mode-hook nil
93 "Run after setting up the `diff-mode' major mode."
94 :type 'hook
95 :options '(diff-delete-empty-files diff-make-unified)
96 :group 'diff-mode)
98 (defvar diff-outline-regexp
99 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
101 ;;;;
102 ;;;; keymap, menu, ...
103 ;;;;
105 (easy-mmode-defmap diff-mode-shared-map
106 '(;; From Pavel Machek's patch-mode.
107 ("n" . diff-hunk-next)
108 ("N" . diff-file-next)
109 ("p" . diff-hunk-prev)
110 ("P" . diff-file-prev)
111 ("k" . diff-hunk-kill)
112 ("K" . diff-file-kill)
113 ;; From compilation-minor-mode.
114 ("}" . diff-file-next)
115 ("{" . diff-file-prev)
116 ("\C-m" . diff-goto-source)
117 ([mouse-2] . diff-goto-source)
118 ;; From XEmacs' diff-mode.
119 ("W" . widen)
120 ;;("." . diff-goto-source) ;display-buffer
121 ;;("f" . diff-goto-source) ;find-file
122 ("o" . diff-goto-source) ;other-window
123 ;;("w" . diff-goto-source) ;other-frame
124 ;;("N" . diff-narrow)
125 ;;("h" . diff-show-header)
126 ;;("j" . diff-show-difference) ;jump to Nth diff
127 ;;("q" . diff-quit)
128 (" " . scroll-up)
129 ("\177" . scroll-down)
130 ;; Our very own bindings.
131 ("A" . diff-ediff-patch)
132 ("r" . diff-restrict-view)
133 ("R" . diff-reverse-direction)
134 ("U" . diff-context->unified)
135 ("C" . diff-unified->context)
136 ("q" . quit-window))
137 "Basic keymap for `diff-mode', bound to various prefix keys.")
139 (easy-mmode-defmap diff-mode-map
140 `(("\e" . ,diff-mode-shared-map)
141 ;; From compilation-minor-mode.
142 ("\C-c\C-c" . diff-goto-source)
143 ;; Misc operations.
144 ("\C-c\C-r" . diff-refine-hunk)
145 ("\C-c\C-s" . diff-split-hunk)
146 ("\C-c\C-a" . diff-apply-hunk)
147 ("\C-c\C-t" . diff-test-hunk)
148 ("\C-c\C-f" . next-error-follow-minor-mode))
149 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
151 (easy-menu-define diff-mode-menu diff-mode-map
152 "Menu for `diff-mode'."
153 '("Diff"
154 ["Jump to Source" diff-goto-source t]
155 ["Apply hunk" diff-apply-hunk t]
156 ["Apply diff with Ediff" diff-ediff-patch t]
157 ["-----" nil nil]
158 ["Reverse direction" diff-reverse-direction t]
159 ["Context -> Unified" diff-context->unified t]
160 ["Unified -> Context" diff-unified->context t]
161 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
164 (defcustom diff-minor-mode-prefix "\C-c="
165 "Prefix key for `diff-minor-mode' commands."
166 :type '(choice (string "\e") (string "C-c=") string)
167 :group 'diff-mode)
169 (easy-mmode-defmap diff-minor-mode-map
170 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
171 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
174 ;;;;
175 ;;;; font-lock support
176 ;;;;
178 (defface diff-header-face
179 '((((class color) (min-colors 88) (background light))
180 :background "grey85")
181 (((class color) (min-colors 88) (background dark))
182 :background "grey45")
183 (((class color) (background light))
184 :foreground "blue1" :weight bold)
185 (((class color) (background dark))
186 :foreground "green" :weight bold)
187 (t :weight bold))
188 "`diff-mode' face inherited by hunk and index header faces.")
189 (defvar diff-header-face 'diff-header-face)
191 (defface diff-file-header-face
192 '((((class color) (min-colors 88) (background light))
193 :background "grey70" :weight bold)
194 (((class color) (min-colors 88) (background dark))
195 :background "grey60" :weight bold)
196 (((class color) (background light))
197 :foreground "yellow" :weight bold)
198 (((class color) (background dark))
199 :foreground "cyan" :weight bold)
200 (t :weight bold)) ; :height 1.3
201 "`diff-mode' face used to highlight file header lines.")
202 (defvar diff-file-header-face 'diff-file-header-face)
204 (defface diff-index-face
205 '((t :inherit diff-file-header-face))
206 "`diff-mode' face used to highlight index header lines.")
207 (defvar diff-index-face 'diff-index-face)
209 (defface diff-hunk-header-face
210 '((t :inherit diff-header-face))
211 "`diff-mode' face used to highlight hunk header lines.")
212 (defvar diff-hunk-header-face 'diff-hunk-header-face)
214 (defface diff-removed-face
215 '((t :inherit diff-changed-face))
216 "`diff-mode' face used to highlight removed lines.")
217 (defvar diff-removed-face 'diff-removed-face)
219 (defface diff-added-face
220 '((t :inherit diff-changed-face))
221 "`diff-mode' face used to highlight added lines.")
222 (defvar diff-added-face 'diff-added-face)
224 (defface diff-changed-face
225 '((((type tty pc) (class color) (background light))
226 :foreground "magenta" :weight bold :slant italic)
227 (((type tty pc) (class color) (background dark))
228 :foreground "yellow" :weight bold :slant italic))
229 "`diff-mode' face used to highlight changed lines.")
230 (defvar diff-changed-face 'diff-changed-face)
232 (defface diff-function-face
233 '((t :inherit diff-context-face))
234 "`diff-mode' face used to highlight function names produced by \"diff -p\".")
235 (defvar diff-function-face 'diff-function-face)
237 (defface diff-context-face
238 '((((class color) (background light))
239 :foreground "grey50")
240 (((class color) (background dark))
241 :foreground "grey70"))
242 "`diff-mode' face used to highlight context and other side-information.")
243 (defvar diff-context-face 'diff-context-face)
245 (defface diff-nonexistent-face
246 '((t :inherit diff-file-header-face))
247 "`diff-mode' face used to highlight nonexistent files in recursive diffs.")
248 (defvar diff-nonexistent-face 'diff-nonexistent-face)
250 (defconst diff-yank-handler '(diff-yank-function))
251 (defun diff-yank-function (text)
252 ;; FIXME: the yank-handler is now called separately on each piece of text
253 ;; with a yank-handler property, so the next-single-property-change call
254 ;; below will always return nil :-( --stef
255 (let ((mixed (next-single-property-change 0 'yank-handler text))
256 (start (point)))
257 ;; First insert the text.
258 (insert text)
259 ;; If the text does not include any diff markers and if we're not
260 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
261 (unless (or mixed (derived-mode-p 'diff-mode))
262 (undo-boundary) ; Just in case the user wanted the prefixes.
263 (let ((re (save-excursion
264 (if (re-search-backward "^[><!][ \t]" start t)
265 (if (eq (char-after) ?!)
266 "^[!+- ][ \t]" "^[<>][ \t]")
267 "^[ <>!+-]"))))
268 (save-excursion
269 (while (re-search-backward re start t)
270 (replace-match "" t t)))))))
273 (defvar diff-font-lock-keywords
274 `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
275 (1 diff-hunk-header-face)
276 (2 diff-function-face))
277 ("^--- .+ ----$" . diff-hunk-header-face) ;context
278 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
279 (1 diff-hunk-header-face)
280 (2 diff-function-face))
281 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
282 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
283 (0 diff-header-face) (2 diff-file-header-face prepend))
284 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face)
285 ("^!.*\n" (0 diff-changed-face))
286 ("^[+>].*\n" (0 diff-added-face))
287 ("^[-<].*\n" (0 diff-removed-face))
288 ("^Index: \\(.+\\).*\n" (0 diff-header-face) (1 diff-index-face prepend))
289 ("^Only in .*\n" . diff-nonexistent-face)
290 ("^#.*" . font-lock-string-face)
291 ("^[^-=+*!<>].*\n" (0 diff-context-face))))
293 (defconst diff-font-lock-defaults
294 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
296 (defvar diff-imenu-generic-expression
297 ;; Prefer second name as first is most likely to be a backup or
298 ;; version-control name. The [\t\n] at the end of the unidiff pattern
299 ;; catches Debian source diff files (which lack the trailing date).
300 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
301 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
303 ;;;;
304 ;;;; Movement
305 ;;;;
307 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
308 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
309 (defvar diff-narrowed-to nil)
311 (defun diff-end-of-hunk (&optional style)
312 (when (looking-at diff-hunk-header-re)
313 (unless style
314 ;; Especially important for unified (because headers are ambiguous).
315 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context))))))
316 (goto-char (match-end 0)))
317 (let ((end (and (re-search-forward (case style
318 ;; A `unified' header is ambiguous.
319 (unified (concat "^[^-+# \\]\\|"
320 diff-file-header-re))
321 (context "^[^-+#! \\]")
322 (normal "^[^<>#\\]")
323 (t "^[^-+#!<> \\]"))
324 nil t)
325 (match-beginning 0))))
326 ;; The return value is used by easy-mmode-define-navigation.
327 (goto-char (or end (point-max)))))
329 (defun diff-beginning-of-hunk ()
330 (beginning-of-line)
331 (unless (looking-at diff-hunk-header-re)
332 (forward-line 1)
333 (condition-case ()
334 (re-search-backward diff-hunk-header-re)
335 (error (error "Can't find the beginning of the hunk")))))
337 (defun diff-beginning-of-file ()
338 (beginning-of-line)
339 (unless (looking-at diff-file-header-re)
340 (forward-line 2)
341 (condition-case ()
342 (re-search-backward diff-file-header-re)
343 (error (error "Can't find the beginning of the file")))))
345 (defun diff-end-of-file ()
346 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
347 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
348 nil 'move)
349 (if (match-beginning 1)
350 (goto-char (match-beginning 1))
351 (beginning-of-line)))
353 ;; Define diff-{hunk,file}-{prev,next}
354 (easy-mmode-define-navigation
355 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
356 (easy-mmode-define-navigation
357 diff-file diff-file-header-re "file" diff-end-of-hunk)
359 (defun diff-restrict-view (&optional arg)
360 "Restrict the view to the current hunk.
361 If the prefix ARG is given, restrict the view to the current file instead."
362 (interactive "P")
363 (save-excursion
364 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk))
365 (narrow-to-region (point)
366 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
367 (point)))
368 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
371 (defun diff-hunk-kill ()
372 "Kill current hunk."
373 (interactive)
374 (diff-beginning-of-hunk)
375 (let* ((start (point))
376 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
377 (match-beginning 0)))
378 (firsthunk (ignore-errors
379 (goto-char start)
380 (diff-beginning-of-file) (diff-hunk-next) (point)))
381 (nextfile (ignore-errors (diff-file-next) (point))))
382 (goto-char start)
383 (if (and firsthunk (= firsthunk start)
384 (or (null nexthunk)
385 (and nextfile (> nexthunk nextfile))))
386 ;; It's the only hunk for this file, so kill the file.
387 (diff-file-kill)
388 (diff-end-of-hunk)
389 (kill-region start (point)))))
391 (defun diff-file-kill ()
392 "Kill current file's hunks."
393 (interactive)
394 (diff-beginning-of-file)
395 (let* ((start (point))
396 (prevhunk (save-excursion
397 (ignore-errors
398 (diff-hunk-prev) (point))))
399 (index (save-excursion
400 (re-search-backward "^Index: " prevhunk t))))
401 (when index (setq start index))
402 (diff-end-of-file)
403 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
404 (kill-region start (point))))
406 (defun diff-kill-junk ()
407 "Kill spurious empty diffs."
408 (interactive)
409 (save-excursion
410 (let ((inhibit-read-only t))
411 (goto-char (point-min))
412 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
413 "\\([^-+!* <>].*\n\\)*?"
414 "\\(\\(Index:\\) \\|"
415 diff-file-header-re "\\)")
416 nil t)
417 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
418 (match-beginning 3))
419 (beginning-of-line)))))
421 (defun diff-count-matches (re start end)
422 (save-excursion
423 (let ((n 0))
424 (goto-char start)
425 (while (re-search-forward re end t) (incf n))
426 n)))
428 (defun diff-split-hunk ()
429 "Split the current (unified diff) hunk at point into two hunks."
430 (interactive)
431 (beginning-of-line)
432 (let ((pos (point))
433 (start (progn (diff-beginning-of-hunk) (point))))
434 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
435 (error "diff-split-hunk only works on unified context diffs"))
436 (forward-line 1)
437 (let* ((start1 (string-to-number (match-string 1)))
438 (start2 (string-to-number (match-string 2)))
439 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
440 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos))))
441 (goto-char pos)
442 ;; Hopefully the after-change-function will not screw us over.
443 (insert "@@ -" (number-to-string newstart1) ",1 +"
444 (number-to-string newstart2) ",1 @@\n")
445 ;; Fix the original hunk-header.
446 (diff-fixup-modifs start pos))))
449 ;;;;
450 ;;;; jump to other buffers
451 ;;;;
453 (defvar diff-remembered-files-alist nil)
455 (defun diff-filename-drop-dir (file)
456 (when (string-match "/" file) (substring file (match-end 0))))
458 (defun diff-merge-strings (ancestor from to)
459 "Merge the diff between ANCESTOR and FROM into TO.
460 Returns the merged string if successful or nil otherwise.
461 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
462 If ANCESTOR = FROM, returns TO.
463 If ANCESTOR = TO, returns FROM.
464 The heuristic is simplistic and only really works for cases
465 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
466 ;; Ideally, we want:
467 ;; AMB ANB CMD -> CND
468 ;; but that's ambiguous if `foo' or `bar' is empty:
469 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
470 (let ((str (concat ancestor "\n" from "\n" to)))
471 (when (and (string-match (concat
472 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
473 "\\1\\(.*\\)\\3\n"
474 "\\(.*\\(\\2\\).*\\)\\'") str)
475 (equal to (match-string 5 str)))
476 (concat (substring str (match-beginning 5) (match-beginning 6))
477 (match-string 4 str)
478 (substring str (match-end 6) (match-end 5))))))
480 (defun diff-tell-file-name (old name)
481 "Tell Emacs where the find the source file of the current hunk.
482 If the OLD prefix arg is passed, tell the file NAME of the old file."
483 (interactive
484 (let* ((old current-prefix-arg)
485 (fs (diff-hunk-file-names current-prefix-arg)))
486 (unless fs (error "No file name to look for"))
487 (list old (read-file-name (format "File for %s: " (car fs))
488 nil (diff-find-file-name old) t))))
489 (let ((fs (diff-hunk-file-names old)))
490 (unless fs (error "No file name to look for"))
491 (push (cons fs name) diff-remembered-files-alist)))
493 (defun diff-hunk-file-names (&optional old)
494 "Give the list of file names textually mentioned for the current hunk."
495 (save-excursion
496 (unless (looking-at diff-file-header-re)
497 (or (ignore-errors (diff-beginning-of-file))
498 (re-search-forward diff-file-header-re nil t)))
499 (let ((limit (save-excursion
500 (condition-case ()
501 (progn (diff-hunk-prev) (point))
502 (error (point-min)))))
503 (header-files
504 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
505 (list (if old (match-string 1) (match-string 3))
506 (if old (match-string 3) (match-string 1)))
507 (forward-line 1) nil)))
508 (delq nil
509 (append
510 (when (and (not old)
511 (save-excursion
512 (re-search-backward "^Index: \\(.+\\)" limit t)))
513 (list (match-string 1)))
514 header-files
515 (when (re-search-backward
516 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
517 nil t)
518 (list (if old (match-string 2) (match-string 4))
519 (if old (match-string 4) (match-string 2)))))))))
521 (defun diff-find-file-name (&optional old)
522 "Return the file corresponding to the current patch.
523 Non-nil OLD means that we want the old file."
524 (save-excursion
525 (unless (looking-at diff-file-header-re)
526 (or (ignore-errors (diff-beginning-of-file))
527 (re-search-forward diff-file-header-re nil t)))
528 (let ((fs (diff-hunk-file-names old)))
530 ;; use any previously used preference
531 (cdr (assoc fs diff-remembered-files-alist))
532 ;; try to be clever and use previous choices as an inspiration
533 (dolist (rf diff-remembered-files-alist)
534 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
535 (if (and newfile (file-exists-p newfile)) (return newfile))))
536 ;; look for each file in turn. If none found, try again but
537 ;; ignoring the first level of directory, ...
538 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
539 (file nil nil))
540 ((or (null files)
541 (setq file (do* ((files files (cdr files))
542 (file (car files) (car files)))
543 ((or (null file) (file-exists-p file))
544 file))))
545 file))
546 ;; <foo>.rej patches implicitly apply to <foo>
547 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
548 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
549 (when (file-exists-p file) file)))
550 ;; if all else fails, ask the user
551 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
552 nil (first fs) t (first fs))))
553 (set (make-local-variable 'diff-remembered-files-alist)
554 (cons (cons fs file) diff-remembered-files-alist))
555 file)))))
558 (defun diff-ediff-patch ()
559 "Call `ediff-patch-file' on the current buffer."
560 (interactive)
561 (condition-case err
562 (ediff-patch-file nil (current-buffer))
563 (wrong-number-of-arguments (ediff-patch-file))))
565 ;;;;
566 ;;;; Conversion functions
567 ;;;;
569 ;;(defvar diff-inhibit-after-change nil
570 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
572 (defun diff-unified->context (start end)
573 "Convert unified diffs to context diffs.
574 START and END are either taken from the region (if a prefix arg is given) or
575 else cover the whole bufer."
576 (interactive (if current-prefix-arg
577 (list (mark) (point))
578 (list (point-min) (point-max))))
579 (unless (markerp end) (setq end (copy-marker end)))
580 (let (;;(diff-inhibit-after-change t)
581 (inhibit-read-only t))
582 (save-excursion
583 (goto-char start)
584 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
585 (< (point) end))
586 (combine-after-change-calls
587 (if (match-beginning 2)
588 ;; we matched a file header
589 (progn
590 ;; use reverse order to make sure the indices are kept valid
591 (replace-match "---" t t nil 3)
592 (replace-match "***" t t nil 2))
593 ;; we matched a hunk header
594 (let ((line1 (match-string 4))
595 (lines1 (match-string 5))
596 (line2 (match-string 6))
597 (lines2 (match-string 7)))
598 (replace-match
599 (concat "***************\n*** " line1 ","
600 (number-to-string (+ (string-to-number line1)
601 (string-to-number lines1)
602 -1)) " ****"))
603 (forward-line 1)
604 (save-restriction
605 (narrow-to-region (point)
606 (progn (diff-end-of-hunk 'unified) (point)))
607 (let ((hunk (buffer-string)))
608 (goto-char (point-min))
609 (if (not (save-excursion (re-search-forward "^-" nil t)))
610 (delete-region (point) (point-max))
611 (goto-char (point-max))
612 (let ((modif nil) last-pt)
613 (while (progn (setq last-pt (point))
614 (= (forward-line -1) 0))
615 (case (char-after)
616 (? (insert " ") (setq modif nil) (backward-char 1))
617 (?+ (delete-region (point) last-pt) (setq modif t))
618 (?- (if (not modif)
619 (progn (forward-char 1)
620 (insert " "))
621 (delete-char 1)
622 (insert "! "))
623 (backward-char 2))
624 (?\\ (when (save-excursion (forward-line -1)
625 (= (char-after) ?+))
626 (delete-region (point) last-pt) (setq modif t)))
627 (t (setq modif nil))))))
628 (goto-char (point-max))
629 (save-excursion
630 (insert "--- " line2 ","
631 (number-to-string (+ (string-to-number line2)
632 (string-to-number lines2)
633 -1)) " ----\n" hunk))
634 ;;(goto-char (point-min))
635 (forward-line 1)
636 (if (not (save-excursion (re-search-forward "^+" nil t)))
637 (delete-region (point) (point-max))
638 (let ((modif nil) (delete nil))
639 (while (not (eobp))
640 (case (char-after)
641 (? (insert " ") (setq modif nil) (backward-char 1))
642 (?- (setq delete t) (setq modif t))
643 (?+ (if (not modif)
644 (progn (forward-char 1)
645 (insert " "))
646 (delete-char 1)
647 (insert "! "))
648 (backward-char 2))
649 (?\\ (when (save-excursion (forward-line 1)
650 (not (eobp)))
651 (setq delete t) (setq modif t)))
652 (t (setq modif nil)))
653 (let ((last-pt (point)))
654 (forward-line 1)
655 (when delete
656 (delete-region last-pt (point))
657 (setq delete nil)))))))))))))))
659 (defun diff-context->unified (start end)
660 "Convert context diffs to unified diffs.
661 START and END are either taken from the region (if a prefix arg is given) or
662 else cover the whole bufer."
663 (interactive (if current-prefix-arg
664 (list (mark) (point))
665 (list (point-min) (point-max))))
666 (unless (markerp end) (setq end (copy-marker end)))
667 (let (;;(diff-inhibit-after-change t)
668 (inhibit-read-only t))
669 (save-excursion
670 (goto-char start)
671 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
672 (< (point) end))
673 (combine-after-change-calls
674 (if (match-beginning 2)
675 ;; we matched a file header
676 (progn
677 ;; use reverse order to make sure the indices are kept valid
678 (replace-match "+++" t t nil 3)
679 (replace-match "---" t t nil 2))
680 ;; we matched a hunk header
681 (let ((line1s (match-string 4))
682 (line1e (match-string 5))
683 (pt1 (match-beginning 0)))
684 (replace-match "")
685 (unless (re-search-forward
686 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
687 (error "Can't find matching `--- n1,n2 ----' line"))
688 (let ((line2s (match-string 1))
689 (line2e (match-string 2))
690 (pt2 (progn
691 (delete-region (progn (beginning-of-line) (point))
692 (progn (forward-line 1) (point)))
693 (point-marker))))
694 (goto-char pt1)
695 (forward-line 1)
696 (while (< (point) pt2)
697 (case (char-after)
698 ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
699 (?\ ;merge with the other half of the chunk
700 (let* ((endline2
701 (save-excursion
702 (goto-char pt2) (forward-line 1) (point)))
703 (c (char-after pt2)))
704 (case c
705 ((?! ?+)
706 (insert "+"
707 (prog1 (buffer-substring (+ pt2 2) endline2)
708 (delete-region pt2 endline2))))
709 (?\ ;FIXME: check consistency
710 (delete-region pt2 endline2)
711 (delete-char 1)
712 (forward-line 1))
713 (?\\ (forward-line 1))
714 (t (delete-char 1) (forward-line 1)))))
715 (t (forward-line 1))))
716 (while (looking-at "[+! ] ")
717 (if (/= (char-after) ?!) (forward-char 1)
718 (delete-char 1) (insert "+"))
719 (delete-char 1) (forward-line 1))
720 (save-excursion
721 (goto-char pt1)
722 (insert "@@ -" line1s ","
723 (number-to-string (- (string-to-number line1e)
724 (string-to-number line1s)
725 -1))
726 " +" line2s ","
727 (number-to-string (- (string-to-number line2e)
728 (string-to-number line2s)
729 -1)) " @@"))))))))))
731 (defun diff-reverse-direction (start end)
732 "Reverse the direction of the diffs.
733 START and END are either taken from the region (if a prefix arg is given) or
734 else cover the whole bufer."
735 (interactive (if current-prefix-arg
736 (list (mark) (point))
737 (list (point-min) (point-max))))
738 (unless (markerp end) (setq end (copy-marker end)))
739 (let (;;(diff-inhibit-after-change t)
740 (inhibit-read-only t))
741 (save-excursion
742 (goto-char start)
743 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
744 (< (point) end))
745 (combine-after-change-calls
746 (cond
747 ;; a file header
748 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
749 ;; a context-diff hunk header
750 ((match-beginning 6)
751 (let ((pt-lines1 (match-beginning 6))
752 (lines1 (match-string 6)))
753 (replace-match "" nil nil nil 6)
754 (forward-line 1)
755 (let ((half1s (point)))
756 (while (looking-at "[-! \\][ \t]\\|#")
757 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
758 (forward-line 1))
759 (let ((half1 (delete-and-extract-region half1s (point))))
760 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
761 (insert half1)
762 (error "Can't find matching `--- n1,n2 ----' line"))
763 (let ((str1 (match-string 1)))
764 (replace-match lines1 nil nil nil 1)
765 (forward-line 1)
766 (let ((half2s (point)))
767 (while (looking-at "[!+ \\][ \t]\\|#")
768 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
769 (forward-line 1))
770 (let ((half2 (delete-and-extract-region half2s (point))))
771 (insert (or half1 ""))
772 (goto-char half1s)
773 (insert (or half2 ""))))
774 (goto-char pt-lines1)
775 (insert str1))))))
776 ;; a unified-diff hunk header
777 ((match-beginning 7)
778 (replace-match "@@ -\\8 +\\7 @@" nil)
779 (forward-line 1)
780 (let ((c (char-after)) first last)
781 (while (case (setq c (char-after))
782 (?- (setq first (or first (point)))
783 (delete-char 1) (insert "+") t)
784 (?+ (setq last (or last (point)))
785 (delete-char 1) (insert "-") t)
786 ((?\\ ?#) t)
787 (t (when (and first last (< first last))
788 (insert (delete-and-extract-region first last)))
789 (setq first nil last nil)
790 (equal ?\ c)))
791 (forward-line 1))))))))))
793 (defun diff-fixup-modifs (start end)
794 "Fixup the hunk headers (in case the buffer was modified).
795 START and END are either taken from the region (if a prefix arg is given) or
796 else cover the whole bufer."
797 (interactive (if current-prefix-arg
798 (list (mark) (point))
799 (list (point-min) (point-max))))
800 (let ((inhibit-read-only t))
801 (save-excursion
802 (goto-char end) (diff-end-of-hunk)
803 (let ((plus 0) (minus 0) (space 0) (bang 0))
804 (while (and (= (forward-line -1) 0) (<= start (point)))
805 (if (not (looking-at
806 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
807 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
808 "\\|--- .+\n\\+\\+\\+ ")))
809 (case (char-after)
810 (?\s (incf space))
811 (?+ (incf plus))
812 (?- (incf minus))
813 (?! (incf bang))
814 ((?\\ ?#) nil)
815 (t (setq space 0 plus 0 minus 0 bang 0)))
816 (cond
817 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
818 (let* ((old1 (match-string 1))
819 (old2 (match-string 2))
820 (new1 (number-to-string (+ space minus)))
821 (new2 (number-to-string (+ space plus))))
822 (unless (string= new2 old2) (replace-match new2 t t nil 2))
823 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
824 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
825 (when (> (+ space bang plus) 0)
826 (let* ((old1 (match-string 1))
827 (old2 (match-string 2))
828 (new (number-to-string
829 (+ space bang plus -1 (string-to-number old1)))))
830 (unless (string= new old2) (replace-match new t t nil 2)))))
831 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
832 (when (> (+ space bang minus) 0)
833 (let* ((old (match-string 1))
834 (new (format
835 (concat "%0" (number-to-string (length old)) "d")
836 (+ space bang minus -1 (string-to-number old)))))
837 (unless (string= new old) (replace-match new t t nil 2))))))
838 (setq space 0 plus 0 minus 0 bang 0)))))))
840 ;;;;
841 ;;;; Hooks
842 ;;;;
844 (defun diff-write-contents-hooks ()
845 "Fixup hunk headers if necessary."
846 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
847 nil)
849 ;; It turns out that making changes in the buffer from within an
850 ;; *-change-function is asking for trouble, whereas making them
851 ;; from a post-command-hook doesn't pose much problems
852 (defvar diff-unhandled-changes nil)
853 (defun diff-after-change-function (beg end len)
854 "Remember to fixup the hunk header.
855 See `after-change-functions' for the meaning of BEG, END and LEN."
856 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
857 ;; incorrect, but it turns out that inhibit-read-only is normally not set
858 ;; inside editing commands, while it tends to be set when the buffer gets
859 ;; updated by an async process or by a conversion function, both of which
860 ;; would rather not be uselessly slowed down by this hook.
861 (when (and (not undo-in-progress) (not inhibit-read-only))
862 (if diff-unhandled-changes
863 (setq diff-unhandled-changes
864 (cons (min beg (car diff-unhandled-changes))
865 (max end (cdr diff-unhandled-changes))))
866 (setq diff-unhandled-changes (cons beg end)))))
868 (defun diff-post-command-hook ()
869 "Fixup hunk headers if necessary."
870 (when (consp diff-unhandled-changes)
871 (ignore-errors
872 (save-excursion
873 (goto-char (car diff-unhandled-changes))
874 ;; Maybe we've cut the end of the hunk before point.
875 (if (and (bolp) (not (bobp))) (backward-char 1))
876 ;; We used to fixup modifs on all the changes, but it turns out
877 ;; that it's safer not to do it on big changes, for example
878 ;; when yanking a big diff, since we might then screw up perfectly
879 ;; correct values. -stef
880 ;; (unless (ignore-errors
881 ;; (diff-beginning-of-hunk)
882 ;; (save-excursion
883 ;; (diff-end-of-hunk)
884 ;; (> (point) (car diff-unhandled-changes))))
885 ;; (goto-char (car diff-unhandled-changes))
886 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
887 ;; (diff-beginning-of-hunk))
888 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
889 (diff-beginning-of-hunk)
890 (when (save-excursion
891 (diff-end-of-hunk)
892 (>= (point) (cdr diff-unhandled-changes)))
893 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
894 (setq diff-unhandled-changes nil)))
896 (defun diff-next-error (arg reset)
897 ;; Select a window that displays the current buffer so that point
898 ;; movements are reflected in that window. Otherwise, the user might
899 ;; never see the hunk corresponding to the source she's jumping to.
900 (pop-to-buffer (current-buffer))
901 (if reset (goto-char (point-min)))
902 (diff-hunk-next arg)
903 (diff-goto-source))
905 ;;;###autoload
906 (define-derived-mode diff-mode fundamental-mode "Diff"
907 "Major mode for viewing/editing context diffs.
908 Supports unified and context diffs as well as (to a lesser extent)
909 normal diffs.
910 When the buffer is read-only, the ESC prefix is not necessary.
911 IF you edit the buffer manually, diff-mode will try to update the hunk
912 headers for you on-the-fly.
914 You can also switch between context diff and unified diff with \\[diff-context->unified],
915 or vice versa with \\[diff-unified->context] and you can also revert the direction of
916 a diff with \\[diff-reverse-direction]."
917 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
918 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
919 (set (make-local-variable 'imenu-generic-expression)
920 diff-imenu-generic-expression)
921 ;; These are not perfect. They would be better done separately for
922 ;; context diffs and unidiffs.
923 ;; (set (make-local-variable 'paragraph-start)
924 ;; (concat "@@ " ; unidiff hunk
925 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
926 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
927 ;; ; start (first or second line)
928 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
929 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
930 ;; compile support
931 (set (make-local-variable 'next-error-function) 'diff-next-error)
933 (when (and (> (point-max) (point-min)) diff-default-read-only)
934 (toggle-read-only t))
935 ;; setup change hooks
936 (if (not diff-update-on-the-fly)
937 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
938 (make-local-variable 'diff-unhandled-changes)
939 (add-hook 'after-change-functions 'diff-after-change-function nil t)
940 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
941 ;; Neat trick from Dave Love to add more bindings in read-only mode:
942 (let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
943 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
944 ;; Turn off this little trick in case the buffer is put in view-mode.
945 (add-hook 'view-mode-hook
946 `(lambda ()
947 (setq minor-mode-overriding-map-alist
948 (delq ',ro-bind minor-mode-overriding-map-alist)))
949 nil t))
950 ;; add-log support
951 (set (make-local-variable 'add-log-current-defun-function)
952 'diff-current-defun)
953 (set (make-local-variable 'add-log-buffer-file-name-function)
954 'diff-find-file-name))
956 ;;;###autoload
957 (define-minor-mode diff-minor-mode
958 "Minor mode for viewing/editing context diffs.
959 \\{diff-minor-mode-map}"
960 :group 'diff-mode :lighter " Diff"
961 ;; FIXME: setup font-lock
962 ;; setup change hooks
963 (if (not diff-update-on-the-fly)
964 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
965 (make-local-variable 'diff-unhandled-changes)
966 (add-hook 'after-change-functions 'diff-after-change-function nil t)
967 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
969 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
971 (defun diff-delete-if-empty ()
972 ;; An empty diff file means there's no more diffs to integrate, so we
973 ;; can just remove the file altogether. Very handy for .rej files if we
974 ;; remove hunks as we apply them.
975 (when (and buffer-file-name
976 (eq 0 (nth 7 (file-attributes buffer-file-name))))
977 (delete-file buffer-file-name)))
979 (defun diff-delete-empty-files ()
980 "Arrange for empty diff files to be removed."
981 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
983 (defun diff-make-unified ()
984 "Turn context diffs into unified diffs if applicable."
985 (if (save-excursion
986 (goto-char (point-min))
987 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
988 (let ((mod (buffer-modified-p)))
989 (unwind-protect
990 (diff-context->unified (point-min) (point-max))
991 (restore-buffer-modified-p mod)))))
994 ;;; Misc operations that have proved useful at some point.
997 (defun diff-next-complex-hunk ()
998 "Jump to the next \"complex\" hunk.
999 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1000 Only works for unified diffs."
1001 (interactive)
1002 (while
1003 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1004 nil t)
1005 (equal (match-string 1) (match-string 2)))))
1007 (defun diff-hunk-text (hunk destp char-offset)
1008 "Return the literal source text from HUNK as (TEXT . OFFSET).
1009 if DESTP is nil TEXT is the source, otherwise the destination text.
1010 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1011 char-offset in TEXT."
1012 (with-temp-buffer
1013 (insert hunk)
1014 (goto-char (point-min))
1015 (let ((src-pos nil)
1016 (dst-pos nil)
1017 (divider-pos nil)
1018 (num-pfx-chars 2))
1019 ;; Set the following variables:
1020 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1021 ;; DST-POS buffer pos of the destination part of the hunk or nil
1022 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1023 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1024 (cond ((looking-at "^@@")
1025 ;; unified diff
1026 (setq num-pfx-chars 1)
1027 (forward-line 1)
1028 (setq src-pos (point) dst-pos (point)))
1029 ((looking-at "^\\*\\*")
1030 ;; context diff
1031 (forward-line 2)
1032 (setq src-pos (point))
1033 (re-search-forward "^--- " nil t)
1034 (forward-line 0)
1035 (setq divider-pos (point))
1036 (forward-line 1)
1037 (setq dst-pos (point)))
1038 ((looking-at "^[0-9]+a[0-9,]+$")
1039 ;; normal diff, insert
1040 (forward-line 1)
1041 (setq dst-pos (point)))
1042 ((looking-at "^[0-9,]+d[0-9]+$")
1043 ;; normal diff, delete
1044 (forward-line 1)
1045 (setq src-pos (point)))
1046 ((looking-at "^[0-9,]+c[0-9,]+$")
1047 ;; normal diff, change
1048 (forward-line 1)
1049 (setq src-pos (point))
1050 (re-search-forward "^---$" nil t)
1051 (forward-line 0)
1052 (setq divider-pos (point))
1053 (forward-line 1)
1054 (setq dst-pos (point)))
1056 (error "Unknown diff hunk type")))
1058 (if (if destp (null dst-pos) (null src-pos))
1059 ;; Implied empty text
1060 (if char-offset '("" . 0) "")
1062 ;; For context diffs, either side can be empty, (if there's only
1063 ;; added or only removed text). We should then use the other side.
1064 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1065 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1067 (when char-offset (goto-char (+ (point-min) char-offset)))
1069 ;; Get rid of anything except the desired text.
1070 (save-excursion
1071 ;; Delete unused text region
1072 (let ((keep (if destp dst-pos src-pos)))
1073 (when (and divider-pos (> divider-pos keep))
1074 (delete-region divider-pos (point-max)))
1075 (delete-region (point-min) keep))
1076 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1077 (let ((kill-char (if destp ?- ?+)))
1078 (goto-char (point-min))
1079 (while (not (eobp))
1080 (if (eq (char-after) kill-char)
1081 (delete-region (point) (progn (forward-line 1) (point)))
1082 (delete-char num-pfx-chars)
1083 (forward-line 1)))))
1085 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1086 (if char-offset (cons text (- (point) (point-min))) text))))))
1089 (defun diff-find-text (text)
1090 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1091 If TEXT isn't found, nil is returned."
1092 (let* ((orig (point))
1093 (forw (and (search-forward text nil t)
1094 (cons (match-beginning 0) (match-end 0))))
1095 (back (and (goto-char (+ orig (length text)))
1096 (search-backward text nil t)
1097 (cons (match-beginning 0) (match-end 0)))))
1098 ;; Choose the closest match.
1099 (if (and forw back)
1100 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1101 (or back forw))))
1103 (defun diff-find-approx-text (text)
1104 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1105 Whitespace differences are ignored."
1106 (let* ((orig (point))
1107 (re (concat "^[ \t\n\f]*"
1108 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1109 "[ \t\n\f]*\n"))
1110 (forw (and (re-search-forward re nil t)
1111 (cons (match-beginning 0) (match-end 0))))
1112 (back (and (goto-char (+ orig (length text)))
1113 (re-search-backward re nil t)
1114 (cons (match-beginning 0) (match-end 0)))))
1115 ;; Choose the closest match.
1116 (if (and forw back)
1117 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1118 (or back forw))))
1120 (defsubst diff-xor (a b) (if a (not b) b))
1122 (defun diff-find-source-location (&optional other-file reverse)
1123 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1124 BUF is the buffer corresponding to the source file.
1125 LINE-OFFSET is the offset between the expected and actual positions
1126 of the text of the hunk or nil if the text was not found.
1127 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1128 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1129 SRC is the variant that was found in the buffer.
1130 SWITCHED is non-nil if the patch is already applied."
1131 (save-excursion
1132 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1133 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1134 (hunk (buffer-substring (point)
1135 (save-excursion (diff-end-of-hunk) (point))))
1136 (old (diff-hunk-text hunk reverse char-offset))
1137 (new (diff-hunk-text hunk (not reverse) char-offset))
1138 ;; Find the location specification.
1139 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1140 (error "Can't find the hunk header")
1141 (if other (match-string 1)
1142 (if (match-end 3) (match-string 3)
1143 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1144 (error "Can't find the hunk separator"))
1145 (match-string 1)))))
1146 (file (or (diff-find-file-name other) (error "Can't find the file")))
1147 (buf (find-file-noselect file)))
1148 ;; Update the user preference if he so wished.
1149 (when (> (prefix-numeric-value other-file) 8)
1150 (setq diff-jump-to-old-file other))
1151 (with-current-buffer buf
1152 (goto-line (string-to-number line))
1153 (let* ((orig-pos (point))
1154 (switched nil)
1155 ;; FIXME: Check for case where both OLD and NEW are found.
1156 (pos (or (diff-find-text (car old))
1157 (progn (setq switched t) (diff-find-text (car new)))
1158 (progn (setq switched nil)
1159 (condition-case nil
1160 (diff-find-approx-text (car old))
1161 (invalid-regexp nil))) ;Regex too big.
1162 (progn (setq switched t)
1163 (condition-case nil
1164 (diff-find-approx-text (car new))
1165 (invalid-regexp nil))) ;Regex too big.
1166 (progn (setq switched nil) nil))))
1167 (nconc
1168 (list buf)
1169 (if pos
1170 (list (count-lines orig-pos (car pos)) pos)
1171 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1172 (if switched (list new old t) (list old new))))))))
1175 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1176 (let ((msg (if dry-run
1177 (if reversed "already applied" "not yet applied")
1178 (if reversed "undone" "applied"))))
1179 (message (cond ((null line-offset) "Hunk text not found")
1180 ((= line-offset 0) "Hunk %s")
1181 ((= line-offset 1) "Hunk %s at offset %d line")
1182 (t "Hunk %s at offset %d lines"))
1183 msg line-offset)))
1186 (defun diff-apply-hunk (&optional reverse)
1187 "Apply the current hunk to the source file and go to the next.
1188 By default, the new source file is patched, but if the variable
1189 `diff-jump-to-old-file' is non-nil, then the old source file is
1190 patched instead (some commands, such as `diff-goto-source' can change
1191 the value of this variable when given an appropriate prefix argument).
1193 With a prefix argument, REVERSE the hunk."
1194 (interactive "P")
1195 (destructuring-bind (buf line-offset pos old new &optional switched)
1196 ;; If REVERSE go to the new file, otherwise go to the old.
1197 (diff-find-source-location (not reverse) reverse)
1198 (cond
1199 ((null line-offset)
1200 (error "Can't find the text to patch"))
1201 ((and switched
1202 ;; A reversed patch was detected, perhaps apply it in reverse.
1203 (not (save-window-excursion
1204 (pop-to-buffer buf)
1205 (goto-char (+ (car pos) (cdr old)))
1206 (y-or-n-p
1207 (if reverse
1208 "Hunk hasn't been applied yet; apply it now? "
1209 "Hunk has already been applied; undo it? ")))))
1210 (message "(Nothing done)"))
1212 ;; Apply the hunk
1213 (with-current-buffer buf
1214 (goto-char (car pos))
1215 (delete-region (car pos) (cdr pos))
1216 (insert (car new)))
1217 ;; Display BUF in a window
1218 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1219 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1220 (when diff-advance-after-apply-hunk
1221 (diff-hunk-next))))))
1224 (defun diff-test-hunk (&optional reverse)
1225 "See whether it's possible to apply the current hunk.
1226 With a prefix argument, try to REVERSE the hunk."
1227 (interactive "P")
1228 (destructuring-bind (buf line-offset pos src dst &optional switched)
1229 ;; If REVERSE go to the new file, otherwise go to the old.
1230 (diff-find-source-location (not reverse) reverse)
1231 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1232 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1235 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1237 (defun diff-goto-source (&optional other-file event)
1238 "Jump to the corresponding source line.
1239 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1240 is given) determines whether to jump to the old or the new file.
1241 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1242 then `diff-jump-to-old-file' is also set, for the next invocations."
1243 (interactive (list current-prefix-arg last-input-event))
1244 ;; When pointing at a removal line, we probably want to jump to
1245 ;; the old location, and else to the new (i.e. as if reverting).
1246 ;; This is a convenient detail when using smerge-diff.
1247 (if event (posn-set-point (event-end event)))
1248 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1249 (destructuring-bind (buf line-offset pos src dst &optional switched)
1250 (diff-find-source-location other-file rev)
1251 (pop-to-buffer buf)
1252 (goto-char (+ (car pos) (cdr src)))
1253 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1256 (defun diff-current-defun ()
1257 "Find the name of function at point.
1258 For use in `add-log-current-defun-function'."
1259 (save-excursion
1260 (when (looking-at diff-hunk-header-re)
1261 (forward-line 1)
1262 (re-search-forward "^[^ ]" nil t))
1263 (destructuring-bind (buf line-offset pos src dst &optional switched)
1264 (diff-find-source-location)
1265 (beginning-of-line)
1266 (or (when (memq (char-after) '(?< ?-))
1267 ;; Cursor is pointing at removed text. This could be a removed
1268 ;; function, in which case, going to the source buffer will
1269 ;; not help since the function is now removed. Instead,
1270 ;; try to figure out the function name just from the code-fragment.
1271 (let ((old (if switched dst src)))
1272 (with-temp-buffer
1273 (insert (car old))
1274 (funcall (with-current-buffer buf major-mode))
1275 (goto-char (+ (point-min) (cdr old)))
1276 (add-log-current-defun))))
1277 (with-current-buffer buf
1278 (goto-char (+ (car pos) (cdr src)))
1279 (add-log-current-defun))))))
1281 (defun diff-refine-hunk ()
1282 "Refine the current hunk by ignoring space differences."
1283 (interactive)
1284 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1285 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1286 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1287 (error "Can't find line number"))
1288 (string-to-number (match-string 1))))
1289 (hunk (delete-and-extract-region
1290 (point) (save-excursion (diff-end-of-hunk) (point))))
1291 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1292 (file1 (make-temp-file "diff1"))
1293 (file2 (make-temp-file "diff2"))
1294 (coding-system-for-read buffer-file-coding-system)
1295 old new)
1296 (unwind-protect
1297 (save-excursion
1298 (setq old (diff-hunk-text hunk nil char-offset))
1299 (setq new (diff-hunk-text hunk t char-offset))
1300 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1301 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1302 (with-temp-buffer
1303 (let ((status
1304 (call-process diff-command nil t nil
1305 opts file1 file2)))
1306 (case status
1307 (0 nil) ;Nothing to reformat.
1308 (1 (goto-char (point-min))
1309 ;; Remove the file-header.
1310 (when (re-search-forward diff-hunk-header-re nil t)
1311 (delete-region (point-min) (match-beginning 0))))
1312 (t (goto-char (point-max))
1313 (unless (bolp) (insert "\n"))
1314 (insert hunk)))
1315 (setq hunk (buffer-string))
1316 (unless (memq status '(0 1))
1317 (error "Diff returned: %s" status)))))
1318 ;; Whatever happens, put back some equivalent text: either the new
1319 ;; one or the original one in case some error happened.
1320 (insert hunk)
1321 (delete-file file1)
1322 (delete-file file2))))
1324 ;; provide the package
1325 (provide 'diff-mode)
1327 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1328 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1329 ;; (diff-mode-load-hook): dropped.
1330 ;; (auto-mode-alist): also catch *.diffs.
1331 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1332 ;; for *.rej files (that lack any file name indication).
1334 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1335 ;; added support for "\ No newline at end of file".
1337 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1338 ;; - added basic `compile' support.
1339 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1340 ;; - diff-kill-file now tries to kill the leading garbage as well.
1342 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1343 ;; - don't use CL in the autoloaded code
1344 ;; - accept diffs using -T
1346 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1347 ;; interface to ediff-patch
1349 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1350 ;; (ediff=patch-file): add bindings to call ediff-patch.
1351 ;; (diff-find-file-name): taken out of diff-goto-source.
1352 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1353 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1355 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1356 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1358 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1359 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1362 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1363 ;;; diff-mode.el ends here