]> code.delx.au - gnu-emacs/blob - lisp/diff-mode.el
(help-make-xrefs): Don't make hyperlinks for incorrect coding systems.
[gnu-emacs] / lisp / diff-mode.el
1 ;;; diff-mode.el --- A mode for viewing/editing context diffs
2
3 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@cs.yale.edu>
6 ;; Keywords: patch diff
7 ;; Revision: $Id: diff-mode.el,v 1.9 2000/08/16 19:56:10 monnier Exp $
8
9 ;; This file is part of GNU Emacs.
10
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.
15
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.
20
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.
25
26 ;;; Commentary:
27
28 ;; Provides support for font-lock patterns, outline-regexps, navigation
29 ;; commands, editing and various conversions as well as jumping
30 ;; to the corresponding source file.
31
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
35
36 ;; to use it, simply add to your .emacs the following lines:
37 ;;
38 ;; (autoload 'diff-mode "diff-mode" "Diff major mode" t)
39 ;; (add-to-list 'auto-mode-alist '("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode))
40
41 ;; Bugs:
42
43 ;; - Reverse doesn't work with normal diffs.
44 ;; - (nitpick) The mark is not always quite right in diff-goto-source.
45 ;; - diff-apply-hunk only works on unified diffs.
46
47 ;; Todo:
48
49 ;; - Add change-log support.
50 ;; - Spice up the minor-mode with font-lock support.
51 ;; - Improve narrowed-view support.
52 ;; - Improve the `compile' support (?).
53 ;; - Recognize pcl-cvs' special string for `cvs-execute-single'.
54 ;; - Support for # comments in context->unified.
55 ;; - Do a fuzzy search in diff-goto-source.
56 ;; - Allow diff.el to use diff-mode.
57 ;; This mostly means ability to jump from half-hunk to half-hunk
58 ;; in context (and normal) diffs and to jump to the corresponding
59 ;; (i.e. new or old) file.
60 ;; - Handle `diff -b' output in context->unified.
61
62 ;;; Code:
63
64 (eval-when-compile (require 'cl))
65
66
67 (defgroup diff-mode ()
68 "Major-mode for viewing/editing diffs"
69 :version "21.1"
70 :group 'tools
71 :group 'diff)
72
73 (defcustom diff-jump-to-old-file-flag nil
74 "*Non-nil means `diff-goto-source' jumps to the old file.
75 Else, it jumps to the new file."
76 :group 'diff-mode
77 :type '(boolean))
78
79 (defcustom diff-update-on-the-fly-flag t
80 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
81 When editing a diff file, the line numbers in the hunk headers
82 need to be kept consistent with the actual diff. This can
83 either be done on the fly (but this sometimes interacts poorly with the
84 undo mechanism) or whenever the file is written (can be slow
85 when editing big diffs)."
86 :group 'diff-mode
87 :type '(boolean))
88
89 (defvar diff-mode-hook nil
90 "Run after setting up the `diff-mode' major mode.")
91
92 (defvar diff-outline-regexp
93 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
94
95 ;;;;
96 ;;;; keymap, menu, ...
97 ;;;;
98
99 (easy-mmode-defmap diff-mode-shared-map
100 '(;; From Pavel Machek's patch-mode.
101 ("n" . diff-hunk-next)
102 ("N" . diff-file-next)
103 ("p" . diff-hunk-prev)
104 ("P" . diff-file-prev)
105 ("k" . diff-hunk-kill)
106 ("K" . diff-file-kill)
107 ;; From compilation-minor-mode.
108 ("}" . diff-file-next)
109 ("{" . diff-file-prev)
110 ("\C-m" . diff-goto-source)
111 ([mouse-2] . diff-mouse-goto-source)
112 ;; From XEmacs' diff-mode.
113 ("W" . widen)
114 ;;("." . diff-goto-source) ;display-buffer
115 ;;("f" . diff-goto-source) ;find-file
116 ("o" . diff-goto-source) ;other-window
117 ;;("w" . diff-goto-source) ;other-frame
118 ;;("N" . diff-narrow)
119 ;;("h" . diff-show-header)
120 ;;("j" . diff-show-difference) ;jump to Nth diff
121 ;;("q" . diff-quit)
122 (" " . scroll-up)
123 ("\177" . scroll-down)
124 ;; Our very own bindings.
125 ("A" . diff-ediff-patch)
126 ("r" . diff-restrict-view)
127 ("R" . diff-reverse-direction)
128 ("U" . diff-context->unified)
129 ("C" . diff-unified->context))
130 "Basic keymap for `diff-mode', bound to various prefix keys.")
131
132 (easy-mmode-defmap diff-mode-map
133 `(("\e" . ,diff-mode-shared-map)
134 ;; From compilation-minor-mode.
135 ("\C-c\C-c" . diff-goto-source)
136 ;; Misc operations.
137 ("\C-cda" . diff-apply-hunk))
138 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
139
140 (easy-menu-define diff-mode-menu diff-mode-map
141 "Menu for `diff-mode'."
142 '("Diff"
143 ["Jump to Source" diff-goto-source t]
144 ["Apply with Ediff" diff-ediff-patch t]
145 ["-----" nil nil]
146 ["Reverse direction" diff-reverse-direction t]
147 ["Context -> Unified" diff-context->unified t]
148 ["Unified -> Context" diff-unified->context t]
149 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
150 ))
151
152 (defcustom diff-minor-mode-prefix "\C-cd"
153 "Prefix key for `diff-minor-mode' commands."
154 :group 'diff-mode
155 :type '(choice (string "\e") (string "C-cd") string))
156
157 (easy-mmode-defmap diff-minor-mode-map
158 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
159 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
160
161
162 ;;;;
163 ;;;; font-lock support
164 ;;;;
165
166 (defface diff-file-header-face
167 '((((class color) (background light))
168 (:background "grey70" :bold t))
169 (t (:bold t)))
170 "diff-mode face used to highlight file header lines."
171 :group 'diff-mode)
172 (defvar diff-file-header-face 'diff-file-header-face)
173
174 (defface diff-index-face
175 '((((class color) (background light))
176 (:background "grey70" :bold t))
177 (t (:bold t)))
178 "diff-mode face used to highlight index header lines."
179 :group 'diff-mode)
180 (defvar diff-index-face 'diff-index-face)
181
182 (defface diff-hunk-header-face
183 '((((class color) (background light))
184 (:background "grey85"))
185 (t (:bold t)))
186 "diff-mode face used to highlight hunk header lines."
187 :group 'diff-mode)
188 (defvar diff-hunk-header-face 'diff-hunk-header-face)
189
190 (defface diff-removed-face
191 '((t ()))
192 "diff-mode face used to highlight removed lines."
193 :group 'diff-mode)
194 (defvar diff-removed-face 'diff-removed-face)
195
196 (defface diff-added-face
197 '((t ()))
198 "diff-mode face used to highlight added lines."
199 :group 'diff-mode)
200 (defvar diff-added-face 'diff-added-face)
201
202 (defface diff-changed-face
203 '((t ()))
204 "diff-mode face used to highlight changed lines."
205 :group 'diff-mode)
206 (defvar diff-changed-face 'diff-changed-face)
207
208 (defvar diff-font-lock-keywords
209 '(("^@@ -[0-9,]+ \\+[0-9,]+ @@.*$" . diff-hunk-header-face) ;unified
210 ("^--- .+ ----$" . diff-hunk-header-face) ;context
211 ("^\\*\\*\\*\\(.+\\*\\*\\*\\|\\*\\{12\\}.*\\)\n" . diff-hunk-header-face) ;context
212 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) .*\n" . diff-file-header-face)
213 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face)
214 ("^!.*\n" . diff-changed-face) ;context
215 ("^[+>].*\n" . diff-added-face)
216 ("^[-<].*\n" . diff-removed-face)
217 ("^Index: .*\n" . diff-index-face)
218 ("^#.*" . font-lock-string-face)
219 ("^[^-=+*!<>].*\n" . font-lock-comment-face)))
220
221 (defconst diff-font-lock-defaults
222 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
223
224 (defvar diff-imenu-generic-expression
225 ;; Prefer second name as first is most likely to be a backup or
226 ;; version-control name.
227 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)\t" 1) ; unidiffs
228 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
229
230 ;;;;
231 ;;;; Compile support
232 ;;;;
233
234 (defvar diff-file-regexp-alist
235 '(("Index: \\(.+\\)" 1)))
236
237 (defvar diff-error-regexp-alist
238 '(("@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@" nil 2)
239 ("--- \\([0-9]+\\),[0-9]+ ----" nil 1)
240 ("\\([0-9]+\\)\\(,[0-9]+\\)?[adc]\\([0-9]+\\)" nil 3)))
241
242 ;;;;
243 ;;;; Movement
244 ;;;;
245
246 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
247 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+\\|\\*\\*\\* .+\n---\\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
248 (defvar diff-narrowed-to nil)
249
250 (defun diff-end-of-hunk (&optional style)
251 (if (looking-at diff-hunk-header-re) (goto-char (match-end 0)))
252 (let ((end (and (re-search-forward (case style
253 (unified "^[^-+# \\]")
254 (context "^[^-+#! \\]")
255 (normal "^[^<>#\\]")
256 (t "^[^-+#!<> \\]"))
257 nil t)
258 (match-beginning 0))))
259 ;; The return value is used by easy-mmode-define-navigation.
260 (goto-char (or end (point-max)))))
261
262 (defun diff-beginning-of-hunk ()
263 (beginning-of-line)
264 (unless (looking-at diff-hunk-header-re)
265 (forward-line 1)
266 (condition-case ()
267 (re-search-backward diff-hunk-header-re)
268 (error (error "Can't find the beginning of the hunk")))))
269
270 (defun diff-beginning-of-file ()
271 (beginning-of-line)
272 (unless (looking-at diff-file-header-re)
273 (forward-line 2)
274 (condition-case ()
275 (re-search-backward diff-file-header-re)
276 (error (error "Can't find the beginning of the file")))))
277
278 (defun diff-end-of-file ()
279 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
280 (re-search-forward "^[^-+#!<>0-9@* \\]" nil 'move)
281 (beginning-of-line))
282
283 ;; Define diff-{hunk,file}-{prev,next}
284 (easy-mmode-define-navigation
285 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk)
286 (easy-mmode-define-navigation
287 diff-file diff-file-header-re "file" diff-end-of-hunk)
288
289 (defun diff-restrict-view (&optional arg)
290 "Restrict the view to the current hunk.
291 If the prefix ARG is given, restrict the view to the current file instead."
292 (interactive "P")
293 (save-excursion
294 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk))
295 (narrow-to-region (point)
296 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
297 (point)))
298 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
299
300
301 (defun diff-hunk-kill ()
302 "Kill current hunk."
303 (interactive)
304 (diff-beginning-of-hunk)
305 (let ((start (point))
306 (firsthunk (save-excursion
307 (ignore-errors
308 (diff-beginning-of-file) (diff-hunk-next) (point))))
309 (nexthunk (save-excursion
310 (ignore-errors
311 (diff-hunk-next) (point))))
312 (nextfile (save-excursion
313 (ignore-errors
314 (diff-file-next) (point)))))
315 (if (and firsthunk (= firsthunk start)
316 (or (null nexthunk)
317 (and nextfile (> nexthunk nextfile))))
318 ;; we're the only hunk for this file, so kill the file
319 (diff-file-kill)
320 (diff-end-of-hunk)
321 (kill-region start (point)))))
322
323 (defun diff-file-kill ()
324 "Kill current file's hunks."
325 (interactive)
326 (diff-beginning-of-file)
327 (let* ((start (point))
328 (prevhunk (save-excursion
329 (ignore-errors
330 (diff-hunk-prev) (point))))
331 (index (save-excursion
332 (re-search-backward "^Index: " prevhunk t))))
333 (when index (setq start index))
334 (diff-end-of-file)
335 (kill-region start (point))))
336
337 (defun diff-kill-junk ()
338 "Kill spurious empty diffs."
339 (interactive)
340 (save-excursion
341 (let ((inhibit-read-only t))
342 (goto-char (point-min))
343 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
344 "\\([^-+!* <>].*\n\\)*?"
345 "\\(\\(Index:\\) \\|"
346 diff-file-header-re "\\)")
347 nil t)
348 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
349 (match-beginning 3))
350 (beginning-of-line)))))
351
352 ;;;;
353 ;;;; jump to other buffers
354 ;;;;
355
356 (defvar diff-remembered-files-alist nil)
357
358 (defun diff-filename-drop-dir (file)
359 (when (string-match "/" file) (substring file (match-end 0))))
360
361 (defun diff-merge-strings (ancestor from to)
362 "Merge the diff between ANCESTOR and FROM into TO.
363 Returns the merged string if successful or nil otherwise.
364 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
365 If ANCESTOR = FROM, returns TO.
366 If ANCESTOR = TO, returns FROM.
367 The heuristic is simplistic and only really works for cases
368 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
369 ;; Ideally, we want:
370 ;; AMB ANB CMD -> CND
371 ;; but that's ambiguous if `foo' or `bar' is empty:
372 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
373 (let ((str (concat ancestor "\n" from "\n" to)))
374 (when (and (string-match (concat
375 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
376 "\\1\\(.*\\)\\3\n"
377 "\\(.*\\(\\2\\).*\\)\\'") str)
378 (equal to (match-string 5 str)))
379 (concat (substring str (match-beginning 5) (match-beginning 6))
380 (match-string 4 str)
381 (substring str (match-end 6) (match-end 5))))))
382
383 (defun diff-find-file-name (&optional old)
384 "Return the file corresponding to the current patch.
385 Non-nil OLD means that we want the old file."
386 (save-excursion
387 (unless (looking-at diff-file-header-re)
388 (or (ignore-errors (diff-beginning-of-file))
389 (re-search-forward diff-file-header-re nil t)))
390 (let* ((limit (save-excursion
391 (condition-case ()
392 (progn (diff-hunk-prev) (point))
393 (error (point-min)))))
394 (header-files
395 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\s-.*\n[-+][-+][-+] \\(\\S-+\\)\\s-.*$")
396 (list (if old (match-string 1) (match-string 2))
397 (if old (match-string 2) (match-string 1)))
398 (forward-line 1) nil))
399 (fs (append
400 (when (save-excursion
401 (re-search-backward "^Index: \\(.+\\)" limit t))
402 (list (match-string 1)))
403 header-files
404 (when (re-search-backward "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?" nil t)
405 (list (if old (match-string 2) (match-string 4))
406 (if old (match-string 4) (match-string 2))))))
407 (fs (delq nil fs)))
408 (or
409 ;; use any previously used preference
410 (cdr (assoc fs diff-remembered-files-alist))
411 ;; try to be clever and use previous choices as an inspiration
412 (dolist (rf diff-remembered-files-alist)
413 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
414 (if (and newfile (file-exists-p newfile)) (return newfile))))
415 ;; look for each file in turn. If none found, try again but
416 ;; ignoring the first level of directory, ...
417 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
418 (file nil nil))
419 ((or (null files)
420 (setq file (do* ((files files (cdr files))
421 (file (car files) (car files)))
422 ((or (null file) (file-exists-p file))
423 file))))
424 file))
425 ;; <foo>.rej patches implicitly apply to <foo>
426 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
427 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
428 (when (file-exists-p file) file)))
429 ;; if all else fails, ask the user
430 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
431 nil (first fs) t (first fs))))
432 (set (make-local-variable 'diff-remembered-files-alist)
433 (cons (cons fs file) diff-remembered-files-alist))
434 file)))))
435
436 (defun diff-find-source-location (&optional other-file)
437 "Find out (FILE LINE SPAN)."
438 (save-excursion
439 (diff-beginning-of-hunk)
440 (let* ((old (if (not other-file) diff-jump-to-old-file-flag
441 (not diff-jump-to-old-file-flag)))
442 ;; Find the location specification.
443 (loc (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
444 (error "Can't find the hunk header")
445 (if old (match-string 1)
446 (if (match-end 3) (match-string 3)
447 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
448 (error "Can't find the hunk separator"))
449 (match-string 1)))))
450 ;; Extract the actual line number.
451 (lines (if (string-match "^\\([0-9]*\\),\\([0-9]*\\)" loc)
452 (cons (string-to-number (match-string 1 loc))
453 (string-to-number (match-string 2 loc)))
454 (cons (string-to-number loc) nil)))
455 (file (diff-find-file-name old))
456 (line (car lines))
457 (span (if (or (null (cdr lines)) (< (cdr lines) 0)) 0
458 ;; Bad hack.
459 (if (< (cdr lines) line) (cdr lines)
460 (- (cdr lines) line)))))
461 ;; Update the user preference if he so wished.
462 (when (> (prefix-numeric-value other-file) 8)
463 (setq diff-jump-to-old-file-flag old))
464 (if (null file) (error "Can't find the file")
465 (list file line span)))))
466
467 (defun diff-goto-source (&optional other-file)
468 "Jump to the corresponding source line.
469 `diff-jump-to-old-file-flag' (or its opposite if the OTHER-FILE prefix arg
470 is give) determines whether to jump to the old or the new file.
471 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
472 then `diff-jump-to-old-file-flag' is also set, for the next invocations."
473 (interactive "P")
474 (save-excursion
475 (let ((loc (diff-find-source-location other-file)))
476 (pop-to-buffer (find-file-noselect (car loc)))
477 (ignore-errors
478 (goto-line (+ (cadr loc) (caddr loc)))
479 (push-mark (point) t t)
480 (goto-line (cadr loc))))))
481
482
483 (defun diff-ediff-patch ()
484 "Call `ediff-patch-file' on the current buffer."
485 (interactive)
486 (condition-case err
487 (ediff-patch-file nil (current-buffer))
488 (wrong-number-of-arguments (ediff-patch-file))))
489
490 ;;;;
491 ;;;; Conversion functions
492 ;;;;
493
494 ;;(defvar diff-inhibit-after-change nil
495 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
496
497 (defun diff-unified->context (start end)
498 "Convert unified diffs to context diffs.
499 START and END are either taken from the region (if a prefix arg is given) or
500 else cover the whole bufer."
501 (interactive (if current-prefix-arg
502 (list (mark) (point))
503 (list (point-min) (point-max))))
504 (unless (markerp end) (setq end (copy-marker end)))
505 (let (;;(diff-inhibit-after-change t)
506 (inhibit-read-only t))
507 (save-excursion
508 (goto-char start)
509 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
510 (< (point) end))
511 (combine-after-change-calls
512 (if (match-beginning 2)
513 ;; we matched a file header
514 (progn
515 ;; use reverse order to make sure the indices are kept valid
516 (replace-match "---" t t nil 3)
517 (replace-match "***" t t nil 2))
518 ;; we matched a hunk header
519 (let ((line1 (match-string 4))
520 (lines1 (match-string 5))
521 (line2 (match-string 6))
522 (lines2 (match-string 7)))
523 (replace-match
524 (concat "***************\n*** " line1 ","
525 (number-to-string (+ (string-to-number line1)
526 (string-to-number lines1)
527 -1)) " ****"))
528 (forward-line 1)
529 (save-restriction
530 (narrow-to-region (point)
531 (progn (diff-end-of-hunk 'unified) (point)))
532 (let ((hunk (buffer-string)))
533 (goto-char (point-min))
534 (if (not (save-excursion (re-search-forward "^-" nil t)))
535 (delete-region (point) (point-max))
536 (goto-char (point-max))
537 (let ((modif nil) last-pt)
538 (while (progn (setq last-pt (point))
539 (= (forward-line -1) 0))
540 (case (char-after)
541 (? (insert " ") (setq modif nil) (backward-char 1))
542 (?+ (delete-region (point) last-pt) (setq modif t))
543 (?- (if (not modif)
544 (progn (forward-char 1)
545 (insert " "))
546 (delete-char 1)
547 (insert "! "))
548 (backward-char 2))
549 (?\\ (when (save-excursion (forward-line -1)
550 (= (char-after) ?+))
551 (delete-region (point) last-pt) (setq modif t)))
552 (t (setq modif nil))))))
553 (goto-char (point-max))
554 (save-excursion
555 (insert "--- " line2 ","
556 (number-to-string (+ (string-to-number line2)
557 (string-to-number lines2)
558 -1)) " ----\n" hunk))
559 ;;(goto-char (point-min))
560 (forward-line 1)
561 (if (not (save-excursion (re-search-forward "^+" nil t)))
562 (delete-region (point) (point-max))
563 (let ((modif nil) (delete nil))
564 (while (not (eobp))
565 (case (char-after)
566 (? (insert " ") (setq modif nil) (backward-char 1))
567 (?- (setq delete t) (setq modif t))
568 (?+ (if (not modif)
569 (progn (forward-char 1)
570 (insert " "))
571 (delete-char 1)
572 (insert "! "))
573 (backward-char 2))
574 (?\\ (when (save-excursion (forward-line 1)
575 (not (eobp)))
576 (setq delete t) (setq modif t)))
577 (t (setq modif nil)))
578 (let ((last-pt (point)))
579 (forward-line 1)
580 (when delete
581 (delete-region last-pt (point))
582 (setq delete nil)))))))))))))))
583
584 (defun diff-context->unified (start end)
585 "Convert context diffs to unified diffs.
586 START and END are either taken from the region (if a prefix arg is given) or
587 else cover the whole bufer."
588 (interactive (if current-prefix-arg
589 (list (mark) (point))
590 (list (point-min) (point-max))))
591 (unless (markerp end) (setq end (copy-marker end)))
592 (let (;;(diff-inhibit-after-change t)
593 (inhibit-read-only t))
594 (save-excursion
595 (goto-char start)
596 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
597 (< (point) end))
598 (combine-after-change-calls
599 (if (match-beginning 2)
600 ;; we matched a file header
601 (progn
602 ;; use reverse order to make sure the indices are kept valid
603 (replace-match "+++" t t nil 3)
604 (replace-match "---" t t nil 2))
605 ;; we matched a hunk header
606 (let ((line1s (match-string 4))
607 (line1e (match-string 5))
608 (pt1 (match-beginning 0)))
609 (replace-match "")
610 (unless (re-search-forward
611 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
612 (error "Can't find matching `--- n1,n2 ----' line"))
613 (let ((line2s (match-string 1))
614 (line2e (match-string 2))
615 (pt2 (progn
616 (delete-region (progn (beginning-of-line) (point))
617 (progn (forward-line 1) (point)))
618 (point-marker))))
619 (goto-char pt1)
620 (forward-line 1)
621 (while (< (point) pt2)
622 (case (char-after)
623 ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
624 (?\ ;merge with the other half of the chunk
625 (let* ((endline2
626 (save-excursion
627 (goto-char pt2) (forward-line 1) (point)))
628 (c (char-after pt2)))
629 (case c
630 ((?! ?+)
631 (insert "+"
632 (prog1 (buffer-substring (+ pt2 2) endline2)
633 (delete-region pt2 endline2))))
634 (?\ ;FIXME: check consistency
635 (delete-region pt2 endline2)
636 (delete-char 1)
637 (forward-line 1))
638 (?\\ (forward-line 1))
639 (t (delete-char 1) (forward-line 1)))))
640 (t (forward-line 1))))
641 (while (looking-at "[+! ] ")
642 (if (/= (char-after) ?!) (forward-char 1)
643 (delete-char 1) (insert "+"))
644 (delete-char 1) (forward-line 1))
645 (save-excursion
646 (goto-char pt1)
647 (insert "@@ -" line1s ","
648 (number-to-string (- (string-to-number line1e)
649 (string-to-number line1s)
650 -1))
651 " +" line2s ","
652 (number-to-string (- (string-to-number line2e)
653 (string-to-number line2s)
654 -1)) " @@"))))))))))
655
656 (defun diff-reverse-direction (start end)
657 "Reverse the direction of the diffs.
658 START and END are either taken from the region (if a prefix arg is given) or
659 else cover the whole bufer."
660 (interactive (if current-prefix-arg
661 (list (mark) (point))
662 (list (point-min) (point-max))))
663 (unless (markerp end) (setq end (copy-marker end)))
664 (let (;;(diff-inhibit-after-change t)
665 (inhibit-read-only t))
666 (save-excursion
667 (goto-char start)
668 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
669 (< (point) end))
670 (combine-after-change-calls
671 (cond
672 ;; a file header
673 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
674 ;; a context-diff hunk header
675 ((match-beginning 6)
676 (let ((pt-lines1 (match-beginning 6))
677 (lines1 (match-string 6)))
678 (replace-match "" nil nil nil 6)
679 (forward-line 1)
680 (let ((half1s (point)))
681 (while (looking-at "[-! \\][ \t]\\|#")
682 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
683 (forward-line 1))
684 (let ((half1 (delete-and-extract-region half1s (point))))
685 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
686 (insert half1)
687 (error "Can't find matching `--- n1,n2 ----' line"))
688 (let ((str1 (match-string 1)))
689 (replace-match lines1 nil nil nil 1)
690 (forward-line 1)
691 (let ((half2s (point)))
692 (while (looking-at "[!+ \\][ \t]\\|#")
693 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
694 (forward-line 1))
695 (let ((half2 (delete-and-extract-region half2s (point))))
696 (insert (or half1 ""))
697 (goto-char half1s)
698 (insert (or half2 ""))))
699 (goto-char pt-lines1)
700 (insert str1))))))
701 ;; a unified-diff hunk header
702 ((match-beginning 7)
703 (replace-match "@@ -\\8 +\\7 @@" nil)
704 (forward-line 1)
705 (let ((c (char-after)) first last)
706 (while (case (setq c (char-after))
707 (?- (setq first (or first (point)))
708 (delete-char 1) (insert "+") t)
709 (?+ (setq last (or last (point)))
710 (delete-char 1) (insert "-") t)
711 ((?\\ ?#) t)
712 (t (when (and first last (< first last))
713 (let ((str
714 (save-excursion
715 (delete-and-extract-region first last))))
716 (insert str)))
717 (setq first nil last nil)
718 (equal ?\ c)))
719 (forward-line 1))))))))))
720
721 (defun diff-fixup-modifs (start end)
722 "Fixup the hunk headers (in case the buffer was modified).
723 START and END are either taken from the region (if a prefix arg is given) or
724 else cover the whole bufer."
725 (interactive (if current-prefix-arg
726 (list (mark) (point))
727 (list (point-min) (point-max))))
728 (let ((inhibit-read-only t))
729 (save-excursion
730 (goto-char end) (diff-end-of-hunk)
731 (let ((plus 0) (minus 0) (space 0) (bang 0))
732 (while (and (= (forward-line -1) 0) (<= start (point)))
733 (if (not (looking-at "\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|[-*][-*][-*] .+ [-*][-*][-*][-*]\\)$"))
734 (case (char-after)
735 (?\ (incf space))
736 (?+ (incf plus))
737 (?- (incf minus))
738 (?! (incf bang))
739 ((?\\ ?#) nil)
740 (t (setq space 0 plus 0 minus 0 bang 0)))
741 (cond
742 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
743 (let* ((old1 (match-string 1))
744 (old2 (match-string 2))
745 (new1 (number-to-string (+ space minus)))
746 (new2 (number-to-string (+ space plus))))
747 (unless (string= new2 old2) (replace-match new2 t t nil 2))
748 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
749 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
750 (when (> (+ space bang plus) 0)
751 (let* ((old1 (match-string 1))
752 (old2 (match-string 2))
753 (new (number-to-string
754 (+ space bang plus -1 (string-to-number old1)))))
755 (unless (string= new old2) (replace-match new t t nil 2)))))
756 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
757 (when (> (+ space bang minus) 0)
758 (let* ((old (match-string 1))
759 (new (format
760 (concat "%0" (number-to-string (length old)) "d")
761 (+ space bang minus -1 (string-to-number old)))))
762 (unless (string= new old) (replace-match new t t nil 2))))))
763 (setq space 0 plus 0 minus 0 bang 0)))))))
764
765 ;;;;
766 ;;;; Hooks
767 ;;;;
768
769 (defun diff-write-contents-hooks ()
770 "Fixup hunk headers if necessary."
771 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
772 nil)
773
774 ;; It turns out that making changes in the buffer from within an
775 ;; *-change-function is asking for trouble, whereas making them
776 ;; from a post-command-hook doesn't pose much problems
777 (defvar diff-unhandled-changes nil)
778 (defun diff-after-change-function (beg end len)
779 "Remember to fixup the hunk header.
780 See `after-change-functions' for the meaning of BEG, END and LEN."
781 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
782 ;; incorrect, but it turns out that inhibit-read-only is normally not set
783 ;; inside editing commands, while it tends to be set when the buffer gets
784 ;; updated by an async process or by a conversion function, both of which
785 ;; would rather not be uselessly slowed down by this hook.
786 (when (and (not undo-in-progress) (not inhibit-read-only))
787 (if diff-unhandled-changes
788 (setq diff-unhandled-changes
789 (cons (min beg (car diff-unhandled-changes))
790 (max beg (cdr diff-unhandled-changes))))
791 (setq diff-unhandled-changes (cons beg end)))))
792
793 (defun diff-post-command-hook ()
794 "Fixup hunk headers if necessary."
795 (when (consp diff-unhandled-changes)
796 (ignore-errors
797 (save-excursion
798 (goto-char (car diff-unhandled-changes))
799 (unless (ignore-errors
800 (diff-beginning-of-hunk)
801 (save-excursion
802 (diff-end-of-hunk)
803 (> (point) (car diff-unhandled-changes))))
804 (goto-char (car diff-unhandled-changes))
805 (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
806 (diff-beginning-of-hunk))
807 (diff-fixup-modifs (point) (cdr diff-unhandled-changes))))
808 (setq diff-unhandled-changes nil)))
809
810 ;;;;
811 ;;;; The main function
812 ;;;;
813
814 ;;;###autoload
815 (define-derived-mode diff-mode fundamental-mode "Diff"
816 "Major mode for viewing/editing context diffs.
817 Supports unified and context diffs as well as (to a lesser extent) normal diffs.
818 When the buffer is read-only, the ESC prefix is not necessary.
819 This mode runs `diff-mode-hook'.
820 \\{diff-mode-map}"
821 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
822 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
823 (set (make-local-variable 'imenu-generic-expression)
824 diff-imenu-generic-expression)
825 ;; compile support
826 (set (make-local-variable 'compilation-file-regexp-alist)
827 diff-file-regexp-alist)
828 (set (make-local-variable 'compilation-error-regexp-alist)
829 diff-error-regexp-alist)
830 (when (string-match "\\.rej\\'" (or buffer-file-name ""))
831 (set (make-local-variable 'compilation-current-file)
832 (substring buffer-file-name 0 (match-beginning 0))))
833 (compilation-shell-minor-mode 1)
834 ;; setup change hooks
835 (toggle-read-only t)
836 (if (not diff-update-on-the-fly-flag)
837 (add-hook 'write-contents-hooks 'diff-write-contents-hooks)
838 (make-local-variable 'diff-unhandled-changes)
839 (add-hook (make-local-hook 'after-change-functions)
840 'diff-after-change-function nil t)
841 (add-hook (make-local-hook 'post-command-hook)
842 'diff-post-command-hook nil t))
843 ;; Neat trick from Dave Love to add more bindings in read-only mode:
844 (add-to-list (make-local-variable 'minor-mode-overriding-map-alist)
845 (cons 'buffer-read-only diff-mode-shared-map)))
846
847 ;;;###autoload
848 (define-minor-mode diff-minor-mode
849 "Minor mode for viewing/editing context diffs.
850 \\{diff-minor-mode-map}"
851 nil " Diff" nil
852 ;; FIXME: setup font-lock
853 ;; setup change hooks
854 (if (not diff-update-on-the-fly-flag)
855 (add-hook 'write-contents-hooks 'diff-write-contents-hooks)
856 (make-local-variable 'diff-unhandled-changes)
857 (add-hook (make-local-hook 'after-change-functions)
858 'diff-after-change-function nil t)
859 (add-hook (make-local-hook 'post-command-hook)
860 'diff-post-command-hook nil t)))
861
862
863 ;;;
864 ;;; Misc operations that have proved useful at some point.
865 ;;;
866
867 (defun diff-next-complex-hunk ()
868 "Jump to the next \"complex\" hunk.
869 \"Complex\" is approximated by \"the hunk changes the number of lines\".
870 Only works for unified diffs."
871 (interactive)
872 (while
873 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
874 nil t)
875 (equal (match-string 1) (match-string 2)))))
876
877
878 (defun diff-filter-lines (char)
879 (goto-char (point-min))
880 (while (not (eobp))
881 (if (eq (char-after) char)
882 (delete-region (point) (progn (forward-line 1) (point)))
883 (delete-char 1)
884 (forward-line 1))))
885
886 (defun diff-apply-hunk (&optional reverse)
887 "Apply the current hunk.
888 With a prefix argument, REVERSE the hunk.
889 FIXME: Only works for unified diffs."
890 (interactive "P")
891 (save-excursion
892 (let ((loc (diff-find-source-location nil)))
893 (diff-beginning-of-hunk)
894 (unless (looking-at diff-hunk-header-re) (error "Help! Mom!"))
895 (goto-char (1+ (match-end 0)))
896 ;; Extract the SRC and DEST strings.
897 (let ((text (buffer-substring (point) (progn (diff-end-of-hunk) (point))))
898 src dest)
899 (with-temp-buffer
900 (insert text)
901 (diff-filter-lines ?+)
902 (setq src (buffer-string))
903 (erase-buffer)
904 (insert text)
905 (diff-filter-lines ?-)
906 (setq dest (buffer-string)))
907 ;; Exchange the two strings if we're reversing the patch.
908 (if reverse (let ((tmp src)) (setq src dest) (setq dest tmp)))
909 ;; Look for SRC in the file.
910 (pop-to-buffer (find-file-noselect (car loc)))
911 (goto-line (cadr loc))
912 (let* ((pos (point))
913 (forw (and (search-forward src nil t)
914 (match-beginning 0)))
915 (back (and (goto-char (+ pos (length src)))
916 (search-backward src nil t)
917 (match-beginning 0))))
918 ;; Choose the closest match.
919 (setq pos (if (and forw back)
920 (if (> (- forw pos) (- pos back)) back forw)
921 (or back forw)))
922 (unless pos (error "Can't find the text to patch"))
923 ;; Do it!
924 (goto-char pos)
925 (delete-char (length src))
926 (insert dest))))))
927
928
929 ;; provide the package
930 (provide 'diff-mode)
931
932 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
933 ;; Revision 1.11 1999/10/09 23:38:29 monnier
934 ;; (diff-mode-load-hook): dropped.
935 ;; (auto-mode-alist): also catch *.diffs.
936 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
937 ;; for *.rej files (that lack any file name indication).
938 ;;
939 ;; Revision 1.10 1999/09/30 15:32:11 monnier
940 ;; added support for "\ No newline at end of file".
941 ;;
942 ;; Revision 1.9 1999/09/15 00:01:13 monnier
943 ;; - added basic `compile' support.
944 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
945 ;; - diff-kill-file now tries to kill the leading garbage as well.
946 ;;
947 ;; Revision 1.8 1999/09/13 21:10:09 monnier
948 ;; - don't use CL in the autoloaded code
949 ;; - accept diffs using -T
950 ;;
951 ;; Revision 1.7 1999/09/05 20:53:03 monnier
952 ;; interface to ediff-patch
953 ;;
954 ;; Revision 1.6 1999/09/01 20:55:13 monnier
955 ;; (ediff=patch-file): add bindings to call ediff-patch.
956 ;; (diff-find-file-name): taken out of diff-goto-source.
957 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
958 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
959 ;;
960 ;; Revision 1.5 1999/08/31 19:18:52 monnier
961 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
962 ;;
963 ;; Revision 1.4 1999/08/31 13:01:44 monnier
964 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
965 ;;
966
967 ;;; diff-mode.el ends here