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