(latexenc-find-file-coding-system): Don't inherit the EOL part of the
[emacs.git] / lisp / diff-mode.el
blobaabd09e98ee36420a49ba7051131ab8ddd4db1f6
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 :group 'diff-mode)
190 (defvar diff-header-face 'diff-header-face)
192 (defface diff-file-header-face
193 '((((class color) (min-colors 88) (background light))
194 :background "grey70" :weight bold)
195 (((class color) (min-colors 88) (background dark))
196 :background "grey60" :weight bold)
197 (((class color) (background light))
198 :foreground "yellow" :weight bold)
199 (((class color) (background dark))
200 :foreground "cyan" :weight bold)
201 (t :weight bold)) ; :height 1.3
202 "`diff-mode' face used to highlight file header lines."
203 :group 'diff-mode)
204 (defvar diff-file-header-face 'diff-file-header-face)
206 (defface diff-index-face
207 '((t :inherit diff-file-header-face))
208 "`diff-mode' face used to highlight index header lines."
209 :group 'diff-mode)
210 (defvar diff-index-face 'diff-index-face)
212 (defface diff-hunk-header-face
213 '((t :inherit diff-header-face))
214 "`diff-mode' face used to highlight hunk header lines."
215 :group 'diff-mode)
216 (defvar diff-hunk-header-face 'diff-hunk-header-face)
218 (defface diff-removed-face
219 '((t :inherit diff-changed-face))
220 "`diff-mode' face used to highlight removed lines."
221 :group 'diff-mode)
222 (defvar diff-removed-face 'diff-removed-face)
224 (defface diff-added-face
225 '((t :inherit diff-changed-face))
226 "`diff-mode' face used to highlight added lines."
227 :group 'diff-mode)
228 (defvar diff-added-face 'diff-added-face)
230 (defface diff-changed-face
231 '((((type tty pc) (class color) (background light))
232 :foreground "magenta" :weight bold :slant italic)
233 (((type tty pc) (class color) (background dark))
234 :foreground "yellow" :weight bold :slant italic))
235 "`diff-mode' face used to highlight changed lines."
236 :group 'diff-mode)
237 (defvar diff-changed-face 'diff-changed-face)
239 (defface diff-function-face
240 '((t :inherit diff-context-face))
241 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
242 :group 'diff-mode)
243 (defvar diff-function-face 'diff-function-face)
245 (defface diff-context-face
246 '((((class color) (background light))
247 :foreground "grey50")
248 (((class color) (background dark))
249 :foreground "grey70"))
250 "`diff-mode' face used to highlight context and other side-information."
251 :group 'diff-mode)
252 (defvar diff-context-face 'diff-context-face)
254 (defface diff-nonexistent-face
255 '((t :inherit diff-file-header-face))
256 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
257 :group 'diff-mode)
258 (defvar diff-nonexistent-face 'diff-nonexistent-face)
260 (defconst diff-yank-handler '(diff-yank-function))
261 (defun diff-yank-function (text)
262 ;; FIXME: the yank-handler is now called separately on each piece of text
263 ;; with a yank-handler property, so the next-single-property-change call
264 ;; below will always return nil :-( --stef
265 (let ((mixed (next-single-property-change 0 'yank-handler text))
266 (start (point)))
267 ;; First insert the text.
268 (insert text)
269 ;; If the text does not include any diff markers and if we're not
270 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
271 (unless (or mixed (derived-mode-p 'diff-mode))
272 (undo-boundary) ; Just in case the user wanted the prefixes.
273 (let ((re (save-excursion
274 (if (re-search-backward "^[><!][ \t]" start t)
275 (if (eq (char-after) ?!)
276 "^[!+- ][ \t]" "^[<>][ \t]")
277 "^[ <>!+-]"))))
278 (save-excursion
279 (while (re-search-backward re start t)
280 (replace-match "" t t)))))))
283 (defvar diff-font-lock-keywords
284 `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
285 (1 diff-hunk-header-face)
286 (2 diff-function-face))
287 ("^--- .+ ----$" . diff-hunk-header-face) ;context
288 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
289 (1 diff-hunk-header-face)
290 (2 diff-function-face))
291 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
292 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
293 (0 diff-header-face) (2 diff-file-header-face prepend))
294 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face)
295 ("^!.*\n" (0 diff-changed-face))
296 ("^[+>].*\n" (0 diff-added-face))
297 ("^[-<].*\n" (0 diff-removed-face))
298 ("^Index: \\(.+\\).*\n" (0 diff-header-face) (1 diff-index-face prepend))
299 ("^Only in .*\n" . diff-nonexistent-face)
300 ("^#.*" . font-lock-string-face)
301 ("^[^-=+*!<>].*\n" (0 diff-context-face))))
303 (defconst diff-font-lock-defaults
304 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
306 (defvar diff-imenu-generic-expression
307 ;; Prefer second name as first is most likely to be a backup or
308 ;; version-control name. The [\t\n] at the end of the unidiff pattern
309 ;; catches Debian source diff files (which lack the trailing date).
310 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
311 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
313 ;;;;
314 ;;;; Movement
315 ;;;;
317 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
318 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
319 (defvar diff-narrowed-to nil)
321 (defun diff-end-of-hunk (&optional style)
322 (when (looking-at diff-hunk-header-re)
323 (unless style
324 ;; Especially important for unified (because headers are ambiguous).
325 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context))))))
326 (goto-char (match-end 0)))
327 (let ((end (and (re-search-forward (case style
328 ;; A `unified' header is ambiguous.
329 (unified (concat "^[^-+# \\]\\|"
330 diff-file-header-re))
331 (context "^[^-+#! \\]")
332 (normal "^[^<>#\\]")
333 (t "^[^-+#!<> \\]"))
334 nil t)
335 (match-beginning 0))))
336 ;; The return value is used by easy-mmode-define-navigation.
337 (goto-char (or end (point-max)))))
339 (defun diff-beginning-of-hunk ()
340 (beginning-of-line)
341 (unless (looking-at diff-hunk-header-re)
342 (forward-line 1)
343 (condition-case ()
344 (re-search-backward diff-hunk-header-re)
345 (error (error "Can't find the beginning of the hunk")))))
347 (defun diff-beginning-of-file ()
348 (beginning-of-line)
349 (unless (looking-at diff-file-header-re)
350 (forward-line 2)
351 (condition-case ()
352 (re-search-backward diff-file-header-re)
353 (error (error "Can't find the beginning of the file")))))
355 (defun diff-end-of-file ()
356 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
357 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
358 nil 'move)
359 (if (match-beginning 1)
360 (goto-char (match-beginning 1))
361 (beginning-of-line)))
363 ;; Define diff-{hunk,file}-{prev,next}
364 (easy-mmode-define-navigation
365 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
366 (easy-mmode-define-navigation
367 diff-file diff-file-header-re "file" diff-end-of-hunk)
369 (defun diff-restrict-view (&optional arg)
370 "Restrict the view to the current hunk.
371 If the prefix ARG is given, restrict the view to the current file instead."
372 (interactive "P")
373 (save-excursion
374 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk))
375 (narrow-to-region (point)
376 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
377 (point)))
378 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
381 (defun diff-hunk-kill ()
382 "Kill current hunk."
383 (interactive)
384 (diff-beginning-of-hunk)
385 (let* ((start (point))
386 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
387 (match-beginning 0)))
388 (firsthunk (ignore-errors
389 (goto-char start)
390 (diff-beginning-of-file) (diff-hunk-next) (point)))
391 (nextfile (ignore-errors (diff-file-next) (point))))
392 (goto-char start)
393 (if (and firsthunk (= firsthunk start)
394 (or (null nexthunk)
395 (and nextfile (> nexthunk nextfile))))
396 ;; It's the only hunk for this file, so kill the file.
397 (diff-file-kill)
398 (diff-end-of-hunk)
399 (kill-region start (point)))))
401 (defun diff-file-kill ()
402 "Kill current file's hunks."
403 (interactive)
404 (diff-beginning-of-file)
405 (let* ((start (point))
406 (prevhunk (save-excursion
407 (ignore-errors
408 (diff-hunk-prev) (point))))
409 (index (save-excursion
410 (re-search-backward "^Index: " prevhunk t))))
411 (when index (setq start index))
412 (diff-end-of-file)
413 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
414 (kill-region start (point))))
416 (defun diff-kill-junk ()
417 "Kill spurious empty diffs."
418 (interactive)
419 (save-excursion
420 (let ((inhibit-read-only t))
421 (goto-char (point-min))
422 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
423 "\\([^-+!* <>].*\n\\)*?"
424 "\\(\\(Index:\\) \\|"
425 diff-file-header-re "\\)")
426 nil t)
427 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
428 (match-beginning 3))
429 (beginning-of-line)))))
431 (defun diff-count-matches (re start end)
432 (save-excursion
433 (let ((n 0))
434 (goto-char start)
435 (while (re-search-forward re end t) (incf n))
436 n)))
438 (defun diff-split-hunk ()
439 "Split the current (unified diff) hunk at point into two hunks."
440 (interactive)
441 (beginning-of-line)
442 (let ((pos (point))
443 (start (progn (diff-beginning-of-hunk) (point))))
444 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
445 (error "diff-split-hunk only works on unified context diffs"))
446 (forward-line 1)
447 (let* ((start1 (string-to-number (match-string 1)))
448 (start2 (string-to-number (match-string 2)))
449 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
450 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos))))
451 (goto-char pos)
452 ;; Hopefully the after-change-function will not screw us over.
453 (insert "@@ -" (number-to-string newstart1) ",1 +"
454 (number-to-string newstart2) ",1 @@\n")
455 ;; Fix the original hunk-header.
456 (diff-fixup-modifs start pos))))
459 ;;;;
460 ;;;; jump to other buffers
461 ;;;;
463 (defvar diff-remembered-files-alist nil)
465 (defun diff-filename-drop-dir (file)
466 (when (string-match "/" file) (substring file (match-end 0))))
468 (defun diff-merge-strings (ancestor from to)
469 "Merge the diff between ANCESTOR and FROM into TO.
470 Returns the merged string if successful or nil otherwise.
471 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
472 If ANCESTOR = FROM, returns TO.
473 If ANCESTOR = TO, returns FROM.
474 The heuristic is simplistic and only really works for cases
475 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
476 ;; Ideally, we want:
477 ;; AMB ANB CMD -> CND
478 ;; but that's ambiguous if `foo' or `bar' is empty:
479 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
480 (let ((str (concat ancestor "\n" from "\n" to)))
481 (when (and (string-match (concat
482 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
483 "\\1\\(.*\\)\\3\n"
484 "\\(.*\\(\\2\\).*\\)\\'") str)
485 (equal to (match-string 5 str)))
486 (concat (substring str (match-beginning 5) (match-beginning 6))
487 (match-string 4 str)
488 (substring str (match-end 6) (match-end 5))))))
490 (defun diff-tell-file-name (old name)
491 "Tell Emacs where the find the source file of the current hunk.
492 If the OLD prefix arg is passed, tell the file NAME of the old file."
493 (interactive
494 (let* ((old current-prefix-arg)
495 (fs (diff-hunk-file-names current-prefix-arg)))
496 (unless fs (error "No file name to look for"))
497 (list old (read-file-name (format "File for %s: " (car fs))
498 nil (diff-find-file-name old) t))))
499 (let ((fs (diff-hunk-file-names old)))
500 (unless fs (error "No file name to look for"))
501 (push (cons fs name) diff-remembered-files-alist)))
503 (defun diff-hunk-file-names (&optional old)
504 "Give the list of file names textually mentioned for the current hunk."
505 (save-excursion
506 (unless (looking-at diff-file-header-re)
507 (or (ignore-errors (diff-beginning-of-file))
508 (re-search-forward diff-file-header-re nil t)))
509 (let ((limit (save-excursion
510 (condition-case ()
511 (progn (diff-hunk-prev) (point))
512 (error (point-min)))))
513 (header-files
514 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
515 (list (if old (match-string 1) (match-string 3))
516 (if old (match-string 3) (match-string 1)))
517 (forward-line 1) nil)))
518 (delq nil
519 (append
520 (when (and (not old)
521 (save-excursion
522 (re-search-backward "^Index: \\(.+\\)" limit t)))
523 (list (match-string 1)))
524 header-files
525 (when (re-search-backward
526 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
527 nil t)
528 (list (if old (match-string 2) (match-string 4))
529 (if old (match-string 4) (match-string 2)))))))))
531 (defun diff-find-file-name (&optional old)
532 "Return the file corresponding to the current patch.
533 Non-nil OLD means that we want the old file."
534 (save-excursion
535 (unless (looking-at diff-file-header-re)
536 (or (ignore-errors (diff-beginning-of-file))
537 (re-search-forward diff-file-header-re nil t)))
538 (let ((fs (diff-hunk-file-names old)))
540 ;; use any previously used preference
541 (cdr (assoc fs diff-remembered-files-alist))
542 ;; try to be clever and use previous choices as an inspiration
543 (dolist (rf diff-remembered-files-alist)
544 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
545 (if (and newfile (file-exists-p newfile)) (return newfile))))
546 ;; look for each file in turn. If none found, try again but
547 ;; ignoring the first level of directory, ...
548 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
549 (file nil nil))
550 ((or (null files)
551 (setq file (do* ((files files (cdr files))
552 (file (car files) (car files)))
553 ((or (null file) (file-exists-p file))
554 file))))
555 file))
556 ;; <foo>.rej patches implicitly apply to <foo>
557 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
558 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
559 (when (file-exists-p file) file)))
560 ;; if all else fails, ask the user
561 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
562 nil (first fs) t (first fs))))
563 (set (make-local-variable 'diff-remembered-files-alist)
564 (cons (cons fs file) diff-remembered-files-alist))
565 file)))))
568 (defun diff-ediff-patch ()
569 "Call `ediff-patch-file' on the current buffer."
570 (interactive)
571 (condition-case err
572 (ediff-patch-file nil (current-buffer))
573 (wrong-number-of-arguments (ediff-patch-file))))
575 ;;;;
576 ;;;; Conversion functions
577 ;;;;
579 ;;(defvar diff-inhibit-after-change nil
580 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
582 (defun diff-unified->context (start end)
583 "Convert unified diffs to context diffs.
584 START and END are either taken from the region (if a prefix arg is given) or
585 else cover the whole bufer."
586 (interactive (if current-prefix-arg
587 (list (mark) (point))
588 (list (point-min) (point-max))))
589 (unless (markerp end) (setq end (copy-marker end)))
590 (let (;;(diff-inhibit-after-change t)
591 (inhibit-read-only t))
592 (save-excursion
593 (goto-char start)
594 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
595 (< (point) end))
596 (combine-after-change-calls
597 (if (match-beginning 2)
598 ;; we matched a file header
599 (progn
600 ;; use reverse order to make sure the indices are kept valid
601 (replace-match "---" t t nil 3)
602 (replace-match "***" t t nil 2))
603 ;; we matched a hunk header
604 (let ((line1 (match-string 4))
605 (lines1 (match-string 5))
606 (line2 (match-string 6))
607 (lines2 (match-string 7)))
608 (replace-match
609 (concat "***************\n*** " line1 ","
610 (number-to-string (+ (string-to-number line1)
611 (string-to-number lines1)
612 -1)) " ****"))
613 (forward-line 1)
614 (save-restriction
615 (narrow-to-region (point)
616 (progn (diff-end-of-hunk 'unified) (point)))
617 (let ((hunk (buffer-string)))
618 (goto-char (point-min))
619 (if (not (save-excursion (re-search-forward "^-" nil t)))
620 (delete-region (point) (point-max))
621 (goto-char (point-max))
622 (let ((modif nil) last-pt)
623 (while (progn (setq last-pt (point))
624 (= (forward-line -1) 0))
625 (case (char-after)
626 (? (insert " ") (setq modif nil) (backward-char 1))
627 (?+ (delete-region (point) last-pt) (setq modif t))
628 (?- (if (not modif)
629 (progn (forward-char 1)
630 (insert " "))
631 (delete-char 1)
632 (insert "! "))
633 (backward-char 2))
634 (?\\ (when (save-excursion (forward-line -1)
635 (= (char-after) ?+))
636 (delete-region (point) last-pt) (setq modif t)))
637 (t (setq modif nil))))))
638 (goto-char (point-max))
639 (save-excursion
640 (insert "--- " line2 ","
641 (number-to-string (+ (string-to-number line2)
642 (string-to-number lines2)
643 -1)) " ----\n" hunk))
644 ;;(goto-char (point-min))
645 (forward-line 1)
646 (if (not (save-excursion (re-search-forward "^+" nil t)))
647 (delete-region (point) (point-max))
648 (let ((modif nil) (delete nil))
649 (while (not (eobp))
650 (case (char-after)
651 (? (insert " ") (setq modif nil) (backward-char 1))
652 (?- (setq delete t) (setq modif t))
653 (?+ (if (not modif)
654 (progn (forward-char 1)
655 (insert " "))
656 (delete-char 1)
657 (insert "! "))
658 (backward-char 2))
659 (?\\ (when (save-excursion (forward-line 1)
660 (not (eobp)))
661 (setq delete t) (setq modif t)))
662 (t (setq modif nil)))
663 (let ((last-pt (point)))
664 (forward-line 1)
665 (when delete
666 (delete-region last-pt (point))
667 (setq delete nil)))))))))))))))
669 (defun diff-context->unified (start end)
670 "Convert context diffs to unified diffs.
671 START and END are either taken from the region (if a prefix arg is given) or
672 else cover the whole bufer."
673 (interactive (if current-prefix-arg
674 (list (mark) (point))
675 (list (point-min) (point-max))))
676 (unless (markerp end) (setq end (copy-marker end)))
677 (let (;;(diff-inhibit-after-change t)
678 (inhibit-read-only t))
679 (save-excursion
680 (goto-char start)
681 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
682 (< (point) end))
683 (combine-after-change-calls
684 (if (match-beginning 2)
685 ;; we matched a file header
686 (progn
687 ;; use reverse order to make sure the indices are kept valid
688 (replace-match "+++" t t nil 3)
689 (replace-match "---" t t nil 2))
690 ;; we matched a hunk header
691 (let ((line1s (match-string 4))
692 (line1e (match-string 5))
693 (pt1 (match-beginning 0)))
694 (replace-match "")
695 (unless (re-search-forward
696 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
697 (error "Can't find matching `--- n1,n2 ----' line"))
698 (let ((line2s (match-string 1))
699 (line2e (match-string 2))
700 (pt2 (progn
701 (delete-region (progn (beginning-of-line) (point))
702 (progn (forward-line 1) (point)))
703 (point-marker))))
704 (goto-char pt1)
705 (forward-line 1)
706 (while (< (point) pt2)
707 (case (char-after)
708 ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
709 (?\ ;merge with the other half of the chunk
710 (let* ((endline2
711 (save-excursion
712 (goto-char pt2) (forward-line 1) (point)))
713 (c (char-after pt2)))
714 (case c
715 ((?! ?+)
716 (insert "+"
717 (prog1 (buffer-substring (+ pt2 2) endline2)
718 (delete-region pt2 endline2))))
719 (?\ ;FIXME: check consistency
720 (delete-region pt2 endline2)
721 (delete-char 1)
722 (forward-line 1))
723 (?\\ (forward-line 1))
724 (t (delete-char 1) (forward-line 1)))))
725 (t (forward-line 1))))
726 (while (looking-at "[+! ] ")
727 (if (/= (char-after) ?!) (forward-char 1)
728 (delete-char 1) (insert "+"))
729 (delete-char 1) (forward-line 1))
730 (save-excursion
731 (goto-char pt1)
732 (insert "@@ -" line1s ","
733 (number-to-string (- (string-to-number line1e)
734 (string-to-number line1s)
735 -1))
736 " +" line2s ","
737 (number-to-string (- (string-to-number line2e)
738 (string-to-number line2s)
739 -1)) " @@"))))))))))
741 (defun diff-reverse-direction (start end)
742 "Reverse the direction of the diffs.
743 START and END are either taken from the region (if a prefix arg is given) or
744 else cover the whole bufer."
745 (interactive (if current-prefix-arg
746 (list (mark) (point))
747 (list (point-min) (point-max))))
748 (unless (markerp end) (setq end (copy-marker end)))
749 (let (;;(diff-inhibit-after-change t)
750 (inhibit-read-only t))
751 (save-excursion
752 (goto-char start)
753 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
754 (< (point) end))
755 (combine-after-change-calls
756 (cond
757 ;; a file header
758 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
759 ;; a context-diff hunk header
760 ((match-beginning 6)
761 (let ((pt-lines1 (match-beginning 6))
762 (lines1 (match-string 6)))
763 (replace-match "" nil nil nil 6)
764 (forward-line 1)
765 (let ((half1s (point)))
766 (while (looking-at "[-! \\][ \t]\\|#")
767 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
768 (forward-line 1))
769 (let ((half1 (delete-and-extract-region half1s (point))))
770 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
771 (insert half1)
772 (error "Can't find matching `--- n1,n2 ----' line"))
773 (let ((str1 (match-string 1)))
774 (replace-match lines1 nil nil nil 1)
775 (forward-line 1)
776 (let ((half2s (point)))
777 (while (looking-at "[!+ \\][ \t]\\|#")
778 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
779 (forward-line 1))
780 (let ((half2 (delete-and-extract-region half2s (point))))
781 (insert (or half1 ""))
782 (goto-char half1s)
783 (insert (or half2 ""))))
784 (goto-char pt-lines1)
785 (insert str1))))))
786 ;; a unified-diff hunk header
787 ((match-beginning 7)
788 (replace-match "@@ -\\8 +\\7 @@" nil)
789 (forward-line 1)
790 (let ((c (char-after)) first last)
791 (while (case (setq c (char-after))
792 (?- (setq first (or first (point)))
793 (delete-char 1) (insert "+") t)
794 (?+ (setq last (or last (point)))
795 (delete-char 1) (insert "-") t)
796 ((?\\ ?#) t)
797 (t (when (and first last (< first last))
798 (insert (delete-and-extract-region first last)))
799 (setq first nil last nil)
800 (equal ?\ c)))
801 (forward-line 1))))))))))
803 (defun diff-fixup-modifs (start end)
804 "Fixup the hunk headers (in case the buffer was modified).
805 START and END are either taken from the region (if a prefix arg is given) or
806 else cover the whole bufer."
807 (interactive (if current-prefix-arg
808 (list (mark) (point))
809 (list (point-min) (point-max))))
810 (let ((inhibit-read-only t))
811 (save-excursion
812 (goto-char end) (diff-end-of-hunk)
813 (let ((plus 0) (minus 0) (space 0) (bang 0))
814 (while (and (= (forward-line -1) 0) (<= start (point)))
815 (if (not (looking-at
816 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
817 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
818 "\\|--- .+\n\\+\\+\\+ ")))
819 (case (char-after)
820 (?\s (incf space))
821 (?+ (incf plus))
822 (?- (incf minus))
823 (?! (incf bang))
824 ((?\\ ?#) nil)
825 (t (setq space 0 plus 0 minus 0 bang 0)))
826 (cond
827 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
828 (let* ((old1 (match-string 1))
829 (old2 (match-string 2))
830 (new1 (number-to-string (+ space minus)))
831 (new2 (number-to-string (+ space plus))))
832 (unless (string= new2 old2) (replace-match new2 t t nil 2))
833 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
834 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
835 (when (> (+ space bang plus) 0)
836 (let* ((old1 (match-string 1))
837 (old2 (match-string 2))
838 (new (number-to-string
839 (+ space bang plus -1 (string-to-number old1)))))
840 (unless (string= new old2) (replace-match new t t nil 2)))))
841 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
842 (when (> (+ space bang minus) 0)
843 (let* ((old (match-string 1))
844 (new (format
845 (concat "%0" (number-to-string (length old)) "d")
846 (+ space bang minus -1 (string-to-number old)))))
847 (unless (string= new old) (replace-match new t t nil 2))))))
848 (setq space 0 plus 0 minus 0 bang 0)))))))
850 ;;;;
851 ;;;; Hooks
852 ;;;;
854 (defun diff-write-contents-hooks ()
855 "Fixup hunk headers if necessary."
856 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
857 nil)
859 ;; It turns out that making changes in the buffer from within an
860 ;; *-change-function is asking for trouble, whereas making them
861 ;; from a post-command-hook doesn't pose much problems
862 (defvar diff-unhandled-changes nil)
863 (defun diff-after-change-function (beg end len)
864 "Remember to fixup the hunk header.
865 See `after-change-functions' for the meaning of BEG, END and LEN."
866 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
867 ;; incorrect, but it turns out that inhibit-read-only is normally not set
868 ;; inside editing commands, while it tends to be set when the buffer gets
869 ;; updated by an async process or by a conversion function, both of which
870 ;; would rather not be uselessly slowed down by this hook.
871 (when (and (not undo-in-progress) (not inhibit-read-only))
872 (if diff-unhandled-changes
873 (setq diff-unhandled-changes
874 (cons (min beg (car diff-unhandled-changes))
875 (max end (cdr diff-unhandled-changes))))
876 (setq diff-unhandled-changes (cons beg end)))))
878 (defun diff-post-command-hook ()
879 "Fixup hunk headers if necessary."
880 (when (consp diff-unhandled-changes)
881 (ignore-errors
882 (save-excursion
883 (goto-char (car diff-unhandled-changes))
884 ;; Maybe we've cut the end of the hunk before point.
885 (if (and (bolp) (not (bobp))) (backward-char 1))
886 ;; We used to fixup modifs on all the changes, but it turns out
887 ;; that it's safer not to do it on big changes, for example
888 ;; when yanking a big diff, since we might then screw up perfectly
889 ;; correct values. -stef
890 ;; (unless (ignore-errors
891 ;; (diff-beginning-of-hunk)
892 ;; (save-excursion
893 ;; (diff-end-of-hunk)
894 ;; (> (point) (car diff-unhandled-changes))))
895 ;; (goto-char (car diff-unhandled-changes))
896 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
897 ;; (diff-beginning-of-hunk))
898 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
899 (diff-beginning-of-hunk)
900 (when (save-excursion
901 (diff-end-of-hunk)
902 (>= (point) (cdr diff-unhandled-changes)))
903 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
904 (setq diff-unhandled-changes nil)))
906 (defun diff-next-error (arg reset)
907 ;; Select a window that displays the current buffer so that point
908 ;; movements are reflected in that window. Otherwise, the user might
909 ;; never see the hunk corresponding to the source she's jumping to.
910 (pop-to-buffer (current-buffer))
911 (if reset (goto-char (point-min)))
912 (diff-hunk-next arg)
913 (diff-goto-source))
915 ;;;###autoload
916 (define-derived-mode diff-mode fundamental-mode "Diff"
917 "Major mode for viewing/editing context diffs.
918 Supports unified and context diffs as well as (to a lesser extent)
919 normal diffs.
920 When the buffer is read-only, the ESC prefix is not necessary.
921 IF you edit the buffer manually, diff-mode will try to update the hunk
922 headers for you on-the-fly.
924 You can also switch between context diff and unified diff with \\[diff-context->unified],
925 or vice versa with \\[diff-unified->context] and you can also revert the direction of
926 a diff with \\[diff-reverse-direction]."
927 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
928 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
929 (set (make-local-variable 'imenu-generic-expression)
930 diff-imenu-generic-expression)
931 ;; These are not perfect. They would be better done separately for
932 ;; context diffs and unidiffs.
933 ;; (set (make-local-variable 'paragraph-start)
934 ;; (concat "@@ " ; unidiff hunk
935 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
936 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
937 ;; ; start (first or second line)
938 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
939 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
940 ;; compile support
941 (set (make-local-variable 'next-error-function) 'diff-next-error)
943 (when (and (> (point-max) (point-min)) diff-default-read-only)
944 (toggle-read-only t))
945 ;; setup change hooks
946 (if (not diff-update-on-the-fly)
947 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
948 (make-local-variable 'diff-unhandled-changes)
949 (add-hook 'after-change-functions 'diff-after-change-function nil t)
950 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
951 ;; Neat trick from Dave Love to add more bindings in read-only mode:
952 (let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
953 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
954 ;; Turn off this little trick in case the buffer is put in view-mode.
955 (add-hook 'view-mode-hook
956 `(lambda ()
957 (setq minor-mode-overriding-map-alist
958 (delq ',ro-bind minor-mode-overriding-map-alist)))
959 nil t))
960 ;; add-log support
961 (set (make-local-variable 'add-log-current-defun-function)
962 'diff-current-defun)
963 (set (make-local-variable 'add-log-buffer-file-name-function)
964 'diff-find-file-name))
966 ;;;###autoload
967 (define-minor-mode diff-minor-mode
968 "Minor mode for viewing/editing context diffs.
969 \\{diff-minor-mode-map}"
970 :group 'diff-mode :lighter " Diff"
971 ;; FIXME: setup font-lock
972 ;; setup change hooks
973 (if (not diff-update-on-the-fly)
974 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
975 (make-local-variable 'diff-unhandled-changes)
976 (add-hook 'after-change-functions 'diff-after-change-function nil t)
977 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
979 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
981 (defun diff-delete-if-empty ()
982 ;; An empty diff file means there's no more diffs to integrate, so we
983 ;; can just remove the file altogether. Very handy for .rej files if we
984 ;; remove hunks as we apply them.
985 (when (and buffer-file-name
986 (eq 0 (nth 7 (file-attributes buffer-file-name))))
987 (delete-file buffer-file-name)))
989 (defun diff-delete-empty-files ()
990 "Arrange for empty diff files to be removed."
991 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
993 (defun diff-make-unified ()
994 "Turn context diffs into unified diffs if applicable."
995 (if (save-excursion
996 (goto-char (point-min))
997 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
998 (let ((mod (buffer-modified-p)))
999 (unwind-protect
1000 (diff-context->unified (point-min) (point-max))
1001 (restore-buffer-modified-p mod)))))
1004 ;;; Misc operations that have proved useful at some point.
1007 (defun diff-next-complex-hunk ()
1008 "Jump to the next \"complex\" hunk.
1009 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1010 Only works for unified diffs."
1011 (interactive)
1012 (while
1013 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1014 nil t)
1015 (equal (match-string 1) (match-string 2)))))
1017 (defun diff-hunk-text (hunk destp char-offset)
1018 "Return the literal source text from HUNK as (TEXT . OFFSET).
1019 if DESTP is nil TEXT is the source, otherwise the destination text.
1020 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1021 char-offset in TEXT."
1022 (with-temp-buffer
1023 (insert hunk)
1024 (goto-char (point-min))
1025 (let ((src-pos nil)
1026 (dst-pos nil)
1027 (divider-pos nil)
1028 (num-pfx-chars 2))
1029 ;; Set the following variables:
1030 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1031 ;; DST-POS buffer pos of the destination part of the hunk or nil
1032 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1033 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1034 (cond ((looking-at "^@@")
1035 ;; unified diff
1036 (setq num-pfx-chars 1)
1037 (forward-line 1)
1038 (setq src-pos (point) dst-pos (point)))
1039 ((looking-at "^\\*\\*")
1040 ;; context diff
1041 (forward-line 2)
1042 (setq src-pos (point))
1043 (re-search-forward "^--- " nil t)
1044 (forward-line 0)
1045 (setq divider-pos (point))
1046 (forward-line 1)
1047 (setq dst-pos (point)))
1048 ((looking-at "^[0-9]+a[0-9,]+$")
1049 ;; normal diff, insert
1050 (forward-line 1)
1051 (setq dst-pos (point)))
1052 ((looking-at "^[0-9,]+d[0-9]+$")
1053 ;; normal diff, delete
1054 (forward-line 1)
1055 (setq src-pos (point)))
1056 ((looking-at "^[0-9,]+c[0-9,]+$")
1057 ;; normal diff, change
1058 (forward-line 1)
1059 (setq src-pos (point))
1060 (re-search-forward "^---$" nil t)
1061 (forward-line 0)
1062 (setq divider-pos (point))
1063 (forward-line 1)
1064 (setq dst-pos (point)))
1066 (error "Unknown diff hunk type")))
1068 (if (if destp (null dst-pos) (null src-pos))
1069 ;; Implied empty text
1070 (if char-offset '("" . 0) "")
1072 ;; For context diffs, either side can be empty, (if there's only
1073 ;; added or only removed text). We should then use the other side.
1074 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1075 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1077 (when char-offset (goto-char (+ (point-min) char-offset)))
1079 ;; Get rid of anything except the desired text.
1080 (save-excursion
1081 ;; Delete unused text region
1082 (let ((keep (if destp dst-pos src-pos)))
1083 (when (and divider-pos (> divider-pos keep))
1084 (delete-region divider-pos (point-max)))
1085 (delete-region (point-min) keep))
1086 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1087 (let ((kill-char (if destp ?- ?+)))
1088 (goto-char (point-min))
1089 (while (not (eobp))
1090 (if (eq (char-after) kill-char)
1091 (delete-region (point) (progn (forward-line 1) (point)))
1092 (delete-char num-pfx-chars)
1093 (forward-line 1)))))
1095 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1096 (if char-offset (cons text (- (point) (point-min))) text))))))
1099 (defun diff-find-text (text)
1100 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1101 If TEXT isn't found, nil is returned."
1102 (let* ((orig (point))
1103 (forw (and (search-forward text nil t)
1104 (cons (match-beginning 0) (match-end 0))))
1105 (back (and (goto-char (+ orig (length text)))
1106 (search-backward text nil t)
1107 (cons (match-beginning 0) (match-end 0)))))
1108 ;; Choose the closest match.
1109 (if (and forw back)
1110 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1111 (or back forw))))
1113 (defun diff-find-approx-text (text)
1114 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1115 Whitespace differences are ignored."
1116 (let* ((orig (point))
1117 (re (concat "^[ \t\n\f]*"
1118 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1119 "[ \t\n\f]*\n"))
1120 (forw (and (re-search-forward re nil t)
1121 (cons (match-beginning 0) (match-end 0))))
1122 (back (and (goto-char (+ orig (length text)))
1123 (re-search-backward re nil t)
1124 (cons (match-beginning 0) (match-end 0)))))
1125 ;; Choose the closest match.
1126 (if (and forw back)
1127 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1128 (or back forw))))
1130 (defsubst diff-xor (a b) (if a (not b) b))
1132 (defun diff-find-source-location (&optional other-file reverse)
1133 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1134 BUF is the buffer corresponding to the source file.
1135 LINE-OFFSET is the offset between the expected and actual positions
1136 of the text of the hunk or nil if the text was not found.
1137 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1138 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1139 SRC is the variant that was found in the buffer.
1140 SWITCHED is non-nil if the patch is already applied."
1141 (save-excursion
1142 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1143 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1144 (hunk (buffer-substring (point)
1145 (save-excursion (diff-end-of-hunk) (point))))
1146 (old (diff-hunk-text hunk reverse char-offset))
1147 (new (diff-hunk-text hunk (not reverse) char-offset))
1148 ;; Find the location specification.
1149 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1150 (error "Can't find the hunk header")
1151 (if other (match-string 1)
1152 (if (match-end 3) (match-string 3)
1153 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1154 (error "Can't find the hunk separator"))
1155 (match-string 1)))))
1156 (file (or (diff-find-file-name other) (error "Can't find the file")))
1157 (buf (find-file-noselect file)))
1158 ;; Update the user preference if he so wished.
1159 (when (> (prefix-numeric-value other-file) 8)
1160 (setq diff-jump-to-old-file other))
1161 (with-current-buffer buf
1162 (goto-line (string-to-number line))
1163 (let* ((orig-pos (point))
1164 (switched nil)
1165 ;; FIXME: Check for case where both OLD and NEW are found.
1166 (pos (or (diff-find-text (car old))
1167 (progn (setq switched t) (diff-find-text (car new)))
1168 (progn (setq switched nil)
1169 (condition-case nil
1170 (diff-find-approx-text (car old))
1171 (invalid-regexp nil))) ;Regex too big.
1172 (progn (setq switched t)
1173 (condition-case nil
1174 (diff-find-approx-text (car new))
1175 (invalid-regexp nil))) ;Regex too big.
1176 (progn (setq switched nil) nil))))
1177 (nconc
1178 (list buf)
1179 (if pos
1180 (list (count-lines orig-pos (car pos)) pos)
1181 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1182 (if switched (list new old t) (list old new))))))))
1185 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1186 (let ((msg (if dry-run
1187 (if reversed "already applied" "not yet applied")
1188 (if reversed "undone" "applied"))))
1189 (message (cond ((null line-offset) "Hunk text not found")
1190 ((= line-offset 0) "Hunk %s")
1191 ((= line-offset 1) "Hunk %s at offset %d line")
1192 (t "Hunk %s at offset %d lines"))
1193 msg line-offset)))
1196 (defun diff-apply-hunk (&optional reverse)
1197 "Apply the current hunk to the source file and go to the next.
1198 By default, the new source file is patched, but if the variable
1199 `diff-jump-to-old-file' is non-nil, then the old source file is
1200 patched instead (some commands, such as `diff-goto-source' can change
1201 the value of this variable when given an appropriate prefix argument).
1203 With a prefix argument, REVERSE the hunk."
1204 (interactive "P")
1205 (destructuring-bind (buf line-offset pos old new &optional switched)
1206 ;; If REVERSE go to the new file, otherwise go to the old.
1207 (diff-find-source-location (not reverse) reverse)
1208 (cond
1209 ((null line-offset)
1210 (error "Can't find the text to patch"))
1211 ((and switched
1212 ;; A reversed patch was detected, perhaps apply it in reverse.
1213 (not (save-window-excursion
1214 (pop-to-buffer buf)
1215 (goto-char (+ (car pos) (cdr old)))
1216 (y-or-n-p
1217 (if reverse
1218 "Hunk hasn't been applied yet; apply it now? "
1219 "Hunk has already been applied; undo it? ")))))
1220 (message "(Nothing done)"))
1222 ;; Apply the hunk
1223 (with-current-buffer buf
1224 (goto-char (car pos))
1225 (delete-region (car pos) (cdr pos))
1226 (insert (car new)))
1227 ;; Display BUF in a window
1228 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1229 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1230 (when diff-advance-after-apply-hunk
1231 (diff-hunk-next))))))
1234 (defun diff-test-hunk (&optional reverse)
1235 "See whether it's possible to apply the current hunk.
1236 With a prefix argument, try to REVERSE the hunk."
1237 (interactive "P")
1238 (destructuring-bind (buf line-offset pos src dst &optional switched)
1239 ;; If REVERSE go to the new file, otherwise go to the old.
1240 (diff-find-source-location (not reverse) reverse)
1241 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1242 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1245 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1247 (defun diff-goto-source (&optional other-file event)
1248 "Jump to the corresponding source line.
1249 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1250 is given) determines whether to jump to the old or the new file.
1251 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1252 then `diff-jump-to-old-file' is also set, for the next invocations."
1253 (interactive (list current-prefix-arg last-input-event))
1254 ;; When pointing at a removal line, we probably want to jump to
1255 ;; the old location, and else to the new (i.e. as if reverting).
1256 ;; This is a convenient detail when using smerge-diff.
1257 (if event (posn-set-point (event-end event)))
1258 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1259 (destructuring-bind (buf line-offset pos src dst &optional switched)
1260 (diff-find-source-location other-file rev)
1261 (pop-to-buffer buf)
1262 (goto-char (+ (car pos) (cdr src)))
1263 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1266 (defun diff-current-defun ()
1267 "Find the name of function at point.
1268 For use in `add-log-current-defun-function'."
1269 (save-excursion
1270 (when (looking-at diff-hunk-header-re)
1271 (forward-line 1)
1272 (re-search-forward "^[^ ]" nil t))
1273 (destructuring-bind (buf line-offset pos src dst &optional switched)
1274 (diff-find-source-location)
1275 (beginning-of-line)
1276 (or (when (memq (char-after) '(?< ?-))
1277 ;; Cursor is pointing at removed text. This could be a removed
1278 ;; function, in which case, going to the source buffer will
1279 ;; not help since the function is now removed. Instead,
1280 ;; try to figure out the function name just from the code-fragment.
1281 (let ((old (if switched dst src)))
1282 (with-temp-buffer
1283 (insert (car old))
1284 (funcall (with-current-buffer buf major-mode))
1285 (goto-char (+ (point-min) (cdr old)))
1286 (add-log-current-defun))))
1287 (with-current-buffer buf
1288 (goto-char (+ (car pos) (cdr src)))
1289 (add-log-current-defun))))))
1291 (defun diff-refine-hunk ()
1292 "Refine the current hunk by ignoring space differences."
1293 (interactive)
1294 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1295 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1296 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1297 (error "Can't find line number"))
1298 (string-to-number (match-string 1))))
1299 (hunk (delete-and-extract-region
1300 (point) (save-excursion (diff-end-of-hunk) (point))))
1301 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1302 (file1 (make-temp-file "diff1"))
1303 (file2 (make-temp-file "diff2"))
1304 (coding-system-for-read buffer-file-coding-system)
1305 old new)
1306 (unwind-protect
1307 (save-excursion
1308 (setq old (diff-hunk-text hunk nil char-offset))
1309 (setq new (diff-hunk-text hunk t char-offset))
1310 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1311 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1312 (with-temp-buffer
1313 (let ((status
1314 (call-process diff-command nil t nil
1315 opts file1 file2)))
1316 (case status
1317 (0 nil) ;Nothing to reformat.
1318 (1 (goto-char (point-min))
1319 ;; Remove the file-header.
1320 (when (re-search-forward diff-hunk-header-re nil t)
1321 (delete-region (point-min) (match-beginning 0))))
1322 (t (goto-char (point-max))
1323 (unless (bolp) (insert "\n"))
1324 (insert hunk)))
1325 (setq hunk (buffer-string))
1326 (unless (memq status '(0 1))
1327 (error "Diff returned: %s" status)))))
1328 ;; Whatever happens, put back some equivalent text: either the new
1329 ;; one or the original one in case some error happened.
1330 (insert hunk)
1331 (delete-file file1)
1332 (delete-file file2))))
1334 ;; provide the package
1335 (provide 'diff-mode)
1337 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1338 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1339 ;; (diff-mode-load-hook): dropped.
1340 ;; (auto-mode-alist): also catch *.diffs.
1341 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1342 ;; for *.rej files (that lack any file name indication).
1344 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1345 ;; added support for "\ No newline at end of file".
1347 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1348 ;; - added basic `compile' support.
1349 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1350 ;; - diff-kill-file now tries to kill the leading garbage as well.
1352 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1353 ;; - don't use CL in the autoloaded code
1354 ;; - accept diffs using -T
1356 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1357 ;; interface to ediff-patch
1359 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1360 ;; (ediff=patch-file): add bindings to call ediff-patch.
1361 ;; (diff-find-file-name): taken out of diff-goto-source.
1362 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1363 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1365 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1366 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1368 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1369 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1372 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1373 ;;; diff-mode.el ends here