]> code.delx.au - gnu-emacs-elpa/blob - swiper.el
Add extra faces for minibuffer highlighting
[gnu-emacs-elpa] / swiper.el
1 ;;; swiper.el --- Isearch with an overview. Oh, man! -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
7 ;; Version: 0.5.1
8 ;; Package-Requires: ((emacs "24.1"))
9 ;; Keywords: matching
10
11 ;; This file is part of GNU Emacs.
12
13 ;; This file 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, or (at your option)
16 ;; any later version.
17
18 ;; This program 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 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27 ;;
28 ;; This package gives an overview of the current regex search
29 ;; candidates. The search regex can be split into groups with a
30 ;; space. Each group is highlighted with a different face.
31 ;;
32 ;; It can double as a quick `regex-builder', although only single
33 ;; lines will be matched.
34 ;;
35 ;; It also provides `ivy-mode': a global minor mode that uses the
36 ;; matching back end of `swiper' for all matching on your system,
37 ;; including file matching. You can use it in place of `ido-mode'
38 ;; (can't have both on at once).
39
40 ;;; Code:
41 (require 'ivy)
42
43 (defgroup swiper nil
44 "`isearch' with an overview."
45 :group 'matching
46 :prefix "swiper-")
47
48 (defface swiper-match-face-1
49 '((t (:inherit isearch-lazy-highlight-face)))
50 "The background face for `swiper' matches.")
51
52 (defface swiper-match-face-2
53 '((t (:inherit isearch)))
54 "Face for `swiper' matches modulo 1.")
55
56 (defface swiper-match-face-3
57 '((t (:inherit match)))
58 "Face for `swiper' matches modulo 2.")
59
60 (defface swiper-match-face-4
61 '((t (:inherit isearch-fail)))
62 "Face for `swiper' matches modulo 3.")
63
64 (defface swiper-minibuffer-match-face-1
65 '((t (:inherit isearch-lazy-highlight-face)))
66 "The background face for `swiper' minibuffer matches.")
67
68 (defface swiper-minibuffer-match-face-2
69 '((t (:inherit isearch)))
70 "Face for `swiper' minibuffer matches modulo 1.")
71
72 (defface swiper-minibuffer-match-face-3
73 '((t (:inherit match)))
74 "Face for `swiper' minibuffer matches modulo 2.")
75
76 (defface swiper-minibuffer-match-face-4
77 '((t (:inherit isearch-fail)))
78 "Face for `swiper' minibuffer matches modulo 3.")
79
80 (defface swiper-line-face
81 '((t (:inherit highlight)))
82 "Face for current `swiper' line.")
83
84 (defcustom swiper-faces '(swiper-match-face-1
85 swiper-match-face-2
86 swiper-match-face-3
87 swiper-match-face-4)
88 "List of `swiper' faces for group matches.")
89
90 (defcustom swiper-minibuffer-faces
91 '(swiper-minibuffer-match-face-1
92 swiper-minibuffer-match-face-2
93 swiper-minibuffer-match-face-3
94 swiper-minibuffer-match-face-4)
95 "List of `swiper' faces for minibuffer group matches.")
96
97 (defcustom swiper-min-highlight 2
98 "Only highlight matches for regexps at least this long."
99 :type 'integer)
100
101 (defvar swiper-map
102 (let ((map (make-sparse-keymap)))
103 (define-key map (kbd "M-q") 'swiper-query-replace)
104 (define-key map (kbd "C-l") 'swiper-recenter-top-bottom)
105 (define-key map (kbd "C-'") 'swiper-avy)
106 map)
107 "Keymap for swiper.")
108
109 (defun swiper-query-replace ()
110 "Start `query-replace' with string to replace from last search string."
111 (interactive)
112 (if (null (window-minibuffer-p))
113 (user-error "Should only be called in the minibuffer through `swiper-map'")
114 (let* ((enable-recursive-minibuffers t)
115 (from (ivy--regex ivy-text))
116 (to (query-replace-read-to from "Query replace" t)))
117 (delete-minibuffer-contents)
118 (ivy-set-action (lambda (_)
119 (with-ivy-window
120 (move-beginning-of-line 1)
121 (perform-replace from to
122 t t nil))))
123 (swiper--cleanup)
124 (exit-minibuffer))))
125
126 (defvar avy-background)
127 (defvar avy-all-windows)
128 (declare-function avy--regex-candidates "ext:avy")
129 (declare-function avy--process "ext:avy")
130 (declare-function avy--overlay-post "ext:avy")
131 (declare-function avy-action-goto "ext:avy")
132
133 ;;;###autoload
134 (defun swiper-avy ()
135 "Jump to one of the current swiper candidates."
136 (interactive)
137 (unless (string= ivy-text "")
138 (with-ivy-window
139 (let* ((avy-all-windows nil)
140 (candidates
141 (avy--regex-candidates
142 (ivy--regex ivy-text)))
143 (avy-background nil)
144 (candidate
145 (avy--process candidates #'avy--overlay-post)))
146 (ivy-quit-and-run
147 (avy-action-goto candidate))))))
148
149 (defun swiper-recenter-top-bottom (&optional arg)
150 "Call (`recenter-top-bottom' ARG)."
151 (interactive "P")
152 (with-ivy-window
153 (recenter-top-bottom arg)))
154
155 (defun swiper-font-lock-ensure ()
156 "Ensure the entired buffer is highlighted."
157 (unless (or (derived-mode-p 'magit-mode)
158 (bound-and-true-p magit-blame-mode)
159 (memq major-mode '(package-menu-mode
160 gnus-summary-mode
161 gnus-article-mode
162 gnus-group-mode
163 emms-playlist-mode erc-mode
164 org-agenda-mode
165 dired-mode
166 jabber-chat-mode
167 elfeed-search-mode
168 fundamental-mode
169 Man-mode
170 woman-mode)))
171 (unless (> (buffer-size) 100000)
172 (if (fboundp 'font-lock-ensure)
173 (font-lock-ensure)
174 (with-no-warnings (font-lock-fontify-buffer))))))
175
176 (defvar swiper--format-spec ""
177 "Store the current candidates format spec.")
178
179 (defvar swiper--width nil
180 "Store the amount of digits needed for the longest line nubmer.")
181
182 (defun swiper--candidates ()
183 "Return a list of this buffer lines."
184 (let ((n-lines (count-lines (point-min) (point-max))))
185 (unless (zerop n-lines)
186 (setq swiper--width (1+ (floor (log n-lines 10))))
187 (setq swiper--format-spec
188 (format "%%-%dd %%s" swiper--width))
189 (let ((line-number 0)
190 candidates)
191 (save-excursion
192 (goto-char (point-min))
193 (swiper-font-lock-ensure)
194 (while (< (point) (point-max))
195 (push (format swiper--format-spec
196 (cl-incf line-number)
197 (buffer-substring
198 (line-beginning-position)
199 (line-end-position)))
200 candidates)
201 (forward-line 1))
202 (nreverse candidates))))))
203
204 (defvar swiper--opoint 1
205 "The point when `swiper' starts.")
206
207 ;;;###autoload
208 (defun swiper (&optional initial-input)
209 "`isearch' with an overview.
210 When non-nil, INITIAL-INPUT is the initial search pattern."
211 (interactive)
212 (swiper--ivy initial-input))
213
214 (defvar swiper--anchor nil
215 "A line number to which the search should be anchored.")
216
217 (defvar swiper--len 0
218 "The last length of input for which an anchoring was made.")
219
220 (defun swiper--init ()
221 "Perform initialization common to both completion methods."
222 (setq swiper--opoint (point))
223 (setq swiper--len 0)
224 (setq swiper--anchor (line-number-at-pos)))
225
226 (defun swiper--re-builder (str)
227 "Transform STR into a swiper regex.
228 This is the regex used in the minibuffer, since the candidates
229 there have line numbers. In the buffer, `ivy--regex' should be used."
230 (cond
231 ((equal str "")
232 "")
233 ((equal str "^")
234 ".")
235 ((string-match "^\\^" str)
236 (setq ivy--old-re "")
237 (let ((re (ivy--regex-plus (substring str 1))))
238 (format "^[0-9][0-9 ]\\{%d\\}%s"
239 swiper--width
240 (if (zerop ivy--subexps)
241 (prog1 (format "\\(%s\\)" re)
242 (setq ivy--subexps 1))
243 re))))
244 (t
245 (ivy--regex-plus str))))
246
247 (defvar swiper-history nil
248 "History for `swiper'.")
249
250 (defun swiper--ivy (&optional initial-input)
251 "`isearch' with an overview using `ivy'.
252 When non-nil, INITIAL-INPUT is the initial search pattern."
253 (interactive)
254 (unless (eq (length (help-function-arglist 'ivy-read)) 4)
255 (warn "You seem to be using the outdated stand-alone \"ivy\" package.
256 Please remove it and update the \"swiper\" package."))
257 (swiper--init)
258 (let ((candidates (swiper--candidates))
259 (preselect (format
260 swiper--format-spec
261 (line-number-at-pos)
262 (buffer-substring-no-properties
263 (line-beginning-position)
264 (line-end-position))))
265 res)
266 (unwind-protect
267 (setq res (ivy-read
268 "Swiper: "
269 candidates
270 :initial-input initial-input
271 :keymap swiper-map
272 :preselect preselect
273 :require-match t
274 :update-fn #'swiper--update-input-ivy
275 :unwind #'swiper--cleanup
276 :re-builder #'swiper--re-builder
277 :history 'swiper-history))
278 (if (null ivy-exit)
279 (goto-char swiper--opoint)
280 (swiper--action res ivy-text)))))
281
282 (defun swiper--ensure-visible ()
283 "Remove overlays hiding point."
284 (let ((overlays (overlays-at (point)))
285 ov expose)
286 (while (setq ov (pop overlays))
287 (if (and (invisible-p (overlay-get ov 'invisible))
288 (setq expose (overlay-get ov 'isearch-open-invisible)))
289 (funcall expose ov)))))
290
291 (defvar swiper--overlays nil
292 "Store overlays.")
293
294 (defun swiper--cleanup ()
295 "Clean up the overlays."
296 (while swiper--overlays
297 (delete-overlay (pop swiper--overlays)))
298 (save-excursion
299 (goto-char (point-min))
300 (isearch-clean-overlays)))
301
302 (defun swiper--update-input-ivy ()
303 "Called when `ivy' input is updated."
304 (with-ivy-window
305 (swiper--cleanup)
306 (let* ((re (ivy--regex ivy-text))
307 (str ivy--current)
308 (num (if (string-match "^[0-9]+" str)
309 (string-to-number (match-string 0 str))
310 0)))
311 (goto-char (point-min))
312 (when (cl-plusp num)
313 (goto-char (point-min))
314 (forward-line (1- num))
315 (if (and (equal ivy-text "")
316 (>= swiper--opoint (line-beginning-position))
317 (<= swiper--opoint (line-end-position)))
318 (goto-char swiper--opoint)
319 (re-search-forward re (line-end-position) t))
320 (isearch-range-invisible (line-beginning-position)
321 (line-end-position))
322 (unless (and (>= (point) (window-start))
323 (<= (point) (window-end (ivy-state-window ivy-last) t)))
324 (recenter)))
325 (swiper--add-overlays re))))
326
327 (defun swiper--add-overlays (re &optional beg end)
328 "Add overlays for RE regexp in visible part of the current buffer.
329 BEG and END, when specified, are the point bounds."
330 (let ((ov (make-overlay
331 (line-beginning-position)
332 (1+ (line-end-position)))))
333 (overlay-put ov 'face 'swiper-line-face)
334 (overlay-put ov 'window (ivy-state-window ivy-last))
335 (push ov swiper--overlays)
336 (let* ((wh (window-height))
337 (beg (or beg (save-excursion
338 (forward-line (- wh))
339 (point))))
340 (end (or end (save-excursion
341 (forward-line wh)
342 (point)))))
343 (when (>= (length re) swiper-min-highlight)
344 (save-excursion
345 (goto-char beg)
346 ;; RE can become an invalid regexp
347 (while (and (ignore-errors (re-search-forward re end t))
348 (> (- (match-end 0) (match-beginning 0)) 0))
349 (let ((i 0))
350 (while (<= i ivy--subexps)
351 (when (match-beginning i)
352 (let ((overlay (make-overlay (match-beginning i)
353 (match-end i)))
354 (face
355 (cond ((zerop ivy--subexps)
356 (cadr swiper-faces))
357 ((zerop i)
358 (car swiper-faces))
359 (t
360 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
361 swiper-faces)))))
362 (push overlay swiper--overlays)
363 (overlay-put overlay 'face face)
364 (overlay-put overlay 'window (ivy-state-window ivy-last))
365 (overlay-put overlay 'priority i)))
366 (cl-incf i)))))))))
367
368 (defun swiper--action (x input)
369 "Goto line X and search for INPUT."
370 (if (null x)
371 (user-error "No candidates")
372 (goto-char (point-min))
373 (forward-line (1- (read x)))
374 (re-search-forward
375 (ivy--regex input) (line-end-position) t)
376 (swiper--ensure-visible)
377 (when (/= (point) swiper--opoint)
378 (unless (and transient-mark-mode mark-active)
379 (push-mark swiper--opoint t)
380 (message "Mark saved where search started")))))
381
382 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
383 (defun swiper-from-isearch ()
384 "Invoke `swiper' from isearch."
385 (interactive)
386 (let ((query (if isearch-regexp
387 isearch-string
388 (regexp-quote isearch-string))))
389 (isearch-exit)
390 (swiper query)))
391
392 (defvar swiper-multi-buffers nil
393 "Store the current list of buffers.")
394
395 (defvar swiper-multi-candidates nil
396 "Store the list of candidates for `swiper-multi'.")
397
398 (defun swiper-multi-prompt ()
399 (format "Buffers (%s): "
400 (mapconcat #'identity swiper-multi-buffers ", ")))
401
402 (defun swiper-multi ()
403 "Select one or more buffers.
404 Run `swiper' for those buffers."
405 (interactive)
406 (setq swiper-multi-buffers nil)
407 (setq swiper-multi-candidates nil)
408 (ivy-read (swiper-multi-prompt)
409 'internal-complete-buffer
410 :action 'swiper-multi-action-1)
411 (ivy-read "Swiper: " swiper-multi-candidates
412 :action 'swiper-multi-action-2
413 :unwind #'swiper--cleanup))
414
415 (defun swiper-multi-action-1 (x)
416 (if (member x swiper-multi-buffers)
417 (progn
418 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
419 (unless (equal x "")
420 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
421 (let ((prompt (swiper-multi-prompt)))
422 (setf (ivy-state-prompt ivy-last) prompt)
423 (setq ivy--prompt (concat "%-4d " prompt)))
424 (cond ((memq this-command '(ivy-done
425 ivy-alt-done
426 ivy-immediate-done))
427 (let ((ww (window-width)))
428 (dolist (buf swiper-multi-buffers)
429 (with-current-buffer buf
430 (setq swiper-multi-candidates
431 (append
432 (mapcar
433 (lambda (s)
434 (setq s (concat s " "))
435 (let ((len (length s)))
436 (put-text-property
437 (1- len) len 'display
438 (concat
439 (make-string
440 (max
441 (- ww
442 (string-width s)
443 (length (buffer-name))
444 1)
445 0)
446 ?\ )
447 (buffer-name))
448 s)
449 s))
450 (swiper--candidates))
451 swiper-multi-candidates))))))
452 ((eq this-command 'ivy-call)
453 (delete-minibuffer-contents))))
454
455 (defun swiper-multi-action-2 (x)
456 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
457 (with-ivy-window
458 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
459 (switch-to-buffer (match-string 1 buf-space))
460 (goto-char (point-min))
461 (forward-line (1- (read x)))
462 (re-search-forward
463 (ivy--regex ivy-text)
464 (line-end-position) t)
465 (unless (eq ivy-exit 'done)
466 (swiper--cleanup)
467 (swiper--add-overlays (ivy--regex ivy-text)))))))
468
469 (provide 'swiper)
470
471 ;;; swiper.el ends here