Renamed xhtml-target.rnc to xhtml-tgt.rnc; all users changed.
[emacs.git] / lisp / smerge-mode.el
blobdcbb97bd79cf9a951d54165edca79d849e359d5b
1 ;;; smerge-mode.el --- Minor mode to resolve diff3 conflicts
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
6 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; Keywords: tools revision-control merge diff3 cvs conflict
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 3, 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., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
26 ;;; Commentary:
28 ;; Provides a lightweight alternative to emerge/ediff.
29 ;; To use it, simply add to your .emacs the following lines:
31 ;; (autoload 'smerge-mode "smerge-mode" nil t)
33 ;; you can even have it turned on automatically with the following
34 ;; piece of code in your .emacs:
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)
43 ;;; Todo:
45 ;; - if requested, ask the user whether he wants to call ediff right away
47 ;;; Code:
49 (eval-when-compile (require 'cl))
52 ;;; The real definition comes later.
53 (defvar smerge-mode)
55 (defgroup smerge ()
56 "Minor mode to highlight and resolve diff3 conflicts."
57 :group 'tools
58 :prefix "smerge-")
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))
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))
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)
82 (defcustom smerge-auto-refine t
83 "Automatically highlight changes in detail as the user visits conflicts."
84 :group 'smerge
85 :type 'boolean)
87 (defface smerge-mine
88 '((((min-colors 88) (background light))
89 (:foreground "blue1"))
90 (((background light))
91 (:foreground "blue"))
92 (((min-colors 88) (background dark))
93 (:foreground "cyan1"))
94 (((background dark))
95 (:foreground "cyan")))
96 "Face for your code."
97 :group 'smerge)
98 ;; backward-compatibility alias
99 (put 'smerge-mine-face 'face-alias 'smerge-mine)
100 (defvar smerge-mine-face 'smerge-mine)
102 (defface smerge-other
103 '((((background light))
104 (:foreground "darkgreen"))
105 (((background dark))
106 (:foreground "lightgreen")))
107 "Face for the other code."
108 :group 'smerge)
109 ;; backward-compatibility alias
110 (put 'smerge-other-face 'face-alias 'smerge-other)
111 (defvar smerge-other-face 'smerge-other)
113 (defface smerge-base
114 '((((min-colors 88) (background light))
115 (:foreground "red1"))
116 (((background light))
117 (:foreground "red"))
118 (((background dark))
119 (:foreground "orange")))
120 "Face for the base code."
121 :group 'smerge)
122 ;; backward-compatibility alias
123 (put 'smerge-base-face 'face-alias 'smerge-base)
124 (defvar smerge-base-face 'smerge-base)
126 (defface smerge-markers
127 '((((background light))
128 (:background "grey85"))
129 (((background dark))
130 (:background "grey30")))
131 "Face for the conflict markers."
132 :group 'smerge)
133 ;; backward-compatibility alias
134 (put 'smerge-markers-face 'face-alias 'smerge-markers)
135 (defvar smerge-markers-face 'smerge-markers)
137 (defface smerge-refined-change
138 '((t :background "yellow"))
139 "Face used for char-based changes shown by `smerge-refine'."
140 :group 'smerge)
142 (easy-mmode-defmap smerge-basic-map
143 `(("n" . smerge-next)
144 ("p" . smerge-prev)
145 ("r" . smerge-resolve)
146 ("a" . smerge-keep-all)
147 ("b" . smerge-keep-base)
148 ("o" . smerge-keep-other)
149 ("m" . smerge-keep-mine)
150 ("E" . smerge-ediff)
151 ("C" . smerge-combine-with-next)
152 ("R" . smerge-refine)
153 ("\C-m" . smerge-keep-current)
154 ("=" . ,(make-sparse-keymap "Diff"))
155 ("=<" "base-mine" . smerge-diff-base-mine)
156 ("=>" "base-other" . smerge-diff-base-other)
157 ("==" "mine-other" . smerge-diff-mine-other))
158 "The base keymap for `smerge-mode'.")
160 (defcustom smerge-command-prefix "\C-c^"
161 "Prefix for `smerge-mode' commands."
162 :group 'smerge
163 :type '(choice (string "\e") (string "\C-c^") (string "") string))
165 (easy-mmode-defmap smerge-mode-map
166 `((,smerge-command-prefix . ,smerge-basic-map))
167 "Keymap for `smerge-mode'.")
169 (defvar smerge-check-cache nil)
170 (make-variable-buffer-local 'smerge-check-cache)
171 (defun smerge-check (n)
172 (condition-case nil
173 (let ((state (cons (point) (buffer-modified-tick))))
174 (unless (equal (cdr smerge-check-cache) state)
175 (smerge-match-conflict)
176 (setq smerge-check-cache (cons (match-data) state)))
177 (nth (* 2 n) (car smerge-check-cache)))
178 (error nil)))
180 (easy-menu-define smerge-mode-menu smerge-mode-map
181 "Menu for `smerge-mode'."
182 '("SMerge"
183 ["Next" smerge-next :help "Go to next conflict"]
184 ["Previous" smerge-prev :help "Go to previous conflict"]
185 "--"
186 ["Keep All" smerge-keep-all :help "Keep all three versions"
187 :active (smerge-check 1)]
188 ["Keep Current" smerge-keep-current :help "Use current (at point) version"
189 :active (and (smerge-check 1) (> (smerge-get-current) 0))]
190 "--"
191 ["Revert to Base" smerge-keep-base :help "Revert to base version"
192 :active (smerge-check 2)]
193 ["Keep Other" smerge-keep-other :help "Keep `other' version"
194 :active (smerge-check 3)]
195 ["Keep Yours" smerge-keep-mine :help "Keep your version"
196 :active (smerge-check 1)]
197 "--"
198 ["Diff Base/Mine" smerge-diff-base-mine
199 :help "Diff `base' and `mine' for current conflict"
200 :active (smerge-check 2)]
201 ["Diff Base/Other" smerge-diff-base-other
202 :help "Diff `base' and `other' for current conflict"
203 :active (smerge-check 2)]
204 ["Diff Mine/Other" smerge-diff-mine-other
205 :help "Diff `mine' and `other' for current conflict"
206 :active (smerge-check 1)]
207 "--"
208 ["Invoke Ediff" smerge-ediff
209 :help "Use Ediff to resolve the conflicts"
210 :active (smerge-check 1)]
211 ["Auto Resolve" smerge-resolve
212 :help "Try auto-resolution heuristics"
213 :active (smerge-check 1)]
214 ["Combine" smerge-combine-with-next
215 :help "Combine current conflict with next"
216 :active (smerge-check 1)]
219 (easy-menu-define smerge-context-menu nil
220 "Context menu for mine area in `smerge-mode'."
221 '(nil
222 ["Keep Current" smerge-keep-current :help "Use current (at point) version"]
223 ["Kill Current" smerge-kill-current :help "Remove current (at point) version"]
224 ["Keep All" smerge-keep-all :help "Keep all three versions"]
225 "---"
226 ["More..." (popup-menu smerge-mode-menu) :help "Show full SMerge mode menu"]
229 (defconst smerge-font-lock-keywords
230 '((smerge-find-conflict
231 (1 smerge-mine-face prepend t)
232 (2 smerge-base-face prepend t)
233 (3 smerge-other-face prepend t)
234 ;; FIXME: `keep' doesn't work right with syntactic fontification.
235 (0 smerge-markers-face keep)
236 (4 nil t t)
237 (5 nil t t)))
238 "Font lock patterns for `smerge-mode'.")
240 (defconst smerge-begin-re "^<<<<<<< \\(.*\\)\n")
241 (defconst smerge-end-re "^>>>>>>> .*\n")
242 (defconst smerge-base-re "^||||||| .*\n")
243 (defconst smerge-other-re "^=======\n")
245 (defvar smerge-conflict-style nil
246 "Keep track of which style of conflict is in use.
247 Can be nil if the style is undecided, or else:
248 - `diff3-E'
249 - `diff3-A'")
251 ;; Compiler pacifiers
252 (defvar font-lock-mode)
253 (defvar font-lock-keywords)
255 ;;;;
256 ;;;; Actual code
257 ;;;;
259 ;; Define smerge-next and smerge-prev
260 (easy-mmode-define-navigation smerge smerge-begin-re "conflict" nil nil
261 (if smerge-auto-refine
262 (condition-case nil (smerge-refine) (error nil))))
264 (defconst smerge-match-names ["conflict" "mine" "base" "other"])
266 (defun smerge-ensure-match (n)
267 (unless (match-end n)
268 (error "No `%s'" (aref smerge-match-names n))))
270 (defun smerge-auto-leave ()
271 (when (and smerge-auto-leave
272 (save-excursion (goto-char (point-min))
273 (not (re-search-forward smerge-begin-re nil t))))
274 (when (and (listp buffer-undo-list) smerge-mode)
275 (push (list 'apply 'smerge-mode 1) buffer-undo-list))
276 (smerge-mode -1)))
279 (defun smerge-keep-all ()
280 "Concatenate all versions."
281 (interactive)
282 (smerge-match-conflict)
283 (let ((mb2 (or (match-beginning 2) (point-max)))
284 (me2 (or (match-end 2) (point-min))))
285 (delete-region (match-end 3) (match-end 0))
286 (delete-region (max me2 (match-end 1)) (match-beginning 3))
287 (if (and (match-end 2) (/= (match-end 1) (match-end 3)))
288 (delete-region (match-end 1) (match-beginning 2)))
289 (delete-region (match-beginning 0) (min (match-beginning 1) mb2))
290 (smerge-auto-leave)))
292 (defun smerge-keep-n (n)
293 (smerge-remove-props (match-beginning 0) (match-end 0))
294 ;; We used to use replace-match, but that did not preserve markers so well.
295 (delete-region (match-end n) (match-end 0))
296 (delete-region (match-beginning 0) (match-beginning n)))
298 (defun smerge-combine-with-next ()
299 "Combine the current conflict with the next one."
300 (interactive)
301 (smerge-match-conflict)
302 (let ((ends nil))
303 (dolist (i '(3 2 1 0))
304 (push (if (match-end i) (copy-marker (match-end i) t)) ends))
305 (setq ends (apply 'vector ends))
306 (goto-char (aref ends 0))
307 (if (not (re-search-forward smerge-begin-re nil t))
308 (error "No next conflict")
309 (smerge-match-conflict)
310 (let ((match-data (mapcar (lambda (m) (if m (copy-marker m)))
311 (match-data))))
312 ;; First copy the in-between text in each alternative.
313 (dolist (i '(1 2 3))
314 (when (aref ends i)
315 (goto-char (aref ends i))
316 (insert-buffer-substring (current-buffer)
317 (aref ends 0) (car match-data))))
318 (delete-region (aref ends 0) (car match-data))
319 ;; Then move the second conflict's alternatives into the first.
320 (dolist (i '(1 2 3))
321 (set-match-data match-data)
322 (when (and (aref ends i) (match-end i))
323 (goto-char (aref ends i))
324 (insert-buffer-substring (current-buffer)
325 (match-beginning i) (match-end i))))
326 (delete-region (car match-data) (cadr match-data))
327 ;; Free the markers.
328 (dolist (m match-data) (if m (move-marker m nil)))
329 (mapc (lambda (m) (if m (move-marker m nil))) ends)))))
331 (defvar smerge-resolve-function
332 (lambda () (error "Don't know how to resolve"))
333 "Mode-specific merge function.
334 The function is called with zero or one argument (non-nil if the resolution
335 function should only apply safe heuristics) and with the match data set
336 according to `smerge-match-conflict'.")
337 (add-to-list 'debug-ignored-errors "Don't know how to resolve")
339 (defvar smerge-text-properties
340 `(help-echo "merge conflict: mouse-3 shows a menu"
341 ;; mouse-face highlight
342 keymap (keymap (down-mouse-3 . smerge-popup-context-menu))))
344 (defun smerge-remove-props (beg end)
345 (remove-overlays beg end 'smerge 'refine)
346 (remove-overlays beg end 'smerge 'conflict)
347 ;; Now that we use overlays rather than text-properties, this function
348 ;; does not cause refontification any more. It can be seen very clearly
349 ;; in buffers where jit-lock-contextually is not t, in which case deleting
350 ;; the "<<<<<<< foobar" leading line leaves the rest of the conflict
351 ;; highlighted as if it were still a valid conflict. Note that in many
352 ;; important cases (such as the previous example) we're actually called
353 ;; during font-locking so inhibit-modification-hooks is non-nil, so we
354 ;; can't just modify the buffer and expect font-lock to be triggered as in:
355 ;; (put-text-property beg end 'smerge-force-highlighting nil)
356 (let ((modified (buffer-modified-p)))
357 (remove-text-properties beg end '(fontified nil))
358 (restore-buffer-modified-p modified)))
360 (defun smerge-popup-context-menu (event)
361 "Pop up the Smerge mode context menu under mouse."
362 (interactive "e")
363 (if (and smerge-mode
364 (save-excursion (posn-set-point (event-end event)) (smerge-check 1)))
365 (progn
366 (posn-set-point (event-end event))
367 (smerge-match-conflict)
368 (let ((i (smerge-get-current))
370 (if (<= i 0)
371 ;; Out of range
372 (popup-menu smerge-mode-menu)
373 ;; Install overlay.
374 (setq o (make-overlay (match-beginning i) (match-end i)))
375 (unwind-protect
376 (progn
377 (overlay-put o 'face 'highlight)
378 (sit-for 0) ;Display the new highlighting.
379 (popup-menu smerge-context-menu))
380 ;; Delete overlay.
381 (delete-overlay o)))))
382 ;; There's no conflict at point, the text-props are just obsolete.
383 (save-excursion
384 (let ((beg (re-search-backward smerge-end-re nil t))
385 (end (re-search-forward smerge-begin-re nil t)))
386 (smerge-remove-props (or beg (point-min)) (or end (point-max)))
387 (push event unread-command-events)))))
389 (defun smerge-resolve (&optional safe)
390 "Resolve the conflict at point intelligently.
391 This relies on mode-specific knowledge and thus only works in
392 some major modes. Uses `smerge-resolve-function' to do the actual work."
393 (interactive)
394 (smerge-match-conflict)
395 (smerge-remove-props (match-beginning 0) (match-end 0))
396 (cond
397 ;; Trivial diff3 -A non-conflicts.
398 ((and (eq (match-end 1) (match-end 3))
399 (eq (match-beginning 1) (match-beginning 3)))
400 (smerge-keep-n 3))
401 ;; Mode-specific conflict resolution.
402 ((condition-case nil
403 (atomic-change-group
404 (if safe
405 (funcall smerge-resolve-function safe)
406 (funcall smerge-resolve-function))
408 (error nil))
409 ;; Nothing to do: the resolution function has done it already.
410 nil)
411 ;; FIXME: Add "if [ diff -b MINE OTHER ]; then select OTHER; fi"
412 ((and (match-end 2)
413 ;; FIXME: Add "diff -b BASE MINE | patch OTHER".
414 ;; FIXME: Add "diff -b BASE OTHER | patch MINE".
415 nil)
417 ((and (not (match-end 2))
418 ;; FIXME: Add "diff -b"-based refinement.
419 nil)
422 (error "Don't know how to resolve")))
423 (smerge-auto-leave))
425 (defun smerge-resolve-all ()
426 "Perform automatic resolution on all conflicts."
427 (interactive)
428 (save-excursion
429 (goto-char (point-min))
430 (while (re-search-forward smerge-begin-re nil t)
431 (condition-case nil
432 (progn
433 (smerge-match-conflict)
434 (smerge-resolve 'safe))
435 (error nil)))))
437 (defun smerge-batch-resolve ()
438 ;; command-line-args-left is what is left of the command line.
439 (if (not noninteractive)
440 (error "`smerge-batch-resolve' is to be used only with -batch"))
441 (while command-line-args-left
442 (let ((file (pop command-line-args-left)))
443 (if (string-match "\\.rej\\'" file)
444 ;; .rej files should never contain diff3 markers, on the other hand,
445 ;; in Arch, .rej files are sometimes used to indicate that the
446 ;; main file has diff3 markers. So you can pass **/*.rej and
447 ;; it will DTRT.
448 (setq file (substring file 0 (match-beginning 0))))
449 (message "Resolving conflicts in %s..." file)
450 (when (file-readable-p file)
451 (with-current-buffer (find-file-noselect file)
452 (smerge-resolve-all)
453 (save-buffer)
454 (kill-buffer (current-buffer)))))))
456 (defun smerge-keep-base ()
457 "Revert to the base version."
458 (interactive)
459 (smerge-match-conflict)
460 (smerge-ensure-match 2)
461 (smerge-keep-n 2)
462 (smerge-auto-leave))
464 (defun smerge-keep-other ()
465 "Use \"other\" version."
466 (interactive)
467 (smerge-match-conflict)
468 ;;(smerge-ensure-match 3)
469 (smerge-keep-n 3)
470 (smerge-auto-leave))
472 (defun smerge-keep-mine ()
473 "Keep your version."
474 (interactive)
475 (smerge-match-conflict)
476 ;;(smerge-ensure-match 1)
477 (smerge-keep-n 1)
478 (smerge-auto-leave))
480 (defun smerge-get-current ()
481 (let ((i 3))
482 (while (or (not (match-end i))
483 (< (point) (match-beginning i))
484 (>= (point) (match-end i)))
485 (decf i))
488 (defun smerge-keep-current ()
489 "Use the current (under the cursor) version."
490 (interactive)
491 (smerge-match-conflict)
492 (let ((i (smerge-get-current)))
493 (if (<= i 0) (error "Not inside a version")
494 (smerge-keep-n i)
495 (smerge-auto-leave))))
497 (defun smerge-kill-current ()
498 "Remove the current (under the cursor) version."
499 (interactive)
500 (smerge-match-conflict)
501 (let ((i (smerge-get-current)))
502 (if (<= i 0) (error "Not inside a version")
503 (let ((left nil))
504 (dolist (n '(3 2 1))
505 (if (and (match-end n) (/= (match-end n) (match-end i)))
506 (push n left)))
507 (if (and (cdr left)
508 (/= (match-end (car left)) (match-end (cadr left))))
509 (ding) ;We don't know how to do that.
510 (smerge-keep-n (car left))
511 (smerge-auto-leave))))))
513 (defun smerge-diff-base-mine ()
514 "Diff 'base' and 'mine' version in current conflict region."
515 (interactive)
516 (smerge-diff 2 1))
518 (defun smerge-diff-base-other ()
519 "Diff 'base' and 'other' version in current conflict region."
520 (interactive)
521 (smerge-diff 2 3))
523 (defun smerge-diff-mine-other ()
524 "Diff 'mine' and 'other' version in current conflict region."
525 (interactive)
526 (smerge-diff 1 3))
528 (defun smerge-match-conflict ()
529 "Get info about the conflict. Puts the info in the `match-data'.
530 The submatches contain:
531 0: the whole conflict.
532 1: your code.
533 2: the base code.
534 3: other code.
535 An error is raised if not inside a conflict."
536 (save-excursion
537 (condition-case nil
538 (let* ((orig-point (point))
540 (_ (forward-line 1))
541 (_ (re-search-backward smerge-begin-re))
543 (start (match-beginning 0))
544 (mine-start (match-end 0))
545 (filename (or (match-string 1) ""))
547 (_ (re-search-forward smerge-end-re))
548 (_ (assert (< orig-point (match-end 0))))
550 (other-end (match-beginning 0))
551 (end (match-end 0))
553 (_ (re-search-backward smerge-other-re start))
555 (mine-end (match-beginning 0))
556 (other-start (match-end 0))
558 base-start base-end)
560 ;; handle the various conflict styles
561 (cond
562 ((save-excursion
563 (goto-char mine-start)
564 (re-search-forward smerge-begin-re end t))
565 ;; There's a nested conflict and we're after the the beginning
566 ;; of the outer one but before the beginning of the inner one.
567 ;; Of course, maybe this is not a nested conflict but in that
568 ;; case it can only be something nastier that we don't know how
569 ;; to handle, so may as well arbitrarily decide to treat it as
570 ;; a nested conflict. --Stef
571 (error "There is a nested conflict"))
573 ((re-search-backward smerge-base-re start t)
574 ;; a 3-parts conflict
575 (set (make-local-variable 'smerge-conflict-style) 'diff3-A)
576 (setq base-end mine-end)
577 (setq mine-end (match-beginning 0))
578 (setq base-start (match-end 0)))
580 ((string= filename (file-name-nondirectory
581 (or buffer-file-name "")))
582 ;; a 2-parts conflict
583 (set (make-local-variable 'smerge-conflict-style) 'diff3-E))
585 ((and (not base-start)
586 (or (eq smerge-conflict-style 'diff3-A)
587 (equal filename "ANCESTOR")
588 (string-match "\\`[.0-9]+\\'" filename)))
589 ;; a same-diff conflict
590 (setq base-start mine-start)
591 (setq base-end mine-end)
592 (setq mine-start other-start)
593 (setq mine-end other-end)))
595 (store-match-data (list start end
596 mine-start mine-end
597 base-start base-end
598 other-start other-end
599 (when base-start (1- base-start)) base-start
600 (1- other-start) other-start))
602 (search-failed (error "Point not in conflict region")))))
604 (add-to-list 'debug-ignored-errors "Point not in conflict region")
606 (defun smerge-conflict-overlay (pos)
607 "Return the conflict overlay at POS if any."
608 (let ((ols (overlays-at pos))
609 conflict)
610 (dolist (ol ols)
611 (if (and (eq (overlay-get ol 'smerge) 'conflict)
612 (> (overlay-end ol) pos))
613 (setq conflict ol)))
614 conflict))
616 (defun smerge-find-conflict (&optional limit)
617 "Find and match a conflict region. Intended as a font-lock MATCHER.
618 The submatches are the same as in `smerge-match-conflict'.
619 Returns non-nil if a match is found between point and LIMIT.
620 Point is moved to the end of the conflict."
621 (let ((found nil)
622 (pos (point))
623 conflict)
624 ;; First check to see if point is already inside a conflict, using
625 ;; the conflict overlays.
626 (while (and (not found) (setq conflict (smerge-conflict-overlay pos)))
627 ;; Check the overlay's validity and kill it if it's out of date.
628 (condition-case nil
629 (progn
630 (goto-char (overlay-start conflict))
631 (smerge-match-conflict)
632 (goto-char (match-end 0))
633 (if (<= (point) pos)
634 (error "Matching backward!")
635 (setq found t)))
636 (error (smerge-remove-props
637 (overlay-start conflict) (overlay-end conflict))
638 (goto-char pos))))
639 ;; If we're not already inside a conflict, look for the next conflict
640 ;; and add/update its overlay.
641 (while (and (not found) (re-search-forward smerge-begin-re limit t))
642 (condition-case nil
643 (progn
644 (smerge-match-conflict)
645 (goto-char (match-end 0))
646 (let ((conflict (smerge-conflict-overlay (1- (point)))))
647 (if conflict
648 ;; Update its location, just in case it got messed up.
649 (move-overlay conflict (match-beginning 0) (match-end 0))
650 (setq conflict (make-overlay (match-beginning 0) (match-end 0)
651 nil 'front-advance nil))
652 (overlay-put conflict 'evaporate t)
653 (overlay-put conflict 'smerge 'conflict)
654 (let ((props smerge-text-properties))
655 (while props
656 (overlay-put conflict (pop props) (pop props))))))
657 (setq found t))
658 (error nil)))
659 found))
661 ;;; Refined change highlighting
663 (defvar smerge-refine-forward-function 'smerge-refine-forward
664 "Function used to determine an \"atomic\" element.
665 You can set it to `forward-char' to get char-level granularity.
666 Its behavior has mainly two restrictions:
667 - if this function encounters a newline, it's important that it stops right
668 after the newline.
669 This only matters if `smerge-refine-ignore-whitespace' is nil.
670 - it needs to be unaffected by changes performed by the `preproc' argument
671 to `smerge-refine-subst'.
672 This only matters if `smerge-refine-weight-hack' is nil.")
674 (defvar smerge-refine-ignore-whitespace t
675 "If non-nil,Indicate that smerge-refine should try to ignore change in whitespace.")
677 (defvar smerge-refine-weight-hack t
678 "If non-nil, pass to diff as many lines as there are chars in the region.
679 I.e. each atomic element (e.g. word) will be copied as many times (on different
680 lines) as it has chars. This has 2 advantages:
681 - if `diff' tries to minimize the number *lines* (rather than chars)
682 added/removed, this adjust the weights so that adding/removing long
683 symbols is considered correspondingly more costly.
684 - `smerge-refine-forward-function' only needs to be called when chopping up
685 the regions, and `forward-char' can be used afterwards.
686 It has the following disadvantages:
687 - cannot use `diff -w' because the weighting causes added spaces in a line
688 to be represented as added copies of some line, so `diff -w' can't do the
689 right thing any more.
690 - may in degenerate cases take a 1KB input region and turn it into a 1MB
691 file to pass to diff.")
693 (defun smerge-refine-forward (n)
694 (let ((case-fold-search nil)
695 (re "[[:upper:]]?[[:lower:]]+\\|[[:upper:]]+\\|[[:digit:]]+\\|.\\|\n"))
696 (when (and smerge-refine-ignore-whitespace
697 ;; smerge-refine-weight-hack causes additional spaces to
698 ;; appear as additional lines as well, so even if diff ignore
699 ;; whitespace changes, it'll report added/removed lines :-(
700 (not smerge-refine-weight-hack))
701 (setq re (concat "[ \t]*\\(?:" re "\\)")))
702 (dotimes (i n)
703 (unless (looking-at re) (error "Smerge refine internal error"))
704 (goto-char (match-end 0)))))
706 (defun smerge-refine-chopup-region (beg end file &optional preproc)
707 "Chopup the region into small elements, one per line.
708 Save the result into FILE.
709 If non-nil, PREPROC is called with no argument in a buffer that contains
710 a copy of the text, just before chopping it up. It can be used to replace
711 chars to try and eliminate some spurious differences."
712 ;; We used to chop up char-by-char rather than word-by-word like ediff
713 ;; does. It had the benefit of simplicity and very fine results, but it
714 ;; often suffered from problem that diff would find correlations where
715 ;; there aren't any, so the resulting "change" didn't make much sense.
716 ;; You can still get this behavior by setting
717 ;; `smerge-refine-forward-function' to `forward-char'.
718 (let ((buf (current-buffer)))
719 (with-temp-buffer
720 (insert-buffer-substring buf beg end)
721 (when preproc (goto-char (point-min)) (funcall preproc))
722 (when smerge-refine-ignore-whitespace
723 ;; It doesn't make much of a difference for diff-fine-highlight
724 ;; because we still have the _/+/</>/! prefix anyway. Can still be
725 ;; useful in other circumstances.
726 (subst-char-in-region (point-min) (point-max) ?\n ?\s))
727 (goto-char (point-min))
728 (while (not (eobp))
729 (funcall smerge-refine-forward-function 1)
730 (let ((s (if (prog2 (forward-char -1) (bolp) (forward-char 1))
732 (buffer-substring (line-beginning-position) (point)))))
733 ;; We add \n after each char except after \n, so we get
734 ;; one line per text char, where each line contains
735 ;; just one char, except for \n chars which are
736 ;; represented by the empty line.
737 (unless (eq (char-before) ?\n) (insert ?\n))
738 ;; HACK ALERT!!
739 (if smerge-refine-weight-hack
740 (dotimes (i (1- (length s))) (insert s "\n")))))
741 (unless (bolp) (error "Smerge refine internal error"))
742 (let ((coding-system-for-write 'emacs-mule))
743 (write-region (point-min) (point-max) file nil 'nomessage)))))
745 (defun smerge-refine-highlight-change (buf beg match-num1 match-num2 props)
746 (with-current-buffer buf
747 (goto-char beg)
748 (let* ((startline (- (string-to-number match-num1) 1))
749 (beg (progn (funcall (if smerge-refine-weight-hack
750 'forward-char
751 smerge-refine-forward-function)
752 startline)
753 (point)))
754 (end (progn (funcall (if smerge-refine-weight-hack
755 'forward-char
756 smerge-refine-forward-function)
757 (if match-num2
758 (- (string-to-number match-num2)
759 startline)
761 (point))))
762 (when smerge-refine-ignore-whitespace
763 (skip-chars-backward " \t\n" beg) (setq end (point))
764 (goto-char beg)
765 (skip-chars-forward " \t\n" end) (setq beg (point)))
766 (when (> end beg)
767 (let ((ol (make-overlay
768 beg end nil
769 ;; Make them tend to shrink rather than spread when editing.
770 'front-advance nil)))
771 (overlay-put ol 'evaporate t)
772 (dolist (x props) (overlay-put ol (car x) (cdr x)))
773 ol)))))
775 (defun smerge-refine-subst (beg1 end1 beg2 end2 props &optional preproc)
776 "Show fine differences in the two regions BEG1..END1 and BEG2..END2.
777 PROPS is an alist of properties to put (via overlays) on the changes.
778 If non-nil, PREPROC is called with no argument in a buffer that contains
779 a copy of a region, just before preparing it to for `diff'. It can be used to
780 replace chars to try and eliminate some spurious differences."
781 (let* ((buf (current-buffer))
782 (pos (point))
783 (file1 (make-temp-file "diff1"))
784 (file2 (make-temp-file "diff2")))
785 ;; Chop up regions into smaller elements and save into files.
786 (smerge-refine-chopup-region beg1 end1 file1 preproc)
787 (smerge-refine-chopup-region beg2 end2 file2 preproc)
789 ;; Call diff on those files.
790 (unwind-protect
791 (with-temp-buffer
792 (let ((coding-system-for-read 'emacs-mule))
793 (call-process diff-command nil t nil
794 (if (and smerge-refine-ignore-whitespace
795 (not smerge-refine-weight-hack))
796 ;; Pass -a so diff treats it as a text file even
797 ;; if it contains \0 and such.
798 ;; Pass -d so as to get the smallest change, but
799 ;; also and more importantly because otherwise it
800 ;; may happen that diff doesn't behave like
801 ;; smerge-refine-weight-hack expects it to.
802 ;; See http://thread.gmane.org/gmane.emacs.devel/82685.
803 "-awd" "-ad")
804 file1 file2))
805 ;; Process diff's output.
806 (goto-char (point-min))
807 (let ((last1 nil)
808 (last2 nil))
809 (while (not (eobp))
810 (if (not (looking-at "\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?\\([acd]\\)\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?$"))
811 (error "Unexpected patch hunk header: %s"
812 (buffer-substring (point) (line-end-position))))
813 (let ((op (char-after (match-beginning 3)))
814 (m1 (match-string 1))
815 (m2 (match-string 2))
816 (m4 (match-string 4))
817 (m5 (match-string 5)))
818 (when (memq op '(?d ?c))
819 (setq last1
820 (smerge-refine-highlight-change buf beg1 m1 m2 props)))
821 (when (memq op '(?a ?c))
822 (setq last2
823 (smerge-refine-highlight-change buf beg2 m4 m5 props))))
824 (forward-line 1) ;Skip hunk header.
825 (and (re-search-forward "^[0-9]" nil 'move) ;Skip hunk body.
826 (goto-char (match-beginning 0))))
827 ;; (assert (or (null last1) (< (overlay-start last1) end1)))
828 ;; (assert (or (null last2) (< (overlay-start last2) end2)))
829 (if smerge-refine-weight-hack
830 (progn
831 ;; (assert (or (null last1) (<= (overlay-end last1) end1)))
832 ;; (assert (or (null last2) (<= (overlay-end last2) end2)))
834 ;; smerge-refine-forward-function when calling in chopup may
835 ;; have stopped because it bumped into EOB whereas in
836 ;; smerge-refine-weight-hack it may go a bit further.
837 (if (and last1 (> (overlay-end last1) end1))
838 (move-overlay last1 (overlay-start last1) end1))
839 (if (and last2 (> (overlay-end last2) end2))
840 (move-overlay last2 (overlay-start last2) end2))
842 (goto-char pos)
843 (delete-file file1)
844 (delete-file file2))))
846 (defun smerge-refine ()
847 "Highlight the parts of the conflict that are different."
848 (interactive)
849 ;; FIXME: make it work with 3-way conflicts.
850 (smerge-match-conflict)
851 (remove-overlays (match-beginning 0) (match-end 0) 'smerge 'refine)
852 (smerge-ensure-match 1)
853 (smerge-ensure-match 3)
854 (smerge-refine-subst (match-beginning 1) (match-end 1)
855 (match-beginning 3) (match-end 3)
856 '((smerge . refine)
857 (face . smerge-refined-change))))
859 (defun smerge-diff (n1 n2)
860 (smerge-match-conflict)
861 (smerge-ensure-match n1)
862 (smerge-ensure-match n2)
863 (let ((name1 (aref smerge-match-names n1))
864 (name2 (aref smerge-match-names n2))
865 ;; Read them before the match-data gets clobbered.
866 (beg1 (match-beginning n1))
867 (end1 (match-end n1))
868 (beg2 (match-beginning n2))
869 (end2 (match-end n2))
870 (file1 (make-temp-file "smerge1"))
871 (file2 (make-temp-file "smerge2"))
872 (dir default-directory)
873 (file (if buffer-file-name (file-relative-name buffer-file-name)))
874 ;; We would want to use `emacs-mule-unix' for read&write, but we
875 ;; bump into problems with the coding-system used by diff to write
876 ;; the file names and the time stamps in the header.
877 ;; `buffer-file-coding-system' is not always correct either, but if
878 ;; the OS/user uses only one coding-system, then it works.
879 (coding-system-for-read buffer-file-coding-system))
880 (write-region beg1 end1 file1 nil 'nomessage)
881 (write-region beg2 end2 file2 nil 'nomessage)
882 (unwind-protect
883 (with-current-buffer (get-buffer-create smerge-diff-buffer-name)
884 (setq default-directory dir)
885 (let ((inhibit-read-only t))
886 (erase-buffer)
887 (let ((status
888 (apply 'call-process diff-command nil t nil
889 (append smerge-diff-switches
890 (list "-L" (concat name1 "/" file)
891 "-L" (concat name2 "/" file)
892 file1 file2)))))
893 (if (eq status 0) (insert "No differences found.\n"))))
894 (goto-char (point-min))
895 (diff-mode)
896 (display-buffer (current-buffer) t))
897 (delete-file file1)
898 (delete-file file2))))
900 ;; compiler pacifiers
901 (defvar smerge-ediff-windows)
902 (defvar smerge-ediff-buf)
903 (defvar ediff-buffer-A)
904 (defvar ediff-buffer-B)
905 (defvar ediff-buffer-C)
906 (defvar ediff-ancestor-buffer)
907 (defvar ediff-quit-hook)
908 (declare-function ediff-cleanup-mess "ediff-util" nil)
910 ;;;###autoload
911 (defun smerge-ediff (&optional name-mine name-other name-base)
912 "Invoke ediff to resolve the conflicts.
913 NAME-MINE, NAME-OTHER, and NAME-BASE, if non-nil, are used for the
914 buffer names."
915 (interactive)
916 (let* ((buf (current-buffer))
917 (mode major-mode)
918 ;;(ediff-default-variant 'default-B)
919 (config (current-window-configuration))
920 (filename (file-name-nondirectory buffer-file-name))
921 (mine (generate-new-buffer
922 (or name-mine (concat "*" filename " MINE*"))))
923 (other (generate-new-buffer
924 (or name-other (concat "*" filename " OTHER*"))))
925 base)
926 (with-current-buffer mine
927 (buffer-disable-undo)
928 (insert-buffer-substring buf)
929 (goto-char (point-min))
930 (while (smerge-find-conflict)
931 (when (match-beginning 2) (setq base t))
932 (smerge-keep-n 1))
933 (buffer-enable-undo)
934 (set-buffer-modified-p nil)
935 (funcall mode))
937 (with-current-buffer other
938 (buffer-disable-undo)
939 (insert-buffer-substring buf)
940 (goto-char (point-min))
941 (while (smerge-find-conflict)
942 (smerge-keep-n 3))
943 (buffer-enable-undo)
944 (set-buffer-modified-p nil)
945 (funcall mode))
947 (when base
948 (setq base (generate-new-buffer
949 (or name-base (concat "*" filename " BASE*"))))
950 (with-current-buffer base
951 (buffer-disable-undo)
952 (insert-buffer-substring buf)
953 (goto-char (point-min))
954 (while (smerge-find-conflict)
955 (if (match-end 2)
956 (smerge-keep-n 2)
957 (delete-region (match-beginning 0) (match-end 0))))
958 (buffer-enable-undo)
959 (set-buffer-modified-p nil)
960 (funcall mode)))
962 ;; the rest of the code is inspired from vc.el
963 ;; Fire up ediff.
964 (set-buffer
965 (if base
966 (ediff-merge-buffers-with-ancestor mine other base)
967 ;; nil 'ediff-merge-revisions-with-ancestor buffer-file-name)
968 (ediff-merge-buffers mine other)))
969 ;; nil 'ediff-merge-revisions buffer-file-name)))
971 ;; Ediff is now set up, and we are in the control buffer.
972 ;; Do a few further adjustments and take precautions for exit.
973 (set (make-local-variable 'smerge-ediff-windows) config)
974 (set (make-local-variable 'smerge-ediff-buf) buf)
975 (set (make-local-variable 'ediff-quit-hook)
976 (lambda ()
977 (let ((buffer-A ediff-buffer-A)
978 (buffer-B ediff-buffer-B)
979 (buffer-C ediff-buffer-C)
980 (buffer-Ancestor ediff-ancestor-buffer)
981 (buf smerge-ediff-buf)
982 (windows smerge-ediff-windows))
983 (ediff-cleanup-mess)
984 (with-current-buffer buf
985 (erase-buffer)
986 (insert-buffer-substring buffer-C)
987 (kill-buffer buffer-A)
988 (kill-buffer buffer-B)
989 (kill-buffer buffer-C)
990 (when (bufferp buffer-Ancestor) (kill-buffer buffer-Ancestor))
991 (set-window-configuration windows)
992 (message "Conflict resolution finished; you may save the buffer")))))
993 (message "Please resolve conflicts now; exit ediff when done")))
996 (defconst smerge-parsep-re
997 (concat smerge-begin-re "\\|" smerge-end-re "\\|"
998 smerge-base-re "\\|" smerge-other-re "\\|"))
1000 ;;;###autoload
1001 (define-minor-mode smerge-mode
1002 "Minor mode to simplify editing output from the diff3 program.
1003 \\{smerge-mode-map}"
1004 :group 'smerge :lighter " SMerge"
1005 (when (and (boundp 'font-lock-mode) font-lock-mode)
1006 (save-excursion
1007 (if smerge-mode
1008 (font-lock-add-keywords nil smerge-font-lock-keywords 'append)
1009 (font-lock-remove-keywords nil smerge-font-lock-keywords))
1010 (goto-char (point-min))
1011 (while (smerge-find-conflict)
1012 (save-excursion
1013 (font-lock-fontify-region (match-beginning 0) (match-end 0) nil)))))
1014 (if (string-match (regexp-quote smerge-parsep-re) paragraph-separate)
1015 (unless smerge-mode
1016 (set (make-local-variable 'paragraph-separate)
1017 (replace-match "" t t paragraph-separate)))
1018 (when smerge-mode
1019 (set (make-local-variable 'paragraph-separate)
1020 (concat smerge-parsep-re paragraph-separate))))
1021 (unless smerge-mode
1022 (smerge-remove-props (point-min) (point-max))))
1025 (provide 'smerge-mode)
1027 ;; arch-tag: 605c8d1e-e43d-4943-a6f3-1bcc4333e690
1028 ;;; smerge-mode.el ends here