Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / lisp / vc / smerge-mode.el
blobcc9c4673345a4778ee90581812766b817476f31d
1 ;;; smerge-mode.el --- Minor mode to resolve diff3 conflicts -*- lexical-binding: t -*-
3 ;; Copyright (C) 1999-2014 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: vc, tools, revision control, merge, diff3, cvs, conflict
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Provides a lightweight alternative to emerge/ediff.
26 ;; To use it, simply add to your .emacs the following lines:
28 ;; (autoload 'smerge-mode "smerge-mode" nil t)
30 ;; you can even have it turned on automatically with the following
31 ;; piece of code in your .emacs:
33 ;; (defun sm-try-smerge ()
34 ;; (save-excursion
35 ;; (goto-char (point-min))
36 ;; (when (re-search-forward "^<<<<<<< " nil t)
37 ;; (smerge-mode 1))))
38 ;; (add-hook 'find-file-hook 'sm-try-smerge t)
40 ;;; Todo:
42 ;; - if requested, ask the user whether he wants to call ediff right away
44 ;;; Code:
46 (eval-when-compile (require 'cl-lib))
47 (require 'diff-mode) ;For diff-auto-refine-mode.
48 (require 'newcomment)
50 ;;; The real definition comes later.
51 (defvar smerge-mode)
53 (defgroup smerge ()
54 "Minor mode to highlight and resolve diff3 conflicts."
55 :group 'tools
56 :prefix "smerge-")
58 (defcustom smerge-diff-buffer-name "*vc-diff*"
59 "Buffer name to use for displaying diffs."
60 :type '(choice
61 (const "*vc-diff*")
62 (const "*cvs-diff*")
63 (const "*smerge-diff*")
64 string))
66 (defcustom smerge-diff-switches
67 (append '("-d" "-b")
68 (if (listp diff-switches) diff-switches (list diff-switches)))
69 "A list of strings specifying switches to be passed to diff.
70 Used in `smerge-diff-base-mine' and related functions."
71 :type '(repeat string))
73 (defcustom smerge-auto-leave t
74 "Non-nil means to leave `smerge-mode' when the last conflict is resolved."
75 :type 'boolean)
77 (defface smerge-mine
78 '((((class color) (min-colors 88) (background light))
79 :background "#ffdddd")
80 (((class color) (min-colors 88) (background dark))
81 :background "#553333")
82 (((class color))
83 :foreground "red"))
84 "Face for your code.")
85 (define-obsolete-face-alias 'smerge-mine-face 'smerge-mine "22.1")
86 (defvar smerge-mine-face 'smerge-mine)
88 (defface smerge-other
89 '((((class color) (min-colors 88) (background light))
90 :background "#ddffdd")
91 (((class color) (min-colors 88) (background dark))
92 :background "#335533")
93 (((class color))
94 :foreground "green"))
95 "Face for the other code.")
96 (define-obsolete-face-alias 'smerge-other-face 'smerge-other "22.1")
97 (defvar smerge-other-face 'smerge-other)
99 (defface smerge-base
100 '((((class color) (min-colors 88) (background light))
101 :background "#ffffaa")
102 (((class color) (min-colors 88) (background dark))
103 :background "#888833")
104 (((class color))
105 :foreground "yellow"))
106 "Face for the base code.")
107 (define-obsolete-face-alias 'smerge-base-face 'smerge-base "22.1")
108 (defvar smerge-base-face 'smerge-base)
110 (defface smerge-markers
111 '((((background light))
112 (:background "grey85"))
113 (((background dark))
114 (:background "grey30")))
115 "Face for the conflict markers.")
116 (define-obsolete-face-alias 'smerge-markers-face 'smerge-markers "22.1")
117 (defvar smerge-markers-face 'smerge-markers)
119 (defface smerge-refined-change
120 '((t nil))
121 "Face used for char-based changes shown by `smerge-refine'.")
123 (defface smerge-refined-removed
124 '((default
125 :inherit smerge-refined-change)
126 (((class color) (min-colors 88) (background light))
127 :background "#ffbbbb")
128 (((class color) (min-colors 88) (background dark))
129 :background "#aa2222")
130 (t :inverse-video t))
131 "Face used for removed characters shown by `smerge-refine'."
132 :version "24.3")
134 (defface smerge-refined-added
135 '((default
136 :inherit smerge-refined-change)
137 (((class color) (min-colors 88) (background light))
138 :background "#aaffaa")
139 (((class color) (min-colors 88) (background dark))
140 :background "#22aa22")
141 (t :inverse-video t))
142 "Face used for added characters shown by `smerge-refine'."
143 :version "24.3")
145 (easy-mmode-defmap smerge-basic-map
146 `(("n" . smerge-next)
147 ("p" . smerge-prev)
148 ("r" . smerge-resolve)
149 ("a" . smerge-keep-all)
150 ("b" . smerge-keep-base)
151 ("o" . smerge-keep-other)
152 ("m" . smerge-keep-mine)
153 ("E" . smerge-ediff)
154 ("C" . smerge-combine-with-next)
155 ("R" . smerge-refine)
156 ("\C-m" . smerge-keep-current)
157 ("=" . ,(make-sparse-keymap "Diff"))
158 ("=<" "base-mine" . smerge-diff-base-mine)
159 ("=>" "base-other" . smerge-diff-base-other)
160 ("==" "mine-other" . smerge-diff-mine-other))
161 "The base keymap for `smerge-mode'.")
163 (defcustom smerge-command-prefix "\C-c^"
164 "Prefix for `smerge-mode' commands."
165 :type '(choice (const :tag "ESC" "\e")
166 (const :tag "C-c ^" "\C-c^" )
167 (const :tag "none" "")
168 string))
170 (easy-mmode-defmap smerge-mode-map
171 `((,smerge-command-prefix . ,smerge-basic-map))
172 "Keymap for `smerge-mode'.")
174 (defvar smerge-check-cache nil)
175 (make-variable-buffer-local 'smerge-check-cache)
176 (defun smerge-check (n)
177 (condition-case nil
178 (let ((state (cons (point) (buffer-modified-tick))))
179 (unless (equal (cdr smerge-check-cache) state)
180 (smerge-match-conflict)
181 (setq smerge-check-cache (cons (match-data) state)))
182 (nth (* 2 n) (car smerge-check-cache)))
183 (error nil)))
185 (easy-menu-define smerge-mode-menu smerge-mode-map
186 "Menu for `smerge-mode'."
187 '("SMerge"
188 ["Next" smerge-next :help "Go to next conflict"]
189 ["Previous" smerge-prev :help "Go to previous conflict"]
190 "--"
191 ["Keep All" smerge-keep-all :help "Keep all three versions"
192 :active (smerge-check 1)]
193 ["Keep Current" smerge-keep-current :help "Use current (at point) version"
194 :active (and (smerge-check 1) (> (smerge-get-current) 0))]
195 "--"
196 ["Revert to Base" smerge-keep-base :help "Revert to base version"
197 :active (smerge-check 2)]
198 ["Keep Other" smerge-keep-other :help "Keep `other' version"
199 :active (smerge-check 3)]
200 ["Keep Yours" smerge-keep-mine :help "Keep your version"
201 :active (smerge-check 1)]
202 "--"
203 ["Diff Base/Mine" smerge-diff-base-mine
204 :help "Diff `base' and `mine' for current conflict"
205 :active (smerge-check 2)]
206 ["Diff Base/Other" smerge-diff-base-other
207 :help "Diff `base' and `other' for current conflict"
208 :active (smerge-check 2)]
209 ["Diff Mine/Other" smerge-diff-mine-other
210 :help "Diff `mine' and `other' for current conflict"
211 :active (smerge-check 1)]
212 "--"
213 ["Invoke Ediff" smerge-ediff
214 :help "Use Ediff to resolve the conflicts"
215 :active (smerge-check 1)]
216 ["Auto Resolve" smerge-resolve
217 :help "Try auto-resolution heuristics"
218 :active (smerge-check 1)]
219 ["Combine" smerge-combine-with-next
220 :help "Combine current conflict with next"
221 :active (smerge-check 1)]
224 (easy-menu-define smerge-context-menu nil
225 "Context menu for mine area in `smerge-mode'."
226 '(nil
227 ["Keep Current" smerge-keep-current :help "Use current (at point) version"]
228 ["Kill Current" smerge-kill-current :help "Remove current (at point) version"]
229 ["Keep All" smerge-keep-all :help "Keep all three versions"]
230 "---"
231 ["More..." (popup-menu smerge-mode-menu) :help "Show full SMerge mode menu"]
234 (defconst smerge-font-lock-keywords
235 '((smerge-find-conflict
236 (1 smerge-mine-face prepend t)
237 (2 smerge-base-face prepend t)
238 (3 smerge-other-face prepend t)
239 ;; FIXME: `keep' doesn't work right with syntactic fontification.
240 (0 smerge-markers-face keep)
241 (4 nil t t)
242 (5 nil t t)))
243 "Font lock patterns for `smerge-mode'.")
245 (defconst smerge-begin-re "^<<<<<<< \\(.*\\)\n")
246 (defconst smerge-end-re "^>>>>>>> \\(.*\\)\n")
247 (defconst smerge-base-re "^||||||| \\(.*\\)\n")
248 (defconst smerge-other-re "^=======\n")
250 (defvar smerge-conflict-style nil
251 "Keep track of which style of conflict is in use.
252 Can be nil if the style is undecided, or else:
253 - `diff3-E'
254 - `diff3-A'")
256 ;; Compiler pacifiers
257 (defvar font-lock-mode)
258 (defvar font-lock-keywords)
260 ;;;;
261 ;;;; Actual code
262 ;;;;
264 ;; Define smerge-next and smerge-prev
265 (easy-mmode-define-navigation smerge smerge-begin-re "conflict" nil nil
266 (if diff-auto-refine-mode
267 (condition-case nil (smerge-refine) (error nil))))
269 (defconst smerge-match-names ["conflict" "mine" "base" "other"])
271 (defun smerge-ensure-match (n)
272 (unless (match-end n)
273 (error "No `%s'" (aref smerge-match-names n))))
275 (defun smerge-auto-leave ()
276 (when (and smerge-auto-leave
277 (save-excursion (goto-char (point-min))
278 (not (re-search-forward smerge-begin-re nil t))))
279 (when (and (listp buffer-undo-list) smerge-mode)
280 (push (list 'apply 'smerge-mode 1) buffer-undo-list))
281 (smerge-mode -1)))
284 (defun smerge-keep-all ()
285 "Concatenate all versions."
286 (interactive)
287 (smerge-match-conflict)
288 (let ((mb2 (or (match-beginning 2) (point-max)))
289 (me2 (or (match-end 2) (point-min))))
290 (delete-region (match-end 3) (match-end 0))
291 (delete-region (max me2 (match-end 1)) (match-beginning 3))
292 (if (and (match-end 2) (/= (match-end 1) (match-end 3)))
293 (delete-region (match-end 1) (match-beginning 2)))
294 (delete-region (match-beginning 0) (min (match-beginning 1) mb2))
295 (smerge-auto-leave)))
297 (defun smerge-keep-n (n)
298 (smerge-remove-props (match-beginning 0) (match-end 0))
299 ;; We used to use replace-match, but that did not preserve markers so well.
300 (delete-region (match-end n) (match-end 0))
301 (delete-region (match-beginning 0) (match-beginning n)))
303 (defun smerge-combine-with-next ()
304 "Combine the current conflict with the next one."
305 ;; `smerge-auto-combine' relies on the finish position (at the beginning
306 ;; of the closing marker).
307 (interactive)
308 (smerge-match-conflict)
309 (let ((ends nil))
310 (dolist (i '(3 2 1 0))
311 (push (if (match-end i) (copy-marker (match-end i) t)) ends))
312 (setq ends (apply 'vector ends))
313 (goto-char (aref ends 0))
314 (if (not (re-search-forward smerge-begin-re nil t))
315 (error "No next conflict")
316 (smerge-match-conflict)
317 (let ((match-data (mapcar (lambda (m) (if m (copy-marker m)))
318 (match-data))))
319 ;; First copy the in-between text in each alternative.
320 (dolist (i '(1 2 3))
321 (when (aref ends i)
322 (goto-char (aref ends i))
323 (insert-buffer-substring (current-buffer)
324 (aref ends 0) (car match-data))))
325 (delete-region (aref ends 0) (car match-data))
326 ;; Then move the second conflict's alternatives into the first.
327 (dolist (i '(1 2 3))
328 (set-match-data match-data)
329 (when (and (aref ends i) (match-end i))
330 (goto-char (aref ends i))
331 (insert-buffer-substring (current-buffer)
332 (match-beginning i) (match-end i))))
333 (delete-region (car match-data) (cadr match-data))
334 ;; Free the markers.
335 (dolist (m match-data) (if m (move-marker m nil)))
336 (mapc (lambda (m) (if m (move-marker m nil))) ends)))))
338 (defvar smerge-auto-combine-max-separation 2
339 "Max number of lines between conflicts that should be combined.")
341 (defun smerge-auto-combine ()
342 "Automatically combine conflicts that are near each other."
343 (interactive)
344 (save-excursion
345 (goto-char (point-min))
346 (while (smerge-find-conflict)
347 ;; 2 is 1 (default) + 1 (the begin markers).
348 (while (save-excursion
349 (smerge-find-conflict
350 (line-beginning-position
351 (+ 2 smerge-auto-combine-max-separation))))
352 (forward-line -1) ;Go back inside the conflict.
353 (smerge-combine-with-next)
354 (forward-line 1) ;Move past the end of the conflict.
355 ))))
357 (defvar smerge-resolve-function
358 (lambda () (user-error "Don't know how to resolve"))
359 "Mode-specific merge function.
360 The function is called with zero or one argument (non-nil if the resolution
361 function should only apply safe heuristics) and with the match data set
362 according to `smerge-match-conflict'.")
364 (defvar smerge-text-properties
365 `(help-echo "merge conflict: mouse-3 shows a menu"
366 ;; mouse-face highlight
367 keymap (keymap (down-mouse-3 . smerge-popup-context-menu))))
369 (defun smerge-remove-props (beg end)
370 (remove-overlays beg end 'smerge 'refine)
371 (remove-overlays beg end 'smerge 'conflict)
372 ;; Now that we use overlays rather than text-properties, this function
373 ;; does not cause refontification any more. It can be seen very clearly
374 ;; in buffers where jit-lock-contextually is not t, in which case deleting
375 ;; the "<<<<<<< foobar" leading line leaves the rest of the conflict
376 ;; highlighted as if it were still a valid conflict. Note that in many
377 ;; important cases (such as the previous example) we're actually called
378 ;; during font-locking so inhibit-modification-hooks is non-nil, so we
379 ;; can't just modify the buffer and expect font-lock to be triggered as in:
380 ;; (put-text-property beg end 'smerge-force-highlighting nil)
381 (with-silent-modifications
382 (remove-text-properties beg end '(fontified nil))))
384 (defun smerge-popup-context-menu (event)
385 "Pop up the Smerge mode context menu under mouse."
386 (interactive "e")
387 (if (and smerge-mode
388 (save-excursion (posn-set-point (event-end event)) (smerge-check 1)))
389 (progn
390 (posn-set-point (event-end event))
391 (smerge-match-conflict)
392 (let ((i (smerge-get-current))
394 (if (<= i 0)
395 ;; Out of range
396 (popup-menu smerge-mode-menu)
397 ;; Install overlay.
398 (setq o (make-overlay (match-beginning i) (match-end i)))
399 (unwind-protect
400 (progn
401 (overlay-put o 'face 'highlight)
402 (sit-for 0) ;Display the new highlighting.
403 (popup-menu smerge-context-menu))
404 ;; Delete overlay.
405 (delete-overlay o)))))
406 ;; There's no conflict at point, the text-props are just obsolete.
407 (save-excursion
408 (let ((beg (re-search-backward smerge-end-re nil t))
409 (end (re-search-forward smerge-begin-re nil t)))
410 (smerge-remove-props (or beg (point-min)) (or end (point-max)))
411 (push event unread-command-events)))))
413 (defun smerge-apply-resolution-patch (buf m0b m0e m3b m3e &optional m2b)
414 "Replace the conflict with a bunch of subconflicts.
415 BUF contains a plain diff between match-1 and match-3."
416 (let ((line 1)
417 (textbuf (current-buffer))
418 (name1 (progn (goto-char m0b)
419 (buffer-substring (+ (point) 8) (line-end-position))))
420 (name2 (when m2b (goto-char m2b) (forward-line -1)
421 (buffer-substring (+ (point) 8) (line-end-position))))
422 (name3 (progn (goto-char m0e) (forward-line -1)
423 (buffer-substring (+ (point) 8) (line-end-position)))))
424 (smerge-remove-props m0b m0e)
425 (delete-region m3e m0e)
426 (delete-region m0b m3b)
427 (setq m3b m0b)
428 (setq m3e (- m3e (- m3b m0b)))
429 (goto-char m3b)
430 (with-current-buffer buf
431 (goto-char (point-min))
432 (while (not (eobp))
433 (if (not (looking-at "\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?\\([acd]\\)\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?$"))
434 (error "Unexpected patch hunk header: %s"
435 (buffer-substring (point) (line-end-position)))
436 (let* ((op (char-after (match-beginning 3)))
437 (startline (+ (string-to-number (match-string 1))
438 ;; No clue why this is the way it is, but line
439 ;; numbers seem to be off-by-one for `a' ops.
440 (if (eq op ?a) 1 0)))
441 (endline (if (eq op ?a) startline
442 (1+ (if (match-end 2)
443 (string-to-number (match-string 2))
444 startline))))
445 (lines (- endline startline))
446 (otherlines (cond
447 ((eq op ?d) nil)
448 ((null (match-end 5)) 1)
449 (t (- (string-to-number (match-string 5))
450 (string-to-number (match-string 4)) -1))))
451 othertext)
452 (forward-line 1) ;Skip header.
453 (forward-line lines) ;Skip deleted text.
454 (if (eq op ?c) (forward-line 1)) ;Skip separator.
455 (setq othertext
456 (if (null otherlines) ""
457 (let ((pos (point)))
458 (dotimes (_i otherlines) (delete-char 2) (forward-line 1))
459 (buffer-substring pos (point)))))
460 (with-current-buffer textbuf
461 (forward-line (- startline line))
462 (insert "<<<<<<< " name1 "\n" othertext
463 (if name2 (concat "||||||| " name2 "\n") "")
464 "=======\n")
465 (forward-line lines)
466 (insert ">>>>>>> " name3 "\n")
467 (setq line endline))))))))
469 (defconst smerge-resolve--normalize-re "[\n\t][ \t\n]*\\| [ \t\n]+")
471 (defun smerge-resolve--extract-comment (beg end)
472 "Extract the text within the comments that span BEG..END."
473 (save-excursion
474 (let ((comments ())
475 combeg)
476 (goto-char beg)
477 (while (and (< (point) end)
478 (setq combeg (comment-search-forward end t)))
479 (let ((beg (point)))
480 (goto-char combeg)
481 (comment-forward 1)
482 (save-excursion
483 (comment-enter-backward)
484 (push " " comments)
485 (push (buffer-substring-no-properties beg (point)) comments))))
486 (push " " comments)
487 (with-temp-buffer
488 (apply #'insert (nreverse comments))
489 (goto-char (point-min))
490 (while (re-search-forward smerge-resolve--normalize-re
491 nil t)
492 (replace-match " "))
493 (buffer-string)))))
495 (defun smerge-resolve--normalize (beg end)
496 (replace-regexp-in-string
497 smerge-resolve--normalize-re " "
498 (concat " " (buffer-substring-no-properties beg end) " ")))
500 (defun smerge-resolve (&optional safe)
501 "Resolve the conflict at point intelligently.
502 This relies on mode-specific knowledge and thus only works in some
503 major modes. Uses `smerge-resolve-function' to do the actual work."
504 (interactive)
505 (smerge-match-conflict)
506 (smerge-remove-props (match-beginning 0) (match-end 0))
507 (let ((md (match-data))
508 (m0b (match-beginning 0))
509 (m1b (match-beginning 1))
510 (m2b (match-beginning 2))
511 (m3b (match-beginning 3))
512 (m0e (match-end 0))
513 (m1e (match-end 1))
514 (m2e (match-end 2))
515 (m3e (match-end 3))
516 (buf (generate-new-buffer " *smerge*"))
517 m b o
518 choice)
519 (unwind-protect
520 (progn
521 (cond
522 ;; Trivial diff3 -A non-conflicts.
523 ((and (eq (match-end 1) (match-end 3))
524 (eq (match-beginning 1) (match-beginning 3)))
525 (smerge-keep-n 3))
526 ;; Mode-specific conflict resolution.
527 ((condition-case nil
528 (atomic-change-group
529 (if safe
530 (funcall smerge-resolve-function safe)
531 (funcall smerge-resolve-function))
533 (error nil))
534 ;; Nothing to do: the resolution function has done it already.
535 nil)
536 ;; Non-conflict.
537 ((and (eq m1e m3e) (eq m1b m3b))
538 (set-match-data md) (smerge-keep-n 3))
539 ;; Refine a 2-way conflict using "diff -b".
540 ;; In case of a 3-way conflict with an empty base
541 ;; (i.e. 2 conflicting additions), we do the same, presuming
542 ;; that the 2 additions should be somehow merged rather
543 ;; than concatenated.
544 ((let ((lines (count-lines m3b m3e)))
545 (setq m (make-temp-file "smm"))
546 (write-region m1b m1e m nil 'silent)
547 (setq o (make-temp-file "smo"))
548 (write-region m3b m3e o nil 'silent)
549 (not (or (eq m1b m1e) (eq m3b m3e)
550 (and (not (zerop (call-process diff-command
551 nil buf nil "-b" o m)))
552 ;; TODO: We don't know how to do the refinement
553 ;; if there's a non-empty ancestor and m1 and m3
554 ;; aren't just plain equal.
555 m2b (not (eq m2b m2e)))
556 (with-current-buffer buf
557 (goto-char (point-min))
558 ;; Make sure there's some refinement.
559 (looking-at
560 (concat "1," (number-to-string lines) "c"))))))
561 (smerge-apply-resolution-patch buf m0b m0e m3b m3e m2b))
562 ;; "Mere whitespace changes" conflicts.
563 ((when m2e
564 (setq b (make-temp-file "smb"))
565 (write-region m2b m2e b nil 'silent)
566 (with-current-buffer buf (erase-buffer))
567 ;; Only minor whitespace changes made locally.
568 ;; BEWARE: pass "-c" 'cause the output is reused in the next test.
569 (zerop (call-process diff-command nil buf nil "-bc" b m)))
570 (set-match-data md)
571 (smerge-keep-n 3))
572 ;; Try "diff -b BASE MINE | patch OTHER".
573 ((when (and (not safe) m2e b
574 ;; If the BASE is empty, this would just concatenate
575 ;; the two, which is rarely right.
576 (not (eq m2b m2e)))
577 ;; BEWARE: we're using here the patch of the previous test.
578 (with-current-buffer buf
579 (zerop (call-process-region
580 (point-min) (point-max) "patch" t nil nil
581 "-r" null-device "--no-backup-if-mismatch"
582 "-fl" o))))
583 (save-restriction
584 (narrow-to-region m0b m0e)
585 (smerge-remove-props m0b m0e)
586 (insert-file-contents o nil nil nil t)))
587 ;; Try "diff -b BASE OTHER | patch MINE".
588 ((when (and (not safe) m2e b
589 ;; If the BASE is empty, this would just concatenate
590 ;; the two, which is rarely right.
591 (not (eq m2b m2e)))
592 (write-region m3b m3e o nil 'silent)
593 (call-process diff-command nil buf nil "-bc" b o)
594 (with-current-buffer buf
595 (zerop (call-process-region
596 (point-min) (point-max) "patch" t nil nil
597 "-r" null-device "--no-backup-if-mismatch"
598 "-fl" m))))
599 (save-restriction
600 (narrow-to-region m0b m0e)
601 (smerge-remove-props m0b m0e)
602 (insert-file-contents m nil nil nil t)))
603 ;; If the conflict is only made of comments, and one of the two
604 ;; changes is only rearranging spaces (e.g. reflowing text) while
605 ;; the other is a real change, drop the space-rearrangement.
606 ((and m2e
607 (comment-only-p m1b m1e)
608 (comment-only-p m2b m2e)
609 (comment-only-p m3b m3e)
610 (let ((t1 (smerge-resolve--extract-comment m1b m1e))
611 (t2 (smerge-resolve--extract-comment m2b m2e))
612 (t3 (smerge-resolve--extract-comment m3b m3e)))
613 (cond
614 ((and (equal t1 t2) (not (equal t2 t3)))
615 (setq choice 3))
616 ((and (not (equal t1 t2)) (equal t2 t3))
617 (setq choice 1)))))
618 (set-match-data md)
619 (smerge-keep-n choice))
620 ;; Idem, when the conflict is contained within a single comment.
621 ((save-excursion
622 (and m2e
623 (nth 4 (syntax-ppss m0b))
624 ;; If there's a conflict earlier in the file,
625 ;; syntax-ppss is not reliable.
626 (not (re-search-backward smerge-begin-re nil t))
627 (progn (goto-char (nth 8 (syntax-ppss m0b)))
628 (forward-comment 1)
629 (> (point) m0e))
630 (let ((t1 (smerge-resolve--normalize m1b m1e))
631 (t2 (smerge-resolve--normalize m2b m2e))
632 (t3 (smerge-resolve--normalize m3b m3e)))
633 (cond
634 ((and (equal t1 t2) (not (equal t2 t3)))
635 (setq choice 3))
636 ((and (not (equal t1 t2)) (equal t2 t3))
637 (setq choice 1))))))
638 (set-match-data md)
639 (smerge-keep-n choice))
641 (user-error "Don't know how to resolve"))))
642 (if (buffer-name buf) (kill-buffer buf))
643 (if m (delete-file m))
644 (if b (delete-file b))
645 (if o (delete-file o))))
646 (smerge-auto-leave))
648 (defun smerge-resolve-all ()
649 "Perform automatic resolution on all conflicts."
650 (interactive)
651 (save-excursion
652 (goto-char (point-min))
653 (while (re-search-forward smerge-begin-re nil t)
654 (condition-case nil
655 (progn
656 (smerge-match-conflict)
657 (smerge-resolve 'safe))
658 (error nil)))))
660 (defun smerge-batch-resolve ()
661 ;; command-line-args-left is what is left of the command line.
662 (if (not noninteractive)
663 (error "`smerge-batch-resolve' is to be used only with -batch"))
664 (while command-line-args-left
665 (let ((file (pop command-line-args-left)))
666 (if (string-match "\\.rej\\'" file)
667 ;; .rej files should never contain diff3 markers, on the other hand,
668 ;; in Arch, .rej files are sometimes used to indicate that the
669 ;; main file has diff3 markers. So you can pass **/*.rej and
670 ;; it will DTRT.
671 (setq file (substring file 0 (match-beginning 0))))
672 (message "Resolving conflicts in %s..." file)
673 (when (file-readable-p file)
674 (with-current-buffer (find-file-noselect file)
675 (smerge-resolve-all)
676 (save-buffer)
677 (kill-buffer (current-buffer)))))))
679 (defun smerge-keep-base ()
680 "Revert to the base version."
681 (interactive)
682 (smerge-match-conflict)
683 (smerge-ensure-match 2)
684 (smerge-keep-n 2)
685 (smerge-auto-leave))
687 (defun smerge-keep-other ()
688 "Use \"other\" version."
689 (interactive)
690 (smerge-match-conflict)
691 ;;(smerge-ensure-match 3)
692 (smerge-keep-n 3)
693 (smerge-auto-leave))
695 (defun smerge-keep-mine ()
696 "Keep your version."
697 (interactive)
698 (smerge-match-conflict)
699 ;;(smerge-ensure-match 1)
700 (smerge-keep-n 1)
701 (smerge-auto-leave))
703 (defun smerge-get-current ()
704 (let ((i 3))
705 (while (or (not (match-end i))
706 (< (point) (match-beginning i))
707 (>= (point) (match-end i)))
708 (cl-decf i))
711 (defun smerge-keep-current ()
712 "Use the current (under the cursor) version."
713 (interactive)
714 (smerge-match-conflict)
715 (let ((i (smerge-get-current)))
716 (if (<= i 0) (error "Not inside a version")
717 (smerge-keep-n i)
718 (smerge-auto-leave))))
720 (defun smerge-kill-current ()
721 "Remove the current (under the cursor) version."
722 (interactive)
723 (smerge-match-conflict)
724 (let ((i (smerge-get-current)))
725 (if (<= i 0) (error "Not inside a version")
726 (let ((left nil))
727 (dolist (n '(3 2 1))
728 (if (and (match-end n) (/= (match-end n) (match-end i)))
729 (push n left)))
730 (if (and (cdr left)
731 (/= (match-end (car left)) (match-end (cadr left))))
732 (ding) ;We don't know how to do that.
733 (smerge-keep-n (car left))
734 (smerge-auto-leave))))))
736 (defun smerge-diff-base-mine ()
737 "Diff 'base' and 'mine' version in current conflict region."
738 (interactive)
739 (smerge-diff 2 1))
741 (defun smerge-diff-base-other ()
742 "Diff 'base' and 'other' version in current conflict region."
743 (interactive)
744 (smerge-diff 2 3))
746 (defun smerge-diff-mine-other ()
747 "Diff 'mine' and 'other' version in current conflict region."
748 (interactive)
749 (smerge-diff 1 3))
751 (defun smerge-match-conflict ()
752 "Get info about the conflict. Puts the info in the `match-data'.
753 The submatches contain:
754 0: the whole conflict.
755 1: your code.
756 2: the base code.
757 3: other code.
758 An error is raised if not inside a conflict."
759 (save-excursion
760 (condition-case nil
761 (let* ((orig-point (point))
763 (_ (forward-line 1))
764 (_ (re-search-backward smerge-begin-re))
766 (start (match-beginning 0))
767 (mine-start (match-end 0))
768 (filename (or (match-string 1) ""))
770 (_ (re-search-forward smerge-end-re))
771 (_ (cl-assert (< orig-point (match-end 0))))
773 (other-end (match-beginning 0))
774 (end (match-end 0))
776 (_ (re-search-backward smerge-other-re start))
778 (mine-end (match-beginning 0))
779 (other-start (match-end 0))
781 base-start base-end)
783 ;; handle the various conflict styles
784 (cond
785 ((save-excursion
786 (goto-char mine-start)
787 (re-search-forward smerge-begin-re end t))
788 ;; There's a nested conflict and we're after the beginning
789 ;; of the outer one but before the beginning of the inner one.
790 ;; Of course, maybe this is not a nested conflict but in that
791 ;; case it can only be something nastier that we don't know how
792 ;; to handle, so may as well arbitrarily decide to treat it as
793 ;; a nested conflict. --Stef
794 (error "There is a nested conflict"))
796 ((re-search-backward smerge-base-re start t)
797 ;; a 3-parts conflict
798 (set (make-local-variable 'smerge-conflict-style) 'diff3-A)
799 (setq base-end mine-end)
800 (setq mine-end (match-beginning 0))
801 (setq base-start (match-end 0)))
803 ((string= filename (file-name-nondirectory
804 (or buffer-file-name "")))
805 ;; a 2-parts conflict
806 (set (make-local-variable 'smerge-conflict-style) 'diff3-E))
808 ((and (not base-start)
809 (or (eq smerge-conflict-style 'diff3-A)
810 (equal filename "ANCESTOR")
811 (string-match "\\`[.0-9]+\\'" filename)))
812 ;; a same-diff conflict
813 (setq base-start mine-start)
814 (setq base-end mine-end)
815 (setq mine-start other-start)
816 (setq mine-end other-end)))
818 (store-match-data (list start end
819 mine-start mine-end
820 base-start base-end
821 other-start other-end
822 (when base-start (1- base-start)) base-start
823 (1- other-start) other-start))
825 (search-failed (user-error "Point not in conflict region")))))
827 (defun smerge-conflict-overlay (pos)
828 "Return the conflict overlay at POS if any."
829 (let ((ols (overlays-at pos))
830 conflict)
831 (dolist (ol ols)
832 (if (and (eq (overlay-get ol 'smerge) 'conflict)
833 (> (overlay-end ol) pos))
834 (setq conflict ol)))
835 conflict))
837 (defun smerge-find-conflict (&optional limit)
838 "Find and match a conflict region. Intended as a font-lock MATCHER.
839 The submatches are the same as in `smerge-match-conflict'.
840 Returns non-nil if a match is found between point and LIMIT.
841 Point is moved to the end of the conflict."
842 (let ((found nil)
843 (pos (point))
844 conflict)
845 ;; First check to see if point is already inside a conflict, using
846 ;; the conflict overlays.
847 (while (and (not found) (setq conflict (smerge-conflict-overlay pos)))
848 ;; Check the overlay's validity and kill it if it's out of date.
849 (condition-case nil
850 (progn
851 (goto-char (overlay-start conflict))
852 (smerge-match-conflict)
853 (goto-char (match-end 0))
854 (if (<= (point) pos)
855 (error "Matching backward!")
856 (setq found t)))
857 (error (smerge-remove-props
858 (overlay-start conflict) (overlay-end conflict))
859 (goto-char pos))))
860 ;; If we're not already inside a conflict, look for the next conflict
861 ;; and add/update its overlay.
862 (while (and (not found) (re-search-forward smerge-begin-re limit t))
863 (condition-case nil
864 (progn
865 (smerge-match-conflict)
866 (goto-char (match-end 0))
867 (let ((conflict (smerge-conflict-overlay (1- (point)))))
868 (if conflict
869 ;; Update its location, just in case it got messed up.
870 (move-overlay conflict (match-beginning 0) (match-end 0))
871 (setq conflict (make-overlay (match-beginning 0) (match-end 0)
872 nil 'front-advance nil))
873 (overlay-put conflict 'evaporate t)
874 (overlay-put conflict 'smerge 'conflict)
875 (let ((props smerge-text-properties))
876 (while props
877 (overlay-put conflict (pop props) (pop props))))))
878 (setq found t))
879 (error nil)))
880 found))
882 ;;; Refined change highlighting
884 (defvar smerge-refine-forward-function 'smerge-refine-forward
885 "Function used to determine an \"atomic\" element.
886 You can set it to `forward-char' to get char-level granularity.
887 Its behavior has mainly two restrictions:
888 - if this function encounters a newline, it's important that it stops right
889 after the newline.
890 This only matters if `smerge-refine-ignore-whitespace' is nil.
891 - it needs to be unaffected by changes performed by the `preproc' argument
892 to `smerge-refine-subst'.
893 This only matters if `smerge-refine-weight-hack' is nil.")
895 (defvar smerge-refine-ignore-whitespace t
896 "If non-nil, indicate that `smerge-refine' should try to ignore change in whitespace.")
898 (defvar smerge-refine-weight-hack t
899 "If non-nil, pass to diff as many lines as there are chars in the region.
900 I.e. each atomic element (e.g. word) will be copied as many times (on different
901 lines) as it has chars. This has two advantages:
902 - if `diff' tries to minimize the number *lines* (rather than chars)
903 added/removed, this adjust the weights so that adding/removing long
904 symbols is considered correspondingly more costly.
905 - `smerge-refine-forward-function' only needs to be called when chopping up
906 the regions, and `forward-char' can be used afterwards.
907 It has the following disadvantages:
908 - cannot use `diff -w' because the weighting causes added spaces in a line
909 to be represented as added copies of some line, so `diff -w' can't do the
910 right thing any more.
911 - may in degenerate cases take a 1KB input region and turn it into a 1MB
912 file to pass to diff.")
914 (defun smerge-refine-forward (n)
915 (let ((case-fold-search nil)
916 (re "[[:upper:]]?[[:lower:]]+\\|[[:upper:]]+\\|[[:digit:]]+\\|.\\|\n"))
917 (when (and smerge-refine-ignore-whitespace
918 ;; smerge-refine-weight-hack causes additional spaces to
919 ;; appear as additional lines as well, so even if diff ignore
920 ;; whitespace changes, it'll report added/removed lines :-(
921 (not smerge-refine-weight-hack))
922 (setq re (concat "[ \t]*\\(?:" re "\\)")))
923 (dotimes (_i n)
924 (unless (looking-at re) (error "Smerge refine internal error"))
925 (goto-char (match-end 0)))))
927 (defun smerge-refine-chopup-region (beg end file &optional preproc)
928 "Chopup the region into small elements, one per line.
929 Save the result into FILE.
930 If non-nil, PREPROC is called with no argument in a buffer that contains
931 a copy of the text, just before chopping it up. It can be used to replace
932 chars to try and eliminate some spurious differences."
933 ;; We used to chop up char-by-char rather than word-by-word like ediff
934 ;; does. It had the benefit of simplicity and very fine results, but it
935 ;; often suffered from problem that diff would find correlations where
936 ;; there aren't any, so the resulting "change" didn't make much sense.
937 ;; You can still get this behavior by setting
938 ;; `smerge-refine-forward-function' to `forward-char'.
939 (let ((buf (current-buffer)))
940 (with-temp-buffer
941 (insert-buffer-substring buf beg end)
942 (when preproc (goto-char (point-min)) (funcall preproc))
943 (when smerge-refine-ignore-whitespace
944 ;; It doesn't make much of a difference for diff-fine-highlight
945 ;; because we still have the _/+/</>/! prefix anyway. Can still be
946 ;; useful in other circumstances.
947 (subst-char-in-region (point-min) (point-max) ?\n ?\s))
948 (goto-char (point-min))
949 (while (not (eobp))
950 (funcall smerge-refine-forward-function 1)
951 (let ((s (if (prog2 (forward-char -1) (bolp) (forward-char 1))
953 (buffer-substring (line-beginning-position) (point)))))
954 ;; We add \n after each char except after \n, so we get
955 ;; one line per text char, where each line contains
956 ;; just one char, except for \n chars which are
957 ;; represented by the empty line.
958 (unless (eq (char-before) ?\n) (insert ?\n))
959 ;; HACK ALERT!!
960 (if smerge-refine-weight-hack
961 (dotimes (_i (1- (length s))) (insert s "\n")))))
962 (unless (bolp) (error "Smerge refine internal error"))
963 (let ((coding-system-for-write 'emacs-mule))
964 (write-region (point-min) (point-max) file nil 'nomessage)))))
966 (defun smerge-refine-highlight-change (buf beg match-num1 match-num2 props)
967 (with-current-buffer buf
968 (goto-char beg)
969 (let* ((startline (- (string-to-number match-num1) 1))
970 (beg (progn (funcall (if smerge-refine-weight-hack
971 'forward-char
972 smerge-refine-forward-function)
973 startline)
974 (point)))
975 (end (progn (funcall (if smerge-refine-weight-hack
976 'forward-char
977 smerge-refine-forward-function)
978 (if match-num2
979 (- (string-to-number match-num2)
980 startline)
982 (point))))
983 (when smerge-refine-ignore-whitespace
984 (skip-chars-backward " \t\n" beg) (setq end (point))
985 (goto-char beg)
986 (skip-chars-forward " \t\n" end) (setq beg (point)))
987 (when (> end beg)
988 (let ((ol (make-overlay
989 beg end nil
990 ;; Make them tend to shrink rather than spread when editing.
991 'front-advance nil)))
992 (overlay-put ol 'evaporate t)
993 (dolist (x props) (overlay-put ol (car x) (cdr x)))
994 ol)))))
996 (defun smerge-refine-subst (beg1 end1 beg2 end2 props-c &optional preproc props-r props-a)
997 "Show fine differences in the two regions BEG1..END1 and BEG2..END2.
998 PROPS-C is an alist of properties to put (via overlays) on the changes.
999 PROPS-R is an alist of properties to put on removed characters.
1000 PROPS-A is an alist of properties to put on added characters.
1001 If PROPS-R and PROPS-A are nil, put PROPS-C on all changes.
1002 If PROPS-C is nil, but PROPS-R and PROPS-A are non-nil,
1003 put PROPS-A on added characters, PROPS-R on removed characters.
1004 If PROPS-C, PROPS-R and PROPS-A are non-nil, put PROPS-C on changed characters,
1005 PROPS-A on added characters, and PROPS-R on removed characters.
1007 If non-nil, PREPROC is called with no argument in a buffer that contains
1008 a copy of a region, just before preparing it to for `diff'. It can be
1009 used to replace chars to try and eliminate some spurious differences."
1010 (let* ((buf (current-buffer))
1011 (pos (point))
1012 deactivate-mark ; The code does not modify any visible buffer.
1013 (file1 (make-temp-file "diff1"))
1014 (file2 (make-temp-file "diff2")))
1015 ;; Chop up regions into smaller elements and save into files.
1016 (smerge-refine-chopup-region beg1 end1 file1 preproc)
1017 (smerge-refine-chopup-region beg2 end2 file2 preproc)
1019 ;; Call diff on those files.
1020 (unwind-protect
1021 (with-temp-buffer
1022 (let ((coding-system-for-read 'emacs-mule))
1023 (call-process diff-command nil t nil
1024 (if (and smerge-refine-ignore-whitespace
1025 (not smerge-refine-weight-hack))
1026 ;; Pass -a so diff treats it as a text file even
1027 ;; if it contains \0 and such.
1028 ;; Pass -d so as to get the smallest change, but
1029 ;; also and more importantly because otherwise it
1030 ;; may happen that diff doesn't behave like
1031 ;; smerge-refine-weight-hack expects it to.
1032 ;; See http://thread.gmane.org/gmane.emacs.devel/82685.
1033 "-awd" "-ad")
1034 file1 file2))
1035 ;; Process diff's output.
1036 (goto-char (point-min))
1037 (let ((last1 nil)
1038 (last2 nil))
1039 (while (not (eobp))
1040 (if (not (looking-at "\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?\\([acd]\\)\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?$"))
1041 (error "Unexpected patch hunk header: %s"
1042 (buffer-substring (point) (line-end-position))))
1043 (let ((op (char-after (match-beginning 3)))
1044 (m1 (match-string 1))
1045 (m2 (match-string 2))
1046 (m4 (match-string 4))
1047 (m5 (match-string 5)))
1048 (when (memq op '(?d ?c))
1049 (setq last1
1050 (smerge-refine-highlight-change
1051 buf beg1 m1 m2
1052 ;; Try to use props-c only for changed chars,
1053 ;; fallback to props-r for changed/removed chars,
1054 ;; but if props-r is nil then fallback to props-c.
1055 (or (and (eq op '?c) props-c) props-r props-c))))
1056 (when (memq op '(?a ?c))
1057 (setq last2
1058 (smerge-refine-highlight-change
1059 buf beg2 m4 m5
1060 ;; Same logic as for removed chars above.
1061 (or (and (eq op '?c) props-c) props-a props-c)))))
1062 (forward-line 1) ;Skip hunk header.
1063 (and (re-search-forward "^[0-9]" nil 'move) ;Skip hunk body.
1064 (goto-char (match-beginning 0))))
1065 ;; (cl-assert (or (null last1) (< (overlay-start last1) end1)))
1066 ;; (cl-assert (or (null last2) (< (overlay-start last2) end2)))
1067 (if smerge-refine-weight-hack
1068 (progn
1069 ;; (cl-assert (or (null last1) (<= (overlay-end last1) end1)))
1070 ;; (cl-assert (or (null last2) (<= (overlay-end last2) end2)))
1072 ;; smerge-refine-forward-function when calling in chopup may
1073 ;; have stopped because it bumped into EOB whereas in
1074 ;; smerge-refine-weight-hack it may go a bit further.
1075 (if (and last1 (> (overlay-end last1) end1))
1076 (move-overlay last1 (overlay-start last1) end1))
1077 (if (and last2 (> (overlay-end last2) end2))
1078 (move-overlay last2 (overlay-start last2) end2))
1080 (goto-char pos)
1081 (delete-file file1)
1082 (delete-file file2))))
1084 (defun smerge-refine (&optional part)
1085 "Highlight the words of the conflict that are different.
1086 For 3-way conflicts, highlights only two of the three parts.
1087 A numeric argument PART can be used to specify which two parts;
1088 repeating the command will highlight other two parts."
1089 (interactive
1090 (if (integerp current-prefix-arg) (list current-prefix-arg)
1091 (smerge-match-conflict)
1092 (let* ((prop (get-text-property (match-beginning 0) 'smerge-refine-part))
1093 (part (if (and (consp prop)
1094 (eq (buffer-chars-modified-tick) (car prop)))
1095 (cdr prop))))
1096 ;; If already highlighted, cycle.
1097 (list (if (integerp part) (1+ (mod part 3)))))))
1099 (if (and (integerp part) (or (< part 1) (> part 3)))
1100 (error "No conflict part nb %s" part))
1101 (smerge-match-conflict)
1102 (remove-overlays (match-beginning 0) (match-end 0) 'smerge 'refine)
1103 ;; Ignore `part' if not applicable, and default it if not provided.
1104 (setq part (cond ((null (match-end 2)) 2)
1105 ((eq (match-end 1) (match-end 3)) 1)
1106 ((integerp part) part)
1107 ;; If one of the parts is empty, any refinement using
1108 ;; it will be trivial and uninteresting.
1109 ((eq (match-end 1) (match-beginning 1)) 1)
1110 ((eq (match-end 3) (match-beginning 3)) 3)
1111 (t 2)))
1112 (let ((n1 (if (eq part 1) 2 1))
1113 (n2 (if (eq part 3) 2 3))
1114 (smerge-use-changed-face
1115 (and (face-differs-from-default-p 'smerge-refined-change)
1116 (not (face-equal 'smerge-refined-change 'smerge-refined-added))
1117 (not (face-equal 'smerge-refined-change 'smerge-refined-removed)))))
1118 (smerge-ensure-match n1)
1119 (smerge-ensure-match n2)
1120 (with-silent-modifications
1121 (put-text-property (match-beginning 0) (1+ (match-beginning 0))
1122 'smerge-refine-part
1123 (cons (buffer-chars-modified-tick) part)))
1124 (smerge-refine-subst (match-beginning n1) (match-end n1)
1125 (match-beginning n2) (match-end n2)
1126 (if smerge-use-changed-face
1127 '((smerge . refine) (face . smerge-refined-change)))
1129 (unless smerge-use-changed-face
1130 '((smerge . refine) (face . smerge-refined-removed)))
1131 (unless smerge-use-changed-face
1132 '((smerge . refine) (face . smerge-refined-added))))))
1134 (defun smerge-diff (n1 n2)
1135 (smerge-match-conflict)
1136 (smerge-ensure-match n1)
1137 (smerge-ensure-match n2)
1138 (let ((name1 (aref smerge-match-names n1))
1139 (name2 (aref smerge-match-names n2))
1140 ;; Read them before the match-data gets clobbered.
1141 (beg1 (match-beginning n1))
1142 (end1 (match-end n1))
1143 (beg2 (match-beginning n2))
1144 (end2 (match-end n2))
1145 (file1 (make-temp-file "smerge1"))
1146 (file2 (make-temp-file "smerge2"))
1147 (dir default-directory)
1148 (file (if buffer-file-name (file-relative-name buffer-file-name)))
1149 ;; We would want to use `emacs-mule-unix' for read&write, but we
1150 ;; bump into problems with the coding-system used by diff to write
1151 ;; the file names and the time stamps in the header.
1152 ;; `buffer-file-coding-system' is not always correct either, but if
1153 ;; the OS/user uses only one coding-system, then it works.
1154 (coding-system-for-read buffer-file-coding-system))
1155 (write-region beg1 end1 file1 nil 'nomessage)
1156 (write-region beg2 end2 file2 nil 'nomessage)
1157 (unwind-protect
1158 (with-current-buffer (get-buffer-create smerge-diff-buffer-name)
1159 (setq default-directory dir)
1160 (let ((inhibit-read-only t))
1161 (erase-buffer)
1162 (let ((status
1163 (apply 'call-process diff-command nil t nil
1164 (append smerge-diff-switches
1165 (list "-L" (concat name1 "/" file)
1166 "-L" (concat name2 "/" file)
1167 file1 file2)))))
1168 (if (eq status 0) (insert "No differences found.\n"))))
1169 (goto-char (point-min))
1170 (diff-mode)
1171 (display-buffer (current-buffer) t))
1172 (delete-file file1)
1173 (delete-file file2))))
1175 ;; compiler pacifiers
1176 (defvar smerge-ediff-windows)
1177 (defvar smerge-ediff-buf)
1178 (defvar ediff-buffer-A)
1179 (defvar ediff-buffer-B)
1180 (defvar ediff-buffer-C)
1181 (defvar ediff-ancestor-buffer)
1182 (defvar ediff-quit-hook)
1183 (declare-function ediff-cleanup-mess "ediff-util" nil)
1185 (defun smerge--get-marker (regexp default)
1186 (save-excursion
1187 (goto-char (point-min))
1188 (if (and (search-forward-regexp regexp nil t)
1189 (> (match-end 1) (match-beginning 1)))
1190 (concat default "=" (match-string-no-properties 1))
1191 default)))
1193 ;;;###autoload
1194 (defun smerge-ediff (&optional name-mine name-other name-base)
1195 "Invoke ediff to resolve the conflicts.
1196 NAME-MINE, NAME-OTHER, and NAME-BASE, if non-nil, are used for the
1197 buffer names."
1198 (interactive)
1199 (let* ((buf (current-buffer))
1200 (mode major-mode)
1201 ;;(ediff-default-variant 'default-B)
1202 (config (current-window-configuration))
1203 (filename (file-name-nondirectory (or buffer-file-name "-")))
1204 (mine (generate-new-buffer
1205 (or name-mine
1206 (concat "*" filename " "
1207 (smerge--get-marker smerge-begin-re "MINE")
1208 "*"))))
1209 (other (generate-new-buffer
1210 (or name-other
1211 (concat "*" filename " "
1212 (smerge--get-marker smerge-end-re "OTHER")
1213 "*"))))
1214 base)
1215 (with-current-buffer mine
1216 (buffer-disable-undo)
1217 (insert-buffer-substring buf)
1218 (goto-char (point-min))
1219 (while (smerge-find-conflict)
1220 (when (match-beginning 2) (setq base t))
1221 (smerge-keep-n 1))
1222 (buffer-enable-undo)
1223 (set-buffer-modified-p nil)
1224 (funcall mode))
1226 (with-current-buffer other
1227 (buffer-disable-undo)
1228 (insert-buffer-substring buf)
1229 (goto-char (point-min))
1230 (while (smerge-find-conflict)
1231 (smerge-keep-n 3))
1232 (buffer-enable-undo)
1233 (set-buffer-modified-p nil)
1234 (funcall mode))
1236 (when base
1237 (setq base (generate-new-buffer
1238 (or name-base
1239 (concat "*" filename " "
1240 (smerge--get-marker smerge-base-re "BASE")
1241 "*"))))
1242 (with-current-buffer base
1243 (buffer-disable-undo)
1244 (insert-buffer-substring buf)
1245 (goto-char (point-min))
1246 (while (smerge-find-conflict)
1247 (if (match-end 2)
1248 (smerge-keep-n 2)
1249 (delete-region (match-beginning 0) (match-end 0))))
1250 (buffer-enable-undo)
1251 (set-buffer-modified-p nil)
1252 (funcall mode)))
1254 ;; the rest of the code is inspired from vc.el
1255 ;; Fire up ediff.
1256 (set-buffer
1257 (if base
1258 (ediff-merge-buffers-with-ancestor mine other base)
1259 ;; nil 'ediff-merge-revisions-with-ancestor buffer-file-name)
1260 (ediff-merge-buffers mine other)))
1261 ;; nil 'ediff-merge-revisions buffer-file-name)))
1263 ;; Ediff is now set up, and we are in the control buffer.
1264 ;; Do a few further adjustments and take precautions for exit.
1265 (set (make-local-variable 'smerge-ediff-windows) config)
1266 (set (make-local-variable 'smerge-ediff-buf) buf)
1267 (set (make-local-variable 'ediff-quit-hook)
1268 (lambda ()
1269 (let ((buffer-A ediff-buffer-A)
1270 (buffer-B ediff-buffer-B)
1271 (buffer-C ediff-buffer-C)
1272 (buffer-Ancestor ediff-ancestor-buffer)
1273 (buf smerge-ediff-buf)
1274 (windows smerge-ediff-windows))
1275 (ediff-cleanup-mess)
1276 (with-current-buffer buf
1277 (erase-buffer)
1278 (insert-buffer-substring buffer-C)
1279 (kill-buffer buffer-A)
1280 (kill-buffer buffer-B)
1281 (kill-buffer buffer-C)
1282 (when (bufferp buffer-Ancestor) (kill-buffer buffer-Ancestor))
1283 (set-window-configuration windows)
1284 (message "Conflict resolution finished; you may save the buffer")))))
1285 (message "Please resolve conflicts now; exit ediff when done")))
1287 (defun smerge-makeup-conflict (pt1 pt2 pt3 &optional pt4)
1288 "Insert diff3 markers to make a new conflict.
1289 Uses point and mark for two of the relevant positions and previous marks
1290 for the other ones.
1291 By default, makes up a 2-way conflict,
1292 with a \\[universal-argument] prefix, makes up a 3-way conflict."
1293 (interactive
1294 (list (point)
1295 (mark)
1296 (progn (pop-mark) (mark))
1297 (when current-prefix-arg (pop-mark) (mark))))
1298 ;; Start from the end so as to avoid problems with pos-changes.
1299 (pcase-let ((`(,pt1 ,pt2 ,pt3 ,pt4)
1300 (sort `(,pt1 ,pt2 ,pt3 ,@(if pt4 (list pt4))) '>=)))
1301 (goto-char pt1) (beginning-of-line)
1302 (insert ">>>>>>> OTHER\n")
1303 (goto-char pt2) (beginning-of-line)
1304 (insert "=======\n")
1305 (goto-char pt3) (beginning-of-line)
1306 (when pt4
1307 (insert "||||||| BASE\n")
1308 (goto-char pt4) (beginning-of-line))
1309 (insert "<<<<<<< MINE\n"))
1310 (if smerge-mode nil (smerge-mode 1))
1311 (smerge-refine))
1314 (defconst smerge-parsep-re
1315 (concat smerge-begin-re "\\|" smerge-end-re "\\|"
1316 smerge-base-re "\\|" smerge-other-re "\\|"))
1318 ;;;###autoload
1319 (define-minor-mode smerge-mode
1320 "Minor mode to simplify editing output from the diff3 program.
1321 With a prefix argument ARG, enable the mode if ARG is positive,
1322 and disable it otherwise. If called from Lisp, enable the mode
1323 if ARG is omitted or nil.
1324 \\{smerge-mode-map}"
1325 :group 'smerge :lighter " SMerge"
1326 (when (and (boundp 'font-lock-mode) font-lock-mode)
1327 (save-excursion
1328 (if smerge-mode
1329 (font-lock-add-keywords nil smerge-font-lock-keywords 'append)
1330 (font-lock-remove-keywords nil smerge-font-lock-keywords))
1331 (goto-char (point-min))
1332 (while (smerge-find-conflict)
1333 (save-excursion
1334 (font-lock-fontify-region (match-beginning 0) (match-end 0) nil)))))
1335 (if (string-match (regexp-quote smerge-parsep-re) paragraph-separate)
1336 (unless smerge-mode
1337 (set (make-local-variable 'paragraph-separate)
1338 (replace-match "" t t paragraph-separate)))
1339 (when smerge-mode
1340 (set (make-local-variable 'paragraph-separate)
1341 (concat smerge-parsep-re paragraph-separate))))
1342 (unless smerge-mode
1343 (smerge-remove-props (point-min) (point-max))))
1345 ;;;###autoload
1346 (defun smerge-start-session ()
1347 "Turn on `smerge-mode' and move point to first conflict marker.
1348 If no conflict maker is found, turn off `smerge-mode'."
1349 (interactive)
1350 (smerge-mode 1)
1351 (condition-case nil
1352 (unless (looking-at smerge-begin-re)
1353 (smerge-next))
1354 (error (smerge-auto-leave))))
1356 (provide 'smerge-mode)
1358 ;;; smerge-mode.el ends here