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