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