(format-seconds): Remove `nonzero' argument in favor of `%z' specifier.
[emacs.git] / lisp / smerge-mode.el
blob8a3f15bac44efdbb3c797751e85a907957efa458
1 ;;; smerge-mode.el --- Minor mode to resolve diff3 conflicts
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; Keywords: tools revision-control merge diff3 cvs conflict
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 3, or (at your option)
14 ;; any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
26 ;;; Commentary:
28 ;; Provides a lightweight alternative to emerge/ediff.
29 ;; To use it, simply add to your .emacs the following lines:
31 ;; (autoload 'smerge-mode "smerge-mode" nil t)
33 ;; you can even have it turned on automatically with the following
34 ;; piece of code in your .emacs:
36 ;; (defun sm-try-smerge ()
37 ;; (save-excursion
38 ;; (goto-char (point-min))
39 ;; (when (re-search-forward "^<<<<<<< " nil t)
40 ;; (smerge-mode 1))))
41 ;; (add-hook 'find-file-hook 'sm-try-smerge t)
43 ;;; Todo:
45 ;; - if requested, ask the user whether he wants to call ediff right away
47 ;;; Code:
49 (eval-when-compile (require 'cl))
52 ;;; The real definition comes later.
53 (defvar smerge-mode)
55 (defgroup smerge ()
56 "Minor mode to highlight and resolve diff3 conflicts."
57 :group 'tools
58 :prefix "smerge-")
60 (defcustom smerge-diff-buffer-name "*vc-diff*"
61 "Buffer name to use for displaying diffs."
62 :group 'smerge
63 :type '(choice
64 (const "*vc-diff*")
65 (const "*cvs-diff*")
66 (const "*smerge-diff*")
67 string))
69 (defcustom smerge-diff-switches
70 (append '("-d" "-b")
71 (if (listp diff-switches) diff-switches (list diff-switches)))
72 "A list of strings specifying switches to be passed to diff.
73 Used in `smerge-diff-base-mine' and related functions."
74 :group 'smerge
75 :type '(repeat string))
77 (defcustom smerge-auto-leave t
78 "Non-nil means to leave `smerge-mode' when the last conflict is resolved."
79 :group 'smerge
80 :type 'boolean)
82 (defcustom smerge-auto-refine t
83 "Automatically highlight changes in detail as the user visits conflicts."
84 :group 'smerge
85 :type 'boolean)
87 (defface smerge-mine
88 '((((min-colors 88) (background light))
89 (:foreground "blue1"))
90 (((background light))
91 (:foreground "blue"))
92 (((min-colors 88) (background dark))
93 (:foreground "cyan1"))
94 (((background dark))
95 (:foreground "cyan")))
96 "Face for your code."
97 :group 'smerge)
98 ;; backward-compatibility alias
99 (put 'smerge-mine-face 'face-alias 'smerge-mine)
100 (defvar smerge-mine-face 'smerge-mine)
102 (defface smerge-other
103 '((((background light))
104 (:foreground "darkgreen"))
105 (((background dark))
106 (:foreground "lightgreen")))
107 "Face for the other code."
108 :group 'smerge)
109 ;; backward-compatibility alias
110 (put 'smerge-other-face 'face-alias 'smerge-other)
111 (defvar smerge-other-face 'smerge-other)
113 (defface smerge-base
114 '((((min-colors 88) (background light))
115 (:foreground "red1"))
116 (((background light))
117 (:foreground "red"))
118 (((background dark))
119 (:foreground "orange")))
120 "Face for the base code."
121 :group 'smerge)
122 ;; backward-compatibility alias
123 (put 'smerge-base-face 'face-alias 'smerge-base)
124 (defvar smerge-base-face 'smerge-base)
126 (defface smerge-markers
127 '((((background light))
128 (:background "grey85"))
129 (((background dark))
130 (:background "grey30")))
131 "Face for the conflict markers."
132 :group 'smerge)
133 ;; backward-compatibility alias
134 (put 'smerge-markers-face 'face-alias 'smerge-markers)
135 (defvar smerge-markers-face 'smerge-markers)
137 (defface smerge-refined-change
138 '((t :background "yellow"))
139 "Face used for char-based changes shown by `smerge-refine'."
140 :group 'smerge)
142 (easy-mmode-defmap smerge-basic-map
143 `(("n" . smerge-next)
144 ("p" . smerge-prev)
145 ("r" . smerge-resolve)
146 ("a" . smerge-keep-all)
147 ("b" . smerge-keep-base)
148 ("o" . smerge-keep-other)
149 ("m" . smerge-keep-mine)
150 ("E" . smerge-ediff)
151 ("C" . smerge-combine-with-next)
152 ("R" . smerge-refine)
153 ("\C-m" . smerge-keep-current)
154 ("=" . ,(make-sparse-keymap "Diff"))
155 ("=<" "base-mine" . smerge-diff-base-mine)
156 ("=>" "base-other" . smerge-diff-base-other)
157 ("==" "mine-other" . smerge-diff-mine-other))
158 "The base keymap for `smerge-mode'.")
160 (defcustom smerge-command-prefix "\C-c^"
161 "Prefix for `smerge-mode' commands."
162 :group 'smerge
163 :type '(choice (string "\e") (string "\C-c^") (string "") string))
165 (easy-mmode-defmap smerge-mode-map
166 `((,smerge-command-prefix . ,smerge-basic-map))
167 "Keymap for `smerge-mode'.")
169 (defvar smerge-check-cache nil)
170 (make-variable-buffer-local 'smerge-check-cache)
171 (defun smerge-check (n)
172 (condition-case nil
173 (let ((state (cons (point) (buffer-modified-tick))))
174 (unless (equal (cdr smerge-check-cache) state)
175 (smerge-match-conflict)
176 (setq smerge-check-cache (cons (match-data) state)))
177 (nth (* 2 n) (car smerge-check-cache)))
178 (error nil)))
180 (easy-menu-define smerge-mode-menu smerge-mode-map
181 "Menu for `smerge-mode'."
182 '("SMerge"
183 ["Next" smerge-next :help "Go to next conflict"]
184 ["Previous" smerge-prev :help "Go to previous conflict"]
185 "--"
186 ["Keep All" smerge-keep-all :help "Keep all three versions"
187 :active (smerge-check 1)]
188 ["Keep Current" smerge-keep-current :help "Use current (at point) version"
189 :active (and (smerge-check 1) (> (smerge-get-current) 0))]
190 "--"
191 ["Revert to Base" smerge-keep-base :help "Revert to base version"
192 :active (smerge-check 2)]
193 ["Keep Other" smerge-keep-other :help "Keep `other' version"
194 :active (smerge-check 3)]
195 ["Keep Yours" smerge-keep-mine :help "Keep your version"
196 :active (smerge-check 1)]
197 "--"
198 ["Diff Base/Mine" smerge-diff-base-mine
199 :help "Diff `base' and `mine' for current conflict"
200 :active (smerge-check 2)]
201 ["Diff Base/Other" smerge-diff-base-other
202 :help "Diff `base' and `other' for current conflict"
203 :active (smerge-check 2)]
204 ["Diff Mine/Other" smerge-diff-mine-other
205 :help "Diff `mine' and `other' for current conflict"
206 :active (smerge-check 1)]
207 "--"
208 ["Invoke Ediff" smerge-ediff
209 :help "Use Ediff to resolve the conflicts"
210 :active (smerge-check 1)]
211 ["Auto Resolve" smerge-resolve
212 :help "Try auto-resolution heuristics"
213 :active (smerge-check 1)]
214 ["Combine" smerge-combine-with-next
215 :help "Combine current conflict with next"
216 :active (smerge-check 1)]
219 (easy-menu-define smerge-context-menu nil
220 "Context menu for mine area in `smerge-mode'."
221 '(nil
222 ["Keep Current" smerge-keep-current :help "Use current (at point) version"]
223 ["Kill Current" smerge-kill-current :help "Remove current (at point) version"]
224 ["Keep All" smerge-keep-all :help "Keep all three versions"]
225 "---"
226 ["More..." (popup-menu smerge-mode-menu) :help "Show full SMerge mode menu"]
229 (defconst smerge-font-lock-keywords
230 '((smerge-find-conflict
231 (1 smerge-mine-face prepend t)
232 (2 smerge-base-face prepend t)
233 (3 smerge-other-face prepend t)
234 ;; FIXME: `keep' doesn't work right with syntactic fontification.
235 (0 smerge-markers-face keep)
236 (4 nil t t)
237 (5 nil t t)))
238 "Font lock patterns for `smerge-mode'.")
240 (defconst smerge-begin-re "^<<<<<<< \\(.*\\)\n")
241 (defconst smerge-end-re "^>>>>>>> .*\n")
242 (defconst smerge-base-re "^||||||| .*\n")
243 (defconst smerge-other-re "^=======\n")
245 (defvar smerge-conflict-style nil
246 "Keep track of which style of conflict is in use.
247 Can be nil if the style is undecided, or else:
248 - `diff3-E'
249 - `diff3-A'")
251 ;; Compiler pacifiers
252 (defvar font-lock-mode)
253 (defvar font-lock-keywords)
255 ;;;;
256 ;;;; Actual code
257 ;;;;
259 ;; Define smerge-next and smerge-prev
260 (easy-mmode-define-navigation smerge smerge-begin-re "conflict" nil nil
261 (if smerge-auto-refine
262 (condition-case nil (smerge-refine) (error nil))))
264 (defconst smerge-match-names ["conflict" "mine" "base" "other"])
266 (defun smerge-ensure-match (n)
267 (unless (match-end n)
268 (error "No `%s'" (aref smerge-match-names n))))
270 (defun smerge-auto-leave ()
271 (when (and smerge-auto-leave
272 (save-excursion (goto-char (point-min))
273 (not (re-search-forward smerge-begin-re nil t))))
274 (when (and (listp buffer-undo-list) smerge-mode)
275 (push (list 'apply 'smerge-mode 1) buffer-undo-list))
276 (smerge-mode -1)))
279 (defun smerge-keep-all ()
280 "Concatenate all versions."
281 (interactive)
282 (smerge-match-conflict)
283 (let ((mb2 (or (match-beginning 2) (point-max)))
284 (me2 (or (match-end 2) (point-min))))
285 (delete-region (match-end 3) (match-end 0))
286 (delete-region (max me2 (match-end 1)) (match-beginning 3))
287 (if (and (match-end 2) (/= (match-end 1) (match-end 3)))
288 (delete-region (match-end 1) (match-beginning 2)))
289 (delete-region (match-beginning 0) (min (match-beginning 1) mb2))
290 (smerge-auto-leave)))
292 (defun smerge-keep-n (n)
293 (smerge-remove-props (match-beginning 0) (match-end 0))
294 ;; We used to use replace-match, but that did not preserve markers so well.
295 (delete-region (match-end n) (match-end 0))
296 (delete-region (match-beginning 0) (match-beginning n)))
298 (defun smerge-combine-with-next ()
299 "Combine the current conflict with the next one."
300 ;; `smerge-auto-combine' relies on the finish position (at the beginning
301 ;; of the closing marker).
302 (interactive)
303 (smerge-match-conflict)
304 (let ((ends nil))
305 (dolist (i '(3 2 1 0))
306 (push (if (match-end i) (copy-marker (match-end i) t)) ends))
307 (setq ends (apply 'vector ends))
308 (goto-char (aref ends 0))
309 (if (not (re-search-forward smerge-begin-re nil t))
310 (error "No next conflict")
311 (smerge-match-conflict)
312 (let ((match-data (mapcar (lambda (m) (if m (copy-marker m)))
313 (match-data))))
314 ;; First copy the in-between text in each alternative.
315 (dolist (i '(1 2 3))
316 (when (aref ends i)
317 (goto-char (aref ends i))
318 (insert-buffer-substring (current-buffer)
319 (aref ends 0) (car match-data))))
320 (delete-region (aref ends 0) (car match-data))
321 ;; Then move the second conflict's alternatives into the first.
322 (dolist (i '(1 2 3))
323 (set-match-data match-data)
324 (when (and (aref ends i) (match-end i))
325 (goto-char (aref ends i))
326 (insert-buffer-substring (current-buffer)
327 (match-beginning i) (match-end i))))
328 (delete-region (car match-data) (cadr match-data))
329 ;; Free the markers.
330 (dolist (m match-data) (if m (move-marker m nil)))
331 (mapc (lambda (m) (if m (move-marker m nil))) ends)))))
333 (defvar smerge-auto-combine-max-separation 2
334 "Max number of lines between conflicts that should be combined.")
336 (defun smerge-auto-combine ()
337 "Automatically combine conflicts that are near each other."
338 (interactive)
339 (save-excursion
340 (goto-char (point-min))
341 (while (smerge-find-conflict)
342 ;; 2 is 1 (default) + 1 (the begin markers).
343 (while (save-excursion
344 (smerge-find-conflict
345 (line-beginning-position
346 (+ 2 smerge-auto-combine-max-separation))))
347 (forward-line -1) ;Go back inside the conflict.
348 (smerge-combine-with-next)
349 (forward-line 1) ;Move past the end of the conflict.
350 ))))
352 (defvar smerge-resolve-function
353 (lambda () (error "Don't know how to resolve"))
354 "Mode-specific merge function.
355 The function is called with zero or one argument (non-nil if the resolution
356 function should only apply safe heuristics) and with the match data set
357 according to `smerge-match-conflict'.")
358 (add-to-list 'debug-ignored-errors "Don't know how to resolve")
360 (defvar smerge-text-properties
361 `(help-echo "merge conflict: mouse-3 shows a menu"
362 ;; mouse-face highlight
363 keymap (keymap (down-mouse-3 . smerge-popup-context-menu))))
365 (defun smerge-remove-props (beg end)
366 (remove-overlays beg end 'smerge 'refine)
367 (remove-overlays beg end 'smerge 'conflict)
368 ;; Now that we use overlays rather than text-properties, this function
369 ;; does not cause refontification any more. It can be seen very clearly
370 ;; in buffers where jit-lock-contextually is not t, in which case deleting
371 ;; the "<<<<<<< foobar" leading line leaves the rest of the conflict
372 ;; highlighted as if it were still a valid conflict. Note that in many
373 ;; important cases (such as the previous example) we're actually called
374 ;; during font-locking so inhibit-modification-hooks is non-nil, so we
375 ;; can't just modify the buffer and expect font-lock to be triggered as in:
376 ;; (put-text-property beg end 'smerge-force-highlighting nil)
377 (let ((modified (buffer-modified-p)))
378 (remove-text-properties beg end '(fontified nil))
379 (restore-buffer-modified-p modified)))
381 (defun smerge-popup-context-menu (event)
382 "Pop up the Smerge mode context menu under mouse."
383 (interactive "e")
384 (if (and smerge-mode
385 (save-excursion (posn-set-point (event-end event)) (smerge-check 1)))
386 (progn
387 (posn-set-point (event-end event))
388 (smerge-match-conflict)
389 (let ((i (smerge-get-current))
391 (if (<= i 0)
392 ;; Out of range
393 (popup-menu smerge-mode-menu)
394 ;; Install overlay.
395 (setq o (make-overlay (match-beginning i) (match-end i)))
396 (unwind-protect
397 (progn
398 (overlay-put o 'face 'highlight)
399 (sit-for 0) ;Display the new highlighting.
400 (popup-menu smerge-context-menu))
401 ;; Delete overlay.
402 (delete-overlay o)))))
403 ;; There's no conflict at point, the text-props are just obsolete.
404 (save-excursion
405 (let ((beg (re-search-backward smerge-end-re nil t))
406 (end (re-search-forward smerge-begin-re nil t)))
407 (smerge-remove-props (or beg (point-min)) (or end (point-max)))
408 (push event unread-command-events)))))
410 (defun smerge-resolve (&optional safe)
411 "Resolve the conflict at point intelligently.
412 This relies on mode-specific knowledge and thus only works in
413 some major modes. Uses `smerge-resolve-function' to do the actual work."
414 (interactive)
415 (smerge-match-conflict)
416 (smerge-remove-props (match-beginning 0) (match-end 0))
417 (cond
418 ;; Trivial diff3 -A non-conflicts.
419 ((and (eq (match-end 1) (match-end 3))
420 (eq (match-beginning 1) (match-beginning 3)))
421 (smerge-keep-n 3))
422 ;; Mode-specific conflict resolution.
423 ((condition-case nil
424 (atomic-change-group
425 (if safe
426 (funcall smerge-resolve-function safe)
427 (funcall smerge-resolve-function))
429 (error nil))
430 ;; Nothing to do: the resolution function has done it already.
431 nil)
432 ;; FIXME: Add "if [ diff -b MINE OTHER ]; then select OTHER; fi"
433 ((and (match-end 2)
434 ;; FIXME: Add "diff -b BASE MINE | patch OTHER".
435 ;; FIXME: Add "diff -b BASE OTHER | patch MINE".
436 nil)
438 ((and (not (match-end 2))
439 ;; FIXME: Add "diff -b"-based refinement.
440 nil)
443 (error "Don't know how to resolve")))
444 (smerge-auto-leave))
446 (defun smerge-resolve-all ()
447 "Perform automatic resolution on all conflicts."
448 (interactive)
449 (save-excursion
450 (goto-char (point-min))
451 (while (re-search-forward smerge-begin-re nil t)
452 (condition-case nil
453 (progn
454 (smerge-match-conflict)
455 (smerge-resolve 'safe))
456 (error nil)))))
458 (defun smerge-batch-resolve ()
459 ;; command-line-args-left is what is left of the command line.
460 (if (not noninteractive)
461 (error "`smerge-batch-resolve' is to be used only with -batch"))
462 (while command-line-args-left
463 (let ((file (pop command-line-args-left)))
464 (if (string-match "\\.rej\\'" file)
465 ;; .rej files should never contain diff3 markers, on the other hand,
466 ;; in Arch, .rej files are sometimes used to indicate that the
467 ;; main file has diff3 markers. So you can pass **/*.rej and
468 ;; it will DTRT.
469 (setq file (substring file 0 (match-beginning 0))))
470 (message "Resolving conflicts in %s..." file)
471 (when (file-readable-p file)
472 (with-current-buffer (find-file-noselect file)
473 (smerge-resolve-all)
474 (save-buffer)
475 (kill-buffer (current-buffer)))))))
477 (defun smerge-keep-base ()
478 "Revert to the base version."
479 (interactive)
480 (smerge-match-conflict)
481 (smerge-ensure-match 2)
482 (smerge-keep-n 2)
483 (smerge-auto-leave))
485 (defun smerge-keep-other ()
486 "Use \"other\" version."
487 (interactive)
488 (smerge-match-conflict)
489 ;;(smerge-ensure-match 3)
490 (smerge-keep-n 3)
491 (smerge-auto-leave))
493 (defun smerge-keep-mine ()
494 "Keep your version."
495 (interactive)
496 (smerge-match-conflict)
497 ;;(smerge-ensure-match 1)
498 (smerge-keep-n 1)
499 (smerge-auto-leave))
501 (defun smerge-get-current ()
502 (let ((i 3))
503 (while (or (not (match-end i))
504 (< (point) (match-beginning i))
505 (>= (point) (match-end i)))
506 (decf i))
509 (defun smerge-keep-current ()
510 "Use the current (under the cursor) version."
511 (interactive)
512 (smerge-match-conflict)
513 (let ((i (smerge-get-current)))
514 (if (<= i 0) (error "Not inside a version")
515 (smerge-keep-n i)
516 (smerge-auto-leave))))
518 (defun smerge-kill-current ()
519 "Remove the current (under the cursor) version."
520 (interactive)
521 (smerge-match-conflict)
522 (let ((i (smerge-get-current)))
523 (if (<= i 0) (error "Not inside a version")
524 (let ((left nil))
525 (dolist (n '(3 2 1))
526 (if (and (match-end n) (/= (match-end n) (match-end i)))
527 (push n left)))
528 (if (and (cdr left)
529 (/= (match-end (car left)) (match-end (cadr left))))
530 (ding) ;We don't know how to do that.
531 (smerge-keep-n (car left))
532 (smerge-auto-leave))))))
534 (defun smerge-diff-base-mine ()
535 "Diff 'base' and 'mine' version in current conflict region."
536 (interactive)
537 (smerge-diff 2 1))
539 (defun smerge-diff-base-other ()
540 "Diff 'base' and 'other' version in current conflict region."
541 (interactive)
542 (smerge-diff 2 3))
544 (defun smerge-diff-mine-other ()
545 "Diff 'mine' and 'other' version in current conflict region."
546 (interactive)
547 (smerge-diff 1 3))
549 (defun smerge-match-conflict ()
550 "Get info about the conflict. Puts the info in the `match-data'.
551 The submatches contain:
552 0: the whole conflict.
553 1: your code.
554 2: the base code.
555 3: other code.
556 An error is raised if not inside a conflict."
557 (save-excursion
558 (condition-case nil
559 (let* ((orig-point (point))
561 (_ (forward-line 1))
562 (_ (re-search-backward smerge-begin-re))
564 (start (match-beginning 0))
565 (mine-start (match-end 0))
566 (filename (or (match-string 1) ""))
568 (_ (re-search-forward smerge-end-re))
569 (_ (assert (< orig-point (match-end 0))))
571 (other-end (match-beginning 0))
572 (end (match-end 0))
574 (_ (re-search-backward smerge-other-re start))
576 (mine-end (match-beginning 0))
577 (other-start (match-end 0))
579 base-start base-end)
581 ;; handle the various conflict styles
582 (cond
583 ((save-excursion
584 (goto-char mine-start)
585 (re-search-forward smerge-begin-re end t))
586 ;; There's a nested conflict and we're after the the beginning
587 ;; of the outer one but before the beginning of the inner one.
588 ;; Of course, maybe this is not a nested conflict but in that
589 ;; case it can only be something nastier that we don't know how
590 ;; to handle, so may as well arbitrarily decide to treat it as
591 ;; a nested conflict. --Stef
592 (error "There is a nested conflict"))
594 ((re-search-backward smerge-base-re start t)
595 ;; a 3-parts conflict
596 (set (make-local-variable 'smerge-conflict-style) 'diff3-A)
597 (setq base-end mine-end)
598 (setq mine-end (match-beginning 0))
599 (setq base-start (match-end 0)))
601 ((string= filename (file-name-nondirectory
602 (or buffer-file-name "")))
603 ;; a 2-parts conflict
604 (set (make-local-variable 'smerge-conflict-style) 'diff3-E))
606 ((and (not base-start)
607 (or (eq smerge-conflict-style 'diff3-A)
608 (equal filename "ANCESTOR")
609 (string-match "\\`[.0-9]+\\'" filename)))
610 ;; a same-diff conflict
611 (setq base-start mine-start)
612 (setq base-end mine-end)
613 (setq mine-start other-start)
614 (setq mine-end other-end)))
616 (store-match-data (list start end
617 mine-start mine-end
618 base-start base-end
619 other-start other-end
620 (when base-start (1- base-start)) base-start
621 (1- other-start) other-start))
623 (search-failed (error "Point not in conflict region")))))
625 (add-to-list 'debug-ignored-errors "Point not in conflict region")
627 (defun smerge-conflict-overlay (pos)
628 "Return the conflict overlay at POS if any."
629 (let ((ols (overlays-at pos))
630 conflict)
631 (dolist (ol ols)
632 (if (and (eq (overlay-get ol 'smerge) 'conflict)
633 (> (overlay-end ol) pos))
634 (setq conflict ol)))
635 conflict))
637 (defun smerge-find-conflict (&optional limit)
638 "Find and match a conflict region. Intended as a font-lock MATCHER.
639 The submatches are the same as in `smerge-match-conflict'.
640 Returns non-nil if a match is found between point and LIMIT.
641 Point is moved to the end of the conflict."
642 (let ((found nil)
643 (pos (point))
644 conflict)
645 ;; First check to see if point is already inside a conflict, using
646 ;; the conflict overlays.
647 (while (and (not found) (setq conflict (smerge-conflict-overlay pos)))
648 ;; Check the overlay's validity and kill it if it's out of date.
649 (condition-case nil
650 (progn
651 (goto-char (overlay-start conflict))
652 (smerge-match-conflict)
653 (goto-char (match-end 0))
654 (if (<= (point) pos)
655 (error "Matching backward!")
656 (setq found t)))
657 (error (smerge-remove-props
658 (overlay-start conflict) (overlay-end conflict))
659 (goto-char pos))))
660 ;; If we're not already inside a conflict, look for the next conflict
661 ;; and add/update its overlay.
662 (while (and (not found) (re-search-forward smerge-begin-re limit t))
663 (condition-case nil
664 (progn
665 (smerge-match-conflict)
666 (goto-char (match-end 0))
667 (let ((conflict (smerge-conflict-overlay (1- (point)))))
668 (if conflict
669 ;; Update its location, just in case it got messed up.
670 (move-overlay conflict (match-beginning 0) (match-end 0))
671 (setq conflict (make-overlay (match-beginning 0) (match-end 0)
672 nil 'front-advance nil))
673 (overlay-put conflict 'evaporate t)
674 (overlay-put conflict 'smerge 'conflict)
675 (let ((props smerge-text-properties))
676 (while props
677 (overlay-put conflict (pop props) (pop props))))))
678 (setq found t))
679 (error nil)))
680 found))
682 ;;; Refined change highlighting
684 (defvar smerge-refine-forward-function 'smerge-refine-forward
685 "Function used to determine an \"atomic\" element.
686 You can set it to `forward-char' to get char-level granularity.
687 Its behavior has mainly two restrictions:
688 - if this function encounters a newline, it's important that it stops right
689 after the newline.
690 This only matters if `smerge-refine-ignore-whitespace' is nil.
691 - it needs to be unaffected by changes performed by the `preproc' argument
692 to `smerge-refine-subst'.
693 This only matters if `smerge-refine-weight-hack' is nil.")
695 (defvar smerge-refine-ignore-whitespace t
696 "If non-nil,Indicate that smerge-refine should try to ignore change in whitespace.")
698 (defvar smerge-refine-weight-hack t
699 "If non-nil, pass to diff as many lines as there are chars in the region.
700 I.e. each atomic element (e.g. word) will be copied as many times (on different
701 lines) as it has chars. This has 2 advantages:
702 - if `diff' tries to minimize the number *lines* (rather than chars)
703 added/removed, this adjust the weights so that adding/removing long
704 symbols is considered correspondingly more costly.
705 - `smerge-refine-forward-function' only needs to be called when chopping up
706 the regions, and `forward-char' can be used afterwards.
707 It has the following disadvantages:
708 - cannot use `diff -w' because the weighting causes added spaces in a line
709 to be represented as added copies of some line, so `diff -w' can't do the
710 right thing any more.
711 - may in degenerate cases take a 1KB input region and turn it into a 1MB
712 file to pass to diff.")
714 (defun smerge-refine-forward (n)
715 (let ((case-fold-search nil)
716 (re "[[:upper:]]?[[:lower:]]+\\|[[:upper:]]+\\|[[:digit:]]+\\|.\\|\n"))
717 (when (and smerge-refine-ignore-whitespace
718 ;; smerge-refine-weight-hack causes additional spaces to
719 ;; appear as additional lines as well, so even if diff ignore
720 ;; whitespace changes, it'll report added/removed lines :-(
721 (not smerge-refine-weight-hack))
722 (setq re (concat "[ \t]*\\(?:" re "\\)")))
723 (dotimes (i n)
724 (unless (looking-at re) (error "Smerge refine internal error"))
725 (goto-char (match-end 0)))))
727 (defun smerge-refine-chopup-region (beg end file &optional preproc)
728 "Chopup the region into small elements, one per line.
729 Save the result into FILE.
730 If non-nil, PREPROC is called with no argument in a buffer that contains
731 a copy of the text, just before chopping it up. It can be used to replace
732 chars to try and eliminate some spurious differences."
733 ;; We used to chop up char-by-char rather than word-by-word like ediff
734 ;; does. It had the benefit of simplicity and very fine results, but it
735 ;; often suffered from problem that diff would find correlations where
736 ;; there aren't any, so the resulting "change" didn't make much sense.
737 ;; You can still get this behavior by setting
738 ;; `smerge-refine-forward-function' to `forward-char'.
739 (let ((buf (current-buffer)))
740 (with-temp-buffer
741 (insert-buffer-substring buf beg end)
742 (when preproc (goto-char (point-min)) (funcall preproc))
743 (when smerge-refine-ignore-whitespace
744 ;; It doesn't make much of a difference for diff-fine-highlight
745 ;; because we still have the _/+/</>/! prefix anyway. Can still be
746 ;; useful in other circumstances.
747 (subst-char-in-region (point-min) (point-max) ?\n ?\s))
748 (goto-char (point-min))
749 (while (not (eobp))
750 (funcall smerge-refine-forward-function 1)
751 (let ((s (if (prog2 (forward-char -1) (bolp) (forward-char 1))
753 (buffer-substring (line-beginning-position) (point)))))
754 ;; We add \n after each char except after \n, so we get
755 ;; one line per text char, where each line contains
756 ;; just one char, except for \n chars which are
757 ;; represented by the empty line.
758 (unless (eq (char-before) ?\n) (insert ?\n))
759 ;; HACK ALERT!!
760 (if smerge-refine-weight-hack
761 (dotimes (i (1- (length s))) (insert s "\n")))))
762 (unless (bolp) (error "Smerge refine internal error"))
763 (let ((coding-system-for-write 'emacs-mule))
764 (write-region (point-min) (point-max) file nil 'nomessage)))))
766 (defun smerge-refine-highlight-change (buf beg match-num1 match-num2 props)
767 (with-current-buffer buf
768 (goto-char beg)
769 (let* ((startline (- (string-to-number match-num1) 1))
770 (beg (progn (funcall (if smerge-refine-weight-hack
771 'forward-char
772 smerge-refine-forward-function)
773 startline)
774 (point)))
775 (end (progn (funcall (if smerge-refine-weight-hack
776 'forward-char
777 smerge-refine-forward-function)
778 (if match-num2
779 (- (string-to-number match-num2)
780 startline)
782 (point))))
783 (when smerge-refine-ignore-whitespace
784 (skip-chars-backward " \t\n" beg) (setq end (point))
785 (goto-char beg)
786 (skip-chars-forward " \t\n" end) (setq beg (point)))
787 (when (> end beg)
788 (let ((ol (make-overlay
789 beg end nil
790 ;; Make them tend to shrink rather than spread when editing.
791 'front-advance nil)))
792 (overlay-put ol 'evaporate t)
793 (dolist (x props) (overlay-put ol (car x) (cdr x)))
794 ol)))))
796 (defun smerge-refine-subst (beg1 end1 beg2 end2 props &optional preproc)
797 "Show fine differences in the two regions BEG1..END1 and BEG2..END2.
798 PROPS is an alist of properties to put (via overlays) on the changes.
799 If non-nil, PREPROC is called with no argument in a buffer that contains
800 a copy of a region, just before preparing it to for `diff'. It can be used to
801 replace chars to try and eliminate some spurious differences."
802 (let* ((buf (current-buffer))
803 (pos (point))
804 (file1 (make-temp-file "diff1"))
805 (file2 (make-temp-file "diff2")))
806 ;; Chop up regions into smaller elements and save into files.
807 (smerge-refine-chopup-region beg1 end1 file1 preproc)
808 (smerge-refine-chopup-region beg2 end2 file2 preproc)
810 ;; Call diff on those files.
811 (unwind-protect
812 (with-temp-buffer
813 (let ((coding-system-for-read 'emacs-mule))
814 (call-process diff-command nil t nil
815 (if (and smerge-refine-ignore-whitespace
816 (not smerge-refine-weight-hack))
817 ;; Pass -a so diff treats it as a text file even
818 ;; if it contains \0 and such.
819 ;; Pass -d so as to get the smallest change, but
820 ;; also and more importantly because otherwise it
821 ;; may happen that diff doesn't behave like
822 ;; smerge-refine-weight-hack expects it to.
823 ;; See http://thread.gmane.org/gmane.emacs.devel/82685.
824 "-awd" "-ad")
825 file1 file2))
826 ;; Process diff's output.
827 (goto-char (point-min))
828 (let ((last1 nil)
829 (last2 nil))
830 (while (not (eobp))
831 (if (not (looking-at "\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?\\([acd]\\)\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)?$"))
832 (error "Unexpected patch hunk header: %s"
833 (buffer-substring (point) (line-end-position))))
834 (let ((op (char-after (match-beginning 3)))
835 (m1 (match-string 1))
836 (m2 (match-string 2))
837 (m4 (match-string 4))
838 (m5 (match-string 5)))
839 (when (memq op '(?d ?c))
840 (setq last1
841 (smerge-refine-highlight-change buf beg1 m1 m2 props)))
842 (when (memq op '(?a ?c))
843 (setq last2
844 (smerge-refine-highlight-change buf beg2 m4 m5 props))))
845 (forward-line 1) ;Skip hunk header.
846 (and (re-search-forward "^[0-9]" nil 'move) ;Skip hunk body.
847 (goto-char (match-beginning 0))))
848 ;; (assert (or (null last1) (< (overlay-start last1) end1)))
849 ;; (assert (or (null last2) (< (overlay-start last2) end2)))
850 (if smerge-refine-weight-hack
851 (progn
852 ;; (assert (or (null last1) (<= (overlay-end last1) end1)))
853 ;; (assert (or (null last2) (<= (overlay-end last2) end2)))
855 ;; smerge-refine-forward-function when calling in chopup may
856 ;; have stopped because it bumped into EOB whereas in
857 ;; smerge-refine-weight-hack it may go a bit further.
858 (if (and last1 (> (overlay-end last1) end1))
859 (move-overlay last1 (overlay-start last1) end1))
860 (if (and last2 (> (overlay-end last2) end2))
861 (move-overlay last2 (overlay-start last2) end2))
863 (goto-char pos)
864 (delete-file file1)
865 (delete-file file2))))
867 (defun smerge-refine ()
868 "Highlight the parts of the conflict that are different."
869 (interactive)
870 ;; FIXME: make it work with 3-way conflicts.
871 (smerge-match-conflict)
872 (remove-overlays (match-beginning 0) (match-end 0) 'smerge 'refine)
873 (smerge-ensure-match 1)
874 (smerge-ensure-match 3)
875 ;; Match 1 and 3 may be one and the same in case of trivial diff3 -A conflict.
876 (let ((n1 (if (eq (match-end 1) (match-end 3)) 2 1)))
877 (smerge-refine-subst (match-beginning n1) (match-end n1)
878 (match-beginning 3) (match-end 3)
879 '((smerge . refine)
880 (face . smerge-refined-change)))))
882 (defun smerge-diff (n1 n2)
883 (smerge-match-conflict)
884 (smerge-ensure-match n1)
885 (smerge-ensure-match n2)
886 (let ((name1 (aref smerge-match-names n1))
887 (name2 (aref smerge-match-names n2))
888 ;; Read them before the match-data gets clobbered.
889 (beg1 (match-beginning n1))
890 (end1 (match-end n1))
891 (beg2 (match-beginning n2))
892 (end2 (match-end n2))
893 (file1 (make-temp-file "smerge1"))
894 (file2 (make-temp-file "smerge2"))
895 (dir default-directory)
896 (file (if buffer-file-name (file-relative-name buffer-file-name)))
897 ;; We would want to use `emacs-mule-unix' for read&write, but we
898 ;; bump into problems with the coding-system used by diff to write
899 ;; the file names and the time stamps in the header.
900 ;; `buffer-file-coding-system' is not always correct either, but if
901 ;; the OS/user uses only one coding-system, then it works.
902 (coding-system-for-read buffer-file-coding-system))
903 (write-region beg1 end1 file1 nil 'nomessage)
904 (write-region beg2 end2 file2 nil 'nomessage)
905 (unwind-protect
906 (with-current-buffer (get-buffer-create smerge-diff-buffer-name)
907 (setq default-directory dir)
908 (let ((inhibit-read-only t))
909 (erase-buffer)
910 (let ((status
911 (apply 'call-process diff-command nil t nil
912 (append smerge-diff-switches
913 (list "-L" (concat name1 "/" file)
914 "-L" (concat name2 "/" file)
915 file1 file2)))))
916 (if (eq status 0) (insert "No differences found.\n"))))
917 (goto-char (point-min))
918 (diff-mode)
919 (display-buffer (current-buffer) t))
920 (delete-file file1)
921 (delete-file file2))))
923 ;; compiler pacifiers
924 (defvar smerge-ediff-windows)
925 (defvar smerge-ediff-buf)
926 (defvar ediff-buffer-A)
927 (defvar ediff-buffer-B)
928 (defvar ediff-buffer-C)
929 (defvar ediff-ancestor-buffer)
930 (defvar ediff-quit-hook)
931 (declare-function ediff-cleanup-mess "ediff-util" nil)
933 ;;;###autoload
934 (defun smerge-ediff (&optional name-mine name-other name-base)
935 "Invoke ediff to resolve the conflicts.
936 NAME-MINE, NAME-OTHER, and NAME-BASE, if non-nil, are used for the
937 buffer names."
938 (interactive)
939 (let* ((buf (current-buffer))
940 (mode major-mode)
941 ;;(ediff-default-variant 'default-B)
942 (config (current-window-configuration))
943 (filename (file-name-nondirectory buffer-file-name))
944 (mine (generate-new-buffer
945 (or name-mine (concat "*" filename " MINE*"))))
946 (other (generate-new-buffer
947 (or name-other (concat "*" filename " OTHER*"))))
948 base)
949 (with-current-buffer mine
950 (buffer-disable-undo)
951 (insert-buffer-substring buf)
952 (goto-char (point-min))
953 (while (smerge-find-conflict)
954 (when (match-beginning 2) (setq base t))
955 (smerge-keep-n 1))
956 (buffer-enable-undo)
957 (set-buffer-modified-p nil)
958 (funcall mode))
960 (with-current-buffer other
961 (buffer-disable-undo)
962 (insert-buffer-substring buf)
963 (goto-char (point-min))
964 (while (smerge-find-conflict)
965 (smerge-keep-n 3))
966 (buffer-enable-undo)
967 (set-buffer-modified-p nil)
968 (funcall mode))
970 (when base
971 (setq base (generate-new-buffer
972 (or name-base (concat "*" filename " BASE*"))))
973 (with-current-buffer base
974 (buffer-disable-undo)
975 (insert-buffer-substring buf)
976 (goto-char (point-min))
977 (while (smerge-find-conflict)
978 (if (match-end 2)
979 (smerge-keep-n 2)
980 (delete-region (match-beginning 0) (match-end 0))))
981 (buffer-enable-undo)
982 (set-buffer-modified-p nil)
983 (funcall mode)))
985 ;; the rest of the code is inspired from vc.el
986 ;; Fire up ediff.
987 (set-buffer
988 (if base
989 (ediff-merge-buffers-with-ancestor mine other base)
990 ;; nil 'ediff-merge-revisions-with-ancestor buffer-file-name)
991 (ediff-merge-buffers mine other)))
992 ;; nil 'ediff-merge-revisions buffer-file-name)))
994 ;; Ediff is now set up, and we are in the control buffer.
995 ;; Do a few further adjustments and take precautions for exit.
996 (set (make-local-variable 'smerge-ediff-windows) config)
997 (set (make-local-variable 'smerge-ediff-buf) buf)
998 (set (make-local-variable 'ediff-quit-hook)
999 (lambda ()
1000 (let ((buffer-A ediff-buffer-A)
1001 (buffer-B ediff-buffer-B)
1002 (buffer-C ediff-buffer-C)
1003 (buffer-Ancestor ediff-ancestor-buffer)
1004 (buf smerge-ediff-buf)
1005 (windows smerge-ediff-windows))
1006 (ediff-cleanup-mess)
1007 (with-current-buffer buf
1008 (erase-buffer)
1009 (insert-buffer-substring buffer-C)
1010 (kill-buffer buffer-A)
1011 (kill-buffer buffer-B)
1012 (kill-buffer buffer-C)
1013 (when (bufferp buffer-Ancestor) (kill-buffer buffer-Ancestor))
1014 (set-window-configuration windows)
1015 (message "Conflict resolution finished; you may save the buffer")))))
1016 (message "Please resolve conflicts now; exit ediff when done")))
1018 (defun smerge-makeup-conflict (pt1 pt2 pt3 &optional pt4)
1019 "Insert diff3 markers to make a new conflict.
1020 Uses point and mark for 2 of the relevant positions and previous marks
1021 for the other ones.
1022 By default, makes up a 2-way conflict,
1023 with a \\[universal-argument] prefix, makes up a 3-way conflict."
1024 (interactive
1025 (list (point)
1026 (mark)
1027 (progn (pop-mark) (mark))
1028 (when current-prefix-arg (pop-mark) (mark))))
1029 ;; Start from the end so as to avoid problems with pos-changes.
1030 (destructuring-bind (pt1 pt2 pt3 &optional pt4)
1031 (sort (list* pt1 pt2 pt3 (if pt4 (list pt4))) '>=)
1032 (goto-char pt1) (beginning-of-line)
1033 (insert ">>>>>>> OTHER\n")
1034 (goto-char pt2) (beginning-of-line)
1035 (insert "=======\n")
1036 (goto-char pt3) (beginning-of-line)
1037 (when pt4
1038 (insert "||||||| BASE\n")
1039 (goto-char pt4) (beginning-of-line))
1040 (insert "<<<<<<< MINE\n"))
1041 (if smerge-mode nil (smerge-mode 1))
1042 (smerge-refine))
1045 (defconst smerge-parsep-re
1046 (concat smerge-begin-re "\\|" smerge-end-re "\\|"
1047 smerge-base-re "\\|" smerge-other-re "\\|"))
1049 ;;;###autoload
1050 (define-minor-mode smerge-mode
1051 "Minor mode to simplify editing output from the diff3 program.
1052 \\{smerge-mode-map}"
1053 :group 'smerge :lighter " SMerge"
1054 (when (and (boundp 'font-lock-mode) font-lock-mode)
1055 (save-excursion
1056 (if smerge-mode
1057 (font-lock-add-keywords nil smerge-font-lock-keywords 'append)
1058 (font-lock-remove-keywords nil smerge-font-lock-keywords))
1059 (goto-char (point-min))
1060 (while (smerge-find-conflict)
1061 (save-excursion
1062 (font-lock-fontify-region (match-beginning 0) (match-end 0) nil)))))
1063 (if (string-match (regexp-quote smerge-parsep-re) paragraph-separate)
1064 (unless smerge-mode
1065 (set (make-local-variable 'paragraph-separate)
1066 (replace-match "" t t paragraph-separate)))
1067 (when smerge-mode
1068 (set (make-local-variable 'paragraph-separate)
1069 (concat smerge-parsep-re paragraph-separate))))
1070 (unless smerge-mode
1071 (smerge-remove-props (point-min) (point-max))))
1073 ;;;###autoload
1074 (defun smerge-start-session ()
1075 "Turn on `smerge-mode' and move point to first conflict marker.
1076 If no conflict maker is found, turn off `smerge-mode'."
1077 (smerge-mode 1)
1078 (condition-case nil
1079 (smerge-next)
1080 (error (smerge-auto-leave))))
1082 (provide 'smerge-mode)
1084 ;; arch-tag: 605c8d1e-e43d-4943-a6f3-1bcc4333e690
1085 ;;; smerge-mode.el ends here