1 ;;; smerge-mode.el --- Minor mode to resolve diff3 conflicts
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 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, or (at your option)
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.
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 ()
38 ;; (goto-char (point-min))
39 ;; (when (re-search-forward "^<<<<<<< " nil t)
41 ;; (add-hook 'find-file-hook 'sm-try-smerge t)
45 ;; - if requested, ask the user whether he wants to call ediff right away
49 (eval-when-compile (require 'cl
))
52 ;;; The real definition comes later.
56 "Minor mode to highlight and resolve diff3 conflicts."
60 (defcustom smerge-diff-buffer-name
"*vc-diff*"
61 "Buffer name to use for displaying diffs."
66 (const "*smerge-diff*")
69 (defcustom smerge-diff-switches
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."
75 :type
'(repeat string
))
77 (defcustom smerge-auto-leave t
78 "Non-nil means to leave `smerge-mode' when the last conflict is resolved."
82 (defcustom smerge-auto-refine t
83 "Automatically highlight changes in detail as the user visits conflicts."
88 '((((min-colors 88) (background light
))
89 (:foreground
"blue1"))
92 (((min-colors 88) (background dark
))
93 (:foreground
"cyan1"))
95 (:foreground
"cyan")))
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"))
106 (:foreground
"lightgreen")))
107 "Face for the other code."
109 ;; backward-compatibility alias
110 (put 'smerge-other-face
'face-alias
'smerge-other
)
111 (defvar smerge-other-face
'smerge-other
)
114 '((((min-colors 88) (background light
))
115 (:foreground
"red1"))
116 (((background light
))
119 (:foreground
"orange")))
120 "Face for the base code."
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"))
130 (:background
"grey30")))
131 "Face for the conflict markers."
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'."
142 (easy-mmode-defmap smerge-basic-map
143 `(("n" . smerge-next
)
145 ("r" . smerge-resolve
)
146 ("a" . smerge-keep-all
)
147 ("b" . smerge-keep-base
)
148 ("o" . smerge-keep-other
)
149 ("m" . smerge-keep-mine
)
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."
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)
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
)))
180 (easy-menu-define smerge-mode-menu smerge-mode-map
181 "Menu for `smerge-mode'."
183 ["Next" smerge-next
:help
"Go to next conflict"]
184 ["Previous" smerge-prev
:help
"Go to previous conflict"]
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))]
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)]
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)]
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'."
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"]
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
)
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:
251 ;; Compiler pacifiers
252 (defvar font-lock-mode
)
253 (defvar font-lock-keywords
)
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
))
279 (defun smerge-keep-all ()
280 "Concatenate all versions."
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 ;; `smerge-auto-combine' relies on the finish position (at the beginning
301 ;; of the closing marker).
303 (smerge-match-conflict)
305 (dolist (i '(3 2 1 0))
306 (push (if (match-end i
) (copy-marker (match-end i
) t
)) ends
))
307 (setq ends
(apply 'vector ends
))
308 (goto-char (aref ends
0))
309 (if (not (re-search-forward smerge-begin-re nil t
))
310 (error "No next conflict")
311 (smerge-match-conflict)
312 (let ((match-data (mapcar (lambda (m) (if m
(copy-marker m
)))
314 ;; First copy the in-between text in each alternative.
317 (goto-char (aref ends i
))
318 (insert-buffer-substring (current-buffer)
319 (aref ends
0) (car match-data
))))
320 (delete-region (aref ends
0) (car match-data
))
321 ;; Then move the second conflict's alternatives into the first.
323 (set-match-data match-data
)
324 (when (and (aref ends i
) (match-end i
))
325 (goto-char (aref ends i
))
326 (insert-buffer-substring (current-buffer)
327 (match-beginning i
) (match-end i
))))
328 (delete-region (car match-data
) (cadr match-data
))
330 (dolist (m match-data
) (if m
(move-marker m nil
)))
331 (mapc (lambda (m) (if m
(move-marker m nil
))) ends
)))))
333 (defvar smerge-auto-combine-max-separation
2
334 "Max number of lines between conflicts that should be combined.")
336 (defun smerge-auto-combine ()
337 "Automatically combine conflicts that are near each other."
340 (goto-char (point-min))
341 (while (smerge-find-conflict)
342 ;; 2 is 1 (default) + 1 (the begin markers).
343 (while (save-excursion
344 (smerge-find-conflict
345 (line-beginning-position
346 (+ 2 smerge-auto-combine-max-separation
))))
347 (forward-line -
1) ;Go back inside the conflict.
348 (smerge-combine-with-next)
349 (forward-line 1) ;Move past the end of the conflict.
352 (defvar smerge-resolve-function
353 (lambda () (error "Don't know how to resolve"))
354 "Mode-specific merge function.
355 The function is called with zero or one argument (non-nil if the resolution
356 function should only apply safe heuristics) and with the match data set
357 according to `smerge-match-conflict'.")
358 (add-to-list 'debug-ignored-errors
"Don't know how to resolve")
360 (defvar smerge-text-properties
361 `(help-echo "merge conflict: mouse-3 shows a menu"
362 ;; mouse-face highlight
363 keymap
(keymap (down-mouse-3 . smerge-popup-context-menu
))))
365 (defun smerge-remove-props (beg end
)
366 (remove-overlays beg end
'smerge
'refine
)
367 (remove-overlays beg end
'smerge
'conflict
)
368 ;; Now that we use overlays rather than text-properties, this function
369 ;; does not cause refontification any more. It can be seen very clearly
370 ;; in buffers where jit-lock-contextually is not t, in which case deleting
371 ;; the "<<<<<<< foobar" leading line leaves the rest of the conflict
372 ;; highlighted as if it were still a valid conflict. Note that in many
373 ;; important cases (such as the previous example) we're actually called
374 ;; during font-locking so inhibit-modification-hooks is non-nil, so we
375 ;; can't just modify the buffer and expect font-lock to be triggered as in:
376 ;; (put-text-property beg end 'smerge-force-highlighting nil)
377 (let ((modified (buffer-modified-p)))
378 (remove-text-properties beg end
'(fontified nil
))
379 (restore-buffer-modified-p modified
)))
381 (defun smerge-popup-context-menu (event)
382 "Pop up the Smerge mode context menu under mouse."
385 (save-excursion (posn-set-point (event-end event
)) (smerge-check 1)))
387 (posn-set-point (event-end event
))
388 (smerge-match-conflict)
389 (let ((i (smerge-get-current))
393 (popup-menu smerge-mode-menu
)
395 (setq o
(make-overlay (match-beginning i
) (match-end i
)))
398 (overlay-put o
'face
'highlight
)
399 (sit-for 0) ;Display the new highlighting.
400 (popup-menu smerge-context-menu
))
402 (delete-overlay o
)))))
403 ;; There's no conflict at point, the text-props are just obsolete.
405 (let ((beg (re-search-backward smerge-end-re nil t
))
406 (end (re-search-forward smerge-begin-re nil t
)))
407 (smerge-remove-props (or beg
(point-min)) (or end
(point-max)))
408 (push event unread-command-events
)))))
410 (defun smerge-apply-resolution-patch (buf m0b m0e m3b m3e
&optional m2b
)
411 "Replace the conflict with a bunch of subconflicts.
412 BUF contains a plain diff between match-1 and match-3."
414 (textbuf (current-buffer))
415 (name1 (progn (goto-char m0b
)
416 (buffer-substring (+ (point) 8) (line-end-position))))
417 (name2 (when m2b
(goto-char m2b
) (forward-line -
1)
418 (buffer-substring (+ (point) 8) (line-end-position))))
419 (name3 (progn (goto-char m0e
) (forward-line -
1)
420 (buffer-substring (+ (point) 8) (line-end-position)))))
421 (smerge-remove-props m0b m0e
)
422 (delete-region m3e m0e
)
423 (delete-region m0b m3b
)
425 (setq m3e
(- m3e
(- m3b m0b
)))
427 (with-current-buffer buf
428 (goto-char (point-min))
430 (if (not (looking-at "\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?\\([acd]\\)\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?$"))
431 (error "Unexpected patch hunk header: %s"
432 (buffer-substring (point) (line-end-position)))
433 (let* ((op (char-after (match-beginning 3)))
434 (startline (+ (string-to-number (match-string 1))
435 ;; No clue why this is the way it is, but line
436 ;; numbers seem to be off-by-one for `a' ops.
437 (if (eq op ?a
) 1 0)))
438 (endline (if (eq op ?a
) startline
439 (1+ (if (match-end 2)
440 (string-to-number (match-string 2))
442 (lines (- endline startline
))
445 ((null (match-end 5)) 1)
446 (t (- (string-to-number (match-string 5))
447 (string-to-number (match-string 4)) -
1))))
449 (forward-line 1) ;Skip header.
450 (forward-line lines
) ;Skip deleted text.
451 (if (eq op ?c
) (forward-line 1)) ;Skip separator.
453 (if (null otherlines
) ""
455 (dotimes (i otherlines
) (delete-char 2) (forward-line 1))
456 (buffer-substring pos
(point)))))
457 (with-current-buffer textbuf
458 (forward-line (- startline line
))
459 (insert "<<<<<<< " name1
"\n" othertext
460 (if name2
(concat "||||||| " name2
))
463 (insert ">>>>>>> " name3
"\n")
464 (setq line endline
))))))))
466 (defun smerge-resolve (&optional safe
)
467 "Resolve the conflict at point intelligently.
468 This relies on mode-specific knowledge and thus only works in
469 some major modes. Uses `smerge-resolve-function' to do the actual work."
471 (smerge-match-conflict)
472 (smerge-remove-props (match-beginning 0) (match-end 0))
473 (let ((md (match-data))
474 (m0b (match-beginning 0))
475 (m1b (match-beginning 1))
476 (m2b (match-beginning 2))
477 (m3b (match-beginning 3))
482 (buf (generate-new-buffer " *smerge*"))
487 ;; Trivial diff3 -A non-conflicts.
488 ((and (eq (match-end 1) (match-end 3))
489 (eq (match-beginning 1) (match-beginning 3)))
491 ;; Mode-specific conflict resolution.
495 (funcall smerge-resolve-function safe
)
496 (funcall smerge-resolve-function
))
499 ;; Nothing to do: the resolution function has done it already.
501 ;; "Mere whitespace" conflicts.
502 ((or (and (eq m1e m3e
) (eq m1b m3b
)) ;Non-conflict.
504 (setq m
(make-temp-file "smm"))
505 (write-region m1b m1e m nil
'silent
)
506 (setq o
(make-temp-file "smo"))
507 (write-region m3b m3e o nil
'silent
)
508 ;; Same patch applied on both sides, with whitespace changes.
509 (zerop (call-process diff-command nil nil nil
"-b" m o
)))
511 (setq b
(make-temp-file "smb"))
512 (write-region m2b m2e b nil
'silent
)
513 ;; Only minor whitespace changes made locally.
514 (zerop (call-process diff-command nil buf nil
"-bc" b m
))))
517 ;; Refine a 2-way conflict using "diff -b".
518 ;; In case of a 3-way conflict with an empty base
519 ;; (i.e. 2 conflicting additions), we do the same, presuming
520 ;; that the 2 additions should be somehow merged rather
521 ;; than concatenated.
522 ((not (or (and m2b
(not (eq m2b m2e
)))
523 (eq m1b m1e
) (eq m3b m3e
)
524 (let ((lines (count-lines m3b m3e
)))
525 (call-process diff-command nil buf nil
"-b" o m
)
526 (with-current-buffer buf
527 (goto-char (point-min))
528 ;; Make sure there's some refinement.
530 (concat "1," (number-to-string lines
) "c"))))))
531 (smerge-apply-resolution-patch buf m0b m0e m3b m3e m2b
))
532 ;; Try "diff -b BASE MINE | patch OTHER".
533 ((when (and (not safe
) m2e b
534 ;; If the BASE is empty, this would just concatenate
535 ;; the two, which is rarely right.
537 (with-current-buffer buf
538 (zerop (call-process-region
539 (point-min) (point-max) "patch" t nil nil
540 "-r" "/dev/null" "--no-backup-if-mismatch"
543 (narrow-to-region m0b m0e
)
544 (smerge-remove-props m0b m0e
)
545 (insert-file-contents o nil nil nil t
)))
546 ;; Try "diff -b BASE OTHER | patch MINE".
547 ((when (and (not safe
) m2e b
548 ;; If the BASE is empty, this would just concatenate
549 ;; the two, which is rarely right.
551 (write-region m3b m3e o nil
'silent
)
552 (call-process diff-command nil buf nil
"-bc" b o
)
553 (with-current-buffer buf
554 (zerop (call-process-region
555 (point-min) (point-max) "patch" t nil nil
556 "-r" "/dev/null" "--no-backup-if-mismatch"
559 (narrow-to-region m0b m0e
)
560 (smerge-remove-props m0b m0e
)
561 (insert-file-contents m nil nil nil t
)))
563 (error "Don't know how to resolve"))))
564 (if (buffer-name buf
) (kill-buffer buf
))
565 (if m
(delete-file m
))
566 (if b
(delete-file b
))
567 (if o
(delete-file o
))))
570 (defun smerge-resolve-all ()
571 "Perform automatic resolution on all conflicts."
574 (goto-char (point-min))
575 (while (re-search-forward smerge-begin-re nil t
)
578 (smerge-match-conflict)
579 (smerge-resolve 'safe
))
582 (defun smerge-batch-resolve ()
583 ;; command-line-args-left is what is left of the command line.
584 (if (not noninteractive
)
585 (error "`smerge-batch-resolve' is to be used only with -batch"))
586 (while command-line-args-left
587 (let ((file (pop command-line-args-left
)))
588 (if (string-match "\\.rej\\'" file
)
589 ;; .rej files should never contain diff3 markers, on the other hand,
590 ;; in Arch, .rej files are sometimes used to indicate that the
591 ;; main file has diff3 markers. So you can pass **/*.rej and
593 (setq file
(substring file
0 (match-beginning 0))))
594 (message "Resolving conflicts in %s..." file
)
595 (when (file-readable-p file
)
596 (with-current-buffer (find-file-noselect file
)
599 (kill-buffer (current-buffer)))))))
601 (defun smerge-keep-base ()
602 "Revert to the base version."
604 (smerge-match-conflict)
605 (smerge-ensure-match 2)
609 (defun smerge-keep-other ()
610 "Use \"other\" version."
612 (smerge-match-conflict)
613 ;;(smerge-ensure-match 3)
617 (defun smerge-keep-mine ()
620 (smerge-match-conflict)
621 ;;(smerge-ensure-match 1)
625 (defun smerge-get-current ()
627 (while (or (not (match-end i
))
628 (< (point) (match-beginning i
))
629 (>= (point) (match-end i
)))
633 (defun smerge-keep-current ()
634 "Use the current (under the cursor) version."
636 (smerge-match-conflict)
637 (let ((i (smerge-get-current)))
638 (if (<= i
0) (error "Not inside a version")
640 (smerge-auto-leave))))
642 (defun smerge-kill-current ()
643 "Remove the current (under the cursor) version."
645 (smerge-match-conflict)
646 (let ((i (smerge-get-current)))
647 (if (<= i
0) (error "Not inside a version")
650 (if (and (match-end n
) (/= (match-end n
) (match-end i
)))
653 (/= (match-end (car left
)) (match-end (cadr left
))))
654 (ding) ;We don't know how to do that.
655 (smerge-keep-n (car left
))
656 (smerge-auto-leave))))))
658 (defun smerge-diff-base-mine ()
659 "Diff 'base' and 'mine' version in current conflict region."
663 (defun smerge-diff-base-other ()
664 "Diff 'base' and 'other' version in current conflict region."
668 (defun smerge-diff-mine-other ()
669 "Diff 'mine' and 'other' version in current conflict region."
673 (defun smerge-match-conflict ()
674 "Get info about the conflict. Puts the info in the `match-data'.
675 The submatches contain:
676 0: the whole conflict.
680 An error is raised if not inside a conflict."
683 (let* ((orig-point (point))
686 (_ (re-search-backward smerge-begin-re
))
688 (start (match-beginning 0))
689 (mine-start (match-end 0))
690 (filename (or (match-string 1) ""))
692 (_ (re-search-forward smerge-end-re
))
693 (_ (assert (< orig-point
(match-end 0))))
695 (other-end (match-beginning 0))
698 (_ (re-search-backward smerge-other-re start
))
700 (mine-end (match-beginning 0))
701 (other-start (match-end 0))
705 ;; handle the various conflict styles
708 (goto-char mine-start
)
709 (re-search-forward smerge-begin-re end t
))
710 ;; There's a nested conflict and we're after the the beginning
711 ;; of the outer one but before the beginning of the inner one.
712 ;; Of course, maybe this is not a nested conflict but in that
713 ;; case it can only be something nastier that we don't know how
714 ;; to handle, so may as well arbitrarily decide to treat it as
715 ;; a nested conflict. --Stef
716 (error "There is a nested conflict"))
718 ((re-search-backward smerge-base-re start t
)
719 ;; a 3-parts conflict
720 (set (make-local-variable 'smerge-conflict-style
) 'diff3-A
)
721 (setq base-end mine-end
)
722 (setq mine-end
(match-beginning 0))
723 (setq base-start
(match-end 0)))
725 ((string= filename
(file-name-nondirectory
726 (or buffer-file-name
"")))
727 ;; a 2-parts conflict
728 (set (make-local-variable 'smerge-conflict-style
) 'diff3-E
))
730 ((and (not base-start
)
731 (or (eq smerge-conflict-style
'diff3-A
)
732 (equal filename
"ANCESTOR")
733 (string-match "\\`[.0-9]+\\'" filename
)))
734 ;; a same-diff conflict
735 (setq base-start mine-start
)
736 (setq base-end mine-end
)
737 (setq mine-start other-start
)
738 (setq mine-end other-end
)))
740 (store-match-data (list start end
743 other-start other-end
744 (when base-start
(1- base-start
)) base-start
745 (1- other-start
) other-start
))
747 (search-failed (error "Point not in conflict region")))))
749 (add-to-list 'debug-ignored-errors
"Point not in conflict region")
751 (defun smerge-conflict-overlay (pos)
752 "Return the conflict overlay at POS if any."
753 (let ((ols (overlays-at pos
))
756 (if (and (eq (overlay-get ol
'smerge
) 'conflict
)
757 (> (overlay-end ol
) pos
))
761 (defun smerge-find-conflict (&optional limit
)
762 "Find and match a conflict region. Intended as a font-lock MATCHER.
763 The submatches are the same as in `smerge-match-conflict'.
764 Returns non-nil if a match is found between point and LIMIT.
765 Point is moved to the end of the conflict."
769 ;; First check to see if point is already inside a conflict, using
770 ;; the conflict overlays.
771 (while (and (not found
) (setq conflict
(smerge-conflict-overlay pos
)))
772 ;; Check the overlay's validity and kill it if it's out of date.
775 (goto-char (overlay-start conflict
))
776 (smerge-match-conflict)
777 (goto-char (match-end 0))
779 (error "Matching backward!")
781 (error (smerge-remove-props
782 (overlay-start conflict
) (overlay-end conflict
))
784 ;; If we're not already inside a conflict, look for the next conflict
785 ;; and add/update its overlay.
786 (while (and (not found
) (re-search-forward smerge-begin-re limit t
))
789 (smerge-match-conflict)
790 (goto-char (match-end 0))
791 (let ((conflict (smerge-conflict-overlay (1- (point)))))
793 ;; Update its location, just in case it got messed up.
794 (move-overlay conflict
(match-beginning 0) (match-end 0))
795 (setq conflict
(make-overlay (match-beginning 0) (match-end 0)
796 nil
'front-advance nil
))
797 (overlay-put conflict
'evaporate t
)
798 (overlay-put conflict
'smerge
'conflict
)
799 (let ((props smerge-text-properties
))
801 (overlay-put conflict
(pop props
) (pop props
))))))
806 ;;; Refined change highlighting
808 (defvar smerge-refine-forward-function
'smerge-refine-forward
809 "Function used to determine an \"atomic\" element.
810 You can set it to `forward-char' to get char-level granularity.
811 Its behavior has mainly two restrictions:
812 - if this function encounters a newline, it's important that it stops right
814 This only matters if `smerge-refine-ignore-whitespace' is nil.
815 - it needs to be unaffected by changes performed by the `preproc' argument
816 to `smerge-refine-subst'.
817 This only matters if `smerge-refine-weight-hack' is nil.")
819 (defvar smerge-refine-ignore-whitespace t
820 "If non-nil,Indicate that smerge-refine should try to ignore change in whitespace.")
822 (defvar smerge-refine-weight-hack t
823 "If non-nil, pass to diff as many lines as there are chars in the region.
824 I.e. each atomic element (e.g. word) will be copied as many times (on different
825 lines) as it has chars. This has 2 advantages:
826 - if `diff' tries to minimize the number *lines* (rather than chars)
827 added/removed, this adjust the weights so that adding/removing long
828 symbols is considered correspondingly more costly.
829 - `smerge-refine-forward-function' only needs to be called when chopping up
830 the regions, and `forward-char' can be used afterwards.
831 It has the following disadvantages:
832 - cannot use `diff -w' because the weighting causes added spaces in a line
833 to be represented as added copies of some line, so `diff -w' can't do the
834 right thing any more.
835 - may in degenerate cases take a 1KB input region and turn it into a 1MB
836 file to pass to diff.")
838 (defun smerge-refine-forward (n)
839 (let ((case-fold-search nil
)
840 (re "[[:upper:]]?[[:lower:]]+\\|[[:upper:]]+\\|[[:digit:]]+\\|.\\|\n"))
841 (when (and smerge-refine-ignore-whitespace
842 ;; smerge-refine-weight-hack causes additional spaces to
843 ;; appear as additional lines as well, so even if diff ignore
844 ;; whitespace changes, it'll report added/removed lines :-(
845 (not smerge-refine-weight-hack
))
846 (setq re
(concat "[ \t]*\\(?:" re
"\\)")))
848 (unless (looking-at re
) (error "Smerge refine internal error"))
849 (goto-char (match-end 0)))))
851 (defun smerge-refine-chopup-region (beg end file
&optional preproc
)
852 "Chopup the region into small elements, one per line.
853 Save the result into FILE.
854 If non-nil, PREPROC is called with no argument in a buffer that contains
855 a copy of the text, just before chopping it up. It can be used to replace
856 chars to try and eliminate some spurious differences."
857 ;; We used to chop up char-by-char rather than word-by-word like ediff
858 ;; does. It had the benefit of simplicity and very fine results, but it
859 ;; often suffered from problem that diff would find correlations where
860 ;; there aren't any, so the resulting "change" didn't make much sense.
861 ;; You can still get this behavior by setting
862 ;; `smerge-refine-forward-function' to `forward-char'.
863 (let ((buf (current-buffer)))
865 (insert-buffer-substring buf beg end
)
866 (when preproc
(goto-char (point-min)) (funcall preproc
))
867 (when smerge-refine-ignore-whitespace
868 ;; It doesn't make much of a difference for diff-fine-highlight
869 ;; because we still have the _/+/</>/! prefix anyway. Can still be
870 ;; useful in other circumstances.
871 (subst-char-in-region (point-min) (point-max) ?
\n ?\s
))
872 (goto-char (point-min))
874 (funcall smerge-refine-forward-function
1)
875 (let ((s (if (prog2 (forward-char -
1) (bolp) (forward-char 1))
877 (buffer-substring (line-beginning-position) (point)))))
878 ;; We add \n after each char except after \n, so we get
879 ;; one line per text char, where each line contains
880 ;; just one char, except for \n chars which are
881 ;; represented by the empty line.
882 (unless (eq (char-before) ?
\n) (insert ?
\n))
884 (if smerge-refine-weight-hack
885 (dotimes (i (1- (length s
))) (insert s
"\n")))))
886 (unless (bolp) (error "Smerge refine internal error"))
887 (let ((coding-system-for-write 'emacs-mule
))
888 (write-region (point-min) (point-max) file nil
'nomessage
)))))
890 (defun smerge-refine-highlight-change (buf beg match-num1 match-num2 props
)
891 (with-current-buffer buf
893 (let* ((startline (- (string-to-number match-num1
) 1))
894 (beg (progn (funcall (if smerge-refine-weight-hack
896 smerge-refine-forward-function
)
899 (end (progn (funcall (if smerge-refine-weight-hack
901 smerge-refine-forward-function
)
903 (- (string-to-number match-num2
)
907 (when smerge-refine-ignore-whitespace
908 (skip-chars-backward " \t\n" beg
) (setq end
(point))
910 (skip-chars-forward " \t\n" end
) (setq beg
(point)))
912 (let ((ol (make-overlay
914 ;; Make them tend to shrink rather than spread when editing.
915 'front-advance nil
)))
916 (overlay-put ol
'evaporate t
)
917 (dolist (x props
) (overlay-put ol
(car x
) (cdr x
)))
920 (defun smerge-refine-subst (beg1 end1 beg2 end2 props
&optional preproc
)
921 "Show fine differences in the two regions BEG1..END1 and BEG2..END2.
922 PROPS is an alist of properties to put (via overlays) on the changes.
923 If non-nil, PREPROC is called with no argument in a buffer that contains
924 a copy of a region, just before preparing it to for `diff'. It can be used to
925 replace chars to try and eliminate some spurious differences."
926 (let* ((buf (current-buffer))
928 (file1 (make-temp-file "diff1"))
929 (file2 (make-temp-file "diff2")))
930 ;; Chop up regions into smaller elements and save into files.
931 (smerge-refine-chopup-region beg1 end1 file1 preproc
)
932 (smerge-refine-chopup-region beg2 end2 file2 preproc
)
934 ;; Call diff on those files.
937 (let ((coding-system-for-read 'emacs-mule
))
938 (call-process diff-command nil t nil
939 (if (and smerge-refine-ignore-whitespace
940 (not smerge-refine-weight-hack
))
941 ;; Pass -a so diff treats it as a text file even
942 ;; if it contains \0 and such.
943 ;; Pass -d so as to get the smallest change, but
944 ;; also and more importantly because otherwise it
945 ;; may happen that diff doesn't behave like
946 ;; smerge-refine-weight-hack expects it to.
947 ;; See http://thread.gmane.org/gmane.emacs.devel/82685.
950 ;; Process diff's output.
951 (goto-char (point-min))
955 (if (not (looking-at "\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?\\([acd]\\)\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?$"))
956 (error "Unexpected patch hunk header: %s"
957 (buffer-substring (point) (line-end-position))))
958 (let ((op (char-after (match-beginning 3)))
959 (m1 (match-string 1))
960 (m2 (match-string 2))
961 (m4 (match-string 4))
962 (m5 (match-string 5)))
963 (when (memq op
'(?d ?c
))
965 (smerge-refine-highlight-change buf beg1 m1 m2 props
)))
966 (when (memq op
'(?a ?c
))
968 (smerge-refine-highlight-change buf beg2 m4 m5 props
))))
969 (forward-line 1) ;Skip hunk header.
970 (and (re-search-forward "^[0-9]" nil
'move
) ;Skip hunk body.
971 (goto-char (match-beginning 0))))
972 ;; (assert (or (null last1) (< (overlay-start last1) end1)))
973 ;; (assert (or (null last2) (< (overlay-start last2) end2)))
974 (if smerge-refine-weight-hack
976 ;; (assert (or (null last1) (<= (overlay-end last1) end1)))
977 ;; (assert (or (null last2) (<= (overlay-end last2) end2)))
979 ;; smerge-refine-forward-function when calling in chopup may
980 ;; have stopped because it bumped into EOB whereas in
981 ;; smerge-refine-weight-hack it may go a bit further.
982 (if (and last1
(> (overlay-end last1
) end1
))
983 (move-overlay last1
(overlay-start last1
) end1
))
984 (if (and last2
(> (overlay-end last2
) end2
))
985 (move-overlay last2
(overlay-start last2
) end2
))
989 (delete-file file2
))))
991 (defun smerge-refine (&optional part
)
992 "Highlight the words of the conflict that are different.
993 For 3-way conflicts, highlights only 2 of the 3 parts.
994 A numeric argument PART can be used to specify which 2 parts;
995 repeating the command will highlight other 2 parts."
997 (if (integerp current-prefix-arg
) (list current-prefix-arg
)
998 (smerge-match-conflict)
999 (let* ((prop (get-text-property (match-beginning 0) 'smerge-refine-part
))
1000 (part (if (and (consp prop
)
1001 (eq (buffer-chars-modified-tick) (car prop
)))
1003 ;; If already highlighted, cycle.
1004 (list (if (integerp part
) (1+ (mod part
3)))))))
1006 (if (and (integerp part
) (or (< part
1) (> part
3)))
1007 (error "No conflict part nb %s" part
))
1008 (smerge-match-conflict)
1009 (remove-overlays (match-beginning 0) (match-end 0) 'smerge
'refine
)
1010 ;; Ignore `part' if not applicable, and default it if not provided.
1011 (setq part
(cond ((null (match-end 2)) 2)
1012 ((eq (match-end 1) (match-end 3)) 1)
1013 ((integerp part
) part
)
1015 (let ((n1 (if (eq part
1) 2 1))
1016 (n2 (if (eq part
3) 2 3)))
1017 (smerge-ensure-match n1
)
1018 (smerge-ensure-match n2
)
1019 (put-text-property (match-beginning 0) (1+ (match-beginning 0))
1021 (cons (buffer-chars-modified-tick) part
))
1022 (smerge-refine-subst (match-beginning n1
) (match-end n1
)
1023 (match-beginning n2
) (match-end n2
)
1025 (face . smerge-refined-change
)))))
1027 (defun smerge-diff (n1 n2
)
1028 (smerge-match-conflict)
1029 (smerge-ensure-match n1
)
1030 (smerge-ensure-match n2
)
1031 (let ((name1 (aref smerge-match-names n1
))
1032 (name2 (aref smerge-match-names n2
))
1033 ;; Read them before the match-data gets clobbered.
1034 (beg1 (match-beginning n1
))
1035 (end1 (match-end n1
))
1036 (beg2 (match-beginning n2
))
1037 (end2 (match-end n2
))
1038 (file1 (make-temp-file "smerge1"))
1039 (file2 (make-temp-file "smerge2"))
1040 (dir default-directory
)
1041 (file (if buffer-file-name
(file-relative-name buffer-file-name
)))
1042 ;; We would want to use `emacs-mule-unix' for read&write, but we
1043 ;; bump into problems with the coding-system used by diff to write
1044 ;; the file names and the time stamps in the header.
1045 ;; `buffer-file-coding-system' is not always correct either, but if
1046 ;; the OS/user uses only one coding-system, then it works.
1047 (coding-system-for-read buffer-file-coding-system
))
1048 (write-region beg1 end1 file1 nil
'nomessage
)
1049 (write-region beg2 end2 file2 nil
'nomessage
)
1051 (with-current-buffer (get-buffer-create smerge-diff-buffer-name
)
1052 (setq default-directory dir
)
1053 (let ((inhibit-read-only t
))
1056 (apply 'call-process diff-command nil t nil
1057 (append smerge-diff-switches
1058 (list "-L" (concat name1
"/" file
)
1059 "-L" (concat name2
"/" file
)
1061 (if (eq status
0) (insert "No differences found.\n"))))
1062 (goto-char (point-min))
1064 (display-buffer (current-buffer) t
))
1066 (delete-file file2
))))
1068 ;; compiler pacifiers
1069 (defvar smerge-ediff-windows
)
1070 (defvar smerge-ediff-buf
)
1071 (defvar ediff-buffer-A
)
1072 (defvar ediff-buffer-B
)
1073 (defvar ediff-buffer-C
)
1074 (defvar ediff-ancestor-buffer
)
1075 (defvar ediff-quit-hook
)
1076 (declare-function ediff-cleanup-mess
"ediff-util" nil
)
1079 (defun smerge-ediff (&optional name-mine name-other name-base
)
1080 "Invoke ediff to resolve the conflicts.
1081 NAME-MINE, NAME-OTHER, and NAME-BASE, if non-nil, are used for the
1084 (let* ((buf (current-buffer))
1086 ;;(ediff-default-variant 'default-B)
1087 (config (current-window-configuration))
1088 (filename (file-name-nondirectory buffer-file-name
))
1089 (mine (generate-new-buffer
1090 (or name-mine
(concat "*" filename
" MINE*"))))
1091 (other (generate-new-buffer
1092 (or name-other
(concat "*" filename
" OTHER*"))))
1094 (with-current-buffer mine
1095 (buffer-disable-undo)
1096 (insert-buffer-substring buf
)
1097 (goto-char (point-min))
1098 (while (smerge-find-conflict)
1099 (when (match-beginning 2) (setq base t
))
1101 (buffer-enable-undo)
1102 (set-buffer-modified-p nil
)
1105 (with-current-buffer other
1106 (buffer-disable-undo)
1107 (insert-buffer-substring buf
)
1108 (goto-char (point-min))
1109 (while (smerge-find-conflict)
1111 (buffer-enable-undo)
1112 (set-buffer-modified-p nil
)
1116 (setq base
(generate-new-buffer
1117 (or name-base
(concat "*" filename
" BASE*"))))
1118 (with-current-buffer base
1119 (buffer-disable-undo)
1120 (insert-buffer-substring buf
)
1121 (goto-char (point-min))
1122 (while (smerge-find-conflict)
1125 (delete-region (match-beginning 0) (match-end 0))))
1126 (buffer-enable-undo)
1127 (set-buffer-modified-p nil
)
1130 ;; the rest of the code is inspired from vc.el
1134 (ediff-merge-buffers-with-ancestor mine other base
)
1135 ;; nil 'ediff-merge-revisions-with-ancestor buffer-file-name)
1136 (ediff-merge-buffers mine other
)))
1137 ;; nil 'ediff-merge-revisions buffer-file-name)))
1139 ;; Ediff is now set up, and we are in the control buffer.
1140 ;; Do a few further adjustments and take precautions for exit.
1141 (set (make-local-variable 'smerge-ediff-windows
) config
)
1142 (set (make-local-variable 'smerge-ediff-buf
) buf
)
1143 (set (make-local-variable 'ediff-quit-hook
)
1145 (let ((buffer-A ediff-buffer-A
)
1146 (buffer-B ediff-buffer-B
)
1147 (buffer-C ediff-buffer-C
)
1148 (buffer-Ancestor ediff-ancestor-buffer
)
1149 (buf smerge-ediff-buf
)
1150 (windows smerge-ediff-windows
))
1151 (ediff-cleanup-mess)
1152 (with-current-buffer buf
1154 (insert-buffer-substring buffer-C
)
1155 (kill-buffer buffer-A
)
1156 (kill-buffer buffer-B
)
1157 (kill-buffer buffer-C
)
1158 (when (bufferp buffer-Ancestor
) (kill-buffer buffer-Ancestor
))
1159 (set-window-configuration windows
)
1160 (message "Conflict resolution finished; you may save the buffer")))))
1161 (message "Please resolve conflicts now; exit ediff when done")))
1163 (defun smerge-makeup-conflict (pt1 pt2 pt3
&optional pt4
)
1164 "Insert diff3 markers to make a new conflict.
1165 Uses point and mark for 2 of the relevant positions and previous marks
1167 By default, makes up a 2-way conflict,
1168 with a \\[universal-argument] prefix, makes up a 3-way conflict."
1172 (progn (pop-mark) (mark))
1173 (when current-prefix-arg
(pop-mark) (mark))))
1174 ;; Start from the end so as to avoid problems with pos-changes.
1175 (destructuring-bind (pt1 pt2 pt3
&optional pt4
)
1176 (sort (list* pt1 pt2 pt3
(if pt4
(list pt4
))) '>=)
1177 (goto-char pt1
) (beginning-of-line)
1178 (insert ">>>>>>> OTHER\n")
1179 (goto-char pt2
) (beginning-of-line)
1180 (insert "=======\n")
1181 (goto-char pt3
) (beginning-of-line)
1183 (insert "||||||| BASE\n")
1184 (goto-char pt4
) (beginning-of-line))
1185 (insert "<<<<<<< MINE\n"))
1186 (if smerge-mode nil
(smerge-mode 1))
1190 (defconst smerge-parsep-re
1191 (concat smerge-begin-re
"\\|" smerge-end-re
"\\|"
1192 smerge-base-re
"\\|" smerge-other-re
"\\|"))
1195 (define-minor-mode smerge-mode
1196 "Minor mode to simplify editing output from the diff3 program.
1197 \\{smerge-mode-map}"
1198 :group
'smerge
:lighter
" SMerge"
1199 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
1202 (font-lock-add-keywords nil smerge-font-lock-keywords
'append
)
1203 (font-lock-remove-keywords nil smerge-font-lock-keywords
))
1204 (goto-char (point-min))
1205 (while (smerge-find-conflict)
1207 (font-lock-fontify-region (match-beginning 0) (match-end 0) nil
)))))
1208 (if (string-match (regexp-quote smerge-parsep-re
) paragraph-separate
)
1210 (set (make-local-variable 'paragraph-separate
)
1211 (replace-match "" t t paragraph-separate
)))
1213 (set (make-local-variable 'paragraph-separate
)
1214 (concat smerge-parsep-re paragraph-separate
))))
1216 (smerge-remove-props (point-min) (point-max))))
1219 (defun smerge-start-session ()
1220 "Turn on `smerge-mode' and move point to first conflict marker.
1221 If no conflict maker is found, turn off `smerge-mode'."
1225 (error (smerge-auto-leave))))
1227 (provide 'smerge-mode
)
1229 ;; arch-tag: 605c8d1e-e43d-4943-a6f3-1bcc4333e690
1230 ;;; smerge-mode.el ends here