1 ;;; smerge-mode.el --- Minor mode to resolve diff3 conflicts
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
4 ;; 2007, 2008 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 of the License, or
14 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
26 ;; Provides a lightweight alternative to emerge/ediff.
27 ;; To use it, simply add to your .emacs the following lines:
29 ;; (autoload 'smerge-mode "smerge-mode" nil t)
31 ;; you can even have it turned on automatically with the following
32 ;; piece of code in your .emacs:
34 ;; (defun sm-try-smerge ()
36 ;; (goto-char (point-min))
37 ;; (when (re-search-forward "^<<<<<<< " nil t)
39 ;; (add-hook 'find-file-hook 'sm-try-smerge t)
43 ;; - if requested, ask the user whether he wants to call ediff right away
47 (eval-when-compile (require 'cl
) (require 'diff-mode
))
50 ;;; The real definition comes later.
54 "Minor mode to highlight and resolve diff3 conflicts."
58 (defcustom smerge-diff-buffer-name
"*vc-diff*"
59 "Buffer name to use for displaying diffs."
64 (const "*smerge-diff*")
67 (defcustom smerge-diff-switches
69 (if (listp diff-switches
) diff-switches
(list diff-switches
)))
70 "A list of strings specifying switches to be passed to diff.
71 Used in `smerge-diff-base-mine' and related functions."
73 :type
'(repeat string
))
75 (defcustom smerge-auto-leave t
76 "Non-nil means to leave `smerge-mode' when the last conflict is resolved."
81 '((((min-colors 88) (background light
))
82 (:foreground
"blue1"))
85 (((min-colors 88) (background dark
))
86 (:foreground
"cyan1"))
88 (:foreground
"cyan")))
91 ;; backward-compatibility alias
92 (put 'smerge-mine-face
'face-alias
'smerge-mine
)
93 (defvar smerge-mine-face
'smerge-mine
)
96 '((((background light
))
97 (:foreground
"darkgreen"))
99 (:foreground
"lightgreen")))
100 "Face for the other code."
102 ;; backward-compatibility alias
103 (put 'smerge-other-face
'face-alias
'smerge-other
)
104 (defvar smerge-other-face
'smerge-other
)
107 '((((min-colors 88) (background light
))
108 (:foreground
"red1"))
109 (((background light
))
112 (:foreground
"orange")))
113 "Face for the base code."
115 ;; backward-compatibility alias
116 (put 'smerge-base-face
'face-alias
'smerge-base
)
117 (defvar smerge-base-face
'smerge-base
)
119 (defface smerge-markers
120 '((((background light
))
121 (:background
"grey85"))
123 (:background
"grey30")))
124 "Face for the conflict markers."
126 ;; backward-compatibility alias
127 (put 'smerge-markers-face
'face-alias
'smerge-markers
)
128 (defvar smerge-markers-face
'smerge-markers
)
130 (defface smerge-refined-change
131 '((t :background
"yellow"))
132 "Face used for char-based changes shown by `smerge-refine'."
135 (easy-mmode-defmap smerge-basic-map
136 `(("n" . smerge-next
)
138 ("r" . smerge-resolve
)
139 ("a" . smerge-keep-all
)
140 ("b" . smerge-keep-base
)
141 ("o" . smerge-keep-other
)
142 ("m" . smerge-keep-mine
)
144 ("C" . smerge-combine-with-next
)
145 ("R" . smerge-refine
)
146 ("\C-m" . smerge-keep-current
)
147 ("=" .
,(make-sparse-keymap "Diff"))
148 ("=<" "base-mine" . smerge-diff-base-mine
)
149 ("=>" "base-other" . smerge-diff-base-other
)
150 ("==" "mine-other" . smerge-diff-mine-other
))
151 "The base keymap for `smerge-mode'.")
153 (defcustom smerge-command-prefix
"\C-c^"
154 "Prefix for `smerge-mode' commands."
156 :type
'(choice (const :tag
"ESC" "\e")
157 (const :tag
"C-c ^" "\C-c^" )
158 (const :tag
"none" "")
161 (easy-mmode-defmap smerge-mode-map
162 `((,smerge-command-prefix .
,smerge-basic-map
))
163 "Keymap for `smerge-mode'.")
165 (defvar smerge-check-cache nil
)
166 (make-variable-buffer-local 'smerge-check-cache
)
167 (defun smerge-check (n)
169 (let ((state (cons (point) (buffer-modified-tick))))
170 (unless (equal (cdr smerge-check-cache
) state
)
171 (smerge-match-conflict)
172 (setq smerge-check-cache
(cons (match-data) state
)))
173 (nth (* 2 n
) (car smerge-check-cache
)))
176 (easy-menu-define smerge-mode-menu smerge-mode-map
177 "Menu for `smerge-mode'."
179 ["Next" smerge-next
:help
"Go to next conflict"]
180 ["Previous" smerge-prev
:help
"Go to previous conflict"]
182 ["Keep All" smerge-keep-all
:help
"Keep all three versions"
183 :active
(smerge-check 1)]
184 ["Keep Current" smerge-keep-current
:help
"Use current (at point) version"
185 :active
(and (smerge-check 1) (> (smerge-get-current) 0))]
187 ["Revert to Base" smerge-keep-base
:help
"Revert to base version"
188 :active
(smerge-check 2)]
189 ["Keep Other" smerge-keep-other
:help
"Keep `other' version"
190 :active
(smerge-check 3)]
191 ["Keep Yours" smerge-keep-mine
:help
"Keep your version"
192 :active
(smerge-check 1)]
194 ["Diff Base/Mine" smerge-diff-base-mine
195 :help
"Diff `base' and `mine' for current conflict"
196 :active
(smerge-check 2)]
197 ["Diff Base/Other" smerge-diff-base-other
198 :help
"Diff `base' and `other' for current conflict"
199 :active
(smerge-check 2)]
200 ["Diff Mine/Other" smerge-diff-mine-other
201 :help
"Diff `mine' and `other' for current conflict"
202 :active
(smerge-check 1)]
204 ["Invoke Ediff" smerge-ediff
205 :help
"Use Ediff to resolve the conflicts"
206 :active
(smerge-check 1)]
207 ["Auto Resolve" smerge-resolve
208 :help
"Try auto-resolution heuristics"
209 :active
(smerge-check 1)]
210 ["Combine" smerge-combine-with-next
211 :help
"Combine current conflict with next"
212 :active
(smerge-check 1)]
215 (easy-menu-define smerge-context-menu nil
216 "Context menu for mine area in `smerge-mode'."
218 ["Keep Current" smerge-keep-current
:help
"Use current (at point) version"]
219 ["Kill Current" smerge-kill-current
:help
"Remove current (at point) version"]
220 ["Keep All" smerge-keep-all
:help
"Keep all three versions"]
222 ["More..." (popup-menu smerge-mode-menu
) :help
"Show full SMerge mode menu"]
225 (defconst smerge-font-lock-keywords
226 '((smerge-find-conflict
227 (1 smerge-mine-face prepend t
)
228 (2 smerge-base-face prepend t
)
229 (3 smerge-other-face prepend t
)
230 ;; FIXME: `keep' doesn't work right with syntactic fontification.
231 (0 smerge-markers-face keep
)
234 "Font lock patterns for `smerge-mode'.")
236 (defconst smerge-begin-re
"^<<<<<<< \\(.*\\)\n")
237 (defconst smerge-end-re
"^>>>>>>> .*\n")
238 (defconst smerge-base-re
"^||||||| .*\n")
239 (defconst smerge-other-re
"^=======\n")
241 (defvar smerge-conflict-style nil
242 "Keep track of which style of conflict is in use.
243 Can be nil if the style is undecided, or else:
247 ;; Compiler pacifiers
248 (defvar font-lock-mode
)
249 (defvar font-lock-keywords
)
255 ;; Define smerge-next and smerge-prev
256 (easy-mmode-define-navigation smerge smerge-begin-re
"conflict" nil nil
257 (if diff-auto-refine-mode
258 (condition-case nil
(smerge-refine) (error nil
))))
260 (defconst smerge-match-names
["conflict" "mine" "base" "other"])
262 (defun smerge-ensure-match (n)
263 (unless (match-end n
)
264 (error "No `%s'" (aref smerge-match-names n
))))
266 (defun smerge-auto-leave ()
267 (when (and smerge-auto-leave
268 (save-excursion (goto-char (point-min))
269 (not (re-search-forward smerge-begin-re nil t
))))
270 (when (and (listp buffer-undo-list
) smerge-mode
)
271 (push (list 'apply
'smerge-mode
1) buffer-undo-list
))
275 (defun smerge-keep-all ()
276 "Concatenate all versions."
278 (smerge-match-conflict)
279 (let ((mb2 (or (match-beginning 2) (point-max)))
280 (me2 (or (match-end 2) (point-min))))
281 (delete-region (match-end 3) (match-end 0))
282 (delete-region (max me2
(match-end 1)) (match-beginning 3))
283 (if (and (match-end 2) (/= (match-end 1) (match-end 3)))
284 (delete-region (match-end 1) (match-beginning 2)))
285 (delete-region (match-beginning 0) (min (match-beginning 1) mb2
))
286 (smerge-auto-leave)))
288 (defun smerge-keep-n (n)
289 (smerge-remove-props (match-beginning 0) (match-end 0))
290 ;; We used to use replace-match, but that did not preserve markers so well.
291 (delete-region (match-end n
) (match-end 0))
292 (delete-region (match-beginning 0) (match-beginning n
)))
294 (defun smerge-combine-with-next ()
295 "Combine the current conflict with the next one."
296 ;; `smerge-auto-combine' relies on the finish position (at the beginning
297 ;; of the closing marker).
299 (smerge-match-conflict)
301 (dolist (i '(3 2 1 0))
302 (push (if (match-end i
) (copy-marker (match-end i
) t
)) ends
))
303 (setq ends
(apply 'vector ends
))
304 (goto-char (aref ends
0))
305 (if (not (re-search-forward smerge-begin-re nil t
))
306 (error "No next conflict")
307 (smerge-match-conflict)
308 (let ((match-data (mapcar (lambda (m) (if m
(copy-marker m
)))
310 ;; First copy the in-between text in each alternative.
313 (goto-char (aref ends i
))
314 (insert-buffer-substring (current-buffer)
315 (aref ends
0) (car match-data
))))
316 (delete-region (aref ends
0) (car match-data
))
317 ;; Then move the second conflict's alternatives into the first.
319 (set-match-data match-data
)
320 (when (and (aref ends i
) (match-end i
))
321 (goto-char (aref ends i
))
322 (insert-buffer-substring (current-buffer)
323 (match-beginning i
) (match-end i
))))
324 (delete-region (car match-data
) (cadr match-data
))
326 (dolist (m match-data
) (if m
(move-marker m nil
)))
327 (mapc (lambda (m) (if m
(move-marker m nil
))) ends
)))))
329 (defvar smerge-auto-combine-max-separation
2
330 "Max number of lines between conflicts that should be combined.")
332 (defun smerge-auto-combine ()
333 "Automatically combine conflicts that are near each other."
336 (goto-char (point-min))
337 (while (smerge-find-conflict)
338 ;; 2 is 1 (default) + 1 (the begin markers).
339 (while (save-excursion
340 (smerge-find-conflict
341 (line-beginning-position
342 (+ 2 smerge-auto-combine-max-separation
))))
343 (forward-line -
1) ;Go back inside the conflict.
344 (smerge-combine-with-next)
345 (forward-line 1) ;Move past the end of the conflict.
348 (defvar smerge-resolve-function
349 (lambda () (error "Don't know how to resolve"))
350 "Mode-specific merge function.
351 The function is called with zero or one argument (non-nil if the resolution
352 function should only apply safe heuristics) and with the match data set
353 according to `smerge-match-conflict'.")
354 (add-to-list 'debug-ignored-errors
"Don't know how to resolve")
356 (defvar smerge-text-properties
357 `(help-echo "merge conflict: mouse-3 shows a menu"
358 ;; mouse-face highlight
359 keymap
(keymap (down-mouse-3 . smerge-popup-context-menu
))))
361 (defun smerge-remove-props (beg end
)
362 (remove-overlays beg end
'smerge
'refine
)
363 (remove-overlays beg end
'smerge
'conflict
)
364 ;; Now that we use overlays rather than text-properties, this function
365 ;; does not cause refontification any more. It can be seen very clearly
366 ;; in buffers where jit-lock-contextually is not t, in which case deleting
367 ;; the "<<<<<<< foobar" leading line leaves the rest of the conflict
368 ;; highlighted as if it were still a valid conflict. Note that in many
369 ;; important cases (such as the previous example) we're actually called
370 ;; during font-locking so inhibit-modification-hooks is non-nil, so we
371 ;; can't just modify the buffer and expect font-lock to be triggered as in:
372 ;; (put-text-property beg end 'smerge-force-highlighting nil)
373 (let ((modified (buffer-modified-p)))
374 (remove-text-properties beg end
'(fontified nil
))
375 (restore-buffer-modified-p modified
)))
377 (defun smerge-popup-context-menu (event)
378 "Pop up the Smerge mode context menu under mouse."
381 (save-excursion (posn-set-point (event-end event
)) (smerge-check 1)))
383 (posn-set-point (event-end event
))
384 (smerge-match-conflict)
385 (let ((i (smerge-get-current))
389 (popup-menu smerge-mode-menu
)
391 (setq o
(make-overlay (match-beginning i
) (match-end i
)))
394 (overlay-put o
'face
'highlight
)
395 (sit-for 0) ;Display the new highlighting.
396 (popup-menu smerge-context-menu
))
398 (delete-overlay o
)))))
399 ;; There's no conflict at point, the text-props are just obsolete.
401 (let ((beg (re-search-backward smerge-end-re nil t
))
402 (end (re-search-forward smerge-begin-re nil t
)))
403 (smerge-remove-props (or beg
(point-min)) (or end
(point-max)))
404 (push event unread-command-events
)))))
406 (defun smerge-apply-resolution-patch (buf m0b m0e m3b m3e
&optional m2b
)
407 "Replace the conflict with a bunch of subconflicts.
408 BUF contains a plain diff between match-1 and match-3."
410 (textbuf (current-buffer))
411 (name1 (progn (goto-char m0b
)
412 (buffer-substring (+ (point) 8) (line-end-position))))
413 (name2 (when m2b
(goto-char m2b
) (forward-line -
1)
414 (buffer-substring (+ (point) 8) (line-end-position))))
415 (name3 (progn (goto-char m0e
) (forward-line -
1)
416 (buffer-substring (+ (point) 8) (line-end-position)))))
417 (smerge-remove-props m0b m0e
)
418 (delete-region m3e m0e
)
419 (delete-region m0b m3b
)
421 (setq m3e
(- m3e
(- m3b m0b
)))
423 (with-current-buffer buf
424 (goto-char (point-min))
426 (if (not (looking-at "\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?\\([acd]\\)\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?$"))
427 (error "Unexpected patch hunk header: %s"
428 (buffer-substring (point) (line-end-position)))
429 (let* ((op (char-after (match-beginning 3)))
430 (startline (+ (string-to-number (match-string 1))
431 ;; No clue why this is the way it is, but line
432 ;; numbers seem to be off-by-one for `a' ops.
433 (if (eq op ?a
) 1 0)))
434 (endline (if (eq op ?a
) startline
435 (1+ (if (match-end 2)
436 (string-to-number (match-string 2))
438 (lines (- endline startline
))
441 ((null (match-end 5)) 1)
442 (t (- (string-to-number (match-string 5))
443 (string-to-number (match-string 4)) -
1))))
445 (forward-line 1) ;Skip header.
446 (forward-line lines
) ;Skip deleted text.
447 (if (eq op ?c
) (forward-line 1)) ;Skip separator.
449 (if (null otherlines
) ""
451 (dotimes (i otherlines
) (delete-char 2) (forward-line 1))
452 (buffer-substring pos
(point)))))
453 (with-current-buffer textbuf
454 (forward-line (- startline line
))
455 (insert "<<<<<<< " name1
"\n" othertext
456 (if name2
(concat "||||||| " name2
"\n") "")
459 (insert ">>>>>>> " name3
"\n")
460 (setq line endline
))))))))
462 (defun smerge-resolve (&optional safe
)
463 "Resolve the conflict at point intelligently.
464 This relies on mode-specific knowledge and thus only works in
465 some major modes. Uses `smerge-resolve-function' to do the actual work."
467 (smerge-match-conflict)
468 (smerge-remove-props (match-beginning 0) (match-end 0))
469 (let ((md (match-data))
470 (m0b (match-beginning 0))
471 (m1b (match-beginning 1))
472 (m2b (match-beginning 2))
473 (m3b (match-beginning 3))
478 (buf (generate-new-buffer " *smerge*"))
483 ;; Trivial diff3 -A non-conflicts.
484 ((and (eq (match-end 1) (match-end 3))
485 (eq (match-beginning 1) (match-beginning 3)))
487 ;; Mode-specific conflict resolution.
491 (funcall smerge-resolve-function safe
)
492 (funcall smerge-resolve-function
))
495 ;; Nothing to do: the resolution function has done it already.
498 ((and (eq m1e m3e
) (eq m1b m3b
))
499 (set-match-data md
) (smerge-keep-n 3))
500 ;; Refine a 2-way conflict using "diff -b".
501 ;; In case of a 3-way conflict with an empty base
502 ;; (i.e. 2 conflicting additions), we do the same, presuming
503 ;; that the 2 additions should be somehow merged rather
504 ;; than concatenated.
505 ((let ((lines (count-lines m3b m3e
)))
506 (setq m
(make-temp-file "smm"))
507 (write-region m1b m1e m nil
'silent
)
508 (setq o
(make-temp-file "smo"))
509 (write-region m3b m3e o nil
'silent
)
510 (not (or (eq m1b m1e
) (eq m3b m3e
)
511 (and (not (zerop (call-process diff-command
512 nil buf nil
"-b" o m
)))
513 ;; TODO: We don't know how to do the refinement
514 ;; if there's a non-empty ancestor and m1 and m3
515 ;; aren't just plain equal.
516 m2b
(not (eq m2b m2e
)))
517 (with-current-buffer buf
518 (goto-char (point-min))
519 ;; Make sure there's some refinement.
521 (concat "1," (number-to-string lines
) "c"))))))
522 (smerge-apply-resolution-patch buf m0b m0e m3b m3e m2b
))
523 ;; "Mere whitespace changes" conflicts.
525 (setq b
(make-temp-file "smb"))
526 (write-region m2b m2e b nil
'silent
)
527 (with-current-buffer buf
(erase-buffer))
528 ;; Only minor whitespace changes made locally.
529 ;; BEWARE: pass "-c" 'cause the output is reused in the next test.
530 (zerop (call-process diff-command nil buf nil
"-bc" b m
)))
533 ;; Try "diff -b BASE MINE | patch OTHER".
534 ((when (and (not safe
) m2e b
535 ;; If the BASE is empty, this would just concatenate
536 ;; the two, which is rarely right.
538 ;; BEWARE: we're using here the patch of the previous test.
539 (with-current-buffer buf
540 (zerop (call-process-region
541 (point-min) (point-max) "patch" t nil nil
542 "-r" "/dev/null" "--no-backup-if-mismatch"
545 (narrow-to-region m0b m0e
)
546 (smerge-remove-props m0b m0e
)
547 (insert-file-contents o nil nil nil t
)))
548 ;; Try "diff -b BASE OTHER | patch MINE".
549 ((when (and (not safe
) m2e b
550 ;; If the BASE is empty, this would just concatenate
551 ;; the two, which is rarely right.
553 (write-region m3b m3e o nil
'silent
)
554 (call-process diff-command nil buf nil
"-bc" b o
)
555 (with-current-buffer buf
556 (zerop (call-process-region
557 (point-min) (point-max) "patch" t nil nil
558 "-r" "/dev/null" "--no-backup-if-mismatch"
561 (narrow-to-region m0b m0e
)
562 (smerge-remove-props m0b m0e
)
563 (insert-file-contents m nil nil nil t
)))
565 (error "Don't know how to resolve"))))
566 (if (buffer-name buf
) (kill-buffer buf
))
567 (if m
(delete-file m
))
568 (if b
(delete-file b
))
569 (if o
(delete-file o
))))
572 (defun smerge-resolve-all ()
573 "Perform automatic resolution on all conflicts."
576 (goto-char (point-min))
577 (while (re-search-forward smerge-begin-re nil t
)
580 (smerge-match-conflict)
581 (smerge-resolve 'safe
))
584 (defun smerge-batch-resolve ()
585 ;; command-line-args-left is what is left of the command line.
586 (if (not noninteractive
)
587 (error "`smerge-batch-resolve' is to be used only with -batch"))
588 (while command-line-args-left
589 (let ((file (pop command-line-args-left
)))
590 (if (string-match "\\.rej\\'" file
)
591 ;; .rej files should never contain diff3 markers, on the other hand,
592 ;; in Arch, .rej files are sometimes used to indicate that the
593 ;; main file has diff3 markers. So you can pass **/*.rej and
595 (setq file
(substring file
0 (match-beginning 0))))
596 (message "Resolving conflicts in %s..." file
)
597 (when (file-readable-p file
)
598 (with-current-buffer (find-file-noselect file
)
601 (kill-buffer (current-buffer)))))))
603 (defun smerge-keep-base ()
604 "Revert to the base version."
606 (smerge-match-conflict)
607 (smerge-ensure-match 2)
611 (defun smerge-keep-other ()
612 "Use \"other\" version."
614 (smerge-match-conflict)
615 ;;(smerge-ensure-match 3)
619 (defun smerge-keep-mine ()
622 (smerge-match-conflict)
623 ;;(smerge-ensure-match 1)
627 (defun smerge-get-current ()
629 (while (or (not (match-end i
))
630 (< (point) (match-beginning i
))
631 (>= (point) (match-end i
)))
635 (defun smerge-keep-current ()
636 "Use the current (under the cursor) version."
638 (smerge-match-conflict)
639 (let ((i (smerge-get-current)))
640 (if (<= i
0) (error "Not inside a version")
642 (smerge-auto-leave))))
644 (defun smerge-kill-current ()
645 "Remove the current (under the cursor) version."
647 (smerge-match-conflict)
648 (let ((i (smerge-get-current)))
649 (if (<= i
0) (error "Not inside a version")
652 (if (and (match-end n
) (/= (match-end n
) (match-end i
)))
655 (/= (match-end (car left
)) (match-end (cadr left
))))
656 (ding) ;We don't know how to do that.
657 (smerge-keep-n (car left
))
658 (smerge-auto-leave))))))
660 (defun smerge-diff-base-mine ()
661 "Diff 'base' and 'mine' version in current conflict region."
665 (defun smerge-diff-base-other ()
666 "Diff 'base' and 'other' version in current conflict region."
670 (defun smerge-diff-mine-other ()
671 "Diff 'mine' and 'other' version in current conflict region."
675 (defun smerge-match-conflict ()
676 "Get info about the conflict. Puts the info in the `match-data'.
677 The submatches contain:
678 0: the whole conflict.
682 An error is raised if not inside a conflict."
685 (let* ((orig-point (point))
688 (_ (re-search-backward smerge-begin-re
))
690 (start (match-beginning 0))
691 (mine-start (match-end 0))
692 (filename (or (match-string 1) ""))
694 (_ (re-search-forward smerge-end-re
))
695 (_ (assert (< orig-point
(match-end 0))))
697 (other-end (match-beginning 0))
700 (_ (re-search-backward smerge-other-re start
))
702 (mine-end (match-beginning 0))
703 (other-start (match-end 0))
707 ;; handle the various conflict styles
710 (goto-char mine-start
)
711 (re-search-forward smerge-begin-re end t
))
712 ;; There's a nested conflict and we're after the the beginning
713 ;; of the outer one but before the beginning of the inner one.
714 ;; Of course, maybe this is not a nested conflict but in that
715 ;; case it can only be something nastier that we don't know how
716 ;; to handle, so may as well arbitrarily decide to treat it as
717 ;; a nested conflict. --Stef
718 (error "There is a nested conflict"))
720 ((re-search-backward smerge-base-re start t
)
721 ;; a 3-parts conflict
722 (set (make-local-variable 'smerge-conflict-style
) 'diff3-A
)
723 (setq base-end mine-end
)
724 (setq mine-end
(match-beginning 0))
725 (setq base-start
(match-end 0)))
727 ((string= filename
(file-name-nondirectory
728 (or buffer-file-name
"")))
729 ;; a 2-parts conflict
730 (set (make-local-variable 'smerge-conflict-style
) 'diff3-E
))
732 ((and (not base-start
)
733 (or (eq smerge-conflict-style
'diff3-A
)
734 (equal filename
"ANCESTOR")
735 (string-match "\\`[.0-9]+\\'" filename
)))
736 ;; a same-diff conflict
737 (setq base-start mine-start
)
738 (setq base-end mine-end
)
739 (setq mine-start other-start
)
740 (setq mine-end other-end
)))
742 (store-match-data (list start end
745 other-start other-end
746 (when base-start
(1- base-start
)) base-start
747 (1- other-start
) other-start
))
749 (search-failed (error "Point not in conflict region")))))
751 (add-to-list 'debug-ignored-errors
"Point not in conflict region")
753 (defun smerge-conflict-overlay (pos)
754 "Return the conflict overlay at POS if any."
755 (let ((ols (overlays-at pos
))
758 (if (and (eq (overlay-get ol
'smerge
) 'conflict
)
759 (> (overlay-end ol
) pos
))
763 (defun smerge-find-conflict (&optional limit
)
764 "Find and match a conflict region. Intended as a font-lock MATCHER.
765 The submatches are the same as in `smerge-match-conflict'.
766 Returns non-nil if a match is found between point and LIMIT.
767 Point is moved to the end of the conflict."
771 ;; First check to see if point is already inside a conflict, using
772 ;; the conflict overlays.
773 (while (and (not found
) (setq conflict
(smerge-conflict-overlay pos
)))
774 ;; Check the overlay's validity and kill it if it's out of date.
777 (goto-char (overlay-start conflict
))
778 (smerge-match-conflict)
779 (goto-char (match-end 0))
781 (error "Matching backward!")
783 (error (smerge-remove-props
784 (overlay-start conflict
) (overlay-end conflict
))
786 ;; If we're not already inside a conflict, look for the next conflict
787 ;; and add/update its overlay.
788 (while (and (not found
) (re-search-forward smerge-begin-re limit t
))
791 (smerge-match-conflict)
792 (goto-char (match-end 0))
793 (let ((conflict (smerge-conflict-overlay (1- (point)))))
795 ;; Update its location, just in case it got messed up.
796 (move-overlay conflict
(match-beginning 0) (match-end 0))
797 (setq conflict
(make-overlay (match-beginning 0) (match-end 0)
798 nil
'front-advance nil
))
799 (overlay-put conflict
'evaporate t
)
800 (overlay-put conflict
'smerge
'conflict
)
801 (let ((props smerge-text-properties
))
803 (overlay-put conflict
(pop props
) (pop props
))))))
808 ;;; Refined change highlighting
810 (defvar smerge-refine-forward-function
'smerge-refine-forward
811 "Function used to determine an \"atomic\" element.
812 You can set it to `forward-char' to get char-level granularity.
813 Its behavior has mainly two restrictions:
814 - if this function encounters a newline, it's important that it stops right
816 This only matters if `smerge-refine-ignore-whitespace' is nil.
817 - it needs to be unaffected by changes performed by the `preproc' argument
818 to `smerge-refine-subst'.
819 This only matters if `smerge-refine-weight-hack' is nil.")
821 (defvar smerge-refine-ignore-whitespace t
822 "If non-nil,Indicate that smerge-refine should try to ignore change in whitespace.")
824 (defvar smerge-refine-weight-hack t
825 "If non-nil, pass to diff as many lines as there are chars in the region.
826 I.e. each atomic element (e.g. word) will be copied as many times (on different
827 lines) as it has chars. This has 2 advantages:
828 - if `diff' tries to minimize the number *lines* (rather than chars)
829 added/removed, this adjust the weights so that adding/removing long
830 symbols is considered correspondingly more costly.
831 - `smerge-refine-forward-function' only needs to be called when chopping up
832 the regions, and `forward-char' can be used afterwards.
833 It has the following disadvantages:
834 - cannot use `diff -w' because the weighting causes added spaces in a line
835 to be represented as added copies of some line, so `diff -w' can't do the
836 right thing any more.
837 - may in degenerate cases take a 1KB input region and turn it into a 1MB
838 file to pass to diff.")
840 (defun smerge-refine-forward (n)
841 (let ((case-fold-search nil
)
842 (re "[[:upper:]]?[[:lower:]]+\\|[[:upper:]]+\\|[[:digit:]]+\\|.\\|\n"))
843 (when (and smerge-refine-ignore-whitespace
844 ;; smerge-refine-weight-hack causes additional spaces to
845 ;; appear as additional lines as well, so even if diff ignore
846 ;; whitespace changes, it'll report added/removed lines :-(
847 (not smerge-refine-weight-hack
))
848 (setq re
(concat "[ \t]*\\(?:" re
"\\)")))
850 (unless (looking-at re
) (error "Smerge refine internal error"))
851 (goto-char (match-end 0)))))
853 (defun smerge-refine-chopup-region (beg end file
&optional preproc
)
854 "Chopup the region into small elements, one per line.
855 Save the result into FILE.
856 If non-nil, PREPROC is called with no argument in a buffer that contains
857 a copy of the text, just before chopping it up. It can be used to replace
858 chars to try and eliminate some spurious differences."
859 ;; We used to chop up char-by-char rather than word-by-word like ediff
860 ;; does. It had the benefit of simplicity and very fine results, but it
861 ;; often suffered from problem that diff would find correlations where
862 ;; there aren't any, so the resulting "change" didn't make much sense.
863 ;; You can still get this behavior by setting
864 ;; `smerge-refine-forward-function' to `forward-char'.
865 (let ((buf (current-buffer)))
867 (insert-buffer-substring buf beg end
)
868 (when preproc
(goto-char (point-min)) (funcall preproc
))
869 (when smerge-refine-ignore-whitespace
870 ;; It doesn't make much of a difference for diff-fine-highlight
871 ;; because we still have the _/+/</>/! prefix anyway. Can still be
872 ;; useful in other circumstances.
873 (subst-char-in-region (point-min) (point-max) ?
\n ?\s
))
874 (goto-char (point-min))
876 (funcall smerge-refine-forward-function
1)
877 (let ((s (if (prog2 (forward-char -
1) (bolp) (forward-char 1))
879 (buffer-substring (line-beginning-position) (point)))))
880 ;; We add \n after each char except after \n, so we get
881 ;; one line per text char, where each line contains
882 ;; just one char, except for \n chars which are
883 ;; represented by the empty line.
884 (unless (eq (char-before) ?
\n) (insert ?
\n))
886 (if smerge-refine-weight-hack
887 (dotimes (i (1- (length s
))) (insert s
"\n")))))
888 (unless (bolp) (error "Smerge refine internal error"))
889 (let ((coding-system-for-write 'emacs-mule
))
890 (write-region (point-min) (point-max) file nil
'nomessage
)))))
892 (defun smerge-refine-highlight-change (buf beg match-num1 match-num2 props
)
893 (with-current-buffer buf
895 (let* ((startline (- (string-to-number match-num1
) 1))
896 (beg (progn (funcall (if smerge-refine-weight-hack
898 smerge-refine-forward-function
)
901 (end (progn (funcall (if smerge-refine-weight-hack
903 smerge-refine-forward-function
)
905 (- (string-to-number match-num2
)
909 (when smerge-refine-ignore-whitespace
910 (skip-chars-backward " \t\n" beg
) (setq end
(point))
912 (skip-chars-forward " \t\n" end
) (setq beg
(point)))
914 (let ((ol (make-overlay
916 ;; Make them tend to shrink rather than spread when editing.
917 'front-advance nil
)))
918 (overlay-put ol
'evaporate t
)
919 (dolist (x props
) (overlay-put ol
(car x
) (cdr x
)))
922 (defun smerge-refine-subst (beg1 end1 beg2 end2 props
&optional preproc
)
923 "Show fine differences in the two regions BEG1..END1 and BEG2..END2.
924 PROPS is an alist of properties to put (via overlays) on the changes.
925 If non-nil, PREPROC is called with no argument in a buffer that contains
926 a copy of a region, just before preparing it to for `diff'. It can be used to
927 replace chars to try and eliminate some spurious differences."
928 (let* ((buf (current-buffer))
930 (file1 (make-temp-file "diff1"))
931 (file2 (make-temp-file "diff2")))
932 ;; Chop up regions into smaller elements and save into files.
933 (smerge-refine-chopup-region beg1 end1 file1 preproc
)
934 (smerge-refine-chopup-region beg2 end2 file2 preproc
)
936 ;; Call diff on those files.
939 (let ((coding-system-for-read 'emacs-mule
))
940 (call-process diff-command nil t nil
941 (if (and smerge-refine-ignore-whitespace
942 (not smerge-refine-weight-hack
))
943 ;; Pass -a so diff treats it as a text file even
944 ;; if it contains \0 and such.
945 ;; Pass -d so as to get the smallest change, but
946 ;; also and more importantly because otherwise it
947 ;; may happen that diff doesn't behave like
948 ;; smerge-refine-weight-hack expects it to.
949 ;; See http://thread.gmane.org/gmane.emacs.devel/82685.
952 ;; Process diff's output.
953 (goto-char (point-min))
957 (if (not (looking-at "\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?\\([acd]\\)\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?$"))
958 (error "Unexpected patch hunk header: %s"
959 (buffer-substring (point) (line-end-position))))
960 (let ((op (char-after (match-beginning 3)))
961 (m1 (match-string 1))
962 (m2 (match-string 2))
963 (m4 (match-string 4))
964 (m5 (match-string 5)))
965 (when (memq op
'(?d ?c
))
967 (smerge-refine-highlight-change buf beg1 m1 m2 props
)))
968 (when (memq op
'(?a ?c
))
970 (smerge-refine-highlight-change buf beg2 m4 m5 props
))))
971 (forward-line 1) ;Skip hunk header.
972 (and (re-search-forward "^[0-9]" nil
'move
) ;Skip hunk body.
973 (goto-char (match-beginning 0))))
974 ;; (assert (or (null last1) (< (overlay-start last1) end1)))
975 ;; (assert (or (null last2) (< (overlay-start last2) end2)))
976 (if smerge-refine-weight-hack
978 ;; (assert (or (null last1) (<= (overlay-end last1) end1)))
979 ;; (assert (or (null last2) (<= (overlay-end last2) end2)))
981 ;; smerge-refine-forward-function when calling in chopup may
982 ;; have stopped because it bumped into EOB whereas in
983 ;; smerge-refine-weight-hack it may go a bit further.
984 (if (and last1
(> (overlay-end last1
) end1
))
985 (move-overlay last1
(overlay-start last1
) end1
))
986 (if (and last2
(> (overlay-end last2
) end2
))
987 (move-overlay last2
(overlay-start last2
) end2
))
991 (delete-file file2
))))
993 (defun smerge-refine (&optional part
)
994 "Highlight the words of the conflict that are different.
995 For 3-way conflicts, highlights only 2 of the 3 parts.
996 A numeric argument PART can be used to specify which 2 parts;
997 repeating the command will highlight other 2 parts."
999 (if (integerp current-prefix-arg
) (list current-prefix-arg
)
1000 (smerge-match-conflict)
1001 (let* ((prop (get-text-property (match-beginning 0) 'smerge-refine-part
))
1002 (part (if (and (consp prop
)
1003 (eq (buffer-chars-modified-tick) (car prop
)))
1005 ;; If already highlighted, cycle.
1006 (list (if (integerp part
) (1+ (mod part
3)))))))
1008 (if (and (integerp part
) (or (< part
1) (> part
3)))
1009 (error "No conflict part nb %s" part
))
1010 (smerge-match-conflict)
1011 (remove-overlays (match-beginning 0) (match-end 0) 'smerge
'refine
)
1012 ;; Ignore `part' if not applicable, and default it if not provided.
1013 (setq part
(cond ((null (match-end 2)) 2)
1014 ((eq (match-end 1) (match-end 3)) 1)
1015 ((integerp part
) part
)
1017 (let ((n1 (if (eq part
1) 2 1))
1018 (n2 (if (eq part
3) 2 3)))
1019 (smerge-ensure-match n1
)
1020 (smerge-ensure-match n2
)
1021 (put-text-property (match-beginning 0) (1+ (match-beginning 0))
1023 (cons (buffer-chars-modified-tick) part
))
1024 (smerge-refine-subst (match-beginning n1
) (match-end n1
)
1025 (match-beginning n2
) (match-end n2
)
1027 (face . smerge-refined-change
)))))
1029 (defun smerge-diff (n1 n2
)
1030 (smerge-match-conflict)
1031 (smerge-ensure-match n1
)
1032 (smerge-ensure-match n2
)
1033 (let ((name1 (aref smerge-match-names n1
))
1034 (name2 (aref smerge-match-names n2
))
1035 ;; Read them before the match-data gets clobbered.
1036 (beg1 (match-beginning n1
))
1037 (end1 (match-end n1
))
1038 (beg2 (match-beginning n2
))
1039 (end2 (match-end n2
))
1040 (file1 (make-temp-file "smerge1"))
1041 (file2 (make-temp-file "smerge2"))
1042 (dir default-directory
)
1043 (file (if buffer-file-name
(file-relative-name buffer-file-name
)))
1044 ;; We would want to use `emacs-mule-unix' for read&write, but we
1045 ;; bump into problems with the coding-system used by diff to write
1046 ;; the file names and the time stamps in the header.
1047 ;; `buffer-file-coding-system' is not always correct either, but if
1048 ;; the OS/user uses only one coding-system, then it works.
1049 (coding-system-for-read buffer-file-coding-system
))
1050 (write-region beg1 end1 file1 nil
'nomessage
)
1051 (write-region beg2 end2 file2 nil
'nomessage
)
1053 (with-current-buffer (get-buffer-create smerge-diff-buffer-name
)
1054 (setq default-directory dir
)
1055 (let ((inhibit-read-only t
))
1058 (apply 'call-process diff-command nil t nil
1059 (append smerge-diff-switches
1060 (list "-L" (concat name1
"/" file
)
1061 "-L" (concat name2
"/" file
)
1063 (if (eq status
0) (insert "No differences found.\n"))))
1064 (goto-char (point-min))
1066 (display-buffer (current-buffer) t
))
1068 (delete-file file2
))))
1070 ;; compiler pacifiers
1071 (defvar smerge-ediff-windows
)
1072 (defvar smerge-ediff-buf
)
1073 (defvar ediff-buffer-A
)
1074 (defvar ediff-buffer-B
)
1075 (defvar ediff-buffer-C
)
1076 (defvar ediff-ancestor-buffer
)
1077 (defvar ediff-quit-hook
)
1078 (declare-function ediff-cleanup-mess
"ediff-util" nil
)
1081 (defun smerge-ediff (&optional name-mine name-other name-base
)
1082 "Invoke ediff to resolve the conflicts.
1083 NAME-MINE, NAME-OTHER, and NAME-BASE, if non-nil, are used for the
1086 (let* ((buf (current-buffer))
1088 ;;(ediff-default-variant 'default-B)
1089 (config (current-window-configuration))
1090 (filename (file-name-nondirectory buffer-file-name
))
1091 (mine (generate-new-buffer
1092 (or name-mine
(concat "*" filename
" MINE*"))))
1093 (other (generate-new-buffer
1094 (or name-other
(concat "*" filename
" OTHER*"))))
1096 (with-current-buffer mine
1097 (buffer-disable-undo)
1098 (insert-buffer-substring buf
)
1099 (goto-char (point-min))
1100 (while (smerge-find-conflict)
1101 (when (match-beginning 2) (setq base t
))
1103 (buffer-enable-undo)
1104 (set-buffer-modified-p nil
)
1107 (with-current-buffer other
1108 (buffer-disable-undo)
1109 (insert-buffer-substring buf
)
1110 (goto-char (point-min))
1111 (while (smerge-find-conflict)
1113 (buffer-enable-undo)
1114 (set-buffer-modified-p nil
)
1118 (setq base
(generate-new-buffer
1119 (or name-base
(concat "*" filename
" BASE*"))))
1120 (with-current-buffer base
1121 (buffer-disable-undo)
1122 (insert-buffer-substring buf
)
1123 (goto-char (point-min))
1124 (while (smerge-find-conflict)
1127 (delete-region (match-beginning 0) (match-end 0))))
1128 (buffer-enable-undo)
1129 (set-buffer-modified-p nil
)
1132 ;; the rest of the code is inspired from vc.el
1136 (ediff-merge-buffers-with-ancestor mine other base
)
1137 ;; nil 'ediff-merge-revisions-with-ancestor buffer-file-name)
1138 (ediff-merge-buffers mine other
)))
1139 ;; nil 'ediff-merge-revisions buffer-file-name)))
1141 ;; Ediff is now set up, and we are in the control buffer.
1142 ;; Do a few further adjustments and take precautions for exit.
1143 (set (make-local-variable 'smerge-ediff-windows
) config
)
1144 (set (make-local-variable 'smerge-ediff-buf
) buf
)
1145 (set (make-local-variable 'ediff-quit-hook
)
1147 (let ((buffer-A ediff-buffer-A
)
1148 (buffer-B ediff-buffer-B
)
1149 (buffer-C ediff-buffer-C
)
1150 (buffer-Ancestor ediff-ancestor-buffer
)
1151 (buf smerge-ediff-buf
)
1152 (windows smerge-ediff-windows
))
1153 (ediff-cleanup-mess)
1154 (with-current-buffer buf
1156 (insert-buffer-substring buffer-C
)
1157 (kill-buffer buffer-A
)
1158 (kill-buffer buffer-B
)
1159 (kill-buffer buffer-C
)
1160 (when (bufferp buffer-Ancestor
) (kill-buffer buffer-Ancestor
))
1161 (set-window-configuration windows
)
1162 (message "Conflict resolution finished; you may save the buffer")))))
1163 (message "Please resolve conflicts now; exit ediff when done")))
1165 (defun smerge-makeup-conflict (pt1 pt2 pt3
&optional pt4
)
1166 "Insert diff3 markers to make a new conflict.
1167 Uses point and mark for 2 of the relevant positions and previous marks
1169 By default, makes up a 2-way conflict,
1170 with a \\[universal-argument] prefix, makes up a 3-way conflict."
1174 (progn (pop-mark) (mark))
1175 (when current-prefix-arg
(pop-mark) (mark))))
1176 ;; Start from the end so as to avoid problems with pos-changes.
1177 (destructuring-bind (pt1 pt2 pt3
&optional pt4
)
1178 (sort (list* pt1 pt2 pt3
(if pt4
(list pt4
))) '>=)
1179 (goto-char pt1
) (beginning-of-line)
1180 (insert ">>>>>>> OTHER\n")
1181 (goto-char pt2
) (beginning-of-line)
1182 (insert "=======\n")
1183 (goto-char pt3
) (beginning-of-line)
1185 (insert "||||||| BASE\n")
1186 (goto-char pt4
) (beginning-of-line))
1187 (insert "<<<<<<< MINE\n"))
1188 (if smerge-mode nil
(smerge-mode 1))
1192 (defconst smerge-parsep-re
1193 (concat smerge-begin-re
"\\|" smerge-end-re
"\\|"
1194 smerge-base-re
"\\|" smerge-other-re
"\\|"))
1197 (define-minor-mode smerge-mode
1198 "Minor mode to simplify editing output from the diff3 program.
1199 \\{smerge-mode-map}"
1200 :group
'smerge
:lighter
" SMerge"
1201 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
1204 (font-lock-add-keywords nil smerge-font-lock-keywords
'append
)
1205 (font-lock-remove-keywords nil smerge-font-lock-keywords
))
1206 (goto-char (point-min))
1207 (while (smerge-find-conflict)
1209 (font-lock-fontify-region (match-beginning 0) (match-end 0) nil
)))))
1210 (if (string-match (regexp-quote smerge-parsep-re
) paragraph-separate
)
1212 (set (make-local-variable 'paragraph-separate
)
1213 (replace-match "" t t paragraph-separate
)))
1215 (set (make-local-variable 'paragraph-separate
)
1216 (concat smerge-parsep-re paragraph-separate
))))
1218 (smerge-remove-props (point-min) (point-max))))
1221 (defun smerge-start-session ()
1222 "Turn on `smerge-mode' and move point to first conflict marker.
1223 If no conflict maker is found, turn off `smerge-mode'."
1226 (unless (looking-at smerge-begin-re
)
1228 (error (smerge-auto-leave))))
1230 (provide 'smerge-mode
)
1232 ;; arch-tag: 605c8d1e-e43d-4943-a6f3-1bcc4333e690
1233 ;;; smerge-mode.el ends here