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