]> code.delx.au - gnu-emacs-elpa/blob - diff-hl.el
Check if the original Dired buffer is still alive
[gnu-emacs-elpa] / diff-hl.el
1 ;;; diff-hl.el --- Highlight uncommitted changes -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2012-2014 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.6.0
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 left side of
29 ;; the window (using the fringe, by default), allows you to jump
30 ;; between 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
64 (defgroup diff-hl nil
65 "VC diff highlighting on the side of a window"
66 :group 'vc)
67
68 (defface diff-hl-insert
69 '((default :inherit diff-added)
70 (((class color)) :foreground "green4"))
71 "Face used to highlight inserted lines."
72 :group 'diff-hl)
73
74 (defface diff-hl-delete
75 '((default :inherit diff-removed)
76 (((class color)) :foreground "red3"))
77 "Face used to highlight deleted lines."
78 :group 'diff-hl)
79
80 (defface diff-hl-change
81 '((default :foreground "blue3")
82 (((class color) (min-colors 88) (background light))
83 :background "#ddddff")
84 (((class color) (min-colors 88) (background dark))
85 :background "#333355"))
86 "Face used to highlight changed lines."
87 :group 'diff-hl)
88
89 (defcustom diff-hl-command-prefix (kbd "C-x v")
90 "The prefix for all `diff-hl' commands."
91 :group 'diff-hl
92 :type 'string)
93
94 (defcustom diff-hl-draw-borders t
95 "Non-nil to draw borders around fringe indicators."
96 :group 'diff-hl
97 :type 'boolean)
98
99 (defcustom diff-hl-highlight-function 'diff-hl-highlight-on-fringe
100 "Function to highlight the current line. Its arguments are
101 overlay, change type and position within a hunk."
102 :group 'diff-hl
103 :type 'function)
104
105 (defcustom diff-hl-fringe-bmp-function 'diff-hl-fringe-bmp-from-pos
106 "Function to choose the fringe bitmap for a given change type
107 and position within a hunk. Should accept two arguments."
108 :group 'diff-hl
109 :type '(choice (const diff-hl-fringe-bmp-from-pos)
110 (const diff-hl-fringe-bmp-from-type)
111 function))
112
113 (defcustom diff-hl-fringe-face-function 'diff-hl-fringe-face-from-type
114 "Function to choose the fringe face for a given change type
115 and position within a hunk. Should accept two arguments."
116 :group 'diff-hl
117 :type 'function)
118
119 (defvar diff-hl-reference-revision nil
120 "Revision to diff against. nil means the most recent one.")
121
122 (defun diff-hl-define-bitmaps ()
123 (let* ((scale (if (and (boundp 'text-scale-mode-amount)
124 (numberp text-scale-mode-amount))
125 (expt text-scale-mode-step text-scale-mode-amount)
126 1))
127 (spacing (or (and (display-graphic-p) (default-value 'line-spacing)) 0))
128 (h (+ (ceiling (* (frame-char-height) scale))
129 (if (floatp spacing)
130 (truncate (* (frame-char-height) spacing))
131 spacing)))
132 (w (frame-parameter nil 'left-fringe))
133 (middle (make-vector h (expt 2 (1- w))))
134 (ones (1- (expt 2 w)))
135 (top (copy-sequence middle))
136 (bottom (copy-sequence middle))
137 (single (copy-sequence middle)))
138 (aset top 0 ones)
139 (aset bottom (1- h) ones)
140 (aset single 0 ones)
141 (aset single (1- h) ones)
142 (define-fringe-bitmap 'diff-hl-bmp-top top h w 'top)
143 (define-fringe-bitmap 'diff-hl-bmp-middle middle h w 'center)
144 (define-fringe-bitmap 'diff-hl-bmp-bottom bottom h w 'bottom)
145 (define-fringe-bitmap 'diff-hl-bmp-single single h w 'top)
146 (let* ((w2 (* (/ w 2) 2))
147 (delete-row (- (expt 2 (1- w2)) 2))
148 (middle-pos (1- (/ w2 2)))
149 (middle-bit (expt 2 middle-pos))
150 (insert-bmp (make-vector w2 (* 3 middle-bit))))
151 (define-fringe-bitmap 'diff-hl-bmp-delete (make-vector 2 delete-row) w2 w2)
152 (aset insert-bmp 0 0)
153 (aset insert-bmp middle-pos delete-row)
154 (aset insert-bmp (1+ middle-pos) delete-row)
155 (aset insert-bmp (1- w2) 0)
156 (define-fringe-bitmap 'diff-hl-bmp-insert insert-bmp w2 w2)
157 )))
158
159 (defun diff-hl-maybe-define-bitmaps ()
160 (when (window-system) ;; No fringes in the console.
161 (unless (fringe-bitmap-p 'diff-hl-bmp-empty)
162 (diff-hl-define-bitmaps)
163 (define-fringe-bitmap 'diff-hl-bmp-empty [0] 1 1 'center))))
164
165 (defvar diff-hl-spec-cache (make-hash-table :test 'equal))
166
167 (defun diff-hl-fringe-spec (type pos)
168 (let* ((key (list type pos diff-hl-fringe-bmp-function))
169 (val (gethash key diff-hl-spec-cache)))
170 (unless val
171 (let* ((face-sym (funcall diff-hl-fringe-face-function type pos))
172 (bmp-sym (funcall diff-hl-fringe-bmp-function type pos)))
173 (setq val (propertize " " 'display `((left-fringe ,bmp-sym ,face-sym))))
174 (puthash key val diff-hl-spec-cache)))
175 val))
176
177 (defun diff-hl-fringe-face-from-type (type _pos)
178 (intern (format "diff-hl-%s" type)))
179
180 (defun diff-hl-fringe-bmp-from-pos (_type pos)
181 (intern (format "diff-hl-bmp-%s" pos)))
182
183 (defun diff-hl-fringe-bmp-from-type (type _pos)
184 (cl-case type
185 (unknown 'question-mark)
186 (change 'exclamation-mark)
187 (ignored 'filled-square)
188 (t (intern (format "diff-hl-bmp-%s" type)))))
189
190 (defvar vc-svn-diff-switches)
191
192 (defmacro diff-hl-with-diff-switches (body)
193 `(let ((vc-git-diff-switches nil)
194 (vc-hg-diff-switches nil)
195 (vc-svn-diff-switches nil)
196 (vc-diff-switches '("-U0"))
197 (vc-disable-async-diff t))
198 ,body))
199
200 (defun diff-hl-changes ()
201 (let* ((file buffer-file-name)
202 (backend (vc-backend file)))
203 (when backend
204 (let ((state (vc-state file backend)))
205 (cond
206 ((or (eq state 'edited)
207 (and (eq state 'up-to-date)
208 ;; VC state is stale in after-revert-hook.
209 (or revert-buffer-in-progress-p
210 ;; Diffing against an older revision.
211 diff-hl-reference-revision)))
212 (let* ((buf-name " *diff-hl* ")
213 diff-auto-refine-mode
214 res)
215 (diff-hl-with-diff-switches
216 (vc-call-backend backend 'diff (list file)
217 diff-hl-reference-revision nil
218 buf-name))
219 (with-current-buffer buf-name
220 (goto-char (point-min))
221 (unless (eobp)
222 (diff-beginning-of-hunk t)
223 (while (looking-at diff-hunk-header-re-unified)
224 (let ((line (string-to-number (match-string 3)))
225 (len (let ((m (match-string 4)))
226 (if m (string-to-number m) 1)))
227 (beg (point)))
228 (diff-end-of-hunk)
229 (let* ((inserts (diff-count-matches "^\\+" beg (point)))
230 (deletes (diff-count-matches "^-" beg (point)))
231 (type (cond ((zerop deletes) 'insert)
232 ((zerop inserts) 'delete)
233 (t 'change))))
234 (when (eq type 'delete)
235 (setq len 1)
236 (cl-incf line))
237 (push (list line len type) res))))))
238 (nreverse res)))
239 ((eq state 'added)
240 `((1 ,(line-number-at-pos (point-max)) insert)))
241 ((eq state 'removed)
242 `((1 ,(line-number-at-pos (point-max)) delete))))))))
243
244 (defun diff-hl-update ()
245 (let ((changes (diff-hl-changes))
246 (current-line 1))
247 (diff-hl-remove-overlays)
248 (save-excursion
249 (goto-char (point-min))
250 (dolist (c changes)
251 (cl-destructuring-bind (line len type) c
252 (forward-line (- line current-line))
253 (setq current-line line)
254 (let ((hunk-beg (point)))
255 (while (cl-plusp len)
256 (diff-hl-add-highlighting
257 type
258 (cond
259 ((not diff-hl-draw-borders) 'empty)
260 ((and (= len 1) (= line current-line)) 'single)
261 ((= len 1) 'bottom)
262 ((= line current-line) 'top)
263 (t 'middle)))
264 (forward-line 1)
265 (cl-incf current-line)
266 (cl-decf len))
267 (let ((h (make-overlay hunk-beg (point)))
268 (hook '(diff-hl-overlay-modified)))
269 (overlay-put h 'diff-hl t)
270 (overlay-put h 'diff-hl-hunk t)
271 (overlay-put h 'modification-hooks hook)
272 (overlay-put h 'insert-in-front-hooks hook)
273 (overlay-put h 'insert-behind-hooks hook))))))))
274
275 (defun diff-hl-add-highlighting (type shape)
276 (let ((o (make-overlay (point) (point))))
277 (overlay-put o 'diff-hl t)
278 (funcall diff-hl-highlight-function o type shape)
279 o))
280
281 (defun diff-hl-highlight-on-fringe (ovl type shape)
282 (overlay-put ovl 'before-string (diff-hl-fringe-spec type shape)))
283
284 (defun diff-hl-remove-overlays ()
285 (dolist (o (overlays-in (point-min) (point-max)))
286 (when (overlay-get o 'diff-hl) (delete-overlay o))))
287
288 (defun diff-hl-overlay-modified (ov after-p _beg _end &optional _length)
289 "Delete the hunk overlay and all our line overlays inside it."
290 (unless after-p
291 (when (overlay-buffer ov)
292 (save-restriction
293 (narrow-to-region (overlay-start ov) (overlay-end ov))
294 (diff-hl-remove-overlays))
295 (delete-overlay ov))))
296
297 (defvar diff-hl-timer nil)
298
299 (defun diff-hl-edit (_beg _end _len)
300 "DTRT when we've `undo'-ne the buffer into unmodified state."
301 (when undo-in-progress
302 (when diff-hl-timer
303 (cancel-timer diff-hl-timer))
304 (setq diff-hl-timer
305 (run-with-idle-timer 0.01 nil #'diff-hl-after-undo (current-buffer)))))
306
307 (defun diff-hl-after-undo (buffer)
308 (with-current-buffer buffer
309 (unless (buffer-modified-p)
310 (diff-hl-update))))
311
312 (defun diff-hl-diff-goto-hunk ()
313 "Run VC diff command and go to the line corresponding to the current."
314 (interactive)
315 (vc-buffer-sync)
316 (let* ((line (line-number-at-pos))
317 (buffer (current-buffer)))
318 (vc-diff-internal t (vc-deduce-fileset) diff-hl-reference-revision nil t)
319 (vc-exec-after `(if (< (line-number-at-pos (point-max)) 3)
320 (with-current-buffer ,buffer (diff-hl-remove-overlays))
321 (diff-hl-diff-skip-to ,line)
322 (setq vc-sentinel-movepoint (point))))))
323
324 (defun diff-hl-diff-skip-to (line)
325 "In `diff-mode', skip to the hunk and line corresponding to LINE
326 in the source file, or the last line of the hunk above it."
327 (diff-hunk-next)
328 (let (found)
329 (while (and (looking-at diff-hunk-header-re-unified) (not found))
330 (let ((hunk-line (string-to-number (match-string 3)))
331 (len (let ((m (match-string 4)))
332 (if m (string-to-number m) 1))))
333 (if (> line (+ hunk-line len))
334 (diff-hunk-next)
335 (setq found t)
336 (if (< line hunk-line)
337 ;; Retreat to the previous hunk.
338 (forward-line -1)
339 (let ((to-go (1+ (- line hunk-line))))
340 (while (cl-plusp to-go)
341 (forward-line 1)
342 (unless (looking-at "^-")
343 (cl-decf to-go))))))))))
344
345 (defun diff-hl-revert-hunk ()
346 "Revert the diff hunk with changes at or above the point."
347 (interactive)
348 (vc-buffer-sync)
349 (let ((diff-buffer (generate-new-buffer-name "*diff-hl*"))
350 (buffer (current-buffer))
351 (line (save-excursion
352 (unless (diff-hl-hunk-overlay-at (point))
353 (diff-hl-previous-hunk))
354 (line-number-at-pos)))
355 (fileset (vc-deduce-fileset)))
356 (unwind-protect
357 (progn
358 (vc-diff-internal nil fileset diff-hl-reference-revision nil
359 nil diff-buffer)
360 (vc-exec-after
361 `(let (beg-line end-line)
362 (when (eobp)
363 (with-current-buffer ,buffer (diff-hl-remove-overlays))
364 (error "Buffer is up-to-date"))
365 (diff-hl-diff-skip-to ,line)
366 (save-excursion
367 (while (looking-at "[-+]") (forward-line 1))
368 (setq end-line (line-number-at-pos (point)))
369 (unless (eobp) (diff-split-hunk)))
370 (unless (looking-at "[-+]") (forward-line -1))
371 (while (looking-at "[-+]") (forward-line -1))
372 (setq beg-line (line-number-at-pos (point)))
373 (unless (looking-at "@")
374 (forward-line 1)
375 (diff-split-hunk))
376 (let ((wbh (window-body-height)))
377 (if (>= wbh (- end-line beg-line))
378 (recenter (/ (+ wbh (- beg-line end-line) 2) 2))
379 (recenter 1)))
380 (unless (yes-or-no-p (format "Revert current hunk in %s?"
381 ,(cl-caadr fileset)))
382 (error "Revert canceled"))
383 (let ((diff-advance-after-apply-hunk nil))
384 (diff-apply-hunk t))
385 (with-current-buffer ,buffer
386 (save-buffer))
387 (message "Hunk reverted"))))
388 (quit-windows-on diff-buffer))))
389
390 (defun diff-hl-hunk-overlay-at (pos)
391 (cl-loop for o in (overlays-in pos (1+ pos))
392 when (overlay-get o 'diff-hl-hunk)
393 return o))
394
395 (defun diff-hl-next-hunk (&optional backward)
396 "Go to the beginning of the next hunk in the current buffer."
397 (interactive)
398 (let ((pos (save-excursion
399 (catch 'found
400 (while (not (if backward (bobp) (eobp)))
401 (goto-char (if backward
402 (previous-overlay-change (point))
403 (next-overlay-change (point))))
404 (let ((o (diff-hl-hunk-overlay-at (point))))
405 (when (and o (= (overlay-start o) (point)))
406 (throw 'found (overlay-start o)))))))))
407 (if pos
408 (goto-char pos)
409 (error "No further hunks found"))))
410
411 (defun diff-hl-previous-hunk ()
412 "Go to the beginning of the previous hunk in the current buffer."
413 (interactive)
414 (diff-hl-next-hunk t))
415
416 (define-prefix-command 'diff-hl-command-map)
417
418 (let ((map diff-hl-command-map))
419 (define-key map "n" 'diff-hl-revert-hunk)
420 (define-key map "[" 'diff-hl-previous-hunk)
421 (define-key map "]" 'diff-hl-next-hunk)
422 map)
423
424 ;;;###autoload
425 (define-minor-mode diff-hl-mode
426 "Toggle VC diff highlighting."
427 :lighter "" :keymap `(([remap vc-diff] . diff-hl-diff-goto-hunk)
428 (,diff-hl-command-prefix . diff-hl-command-map))
429 (if diff-hl-mode
430 (progn
431 (diff-hl-maybe-define-bitmaps)
432 (add-hook 'after-save-hook 'diff-hl-update nil t)
433 (add-hook 'after-change-functions 'diff-hl-edit nil t)
434 (add-hook (if vc-mode
435 ;; Defer until the end of this hook, so that its
436 ;; elements can modify the update behavior.
437 'diff-hl-mode-on-hook
438 ;; If we're only opening the file now,
439 ;; `vc-find-file-hook' likely hasn't run yet, so
440 ;; let's wait until the state information is
441 ;; saved, in order not to fetch it twice.
442 'find-file-hook)
443 'diff-hl-update t t)
444 (add-hook 'vc-checkin-hook 'diff-hl-update nil t)
445 (add-hook 'after-revert-hook 'diff-hl-update nil t)
446 ;; Magit does call `auto-revert-handler', but it usually
447 ;; doesn't do much, because `buffer-stale--default-function'
448 ;; doesn't care about changed VC state.
449 ;; https://github.com/magit/magit/issues/603
450 (add-hook 'magit-revert-buffer-hook 'diff-hl-update nil t)
451 (add-hook 'text-scale-mode-hook 'diff-hl-define-bitmaps nil t))
452 (remove-hook 'after-save-hook 'diff-hl-update t)
453 (remove-hook 'after-change-functions 'diff-hl-edit t)
454 (remove-hook 'find-file-hook 'diff-hl-update t)
455 (remove-hook 'vc-checkin-hook 'diff-hl-update t)
456 (remove-hook 'after-revert-hook 'diff-hl-update t)
457 (remove-hook 'magit-revert-buffer-hook 'diff-hl-update t)
458 (remove-hook 'text-scale-mode-hook 'diff-hl-define-bitmaps t)
459 (diff-hl-remove-overlays)))
460
461 (when (require 'smartrep nil t)
462 (let (smart-keys)
463 (cl-labels ((scan (map)
464 (map-keymap
465 (lambda (event binding)
466 (if (consp binding)
467 (scan binding)
468 (when (characterp event)
469 (push (cons (string event) binding) smart-keys))))
470 map)))
471 (scan diff-hl-command-map)
472 (smartrep-define-key diff-hl-mode-map diff-hl-command-prefix smart-keys))))
473
474 (defun diff-hl-dir-update ()
475 (dolist (pair (if (vc-dir-marked-files)
476 (vc-dir-marked-only-files-and-states)
477 (vc-dir-child-files-and-states)))
478 (when (eq 'up-to-date (cdr pair))
479 (let ((buffer (find-buffer-visiting (car pair))))
480 (when buffer
481 (with-current-buffer buffer
482 (diff-hl-remove-overlays)))))))
483
484 (define-minor-mode diff-hl-dir-mode
485 "Toggle `diff-hl-mode' integration in a `vc-dir-mode' buffer."
486 :lighter ""
487 (if diff-hl-dir-mode
488 (add-hook 'vc-checkin-hook 'diff-hl-dir-update t t)
489 (remove-hook 'vc-checkin-hook 'diff-hl-dir-update t)))
490
491 ;;;###autoload
492 (defun turn-on-diff-hl-mode ()
493 "Turn on `diff-hl-mode' or `diff-hl-dir-mode' in a buffer if appropriate."
494 (cond
495 (buffer-file-name
496 (diff-hl-mode 1))
497 ((eq major-mode 'vc-dir-mode)
498 (diff-hl-dir-mode 1))))
499
500 ;;;###autoload
501 (define-globalized-minor-mode global-diff-hl-mode diff-hl-mode
502 turn-on-diff-hl-mode :after-hook (diff-hl-global-mode-change))
503
504 (defun diff-hl-global-mode-change ()
505 (unless global-diff-hl-mode
506 (dolist (buf (buffer-list))
507 (with-current-buffer buf
508 (when diff-hl-dir-mode
509 (diff-hl-dir-mode -1))))))
510
511 (provide 'diff-hl)
512
513 ;;; diff-hl.el ends here