]> code.delx.au - gnu-emacs-elpa/blob - diff-hl.el
Merge pull request #51 from tarsius/keep-bindings
[gnu-emacs-elpa] / diff-hl.el
1 ;;; diff-hl.el --- Highlight uncommitted changes -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2012-2015 Free Software Foundation, Inc.
4
5 ;; Author: Dmitry Gutov <dgutov@yandex.ru>
6 ;; URL: https://github.com/dgutov/diff-hl
7 ;; Keywords: vc, diff
8 ;; Version: 1.7.1
9 ;; Package-Requires: ((cl-lib "0.2"))
10
11 ;; This file is part of GNU Emacs.
12
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.
17
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.
22
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/>.
25
26 ;;; Commentary:
27
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.
31
32 ;; Provided commands:
33 ;;
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 ]
38 ;;
39 ;; The mode takes advantage of `smartrep' if it is installed.
40
41 ;; Add either of the following to your init file.
42 ;;
43 ;; To use it in all buffers:
44 ;;
45 ;; (global-diff-hl-mode)
46 ;;
47 ;; Only in `prog-mode' buffers, with `vc-dir' integration:
48 ;;
49 ;; (add-hook 'prog-mode-hook 'turn-on-diff-hl-mode)
50 ;; (add-hook 'vc-dir-mode-hook 'turn-on-diff-hl-mode)
51
52 ;;; Code:
53
54 (require 'fringe)
55 (require 'diff-mode)
56 (require 'vc)
57 (require 'vc-dir)
58 (eval-when-compile
59 (require 'cl-lib)
60 (require 'vc-git)
61 (require 'vc-hg)
62 (require 'face-remap)
63 (declare-function smartrep-define-key 'smartrep))
64
65 (defgroup diff-hl nil
66 "VC diff highlighting on the side of a window"
67 :group 'vc)
68
69 (defface diff-hl-insert
70 '((default :inherit diff-added)
71 (((class color)) :foreground "green4"))
72 "Face used to highlight inserted lines."
73 :group 'diff-hl)
74
75 (defface diff-hl-delete
76 '((default :inherit diff-removed)
77 (((class color)) :foreground "red3"))
78 "Face used to highlight deleted lines."
79 :group 'diff-hl)
80
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."
88 :group 'diff-hl)
89
90 (defcustom diff-hl-command-prefix (kbd "C-x v")
91 "The prefix for all `diff-hl' commands."
92 :group 'diff-hl
93 :type 'string)
94
95 (defcustom diff-hl-draw-borders t
96 "Non-nil to draw borders around fringe indicators."
97 :group 'diff-hl
98 :type 'boolean)
99
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."
103 :group 'diff-hl
104 :type 'function)
105
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."
109 :group 'diff-hl
110 :type '(choice (const diff-hl-fringe-bmp-from-pos)
111 (const diff-hl-fringe-bmp-from-type)
112 function))
113
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."
117 :group 'diff-hl
118 :type 'function)
119
120 (defcustom diff-hl-side 'left
121 "Which side to use for indicators."
122 :type '(choice (const left)
123 (const right))
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)))))
129
130 (defvar diff-hl-reference-revision nil
131 "Revision to diff against. nil means the most recent one.")
132
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)
137 1))
138 (spacing (or (and (display-graphic-p) (default-value 'line-spacing)) 0))
139 (h (+ (ceiling (* (frame-char-height) scale))
140 (if (floatp spacing)
141 (truncate (* (frame-char-height) spacing))
142 spacing)))
143 (w (min (frame-parameter nil (intern (format "%s-fringe" diff-hl-side)))
144 16))
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)))
150 (aset top 0 ones)
151 (aset bottom (1- h) ones)
152 (aset single 0 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)
173 )))
174
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))))
180
181 (defvar diff-hl-spec-cache (make-hash-table :test 'equal))
182
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)))
188 (unless val
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)))
194 val))
195
196 (defun diff-hl-fringe-face-from-type (type _pos)
197 (intern (format "diff-hl-%s" type)))
198
199 (defun diff-hl-fringe-bmp-from-pos (_type pos)
200 (intern (format "diff-hl-bmp-%s" pos)))
201
202 (defun diff-hl-fringe-bmp-from-type (type _pos)
203 (cl-case type
204 (unknown 'question-mark)
205 (change 'exclamation-mark)
206 (ignored 'diff-hl-bmp-i)
207 (t (intern (format "diff-hl-bmp-%s" type)))))
208
209 (defvar vc-svn-diff-switches)
210
211 (defmacro diff-hl-with-diff-switches (body)
212 `(let ((vc-git-diff-switches nil)
213 (vc-hg-diff-switches nil)
214 (vc-svn-diff-switches nil)
215 (vc-diff-switches '("-U0"))
216 ,@(when (boundp 'vc-disable-async-diff)
217 '((vc-disable-async-diff t))))
218 ,body))
219
220 (defun diff-hl-changes ()
221 (let* ((file buffer-file-name)
222 (backend (vc-backend file)))
223 (when backend
224 (let ((state (vc-state file backend)))
225 (cond
226 ((or (eq state 'edited)
227 (and (eq state 'up-to-date)
228 ;; VC state is stale in after-revert-hook.
229 (or revert-buffer-in-progress-p
230 ;; Diffing against an older revision.
231 diff-hl-reference-revision)))
232 (let* ((buf-name " *diff-hl* ")
233 diff-auto-refine-mode
234 res)
235 (diff-hl-with-diff-switches
236 (vc-call-backend backend 'diff (list file)
237 diff-hl-reference-revision nil
238 buf-name))
239 (with-current-buffer buf-name
240 (goto-char (point-min))
241 (unless (eobp)
242 (ignore-errors
243 (diff-beginning-of-hunk t))
244 (while (looking-at diff-hunk-header-re-unified)
245 (let ((line (string-to-number (match-string 3)))
246 (len (let ((m (match-string 4)))
247 (if m (string-to-number m) 1)))
248 (beg (point)))
249 (diff-end-of-hunk)
250 (let* ((inserts (diff-count-matches "^\\+" beg (point)))
251 (deletes (diff-count-matches "^-" beg (point)))
252 (type (cond ((zerop deletes) 'insert)
253 ((zerop inserts) 'delete)
254 (t 'change))))
255 (when (eq type 'delete)
256 (setq len 1)
257 (cl-incf line))
258 (push (list line len type) res))))))
259 (nreverse res)))
260 ((eq state 'added)
261 `((1 ,(line-number-at-pos (point-max)) insert)))
262 ((eq state 'removed)
263 `((1 ,(line-number-at-pos (point-max)) delete))))))))
264
265 (defun diff-hl-update ()
266 (let ((changes (diff-hl-changes))
267 (current-line 1))
268 (diff-hl-remove-overlays)
269 (save-excursion
270 (save-restriction
271 (widen)
272 (goto-char (point-min))
273 (dolist (c changes)
274 (cl-destructuring-bind (line len type) c
275 (forward-line (- line current-line))
276 (setq current-line line)
277 (let ((hunk-beg (point)))
278 (while (cl-plusp len)
279 (diff-hl-add-highlighting
280 type
281 (cond
282 ((not diff-hl-draw-borders) 'empty)
283 ((and (= len 1) (= line current-line)) 'single)
284 ((= len 1) 'bottom)
285 ((= line current-line) 'top)
286 (t 'middle)))
287 (forward-line 1)
288 (cl-incf current-line)
289 (cl-decf len))
290 (let ((h (make-overlay hunk-beg (point)))
291 (hook '(diff-hl-overlay-modified)))
292 (overlay-put h 'diff-hl t)
293 (overlay-put h 'diff-hl-hunk t)
294 (overlay-put h 'modification-hooks hook)
295 (overlay-put h 'insert-in-front-hooks hook)
296 (overlay-put h 'insert-behind-hooks hook)))))))))
297
298 (defun diff-hl-add-highlighting (type shape)
299 (let ((o (make-overlay (point) (point))))
300 (overlay-put o 'diff-hl t)
301 (funcall diff-hl-highlight-function o type shape)
302 o))
303
304 (defun diff-hl-highlight-on-fringe (ovl type shape)
305 (overlay-put ovl 'before-string (diff-hl-fringe-spec type shape
306 diff-hl-side)))
307
308 (defun diff-hl-remove-overlays (&optional beg end)
309 (save-restriction
310 (widen)
311 (dolist (o (overlays-in (or beg (point-min)) (or end (point-max))))
312 (when (overlay-get o 'diff-hl) (delete-overlay o)))))
313
314 (defun diff-hl-overlay-modified (ov after-p _beg _end &optional _length)
315 "Delete the hunk overlay and all our line overlays inside it."
316 (unless after-p
317 (when (overlay-buffer ov)
318 (diff-hl-remove-overlays (overlay-start ov) (overlay-end ov))
319 (delete-overlay ov))))
320
321 (defvar diff-hl-timer nil)
322
323 (defun diff-hl-edit (_beg _end _len)
324 "DTRT when we've `undo'-ne the buffer into unmodified state."
325 (when undo-in-progress
326 (when diff-hl-timer
327 (cancel-timer diff-hl-timer))
328 (setq diff-hl-timer
329 (run-with-idle-timer 0.01 nil #'diff-hl-after-undo (current-buffer)))))
330
331 (defun diff-hl-after-undo (buffer)
332 (with-current-buffer buffer
333 (unless (buffer-modified-p)
334 (diff-hl-update))))
335
336 (defun diff-hl-diff-goto-hunk ()
337 "Run VC diff command and go to the line corresponding to the current."
338 (interactive)
339 (vc-buffer-sync)
340 (let* ((line (line-number-at-pos))
341 (buffer (current-buffer)))
342 (vc-diff-internal t (vc-deduce-fileset) diff-hl-reference-revision nil t)
343 (vc-exec-after `(if (< (line-number-at-pos (point-max)) 3)
344 (with-current-buffer ,buffer (diff-hl-remove-overlays))
345 (diff-hl-diff-skip-to ,line)
346 (setq vc-sentinel-movepoint (point))))))
347
348 (defun diff-hl-diff-skip-to (line)
349 "In `diff-mode', skip to the hunk and line corresponding to LINE
350 in the source file, or the last line of the hunk above it."
351 (diff-hunk-next)
352 (let (found)
353 (while (and (looking-at diff-hunk-header-re-unified) (not found))
354 (let ((hunk-line (string-to-number (match-string 3)))
355 (len (let ((m (match-string 4)))
356 (if m (string-to-number m) 1))))
357 (if (> line (+ hunk-line len))
358 (diff-hunk-next)
359 (setq found t)
360 (if (< line hunk-line)
361 ;; Retreat to the previous hunk.
362 (forward-line -1)
363 (let ((to-go (1+ (- line hunk-line))))
364 (while (cl-plusp to-go)
365 (forward-line 1)
366 (unless (looking-at "^-")
367 (cl-decf to-go))))))))))
368
369 (defun diff-hl-revert-hunk ()
370 "Revert the diff hunk with changes at or above the point."
371 (interactive)
372 (vc-buffer-sync)
373 (let ((diff-buffer (generate-new-buffer-name "*diff-hl*"))
374 (buffer (current-buffer))
375 (line (save-excursion
376 (unless (diff-hl-hunk-overlay-at (point))
377 (diff-hl-previous-hunk))
378 (line-number-at-pos)))
379 (fileset (vc-deduce-fileset)))
380 (unwind-protect
381 (progn
382 (vc-diff-internal nil fileset diff-hl-reference-revision nil
383 nil diff-buffer)
384 (vc-exec-after
385 `(let (beg-line end-line)
386 (when (eobp)
387 (with-current-buffer ,buffer (diff-hl-remove-overlays))
388 (error "Buffer is up-to-date"))
389 (diff-hl-diff-skip-to ,line)
390 (save-excursion
391 (while (looking-at "[-+]") (forward-line 1))
392 (setq end-line (line-number-at-pos (point)))
393 (unless (eobp) (diff-split-hunk)))
394 (unless (looking-at "[-+]") (forward-line -1))
395 (while (looking-at "[-+]") (forward-line -1))
396 (setq beg-line (line-number-at-pos (point)))
397 (unless (looking-at "@")
398 (forward-line 1)
399 (diff-split-hunk))
400 (let ((wbh (window-body-height)))
401 (if (>= wbh (- end-line beg-line))
402 (recenter (/ (+ wbh (- beg-line end-line) 2) 2))
403 (recenter 1)))
404 (unless (yes-or-no-p (format "Revert current hunk in %s?"
405 ,(cl-caadr fileset)))
406 (error "Revert canceled"))
407 (let ((diff-advance-after-apply-hunk nil))
408 (diff-apply-hunk t))
409 (with-current-buffer ,buffer
410 (save-buffer))
411 (message "Hunk reverted"))))
412 (quit-windows-on diff-buffer))))
413
414 (defun diff-hl-hunk-overlay-at (pos)
415 (cl-loop for o in (overlays-in pos (1+ pos))
416 when (overlay-get o 'diff-hl-hunk)
417 return o))
418
419 (defun diff-hl-next-hunk (&optional backward)
420 "Go to the beginning of the next hunk in the current buffer."
421 (interactive)
422 (let ((pos (save-excursion
423 (catch 'found
424 (while (not (if backward (bobp) (eobp)))
425 (goto-char (if backward
426 (previous-overlay-change (point))
427 (next-overlay-change (point))))
428 (let ((o (diff-hl-hunk-overlay-at (point))))
429 (when (and o (= (overlay-start o) (point)))
430 (throw 'found (overlay-start o)))))))))
431 (if pos
432 (goto-char pos)
433 (error "No further hunks found"))))
434
435 (defun diff-hl-previous-hunk ()
436 "Go to the beginning of the previous hunk in the current buffer."
437 (interactive)
438 (diff-hl-next-hunk t))
439
440 (defvar diff-hl-command-map
441 (let ((map (make-sparse-keymap)))
442 (define-key map "n" 'diff-hl-revert-hunk)
443 (define-key map "[" 'diff-hl-previous-hunk)
444 (define-key map "]" 'diff-hl-next-hunk)
445 map))
446 (fset 'diff-hl-command-map diff-hl-command-map)
447
448 ;;;###autoload
449 (define-minor-mode diff-hl-mode
450 "Toggle VC diff highlighting."
451 :lighter "" :keymap `(([remap vc-diff] . diff-hl-diff-goto-hunk)
452 (,diff-hl-command-prefix . diff-hl-command-map))
453 (if diff-hl-mode
454 (progn
455 (diff-hl-maybe-define-bitmaps)
456 (add-hook 'after-save-hook 'diff-hl-update nil t)
457 (add-hook 'after-change-functions 'diff-hl-edit nil t)
458 (add-hook (if vc-mode
459 ;; Defer until the end of this hook, so that its
460 ;; elements can modify the update behavior.
461 'diff-hl-mode-on-hook
462 ;; If we're only opening the file now,
463 ;; `vc-find-file-hook' likely hasn't run yet, so
464 ;; let's wait until the state information is
465 ;; saved, in order not to fetch it twice.
466 'find-file-hook)
467 'diff-hl-update t t)
468 (add-hook 'vc-checkin-hook 'diff-hl-update nil t)
469 (add-hook 'after-revert-hook 'diff-hl-update nil t)
470 ;; Magit does call `auto-revert-handler', but it usually
471 ;; doesn't do much, because `buffer-stale--default-function'
472 ;; doesn't care about changed VC state.
473 ;; https://github.com/magit/magit/issues/603
474 (add-hook 'magit-revert-buffer-hook 'diff-hl-update nil t)
475 ;; Magit 2+ doesn't do the above and calls this instead,
476 ;; but only when it doesn't call `revert-buffer':
477 (add-hook 'magit-not-reverted-hook 'diff-hl-update nil t)
478 (add-hook 'auto-revert-mode-hook 'diff-hl-update nil t)
479 (add-hook 'text-scale-mode-hook 'diff-hl-define-bitmaps nil t))
480 (remove-hook 'after-save-hook 'diff-hl-update t)
481 (remove-hook 'after-change-functions 'diff-hl-edit t)
482 (remove-hook 'find-file-hook 'diff-hl-update t)
483 (remove-hook 'vc-checkin-hook 'diff-hl-update t)
484 (remove-hook 'after-revert-hook 'diff-hl-update t)
485 (remove-hook 'magit-revert-buffer-hook 'diff-hl-update t)
486 (remove-hook 'magit-not-reverted-hook 'diff-hl-update t)
487 (remove-hook 'auto-revert-mode-hook 'diff-hl-update t)
488 (remove-hook 'text-scale-mode-hook 'diff-hl-define-bitmaps t)
489 (diff-hl-remove-overlays)))
490
491 (when (require 'smartrep nil t)
492 (let (smart-keys)
493 (cl-labels ((scan (map)
494 (map-keymap
495 (lambda (event binding)
496 (if (consp binding)
497 (scan binding)
498 (when (characterp event)
499 (push (cons (string event) binding) smart-keys))))
500 map)))
501 (scan diff-hl-command-map)
502 (smartrep-define-key diff-hl-mode-map diff-hl-command-prefix smart-keys))))
503
504 (defun diff-hl-dir-update ()
505 (dolist (pair (if (vc-dir-marked-files)
506 (vc-dir-marked-only-files-and-states)
507 (vc-dir-child-files-and-states)))
508 (when (eq 'up-to-date (cdr pair))
509 (let ((buffer (find-buffer-visiting (car pair))))
510 (when buffer
511 (with-current-buffer buffer
512 (diff-hl-remove-overlays)))))))
513
514 (define-minor-mode diff-hl-dir-mode
515 "Toggle `diff-hl-mode' integration in a `vc-dir-mode' buffer."
516 :lighter ""
517 (if diff-hl-dir-mode
518 (add-hook 'vc-checkin-hook 'diff-hl-dir-update t t)
519 (remove-hook 'vc-checkin-hook 'diff-hl-dir-update t)))
520
521 ;;;###autoload
522 (defun turn-on-diff-hl-mode ()
523 "Turn on `diff-hl-mode' or `diff-hl-dir-mode' in a buffer if appropriate."
524 (cond
525 (buffer-file-name
526 (diff-hl-mode 1))
527 ((eq major-mode 'vc-dir-mode)
528 (diff-hl-dir-mode 1))))
529
530 ;;;###autoload
531 (define-globalized-minor-mode global-diff-hl-mode diff-hl-mode
532 turn-on-diff-hl-mode :after-hook (diff-hl-global-mode-change))
533
534 (defun diff-hl-global-mode-change ()
535 (unless global-diff-hl-mode
536 (dolist (buf (buffer-list))
537 (with-current-buffer buf
538 (when diff-hl-dir-mode
539 (diff-hl-dir-mode -1))))))
540
541 (provide 'diff-hl)
542
543 ;;; diff-hl.el ends here