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