1 ;;; diff-hl.el --- Highlight uncommitted changes using VC -*- lexical-binding: t -*-
3 ;; Copyright (C) 2012-2016 Free Software Foundation, Inc.
5 ;; Author: Dmitry Gutov <dgutov@yandex.ru>
6 ;; URL: https://github.com/dgutov/diff-hl
9 ;; Package-Requires: ((cl-lib "0.2"))
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; `diff-hl-mode' highlights uncommitted changes on the side of the
29 ;; window (using the fringe, by default), allows you to jump between
30 ;; the hunks and revert them selectively.
34 ;; `diff-hl-diff-goto-hunk' C-x v =
35 ;; `diff-hl-revert-hunk' C-x v n
36 ;; `diff-hl-previous-hunk' C-x v [
37 ;; `diff-hl-next-hunk' C-x v ]
39 ;; The mode takes advantage of `smartrep' if it is installed.
41 ;; Add either of the following to your init file.
43 ;; To use it in all buffers:
45 ;; (global-diff-hl-mode)
47 ;; Only in `prog-mode' buffers, with `vc-dir' integration:
49 ;; (add-hook 'prog-mode-hook 'turn-on-diff-hl-mode)
50 ;; (add-hook 'vc-dir-mode-hook 'turn-on-diff-hl-mode)
63 (declare-function smartrep-define-key 'smartrep))
66 "VC diff highlighting on the side of a window"
69 (defface diff-hl-insert
70 '((default :inherit diff-added)
71 (((class color)) :foreground "green4"))
72 "Face used to highlight inserted lines."
75 (defface diff-hl-delete
76 '((default :inherit diff-removed)
77 (((class color)) :foreground "red3"))
78 "Face used to highlight deleted lines."
81 (defface diff-hl-change
82 '((default :foreground "blue3")
83 (((class color) (min-colors 88) (background light))
84 :background "#ddddff")
85 (((class color) (min-colors 88) (background dark))
86 :background "#333355"))
87 "Face used to highlight changed lines."
90 (defcustom diff-hl-command-prefix (kbd "C-x v")
91 "The prefix for all `diff-hl' commands."
95 (defcustom diff-hl-draw-borders t
96 "Non-nil to draw borders around fringe indicators."
100 (defcustom diff-hl-highlight-function 'diff-hl-highlight-on-fringe
101 "Function to highlight the current line. Its arguments are
102 overlay, change type and position within a hunk."
106 (defcustom diff-hl-fringe-bmp-function 'diff-hl-fringe-bmp-from-pos
107 "Function to choose the fringe bitmap for a given change type
108 and position within a hunk. Should accept two arguments."
110 :type '(choice (const diff-hl-fringe-bmp-from-pos)
111 (const diff-hl-fringe-bmp-from-type)
114 (defcustom diff-hl-fringe-face-function 'diff-hl-fringe-face-from-type
115 "Function to choose the fringe face for a given change type
116 and position within a hunk. Should accept two arguments."
120 (defcustom diff-hl-side 'left
121 "Which side to use for indicators."
122 :type '(choice (const left)
124 :set (lambda (var value)
125 (let ((on (bound-and-true-p global-diff-hl-mode)))
126 (when on (global-diff-hl-mode -1))
127 (set-default var value)
128 (when on (global-diff-hl-mode 1)))))
130 (defvar diff-hl-reference-revision nil
131 "Revision to diff against. nil means the most recent one.")
133 (defun diff-hl-define-bitmaps ()
134 (let* ((scale (if (and (boundp 'text-scale-mode-amount)
135 (numberp text-scale-mode-amount))
136 (expt text-scale-mode-step text-scale-mode-amount)
138 (spacing (or (and (display-graphic-p) (default-value 'line-spacing)) 0))
139 (h (+ (ceiling (* (frame-char-height) scale))
141 (truncate (* (frame-char-height) spacing))
143 (w (min (frame-parameter nil (intern (format "%s-fringe" diff-hl-side)))
145 (middle (make-vector h (expt 2 (1- w))))
146 (ones (1- (expt 2 w)))
147 (top (copy-sequence middle))
148 (bottom (copy-sequence middle))
149 (single (copy-sequence middle)))
151 (aset bottom (1- h) ones)
153 (aset single (1- h) ones)
154 (define-fringe-bitmap 'diff-hl-bmp-top top h w 'top)
155 (define-fringe-bitmap 'diff-hl-bmp-middle middle h w 'center)
156 (define-fringe-bitmap 'diff-hl-bmp-bottom bottom h w 'bottom)
157 (define-fringe-bitmap 'diff-hl-bmp-single single h w 'top)
158 (define-fringe-bitmap 'diff-hl-bmp-i [3 3 0 3 3 3 3 3 3 3] nil 2 'center)
159 (let* ((w2 (* (/ w 2) 2))
160 ;; When fringes are disabled, it's easier to fix up the width,
161 ;; instead of doing nothing (#20).
162 (w2 (if (zerop w2) 2 w2))
163 (delete-row (- (expt 2 (1- w2)) 2))
164 (middle-pos (1- (/ w2 2)))
165 (middle-bit (expt 2 middle-pos))
166 (insert-bmp (make-vector w2 (* 3 middle-bit))))
167 (define-fringe-bitmap 'diff-hl-bmp-delete (make-vector 2 delete-row) w2 w2)
168 (aset insert-bmp 0 0)
169 (aset insert-bmp middle-pos delete-row)
170 (aset insert-bmp (1+ middle-pos) delete-row)
171 (aset insert-bmp (1- w2) 0)
172 (define-fringe-bitmap 'diff-hl-bmp-insert insert-bmp w2 w2)
175 (defun diff-hl-maybe-define-bitmaps ()
176 (when (window-system) ;; No fringes in the console.
177 (unless (fringe-bitmap-p 'diff-hl-bmp-empty)
178 (diff-hl-define-bitmaps)
179 (define-fringe-bitmap 'diff-hl-bmp-empty [0] 1 1 'center))))
181 (defvar diff-hl-spec-cache (make-hash-table :test 'equal))
183 (defun diff-hl-fringe-spec (type pos side)
184 (let* ((key (list type pos side
185 diff-hl-fringe-face-function
186 diff-hl-fringe-bmp-function))
187 (val (gethash key diff-hl-spec-cache)))
189 (let* ((face-sym (funcall diff-hl-fringe-face-function type pos))
190 (bmp-sym (funcall diff-hl-fringe-bmp-function type pos)))
191 (setq val (propertize " " 'display `((,(intern (format "%s-fringe" side))
192 ,bmp-sym ,face-sym))))
193 (puthash key val diff-hl-spec-cache)))
196 (defun diff-hl-fringe-face-from-type (type _pos)
197 (intern (format "diff-hl-%s" type)))
199 (defun diff-hl-fringe-bmp-from-pos (_type pos)
200 (intern (format "diff-hl-bmp-%s" pos)))
202 (defun diff-hl-fringe-bmp-from-type (type _pos)
204 (unknown 'question-mark)
205 (change 'exclamation-mark)
206 (ignored 'diff-hl-bmp-i)
207 (t (intern (format "diff-hl-bmp-%s" type)))))
209 (defvar vc-svn-diff-switches)
211 (defmacro diff-hl-with-diff-switches (body)
212 ;; https://github.com/dgutov/diff-hl/issues/67
213 `(let ((vc-git-diff-switches '("-U0"))
214 (vc-hg-diff-switches nil)
215 (vc-svn-diff-switches nil)
216 (vc-diff-switches '("-U0"))
217 ,@(when (boundp 'vc-disable-async-diff)
218 '((vc-disable-async-diff t))))
221 (defun diff-hl-modified-p (state)
222 (or (eq state 'edited)
223 (and (eq state 'up-to-date)
224 ;; VC state is stale in after-revert-hook.
225 (or revert-buffer-in-progress-p
226 ;; Diffing against an older revision.
227 diff-hl-reference-revision))))
229 (defun diff-hl-changes-buffer (file backend)
230 (let ((buf-name " *diff-hl* "))
231 (diff-hl-with-diff-switches
232 (vc-call-backend backend 'diff (list file)
233 diff-hl-reference-revision nil
237 (defun diff-hl-changes ()
238 (let* ((file buffer-file-name)
239 (backend (vc-backend file)))
241 (let ((state (vc-state file backend)))
243 ((diff-hl-modified-p state)
244 (let* (diff-auto-refine-mode res)
245 (with-current-buffer (diff-hl-changes-buffer file backend)
246 (goto-char (point-min))
249 (diff-beginning-of-hunk t))
250 (while (looking-at diff-hunk-header-re-unified)
251 (let ((line (string-to-number (match-string 3)))
252 (len (let ((m (match-string 4)))
253 (if m (string-to-number m) 1)))
256 (let* ((inserts (diff-count-matches "^\\+" beg (point)))
257 (deletes (diff-count-matches "^-" beg (point)))
258 (type (cond ((zerop deletes) 'insert)
259 ((zerop inserts) 'delete)
261 (when (eq type 'delete)
264 (push (list line len type) res))))))
267 `((1 ,(line-number-at-pos (point-max)) insert)))
269 `((1 ,(line-number-at-pos (point-max)) delete))))))))
271 (defun diff-hl-update ()
272 (let ((changes (diff-hl-changes))
274 (diff-hl-remove-overlays)
278 (goto-char (point-min))
280 (cl-destructuring-bind (line len type) c
281 (forward-line (- line current-line))
282 (setq current-line line)
283 (let ((hunk-beg (point)))
284 (while (cl-plusp len)
285 (diff-hl-add-highlighting
288 ((not diff-hl-draw-borders) 'empty)
289 ((and (= len 1) (= line current-line)) 'single)
291 ((= line current-line) 'top)
294 (cl-incf current-line)
296 (let ((h (make-overlay hunk-beg (point)))
297 (hook '(diff-hl-overlay-modified)))
298 (overlay-put h 'diff-hl t)
299 (overlay-put h 'diff-hl-hunk t)
300 (overlay-put h 'modification-hooks hook)
301 (overlay-put h 'insert-in-front-hooks hook)
302 (overlay-put h 'insert-behind-hooks hook)))))))))
304 (defun diff-hl-add-highlighting (type shape)
305 (let ((o (make-overlay (point) (point))))
306 (overlay-put o 'diff-hl t)
307 (funcall diff-hl-highlight-function o type shape)
310 (defun diff-hl-highlight-on-fringe (ovl type shape)
311 (overlay-put ovl 'before-string (diff-hl-fringe-spec type shape
314 (defun diff-hl-remove-overlays (&optional beg end)
317 (dolist (o (overlays-in (or beg (point-min)) (or end (point-max))))
318 (when (overlay-get o 'diff-hl) (delete-overlay o)))))
320 (defun diff-hl-overlay-modified (ov after-p _beg _end &optional _length)
321 "Delete the hunk overlay and all our line overlays inside it."
323 (when (overlay-buffer ov)
324 (diff-hl-remove-overlays (overlay-start ov) (overlay-end ov))
325 (delete-overlay ov))))
327 (defvar diff-hl-timer nil)
329 (defun diff-hl-edit (_beg _end _len)
330 "DTRT when we've `undo'-ne the buffer into unmodified state."
331 (when undo-in-progress
333 (cancel-timer diff-hl-timer))
335 (run-with-idle-timer 0.01 nil #'diff-hl-after-undo (current-buffer)))))
337 (defun diff-hl-after-undo (buffer)
338 (with-current-buffer buffer
339 (unless (buffer-modified-p)
342 (defun diff-hl-diff-goto-hunk ()
343 "Run VC diff command and go to the line corresponding to the current."
346 (let* ((line (line-number-at-pos))
347 (buffer (current-buffer)))
348 (vc-diff-internal t (vc-deduce-fileset) diff-hl-reference-revision nil t)
349 (vc-exec-after `(if (< (line-number-at-pos (point-max)) 3)
350 (with-current-buffer ,buffer (diff-hl-remove-overlays))
351 (diff-hl-diff-skip-to ,line)
352 (setq vc-sentinel-movepoint (point))))))
354 (defun diff-hl-diff-skip-to (line)
355 "In `diff-mode', skip to the hunk and line corresponding to LINE
356 in the source file, or the last line of the hunk above it."
359 (while (and (looking-at diff-hunk-header-re-unified) (not found))
360 (let ((hunk-line (string-to-number (match-string 3)))
361 (len (let ((m (match-string 4)))
362 (if m (string-to-number m) 1))))
363 (if (> line (+ hunk-line len))
366 (if (< line hunk-line)
367 ;; Retreat to the previous hunk.
369 (let ((to-go (1+ (- line hunk-line))))
370 (while (cl-plusp to-go)
372 (unless (looking-at "^-")
373 (cl-decf to-go))))))))))
375 (defun diff-hl-revert-hunk ()
376 "Revert the diff hunk with changes at or above the point."
379 (let ((diff-buffer (generate-new-buffer-name "*diff-hl*"))
380 (buffer (current-buffer))
381 (line (save-excursion
382 (unless (diff-hl-hunk-overlay-at (point))
383 (diff-hl-previous-hunk))
384 (line-number-at-pos)))
385 (fileset (vc-deduce-fileset)))
388 (vc-diff-internal nil fileset diff-hl-reference-revision nil
391 `(let (beg-line end-line)
393 (with-current-buffer ,buffer (diff-hl-remove-overlays))
394 (error "Buffer is up-to-date"))
395 (let (diff-auto-refine-mode)
396 (diff-hl-diff-skip-to ,line))
398 (while (looking-at "[-+]") (forward-line 1))
399 (setq end-line (line-number-at-pos (point)))
400 (unless (eobp) (diff-split-hunk)))
401 (unless (looking-at "[-+]") (forward-line -1))
402 (while (looking-at "[-+]") (forward-line -1))
403 (setq beg-line (line-number-at-pos (point)))
404 (unless (looking-at "@")
407 (let ((wbh (window-body-height)))
408 (if (>= wbh (- end-line beg-line))
409 (recenter (/ (+ wbh (- beg-line end-line) 2) 2))
411 (when diff-auto-refine-mode
413 (unless (yes-or-no-p (format "Revert current hunk in %s?"
414 ,(cl-caadr fileset)))
415 (error "Revert canceled"))
416 (let ((diff-advance-after-apply-hunk nil))
418 (with-current-buffer ,buffer
420 (message "Hunk reverted"))))
421 (quit-windows-on diff-buffer t))))
423 (defun diff-hl-hunk-overlay-at (pos)
424 (cl-loop for o in (overlays-in pos (1+ pos))
425 when (overlay-get o 'diff-hl-hunk)
428 (defun diff-hl-next-hunk (&optional backward)
429 "Go to the beginning of the next hunk in the current buffer."
431 (let ((pos (save-excursion
433 (while (not (if backward (bobp) (eobp)))
434 (goto-char (if backward
435 (previous-overlay-change (point))
436 (next-overlay-change (point))))
437 (let ((o (diff-hl-hunk-overlay-at (point))))
438 (when (and o (= (overlay-start o) (point)))
439 (throw 'found (overlay-start o)))))))))
442 (error "No further hunks found"))))
444 (defun diff-hl-previous-hunk ()
445 "Go to the beginning of the previous hunk in the current buffer."
447 (diff-hl-next-hunk t))
449 (defun diff-hl-mark-hunk ()
451 (let ((hunk (diff-hl-hunk-overlay-at (point))))
453 (error "No hunk at point"))
454 (goto-char (overlay-start hunk))
455 (push-mark (overlay-end hunk) nil t)))
457 (defvar diff-hl-command-map
458 (let ((map (make-sparse-keymap)))
459 (define-key map "n" 'diff-hl-revert-hunk)
460 (define-key map "[" 'diff-hl-previous-hunk)
461 (define-key map "]" 'diff-hl-next-hunk)
463 (fset 'diff-hl-command-map diff-hl-command-map)
466 (define-minor-mode diff-hl-mode
467 "Toggle VC diff highlighting."
468 :lighter "" :keymap `(([remap vc-diff] . diff-hl-diff-goto-hunk)
469 (,diff-hl-command-prefix . diff-hl-command-map))
472 (diff-hl-maybe-define-bitmaps)
473 (add-hook 'after-save-hook 'diff-hl-update nil t)
474 (add-hook 'after-change-functions 'diff-hl-edit nil t)
475 (add-hook (if vc-mode
476 ;; Defer until the end of this hook, so that its
477 ;; elements can modify the update behavior.
478 'diff-hl-mode-on-hook
479 ;; If we're only opening the file now,
480 ;; `vc-find-file-hook' likely hasn't run yet, so
481 ;; let's wait until the state information is
482 ;; saved, in order not to fetch it twice.
485 (add-hook 'vc-checkin-hook 'diff-hl-update nil t)
486 (add-hook 'after-revert-hook 'diff-hl-update nil t)
487 ;; Magit does call `auto-revert-handler', but it usually
488 ;; doesn't do much, because `buffer-stale--default-function'
489 ;; doesn't care about changed VC state.
490 ;; https://github.com/magit/magit/issues/603
491 (add-hook 'magit-revert-buffer-hook 'diff-hl-update nil t)
492 ;; Magit versions 2.0-2.3 don't do the above and call this
493 ;; instead, but only when they dosn't call `revert-buffer':
494 (add-hook 'magit-not-reverted-hook 'diff-hl-update nil t)
495 (add-hook 'auto-revert-mode-hook 'diff-hl-update nil t)
496 (add-hook 'text-scale-mode-hook 'diff-hl-define-bitmaps nil t))
497 (remove-hook 'after-save-hook 'diff-hl-update t)
498 (remove-hook 'after-change-functions 'diff-hl-edit t)
499 (remove-hook 'find-file-hook 'diff-hl-update t)
500 (remove-hook 'vc-checkin-hook 'diff-hl-update t)
501 (remove-hook 'after-revert-hook 'diff-hl-update t)
502 (remove-hook 'magit-revert-buffer-hook 'diff-hl-update t)
503 (remove-hook 'magit-not-reverted-hook 'diff-hl-update t)
504 (remove-hook 'auto-revert-mode-hook 'diff-hl-update t)
505 (remove-hook 'text-scale-mode-hook 'diff-hl-define-bitmaps t)
506 (diff-hl-remove-overlays)))
508 (when (require 'smartrep nil t)
510 (cl-labels ((scan (map)
512 (lambda (event binding)
515 (when (characterp event)
516 (push (cons (string event) binding) smart-keys))))
518 (scan diff-hl-command-map)
519 (smartrep-define-key diff-hl-mode-map diff-hl-command-prefix smart-keys))))
521 (declare-function magit-toplevel "magit-git")
522 (declare-function magit-unstaged-files "magit-git")
524 (defun diff-hl-magit-post-refresh ()
525 (let* ((topdir (magit-toplevel))
527 (mapcar (lambda (file) (expand-file-name file topdir))
528 (magit-unstaged-files t)))
529 (unmodified-states '(up-to-date ignored unregistered)))
530 (dolist (buf (buffer-list))
531 (when (and (buffer-local-value 'diff-hl-mode buf)
532 (not (buffer-modified-p buf))
533 (file-in-directory-p (buffer-file-name buf) topdir))
534 (with-current-buffer buf
535 (let* ((file buffer-file-name)
536 (backend (vc-backend file)))
539 ((member file modified-files)
540 (when (memq (vc-state file) unmodified-states)
541 (vc-state-refresh file backend))
543 ((not (memq (vc-state file backend) unmodified-states))
544 (vc-state-refresh file backend)
545 (diff-hl-update))))))))))
547 (defun diff-hl-dir-update ()
548 (dolist (pair (if (vc-dir-marked-files)
549 (vc-dir-marked-only-files-and-states)
550 (vc-dir-child-files-and-states)))
551 (when (eq 'up-to-date (cdr pair))
552 (let ((buffer (find-buffer-visiting (car pair))))
554 (with-current-buffer buffer
555 (diff-hl-remove-overlays)))))))
557 (define-minor-mode diff-hl-dir-mode
558 "Toggle `diff-hl-mode' integration in a `vc-dir-mode' buffer."
561 (add-hook 'vc-checkin-hook 'diff-hl-dir-update t t)
562 (remove-hook 'vc-checkin-hook 'diff-hl-dir-update t)))
565 (defun turn-on-diff-hl-mode ()
566 "Turn on `diff-hl-mode' or `diff-hl-dir-mode' in a buffer if appropriate."
570 ((eq major-mode 'vc-dir-mode)
571 (diff-hl-dir-mode 1))))
574 (define-globalized-minor-mode global-diff-hl-mode diff-hl-mode
575 turn-on-diff-hl-mode :after-hook (diff-hl-global-mode-change))
577 (defun diff-hl-global-mode-change ()
578 (unless global-diff-hl-mode
579 (dolist (buf (buffer-list))
580 (with-current-buffer buf
581 (when diff-hl-dir-mode
582 (diff-hl-dir-mode -1))))))
586 ;;; diff-hl.el ends here