;;; wdiff -- highlight output of a wdiff using extents
(defun wdiff-highlight-transform (regexp face)
  "Internal: for search match of regexp replace it with group 1 and add extent"
  (while (re-search-forward regexp nil t)
    (let ((diff (- (match-beginning 1) (match-beginning 0))) 
	  extent)
      (replace-match "\\1")
      (setq extent (make-extent (- (match-beginning 1) diff) (- (match-end 1) diff)))
      (set-extent-property extent 'face face))
    ))

(defun wdiff-highlight ()
  (mapcar #'delete-extent (extent-list))
  (save-excursion
    (beginning-of-buffer)
    (wdiff-highlight-transform "{\\+\\(.*?\\)\\+}" '(green))
    (beginning-of-buffer)
    (wdiff-highlight-transform "\\[-\\(.*?\\)-\\]" '(red))
    ))

(defconst wdiff-options "--avoid-wraps"
    "Options given to wdiff")

(defun wdiff-last-version ()
  "wdiff this buffer with its last CVS version"
  (interactive)
  (or (buffer-file-name)
      (error "You can only wdiff a buffer that has a real file"))
  (let ((buffer (get-buffer-create "*wdiff*"))
	(file (file-name-nondirectory (buffer-file-name)))
	(offset (- (point) (point-min)))
	)
    (shell-command (format "cvs -q up -p %s | wdiff %s - %s" file wdiff-options file) buffer)
    (switch-to-buffer-other-window buffer)
    (goto-char offset)			; same place where we were in the original buffer
    (wdiff-highlight)
    ))
  
