Merge from emacs--rel--22
[bpt/emacs.git] / lisp / smerge-mode.el
1 ;;; smerge-mode.el --- Minor mode to resolve diff3 conflicts
2
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5
6 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; Keywords: tools revision-control merge diff3 cvs conflict
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 3, 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., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Commentary:
27
28 ;; Provides a lightweight alternative to emerge/ediff.
29 ;; To use it, simply add to your .emacs the following lines:
30 ;;
31 ;; (autoload 'smerge-mode "smerge-mode" nil t)
32 ;;
33 ;; you can even have it turned on automatically with the following
34 ;; piece of code in your .emacs:
35 ;;
36 ;; (defun sm-try-smerge ()
37 ;; (save-excursion
38 ;; (goto-char (point-min))
39 ;; (when (re-search-forward "^<<<<<<< " nil t)
40 ;; (smerge-mode 1))))
41 ;; (add-hook 'find-file-hook 'sm-try-smerge t)
42
43 ;;; Todo:
44
45 ;; - if requested, ask the user whether he wants to call ediff right away
46
47 ;;; Code:
48
49 (eval-when-compile (require 'cl))
50
51
52 ;;; The real definition comes later.
53 (defvar smerge-mode)
54
55 (defgroup smerge ()
56 "Minor mode to highlight and resolve diff3 conflicts."
57 :group 'tools
58 :prefix "smerge-")
59
60 (defcustom smerge-diff-buffer-name "*vc-diff*"
61 "Buffer name to use for displaying diffs."
62 :group 'smerge
63 :type '(choice
64 (const "*vc-diff*")
65 (const "*cvs-diff*")
66 (const "*smerge-diff*")
67 string))
68
69 (defcustom smerge-diff-switches
70 (append '("-d" "-b")
71 (if (listp diff-switches) diff-switches (list diff-switches)))
72 "A list of strings specifying switches to be passed to diff.
73 Used in `smerge-diff-base-mine' and related functions."
74 :group 'smerge
75 :type '(repeat string))
76
77 (defcustom smerge-auto-leave t
78 "Non-nil means to leave `smerge-mode' when the last conflict is resolved."
79 :group 'smerge
80 :type 'boolean)
81
82 (defface smerge-mine
83 '((((min-colors 88) (background light))
84 (:foreground "blue1"))
85 (((background light))
86 (:foreground "blue"))
87 (((min-colors 88) (background dark))
88 (:foreground "cyan1"))
89 (((background dark))
90 (:foreground "cyan")))
91 "Face for your code."
92 :group 'smerge)
93 ;; backward-compatibility alias
94 (put 'smerge-mine-face 'face-alias 'smerge-mine)
95 (defvar smerge-mine-face 'smerge-mine)
96
97 (defface smerge-other
98 '((((background light))
99 (:foreground "darkgreen"))
100 (((background dark))
101 (:foreground "lightgreen")))
102 "Face for the other code."
103 :group 'smerge)
104 ;; backward-compatibility alias
105 (put 'smerge-other-face 'face-alias 'smerge-other)
106 (defvar smerge-other-face 'smerge-other)
107
108 (defface smerge-base
109 '((((min-colors 88) (background light))
110 (:foreground "red1"))
111 (((background light))
112 (:foreground "red"))
113 (((background dark))
114 (:foreground "orange")))
115 "Face for the base code."
116 :group 'smerge)
117 ;; backward-compatibility alias
118 (put 'smerge-base-face 'face-alias 'smerge-base)
119 (defvar smerge-base-face 'smerge-base)
120
121 (defface smerge-markers
122 '((((background light))
123 (:background "grey85"))
124 (((background dark))
125 (:background "grey30")))
126 "Face for the conflict markers."
127 :group 'smerge)
128 ;; backward-compatibility alias
129 (put 'smerge-markers-face 'face-alias 'smerge-markers)
130 (defvar smerge-markers-face 'smerge-markers)
131
132 (defface smerge-refined-change
133 '((t :background "yellow"))
134 "Face used for char-based changes shown by `smerge-refine'."
135 :group 'smerge)
136
137 (easy-mmode-defmap smerge-basic-map
138 `(("n" . smerge-next)
139 ("p" . smerge-prev)
140 ("r" . smerge-resolve)
141 ("a" . smerge-keep-all)
142 ("b" . smerge-keep-base)
143 ("o" . smerge-keep-other)
144 ("m" . smerge-keep-mine)
145 ("E" . smerge-ediff)
146 ("C" . smerge-combine-with-next)
147 ("R" . smerge-refine)
148 ("\C-m" . smerge-keep-current)
149 ("=" . ,(make-sparse-keymap "Diff"))
150 ("=<" "base-mine" . smerge-diff-base-mine)
151 ("=>" "base-other" . smerge-diff-base-other)
152 ("==" "mine-other" . smerge-diff-mine-other))
153 "The base keymap for `smerge-mode'.")
154
155 (defcustom smerge-command-prefix "\C-c^"
156 "Prefix for `smerge-mode' commands."
157 :group 'smerge
158 :type '(choice (string "\e") (string "\C-c^") (string "") string))
159
160 (easy-mmode-defmap smerge-mode-map
161 `((,smerge-command-prefix . ,smerge-basic-map))
162 "Keymap for `smerge-mode'.")
163
164 (defvar smerge-check-cache nil)
165 (make-variable-buffer-local 'smerge-check-cache)
166 (defun smerge-check (n)
167 (condition-case nil
168 (let ((state (cons (point) (buffer-modified-tick))))
169 (unless (equal (cdr smerge-check-cache) state)
170 (smerge-match-conflict)
171 (setq smerge-check-cache (cons (match-data) state)))
172 (nth (* 2 n) (car smerge-check-cache)))
173 (error nil)))
174
175 (easy-menu-define smerge-mode-menu smerge-mode-map
176 "Menu for `smerge-mode'."
177 '("SMerge"
178 ["Next" smerge-next :help "Go to next conflict"]
179 ["Previous" smerge-prev :help "Go to previous conflict"]
180 "--"
181 ["Keep All" smerge-keep-all :help "Keep all three versions"
182 :active (smerge-check 1)]
183 ["Keep Current" smerge-keep-current :help "Use current (at point) version"
184 :active (and (smerge-check 1) (> (smerge-get-current) 0))]
185 "--"
186 ["Revert to Base" smerge-keep-base :help "Revert to base version"
187 :active (smerge-check 2)]
188 ["Keep Other" smerge-keep-other :help "Keep `other' version"
189 :active (smerge-check 3)]
190 ["Keep Yours" smerge-keep-mine :help "Keep your version"
191 :active (smerge-check 1)]
192 "--"
193 ["Diff Base/Mine" smerge-diff-base-mine
194 :help "Diff `base' and `mine' for current conflict"
195 :active (smerge-check 2)]
196 ["Diff Base/Other" smerge-diff-base-other
197 :help "Diff `base' and `other' for current conflict"
198 :active (smerge-check 2)]
199 ["Diff Mine/Other" smerge-diff-mine-other
200 :help "Diff `mine' and `other' for current conflict"
201 :active (smerge-check 1)]
202 "--"
203 ["Invoke Ediff" smerge-ediff
204 :help "Use Ediff to resolve the conflicts"
205 :active (smerge-check 1)]
206 ["Auto Resolve" smerge-resolve
207 :help "Try auto-resolution heuristics"
208 :active (smerge-check 1)]
209 ["Combine" smerge-combine-with-next
210 :help "Combine current conflict with next"
211 :active (smerge-check 1)]
212 ))
213
214 (easy-menu-define smerge-context-menu nil
215 "Context menu for mine area in `smerge-mode'."
216 '(nil
217 ["Keep Current" smerge-keep-current :help "Use current (at point) version"]
218 ["Kill Current" smerge-kill-current :help "Remove current (at point) version"]
219 ["Keep All" smerge-keep-all :help "Keep all three versions"]
220 "---"
221 ["More..." (popup-menu smerge-mode-menu) :help "Show full SMerge mode menu"]
222 ))
223
224 (defconst smerge-font-lock-keywords
225 '((smerge-find-conflict
226 (1 smerge-mine-face prepend t)
227 (2 smerge-base-face prepend t)
228 (3 smerge-other-face prepend t)
229 ;; FIXME: `keep' doesn't work right with syntactic fontification.
230 (0 smerge-markers-face keep)
231 (4 nil t t)
232 (5 nil t t)))
233 "Font lock patterns for `smerge-mode'.")
234
235 (defconst smerge-begin-re "^<<<<<<< \\(.*\\)\n")
236 (defconst smerge-end-re "^>>>>>>> .*\n")
237 (defconst smerge-base-re "^||||||| .*\n")
238 (defconst smerge-other-re "^=======\n")
239
240 (defvar smerge-conflict-style nil
241 "Keep track of which style of conflict is in use.
242 Can be nil if the style is undecided, or else:
243 - `diff3-E'
244 - `diff3-A'")
245
246 ;; Compiler pacifiers
247 (defvar font-lock-mode)
248 (defvar font-lock-keywords)
249
250 ;;;;
251 ;;;; Actual code
252 ;;;;
253
254 ;; Define smerge-next and smerge-prev
255 (easy-mmode-define-navigation smerge smerge-begin-re "conflict")
256
257 (defconst smerge-match-names ["conflict" "mine" "base" "other"])
258
259 (defun smerge-ensure-match (n)
260 (unless (match-end n)
261 (error "No `%s'" (aref smerge-match-names n))))
262
263 (defun smerge-auto-leave ()
264 (when (and smerge-auto-leave
265 (save-excursion (goto-char (point-min))
266 (not (re-search-forward smerge-begin-re nil t))))
267 (when (and (listp buffer-undo-list) smerge-mode)
268 (push (list 'apply 'smerge-mode 1) buffer-undo-list))
269 (smerge-mode -1)))
270
271
272 (defun smerge-keep-all ()
273 "Concatenate all versions."
274 (interactive)
275 (smerge-match-conflict)
276 (let ((mb2 (or (match-beginning 2) (point-max)))
277 (me2 (or (match-end 2) (point-min))))
278 (delete-region (match-end 3) (match-end 0))
279 (delete-region (max me2 (match-end 1)) (match-beginning 3))
280 (if (and (match-end 2) (/= (match-end 1) (match-end 3)))
281 (delete-region (match-end 1) (match-beginning 2)))
282 (delete-region (match-beginning 0) (min (match-beginning 1) mb2))
283 (smerge-auto-leave)))
284
285 (defun smerge-keep-n (n)
286 (smerge-remove-props (match-beginning 0) (match-end 0))
287 ;; We used to use replace-match, but that did not preserve markers so well.
288 (delete-region (match-end n) (match-end 0))
289 (delete-region (match-beginning 0) (match-beginning n)))
290
291 (defun smerge-combine-with-next ()
292 "Combine the current conflict with the next one."
293 (interactive)
294 (smerge-match-conflict)
295 (let ((ends nil))
296 (dolist (i '(3 2 1 0))
297 (push (if (match-end i) (copy-marker (match-end i) t)) ends))
298 (setq ends (apply 'vector ends))
299 (goto-char (aref ends 0))
300 (if (not (re-search-forward smerge-begin-re nil t))
301 (error "No next conflict")
302 (smerge-match-conflict)
303 (let ((match-data (mapcar (lambda (m) (if m (copy-marker m)))
304 (match-data))))
305 ;; First copy the in-between text in each alternative.
306 (dolist (i '(1 2 3))
307 (when (aref ends i)
308 (goto-char (aref ends i))
309 (insert-buffer-substring (current-buffer)
310 (aref ends 0) (car match-data))))
311 (delete-region (aref ends 0) (car match-data))
312 ;; Then move the second conflict's alternatives into the first.
313 (dolist (i '(1 2 3))
314 (set-match-data match-data)
315 (when (and (aref ends i) (match-end i))
316 (goto-char (aref ends i))
317 (insert-buffer-substring (current-buffer)
318 (match-beginning i) (match-end i))))
319 (delete-region (car match-data) (cadr match-data))
320 ;; Free the markers.
321 (dolist (m match-data) (if m (move-marker m nil)))
322 (mapc (lambda (m) (if m (move-marker m nil))) ends)))))
323
324 (defvar smerge-resolve-function
325 (lambda () (error "Don't know how to resolve"))
326 "Mode-specific merge function.
327 The function is called with zero or one argument (non-nil if the resolution
328 function should only apply safe heuristics) and with the match data set
329 according to `smerge-match-conflict'.")
330 (add-to-list 'debug-ignored-errors "Don't know how to resolve")
331
332 (defvar smerge-text-properties
333 `(help-echo "merge conflict: mouse-3 shows a menu"
334 ;; mouse-face highlight
335 keymap (keymap (down-mouse-3 . smerge-popup-context-menu))))
336
337 (defun smerge-remove-props (beg end)
338 (remove-overlays beg end 'smerge 'refine)
339 (remove-overlays beg end 'smerge 'conflict)
340 ;; Now that we use overlays rather than text-properties, this function
341 ;; does not cause refontification any more. It can be seen very clearly
342 ;; in buffers where jit-lock-contextually is not t, in which case deleting
343 ;; the "<<<<<<< foobar" leading line leaves the rest of the conflict
344 ;; highlighted as if it were still a valid conflict. Note that in many
345 ;; important cases (such as the previous example) we're actually called
346 ;; during font-locking so inhibit-modification-hooks is non-nil, so we
347 ;; can't just modify the buffer and expect font-lock to be triggered as in:
348 ;; (put-text-property beg end 'smerge-force-highlighting nil)
349 (let ((modified (buffer-modified-p)))
350 (remove-text-properties beg end '(fontified nil))
351 (restore-buffer-modified-p modified)))
352
353 (defun smerge-popup-context-menu (event)
354 "Pop up the Smerge mode context menu under mouse."
355 (interactive "e")
356 (if (and smerge-mode
357 (save-excursion (posn-set-point (event-end event)) (smerge-check 1)))
358 (progn
359 (posn-set-point (event-end event))
360 (smerge-match-conflict)
361 (let ((i (smerge-get-current))
362 o)
363 (if (<= i 0)
364 ;; Out of range
365 (popup-menu smerge-mode-menu)
366 ;; Install overlay.
367 (setq o (make-overlay (match-beginning i) (match-end i)))
368 (unwind-protect
369 (progn
370 (overlay-put o 'face 'highlight)
371 (sit-for 0) ;Display the new highlighting.
372 (popup-menu smerge-context-menu))
373 ;; Delete overlay.
374 (delete-overlay o)))))
375 ;; There's no conflict at point, the text-props are just obsolete.
376 (save-excursion
377 (let ((beg (re-search-backward smerge-end-re nil t))
378 (end (re-search-forward smerge-begin-re nil t)))
379 (smerge-remove-props (or beg (point-min)) (or end (point-max)))
380 (push event unread-command-events)))))
381
382 (defun smerge-resolve (&optional safe)
383 "Resolve the conflict at point intelligently.
384 This relies on mode-specific knowledge and thus only works in
385 some major modes. Uses `smerge-resolve-function' to do the actual work."
386 (interactive)
387 (smerge-match-conflict)
388 (smerge-remove-props (match-beginning 0) (match-end 0))
389 (cond
390 ;; Trivial diff3 -A non-conflicts.
391 ((and (eq (match-end 1) (match-end 3))
392 (eq (match-beginning 1) (match-beginning 3)))
393 (smerge-keep-n 3))
394 ;; Mode-specific conflict resolution.
395 ((condition-case nil
396 (atomic-change-group
397 (if safe
398 (funcall smerge-resolve-function safe)
399 (funcall smerge-resolve-function))
400 t)
401 (error nil))
402 ;; Nothing to do: the resolution function has done it already.
403 nil)
404 ;; FIXME: Add "if [ diff -b MINE OTHER ]; then select OTHER; fi"
405 ((and (match-end 2)
406 ;; FIXME: Add "diff -b BASE MINE | patch OTHER".
407 ;; FIXME: Add "diff -b BASE OTHER | patch MINE".
408 nil)
409 )
410 ((and (not (match-end 2))
411 ;; FIXME: Add "diff -b"-based refinement.
412 nil)
413 )
414 (t
415 (error "Don't know how to resolve")))
416 (smerge-auto-leave))
417
418 (defun smerge-resolve-all ()
419 "Perform automatic resolution on all conflicts."
420 (interactive)
421 (save-excursion
422 (goto-char (point-min))
423 (while (re-search-forward smerge-begin-re nil t)
424 (condition-case nil
425 (progn
426 (smerge-match-conflict)
427 (smerge-resolve 'safe))
428 (error nil)))))
429
430 (defun smerge-batch-resolve ()
431 ;; command-line-args-left is what is left of the command line.
432 (if (not noninteractive)
433 (error "`smerge-batch-resolve' is to be used only with -batch"))
434 (while command-line-args-left
435 (let ((file (pop command-line-args-left)))
436 (message "Resolving conflicts in %s..." file)
437 (when (file-readable-p file)
438 (with-current-buffer (find-file-noselect file)
439 (smerge-resolve-all)
440 (save-buffer)
441 (kill-buffer (current-buffer)))))))
442
443 (defun smerge-keep-base ()
444 "Revert to the base version."
445 (interactive)
446 (smerge-match-conflict)
447 (smerge-ensure-match 2)
448 (smerge-keep-n 2)
449 (smerge-auto-leave))
450
451 (defun smerge-keep-other ()
452 "Use \"other\" version."
453 (interactive)
454 (smerge-match-conflict)
455 ;;(smerge-ensure-match 3)
456 (smerge-keep-n 3)
457 (smerge-auto-leave))
458
459 (defun smerge-keep-mine ()
460 "Keep your version."
461 (interactive)
462 (smerge-match-conflict)
463 ;;(smerge-ensure-match 1)
464 (smerge-keep-n 1)
465 (smerge-auto-leave))
466
467 (defun smerge-get-current ()
468 (let ((i 3))
469 (while (or (not (match-end i))
470 (< (point) (match-beginning i))
471 (>= (point) (match-end i)))
472 (decf i))
473 i))
474
475 (defun smerge-keep-current ()
476 "Use the current (under the cursor) version."
477 (interactive)
478 (smerge-match-conflict)
479 (let ((i (smerge-get-current)))
480 (if (<= i 0) (error "Not inside a version")
481 (smerge-keep-n i)
482 (smerge-auto-leave))))
483
484 (defun smerge-kill-current ()
485 "Remove the current (under the cursor) version."
486 (interactive)
487 (smerge-match-conflict)
488 (let ((i (smerge-get-current)))
489 (if (<= i 0) (error "Not inside a version")
490 (let ((left nil))
491 (dolist (n '(3 2 1))
492 (if (and (match-end n) (/= (match-end n) (match-end i)))
493 (push n left)))
494 (if (and (cdr left)
495 (/= (match-end (car left)) (match-end (cadr left))))
496 (ding) ;We don't know how to do that.
497 (smerge-keep-n (car left))
498 (smerge-auto-leave))))))
499
500 (defun smerge-diff-base-mine ()
501 "Diff 'base' and 'mine' version in current conflict region."
502 (interactive)
503 (smerge-diff 2 1))
504
505 (defun smerge-diff-base-other ()
506 "Diff 'base' and 'other' version in current conflict region."
507 (interactive)
508 (smerge-diff 2 3))
509
510 (defun smerge-diff-mine-other ()
511 "Diff 'mine' and 'other' version in current conflict region."
512 (interactive)
513 (smerge-diff 1 3))
514
515 (defun smerge-match-conflict ()
516 "Get info about the conflict. Puts the info in the `match-data'.
517 The submatches contain:
518 0: the whole conflict.
519 1: your code.
520 2: the base code.
521 3: other code.
522 An error is raised if not inside a conflict."
523 (save-excursion
524 (condition-case nil
525 (let* ((orig-point (point))
526
527 (_ (forward-line 1))
528 (_ (re-search-backward smerge-begin-re))
529
530 (start (match-beginning 0))
531 (mine-start (match-end 0))
532 (filename (or (match-string 1) ""))
533
534 (_ (re-search-forward smerge-end-re))
535 (_ (assert (< orig-point (match-end 0))))
536
537 (other-end (match-beginning 0))
538 (end (match-end 0))
539
540 (_ (re-search-backward smerge-other-re start))
541
542 (mine-end (match-beginning 0))
543 (other-start (match-end 0))
544
545 base-start base-end)
546
547 ;; handle the various conflict styles
548 (cond
549 ((save-excursion
550 (goto-char mine-start)
551 (re-search-forward smerge-begin-re end t))
552 ;; There's a nested conflict and we're after the the beginning
553 ;; of the outer one but before the beginning of the inner one.
554 ;; Of course, maybe this is not a nested conflict but in that
555 ;; case it can only be something nastier that we don't know how
556 ;; to handle, so may as well arbitrarily decide to treat it as
557 ;; a nested conflict. --Stef
558 (error "There is a nested conflict"))
559
560 ((re-search-backward smerge-base-re start t)
561 ;; a 3-parts conflict
562 (set (make-local-variable 'smerge-conflict-style) 'diff3-A)
563 (setq base-end mine-end)
564 (setq mine-end (match-beginning 0))
565 (setq base-start (match-end 0)))
566
567 ((string= filename (file-name-nondirectory
568 (or buffer-file-name "")))
569 ;; a 2-parts conflict
570 (set (make-local-variable 'smerge-conflict-style) 'diff3-E))
571
572 ((and (not base-start)
573 (or (eq smerge-conflict-style 'diff3-A)
574 (equal filename "ANCESTOR")
575 (string-match "\\`[.0-9]+\\'" filename)))
576 ;; a same-diff conflict
577 (setq base-start mine-start)
578 (setq base-end mine-end)
579 (setq mine-start other-start)
580 (setq mine-end other-end)))
581
582 (store-match-data (list start end
583 mine-start mine-end
584 base-start base-end
585 other-start other-end
586 (when base-start (1- base-start)) base-start
587 (1- other-start) other-start))
588 t)
589 (search-failed (error "Point not in conflict region")))))
590
591 (add-to-list 'debug-ignored-errors "Point not in conflict region")
592
593 (defun smerge-conflict-overlay (pos)
594 "Return the conflict overlay at POS if any."
595 (let ((ols (overlays-at pos))
596 conflict)
597 (dolist (ol ols)
598 (if (and (eq (overlay-get ol 'smerge) 'conflict)
599 (> (overlay-end ol) pos))
600 (setq conflict ol)))
601 conflict))
602
603 (defun smerge-find-conflict (&optional limit)
604 "Find and match a conflict region. Intended as a font-lock MATCHER.
605 The submatches are the same as in `smerge-match-conflict'.
606 Returns non-nil if a match is found between point and LIMIT.
607 Point is moved to the end of the conflict."
608 (let ((found nil)
609 (pos (point))
610 conflict)
611 ;; First check to see if point is already inside a conflict, using
612 ;; the conflict overlays.
613 (while (and (not found) (setq conflict (smerge-conflict-overlay pos)))
614 ;; Check the overlay's validity and kill it if it's out of date.
615 (condition-case nil
616 (progn
617 (goto-char (overlay-start conflict))
618 (smerge-match-conflict)
619 (goto-char (match-end 0))
620 (if (<= (point) pos)
621 (error "Matching backward!")
622 (setq found t)))
623 (error (smerge-remove-props
624 (overlay-start conflict) (overlay-end conflict))
625 (goto-char pos))))
626 ;; If we're not already inside a conflict, look for the next conflict
627 ;; and add/update its overlay.
628 (while (and (not found) (re-search-forward smerge-begin-re limit t))
629 (condition-case nil
630 (progn
631 (smerge-match-conflict)
632 (goto-char (match-end 0))
633 (let ((conflict (smerge-conflict-overlay (1- (point)))))
634 (if conflict
635 ;; Update its location, just in case it got messed up.
636 (move-overlay conflict (match-beginning 0) (match-end 0))
637 (setq conflict (make-overlay (match-beginning 0) (match-end 0)
638 nil 'front-advance nil))
639 (overlay-put conflict 'evaporate t)
640 (overlay-put conflict 'smerge 'conflict)
641 (let ((props smerge-text-properties))
642 (while props
643 (overlay-put conflict (pop props) (pop props))))))
644 (setq found t))
645 (error nil)))
646 found))
647
648 (defun smerge-refine-chopup-region (beg end file &optional preproc)
649 "Chopup the region into small elements, one per line.
650 Save the result into FILE.
651 If non-nil, PREPROC is called with no argument in a buffer that contains
652 a copy of the text, just before chopping it up. It can be used to replace
653 chars to try and eliminate some spurious differences."
654 ;; ediff chops up into words, where the definition of a word is
655 ;; customizable. Instead we here keep only one char per line.
656 ;; The advantages are that there's nothing to configure, that we get very
657 ;; fine results, and that it's trivial to map the line numbers in the
658 ;; output of diff back into buffer positions. The disadvantage is that it
659 ;; can take more time to compute the diff and that the result is sometimes
660 ;; too fine. I'm not too concerned about the slowdown because conflicts
661 ;; are usually significantly smaller than the whole file. As for the
662 ;; problem of too-fine-refinement, I have found it to be unimportant
663 ;; especially when you consider the cases where the fine-grain is just
664 ;; what you want.
665 (let ((buf (current-buffer)))
666 (with-temp-buffer
667 (insert-buffer-substring buf beg end)
668 (when preproc (goto-char (point-min)) (funcall preproc))
669 (goto-char (point-min))
670 (while (not (eobp))
671 (forward-char 1)
672 ;; We add \n after each char except after \n, so we get one line per
673 ;; text char, where each line contains just one char, except for \n
674 ;; chars which are represented by the empty line.
675 (unless (eq (char-before) ?\n) (insert ?\n)))
676 (let ((coding-system-for-write 'emacs-mule))
677 (write-region (point-min) (point-max) file nil 'nomessage)))))
678
679 (defun smerge-refine-highlight-change (buf beg match-num1 match-num2 props)
680 (let* ((startline (string-to-number (match-string match-num1)))
681 (ol (make-overlay
682 (+ beg startline -1)
683 (+ beg (if (match-end match-num2)
684 (string-to-number (match-string match-num2))
685 startline))
686 buf
687 ;; Make them tend to shrink rather than spread when editing.
688 'front-advance nil)))
689 (overlay-put ol 'evaporate t)
690 (dolist (x props)
691 (overlay-put ol (car x) (cdr x)))))
692
693 (defun smerge-refine-subst (beg1 end1 beg2 end2 props &optional preproc)
694 "Show fine differences in the two regions BEG1..END1 and BEG2..END2.
695 PROPS is an alist of properties to put (via overlays) on the changes.
696 If non-nil, PREPROC is called with no argument in a buffer that contains
697 a copy of a region, just before preparing it to for `diff'. It can be used to
698 replace chars to try and eliminate some spurious differences."
699 (let* ((buf (current-buffer))
700 (file1 (make-temp-file "diff1"))
701 (file2 (make-temp-file "diff2")))
702
703 ;; Chop up regions into smaller elements and save into files.
704 (smerge-refine-chopup-region beg1 end1 file1 preproc)
705 (smerge-refine-chopup-region beg2 end2 file2 preproc)
706
707 ;; Call diff on those files.
708 (unwind-protect
709 (with-temp-buffer
710 (let ((coding-system-for-read 'emacs-mule))
711 ;; Don't forget -a to make sure diff treats it as a text file
712 ;; even if it contains \0 and such.
713 (call-process diff-command nil t nil "-a" file1 file2))
714 ;; Process diff's output.
715 (goto-char (point-min))
716 (while (not (eobp))
717 (if (not (looking-at "\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?\\([acd]\\)\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?$"))
718 (error "Unexpected patch hunk header: %s"
719 (buffer-substring (point) (line-end-position)))
720 (let ((op (char-after (match-beginning 3))))
721 (when (memq op '(?d ?c))
722 (smerge-refine-highlight-change buf beg1 1 2 props))
723 (when (memq op '(?a ?c))
724 (smerge-refine-highlight-change buf beg2 4 5 props)))
725 (forward-line 1) ;Skip hunk header.
726 (and (re-search-forward "^[0-9]" nil 'move) ;Skip hunk body.
727 (goto-char (match-beginning 0))))))
728 (delete-file file1)
729 (delete-file file2))))
730
731 (defun smerge-refine ()
732 "Highlight the parts of the conflict that are different."
733 (interactive)
734 ;; FIXME: make it work with 3-way conflicts.
735 (smerge-match-conflict)
736 (remove-overlays (match-beginning 0) (match-end 0) 'smerge 'refine)
737 (smerge-ensure-match 1)
738 (smerge-ensure-match 3)
739 (smerge-refine-subst (match-beginning 1) (match-end 1)
740 (match-beginning 3) (match-end 3)
741 '((smerge . refine)
742 (face . smerge-refined-change))))
743
744 (defun smerge-diff (n1 n2)
745 (smerge-match-conflict)
746 (smerge-ensure-match n1)
747 (smerge-ensure-match n2)
748 (let ((name1 (aref smerge-match-names n1))
749 (name2 (aref smerge-match-names n2))
750 ;; Read them before the match-data gets clobbered.
751 (beg1 (match-beginning n1))
752 (end1 (match-end n1))
753 (beg2 (match-beginning n2))
754 (end2 (match-end n2))
755 (file1 (make-temp-file "smerge1"))
756 (file2 (make-temp-file "smerge2"))
757 (dir default-directory)
758 (file (if buffer-file-name (file-relative-name buffer-file-name)))
759 ;; We would want to use `emacs-mule-unix' for read&write, but we
760 ;; bump into problems with the coding-system used by diff to write
761 ;; the file names and the time stamps in the header.
762 ;; `buffer-file-coding-system' is not always correct either, but if
763 ;; the OS/user uses only one coding-system, then it works.
764 (coding-system-for-read buffer-file-coding-system))
765 (write-region beg1 end1 file1 nil 'nomessage)
766 (write-region beg2 end2 file2 nil 'nomessage)
767 (unwind-protect
768 (with-current-buffer (get-buffer-create smerge-diff-buffer-name)
769 (setq default-directory dir)
770 (let ((inhibit-read-only t))
771 (erase-buffer)
772 (let ((status
773 (apply 'call-process diff-command nil t nil
774 (append smerge-diff-switches
775 (list "-L" (concat name1 "/" file)
776 "-L" (concat name2 "/" file)
777 file1 file2)))))
778 (if (eq status 0) (insert "No differences found.\n"))))
779 (goto-char (point-min))
780 (diff-mode)
781 (display-buffer (current-buffer) t))
782 (delete-file file1)
783 (delete-file file2))))
784
785 ;; compiler pacifiers
786 (defvar smerge-ediff-windows)
787 (defvar smerge-ediff-buf)
788 (defvar ediff-buffer-A)
789 (defvar ediff-buffer-B)
790 (defvar ediff-buffer-C)
791 (defvar ediff-ancestor-buffer)
792 (defvar ediff-quit-hook)
793
794 ;;;###autoload
795 (defun smerge-ediff (&optional name-mine name-other name-base)
796 "Invoke ediff to resolve the conflicts.
797 NAME-MINE, NAME-OTHER, and NAME-BASE, if non-nil, are used for the
798 buffer names."
799 (interactive)
800 (let* ((buf (current-buffer))
801 (mode major-mode)
802 ;;(ediff-default-variant 'default-B)
803 (config (current-window-configuration))
804 (filename (file-name-nondirectory buffer-file-name))
805 (mine (generate-new-buffer
806 (or name-mine (concat "*" filename " MINE*"))))
807 (other (generate-new-buffer
808 (or name-other (concat "*" filename " OTHER*"))))
809 base)
810 (with-current-buffer mine
811 (buffer-disable-undo)
812 (insert-buffer-substring buf)
813 (goto-char (point-min))
814 (while (smerge-find-conflict)
815 (when (match-beginning 2) (setq base t))
816 (smerge-keep-n 1))
817 (buffer-enable-undo)
818 (set-buffer-modified-p nil)
819 (funcall mode))
820
821 (with-current-buffer other
822 (buffer-disable-undo)
823 (insert-buffer-substring buf)
824 (goto-char (point-min))
825 (while (smerge-find-conflict)
826 (smerge-keep-n 3))
827 (buffer-enable-undo)
828 (set-buffer-modified-p nil)
829 (funcall mode))
830
831 (when base
832 (setq base (generate-new-buffer
833 (or name-base (concat "*" filename " BASE*"))))
834 (with-current-buffer base
835 (buffer-disable-undo)
836 (insert-buffer-substring buf)
837 (goto-char (point-min))
838 (while (smerge-find-conflict)
839 (if (match-end 2)
840 (smerge-keep-n 2)
841 (delete-region (match-beginning 0) (match-end 0))))
842 (buffer-enable-undo)
843 (set-buffer-modified-p nil)
844 (funcall mode)))
845
846 ;; the rest of the code is inspired from vc.el
847 ;; Fire up ediff.
848 (set-buffer
849 (if base
850 (ediff-merge-buffers-with-ancestor mine other base)
851 ;; nil 'ediff-merge-revisions-with-ancestor buffer-file-name)
852 (ediff-merge-buffers mine other)))
853 ;; nil 'ediff-merge-revisions buffer-file-name)))
854
855 ;; Ediff is now set up, and we are in the control buffer.
856 ;; Do a few further adjustments and take precautions for exit.
857 (set (make-local-variable 'smerge-ediff-windows) config)
858 (set (make-local-variable 'smerge-ediff-buf) buf)
859 (set (make-local-variable 'ediff-quit-hook)
860 (lambda ()
861 (let ((buffer-A ediff-buffer-A)
862 (buffer-B ediff-buffer-B)
863 (buffer-C ediff-buffer-C)
864 (buffer-Ancestor ediff-ancestor-buffer)
865 (buf smerge-ediff-buf)
866 (windows smerge-ediff-windows))
867 (ediff-cleanup-mess)
868 (with-current-buffer buf
869 (erase-buffer)
870 (insert-buffer-substring buffer-C)
871 (kill-buffer buffer-A)
872 (kill-buffer buffer-B)
873 (kill-buffer buffer-C)
874 (when (bufferp buffer-Ancestor) (kill-buffer buffer-Ancestor))
875 (set-window-configuration windows)
876 (message "Conflict resolution finished; you may save the buffer")))))
877 (message "Please resolve conflicts now; exit ediff when done")))
878
879
880 (defconst smerge-parsep-re
881 (concat smerge-begin-re "\\|" smerge-end-re "\\|"
882 smerge-base-re "\\|" smerge-other-re "\\|"))
883
884 ;;;###autoload
885 (define-minor-mode smerge-mode
886 "Minor mode to simplify editing output from the diff3 program.
887 \\{smerge-mode-map}"
888 :group 'smerge :lighter " SMerge"
889 (when (and (boundp 'font-lock-mode) font-lock-mode)
890 (save-excursion
891 (if smerge-mode
892 (font-lock-add-keywords nil smerge-font-lock-keywords 'append)
893 (font-lock-remove-keywords nil smerge-font-lock-keywords))
894 (goto-char (point-min))
895 (while (smerge-find-conflict)
896 (save-excursion
897 (font-lock-fontify-region (match-beginning 0) (match-end 0) nil)))))
898 (if (string-match (regexp-quote smerge-parsep-re) paragraph-separate)
899 (unless smerge-mode
900 (set (make-local-variable 'paragraph-separate)
901 (replace-match "" t t paragraph-separate)))
902 (when smerge-mode
903 (set (make-local-variable 'paragraph-separate)
904 (concat smerge-parsep-re paragraph-separate))))
905 (unless smerge-mode
906 (smerge-remove-props (point-min) (point-max))))
907
908
909 (provide 'smerge-mode)
910
911 ;; arch-tag: 605c8d1e-e43d-4943-a6f3-1bcc4333e690
912 ;;; smerge-mode.el ends here