1 ;;; swiper.el --- Isearch with an overview. Oh, man! -*- lexical-binding: t -*-
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
8 ;; Package-Requires: ((emacs "24.1"))
11 ;; This file is part of GNU Emacs.
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)
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.
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
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.
32 ;; It can double as a quick `regex-builder', although only single
33 ;; lines will be matched.
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).
44 "`isearch' with an overview."
48 (defface swiper-match-face-1
49 '((t (:inherit isearch-lazy-highlight-face)))
50 "The background face for `swiper' matches.")
52 (defface swiper-match-face-2
53 '((t (:inherit isearch)))
54 "Face for `swiper' matches modulo 1.")
56 (defface swiper-match-face-3
57 '((t (:inherit match)))
58 "Face for `swiper' matches modulo 2.")
60 (defface swiper-match-face-4
61 '((t (:inherit isearch-fail)))
62 "Face for `swiper' matches modulo 3.")
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)
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.")
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.")
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.")
93 (defface swiper-line-face
94 '((t (:inherit highlight)))
95 "Face for current `swiper' line.")
97 (defcustom swiper-faces '(swiper-match-face-1
101 "List of `swiper' faces for group matches.")
103 (defcustom swiper-min-highlight 2
104 "Only highlight matches for regexps at least this long."
108 (let ((map (make-sparse-keymap)))
109 (define-key map (kbd "M-q") 'swiper-query-replace)
110 (define-key map (kbd "C-l") 'swiper-recenter-top-bottom)
111 (define-key map (kbd "C-'") 'swiper-avy)
113 "Keymap for swiper.")
115 (defun swiper-query-replace ()
116 "Start `query-replace' with string to replace from last search string."
118 (if (null (window-minibuffer-p))
119 (user-error "Should only be called in the minibuffer through `swiper-map'")
120 (let* ((enable-recursive-minibuffers t)
121 (from (ivy--regex ivy-text))
122 (to (query-replace-read-to from "Query replace" t)))
123 (delete-minibuffer-contents)
124 (ivy-set-action (lambda (_)
126 (move-beginning-of-line 1)
127 (perform-replace from to
132 (defvar avy-background)
133 (defvar avy-all-windows)
134 (declare-function avy--regex-candidates "ext:avy")
135 (declare-function avy--process "ext:avy")
136 (declare-function avy--overlay-post "ext:avy")
137 (declare-function avy-action-goto "ext:avy")
141 "Jump to one of the current swiper candidates."
143 (unless (string= ivy-text "")
144 (let* ((avy-all-windows nil)
147 (avy--regex-candidates
148 (ivy--regex ivy-text)))
151 (narrow-to-region (window-start) (window-end))
152 (goto-char (point-min))
155 (while (< (point) (point-max))
156 (push (cons (1+ (point))
161 (candidate (unwind-protect
163 (avy--make-backgrounds
164 (append (avy-window-list)
165 (list (ivy-state-window ivy-last))))
166 (if (eq avy-style 'de-bruijn)
169 (avy-read (avy-tree candidates avy-keys)
171 #'avy--remove-leading-chars))
174 (if (window-minibuffer-p (cdr candidate))
176 (ivy-set-index (- (line-number-at-pos (car candidate)) 2))
181 (avy-action-goto (caar candidate)))))))
183 (defun swiper-recenter-top-bottom (&optional arg)
184 "Call (`recenter-top-bottom' ARG)."
187 (recenter-top-bottom arg)))
189 (defun swiper-font-lock-ensure ()
190 "Ensure the entired buffer is highlighted."
191 (unless (or (derived-mode-p 'magit-mode)
192 (bound-and-true-p magit-blame-mode)
193 (memq major-mode '(package-menu-mode
197 emms-playlist-mode erc-mode
208 (unless (> (buffer-size) 100000)
209 (if (fboundp 'font-lock-ensure)
211 (with-no-warnings (font-lock-fontify-buffer))))))
213 (defvar swiper--format-spec ""
214 "Store the current candidates format spec.")
216 (defvar swiper--width nil
217 "Store the amount of digits needed for the longest line nubmer.")
219 (defvar swiper-use-visual-line nil
220 "When non-nil, use `line-move' instead of `forward-line'.")
222 (defun swiper--candidates ()
223 "Return a list of this buffer lines."
224 (setq swiper-use-visual-line
225 (and (not (eq major-mode 'org-mode))
227 (< (buffer-size) 20000)))
228 (let ((n-lines (count-lines (point-min) (point-max))))
229 (unless (zerop n-lines)
230 (setq swiper--width (1+ (floor (log n-lines 10))))
231 (setq swiper--format-spec
232 (format "%%-%dd " swiper--width))
233 (let ((line-number 0)
234 (advancer (if swiper-use-visual-line
235 (lambda (arg) (line-move arg t))
239 (goto-char (point-min))
240 (swiper-font-lock-ensure)
241 (while (< (point) (point-max))
242 (let ((str (concat " " (buffer-substring
244 (if swiper-use-visual-line
248 (line-end-position))))))
249 (put-text-property 0 1 'display
250 (format swiper--format-spec
251 (cl-incf line-number))
253 (push str candidates))
254 (funcall advancer 1))
255 (nreverse candidates))))))
257 (defvar swiper--opoint 1
258 "The point when `swiper' starts.")
261 (defun swiper (&optional initial-input)
262 "`isearch' with an overview.
263 When non-nil, INITIAL-INPUT is the initial search pattern."
265 (swiper--ivy initial-input))
267 (defvar swiper--anchor nil
268 "A line number to which the search should be anchored.")
270 (defvar swiper--len 0
271 "The last length of input for which an anchoring was made.")
273 (defun swiper--init ()
274 "Perform initialization common to both completion methods."
275 (setq swiper--opoint (point))
277 (setq swiper--anchor (line-number-at-pos)))
279 (defun swiper--re-builder (str)
280 "Transform STR into a swiper regex.
281 This is the regex used in the minibuffer, since the candidates
282 there have line numbers. In the buffer, `ivy--regex' should be used."
288 ((string-match "^\\^" str)
289 (setq ivy--old-re "")
290 (let ((re (ivy--regex-plus (substring str 1))))
291 (format "^[0-9][0-9 ]\\{%d\\}%s"
293 (if (zerop ivy--subexps)
294 (prog1 (format "\\(%s\\)" re)
295 (setq ivy--subexps 1))
298 (ivy--regex-plus str))))
300 (defvar swiper-history nil
301 "History for `swiper'.")
303 (defun swiper--ivy (&optional initial-input)
304 "`isearch' with an overview using `ivy'.
305 When non-nil, INITIAL-INPUT is the initial search pattern."
308 (let ((candidates (swiper--candidates))
309 (preselect (buffer-substring-no-properties
310 (line-beginning-position)
311 (line-end-position)))
312 (minibuffer-allow-text-properties t)
318 :initial-input initial-input
322 :update-fn #'swiper--update-input-ivy
323 :unwind #'swiper--cleanup
324 :re-builder #'swiper--re-builder
325 :history 'swiper-history))
327 (goto-char swiper--opoint)
328 (swiper--action res ivy-text)))))
330 (defun swiper--ensure-visible ()
331 "Remove overlays hiding point."
332 (let ((overlays (overlays-at (point)))
334 (while (setq ov (pop overlays))
335 (if (and (invisible-p (overlay-get ov 'invisible))
336 (setq expose (overlay-get ov 'isearch-open-invisible)))
337 (funcall expose ov)))))
339 (defvar swiper--overlays nil
342 (defun swiper--cleanup ()
343 "Clean up the overlays."
344 (while swiper--overlays
345 (delete-overlay (pop swiper--overlays)))
347 (goto-char (point-min))
348 (isearch-clean-overlays)))
350 (defun swiper--update-input-ivy ()
351 "Called when `ivy' input is updated."
354 (when (> (length ivy--current) 0)
355 (let* ((re (funcall ivy--regex-function ivy-text))
356 (re (if (stringp re) re (caar re)))
357 (str (get-text-property 0 'display ivy--current))
358 (num (if (string-match "^[0-9]+" str)
359 (string-to-number (match-string 0 str))
361 (goto-char (point-min))
363 (goto-char (point-min))
364 (if swiper-use-visual-line
366 (forward-line (1- num)))
367 (if (and (equal ivy-text "")
368 (>= swiper--opoint (line-beginning-position))
369 (<= swiper--opoint (line-end-position)))
370 (goto-char swiper--opoint)
371 (re-search-forward re (line-end-position) t))
372 (isearch-range-invisible (line-beginning-position)
374 (unless (and (>= (point) (window-start))
375 (<= (point) (window-end (ivy-state-window ivy-last) t)))
377 (swiper--add-overlays re)))))
379 (defun swiper--add-overlays (re &optional beg end)
380 "Add overlays for RE regexp in visible part of the current buffer.
381 BEG and END, when specified, are the point bounds."
382 (let ((ov (if visual-line-mode
385 (beginning-of-visual-line)
391 (line-beginning-position)
392 (1+ (line-end-position))))))
393 (overlay-put ov 'face 'swiper-line-face)
394 (overlay-put ov 'window (ivy-state-window ivy-last))
395 (push ov swiper--overlays)
396 (let* ((wh (window-height))
397 (beg (or beg (save-excursion
398 (forward-line (- wh))
400 (end (or end (save-excursion
403 (when (>= (length re) swiper-min-highlight)
406 ;; RE can become an invalid regexp
407 (while (and (ignore-errors (re-search-forward re end t))
408 (> (- (match-end 0) (match-beginning 0)) 0))
410 (while (<= i ivy--subexps)
411 (when (match-beginning i)
412 (let ((overlay (make-overlay (match-beginning i)
415 (cond ((zerop ivy--subexps)
420 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
422 (push overlay swiper--overlays)
423 (overlay-put overlay 'face face)
424 (overlay-put overlay 'window (ivy-state-window ivy-last))
425 (overlay-put overlay 'priority i)))
428 (defun swiper--action (x input)
429 "Goto line X and search for INPUT."
431 (user-error "No candidates")
432 (goto-char (point-min))
433 (funcall (if swiper-use-visual-line
436 (1- (read (get-text-property 0 'display x))))
438 (ivy--regex input) (line-end-position) t)
439 (swiper--ensure-visible)
440 (when (/= (point) swiper--opoint)
441 (unless (and transient-mark-mode mark-active)
442 (push-mark swiper--opoint t)
443 (message "Mark saved where search started")))))
445 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
446 (defun swiper-from-isearch ()
447 "Invoke `swiper' from isearch."
449 (let ((query (if isearch-regexp
451 (regexp-quote isearch-string))))
455 (defvar swiper-multi-buffers nil
456 "Store the current list of buffers.")
458 (defvar swiper-multi-candidates nil
459 "Store the list of candidates for `swiper-multi'.")
461 (defun swiper-multi-prompt ()
462 (format "Buffers (%s): "
463 (mapconcat #'identity swiper-multi-buffers ", ")))
465 (defun swiper-multi ()
466 "Select one or more buffers.
467 Run `swiper' for those buffers."
469 (setq swiper-multi-buffers nil)
470 (setq swiper-multi-candidates nil)
471 (ivy-read (swiper-multi-prompt)
472 'internal-complete-buffer
473 :action 'swiper-multi-action-1)
474 (ivy-read "Swiper: " swiper-multi-candidates
475 :action 'swiper-multi-action-2
476 :unwind #'swiper--cleanup))
478 (defun swiper-multi-action-1 (x)
479 (if (member x swiper-multi-buffers)
481 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
483 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
484 (let ((prompt (swiper-multi-prompt)))
485 (setf (ivy-state-prompt ivy-last) prompt)
486 (setq ivy--prompt (concat "%-4d " prompt)))
487 (cond ((memq this-command '(ivy-done
490 (let ((ww (window-width)))
491 (dolist (buf swiper-multi-buffers)
492 (with-current-buffer buf
493 (setq swiper-multi-candidates
497 (setq s (concat s " "))
498 (let ((len (length s)))
500 (1- len) len 'display
506 (length (buffer-name))
513 (swiper--candidates))
514 swiper-multi-candidates))))))
515 ((eq this-command 'ivy-call)
516 (delete-minibuffer-contents))))
518 (defun swiper-multi-action-2 (x)
519 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
521 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
522 (switch-to-buffer (match-string 1 buf-space))
523 (goto-char (point-min))
524 (forward-line (1- (read x)))
526 (ivy--regex ivy-text)
527 (line-end-position) t)
528 (unless (eq ivy-exit 'done)
530 (swiper--add-overlays (ivy--regex ivy-text)))))))
534 ;;; swiper.el ends here