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 '((t (:inherit isearch-lazy-highlight-face)))
66 "The background face for `swiper' minibuffer matches.")
68 (defface swiper-minibuffer-match-face-2
69 '((t (:inherit isearch)))
70 "Face for `swiper' minibuffer matches modulo 1.")
72 (defface swiper-minibuffer-match-face-3
73 '((t (:inherit match)))
74 "Face for `swiper' minibuffer matches modulo 2.")
76 (defface swiper-minibuffer-match-face-4
77 '((t (:inherit isearch-fail)))
78 "Face for `swiper' minibuffer matches modulo 3.")
80 (defface swiper-line-face
81 '((t (:inherit highlight)))
82 "Face for current `swiper' line.")
84 (defcustom swiper-faces '(swiper-match-face-1
88 "List of `swiper' faces for group matches.")
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.")
97 (defcustom swiper-min-highlight 2
98 "Only highlight matches for regexps at least this long."
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)
107 "Keymap for swiper.")
109 (defun swiper-query-replace ()
110 "Start `query-replace' with string to replace from last search string."
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 (_)
120 (move-beginning-of-line 1)
121 (perform-replace from to
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")
135 "Jump to one of the current swiper candidates."
137 (unless (string= ivy-text "")
139 (let* ((avy-all-windows nil)
141 (avy--regex-candidates
142 (ivy--regex ivy-text)))
145 (avy--process candidates #'avy--overlay-post)))
147 (avy-action-goto candidate))))))
149 (defun swiper-recenter-top-bottom (&optional arg)
150 "Call (`recenter-top-bottom' ARG)."
153 (recenter-top-bottom arg)))
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
163 emms-playlist-mode erc-mode
171 (unless (> (buffer-size) 100000)
172 (if (fboundp 'font-lock-ensure)
174 (with-no-warnings (font-lock-fontify-buffer))))))
176 (defvar swiper--format-spec ""
177 "Store the current candidates format spec.")
179 (defvar swiper--width nil
180 "Store the amount of digits needed for the longest line nubmer.")
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)
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)
198 (line-beginning-position)
199 (line-end-position)))
202 (nreverse candidates))))))
204 (defvar swiper--opoint 1
205 "The point when `swiper' starts.")
208 (defun swiper (&optional initial-input)
209 "`isearch' with an overview.
210 When non-nil, INITIAL-INPUT is the initial search pattern."
212 (swiper--ivy initial-input))
214 (defvar swiper--anchor nil
215 "A line number to which the search should be anchored.")
217 (defvar swiper--len 0
218 "The last length of input for which an anchoring was made.")
220 (defun swiper--init ()
221 "Perform initialization common to both completion methods."
222 (setq swiper--opoint (point))
224 (setq swiper--anchor (line-number-at-pos)))
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."
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"
240 (if (zerop ivy--subexps)
241 (prog1 (format "\\(%s\\)" re)
242 (setq ivy--subexps 1))
245 (ivy--regex-plus str))))
247 (defvar swiper-history nil
248 "History for `swiper'.")
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."
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."))
258 (let ((candidates (swiper--candidates))
262 (buffer-substring-no-properties
263 (line-beginning-position)
264 (line-end-position))))
270 :initial-input initial-input
274 :update-fn #'swiper--update-input-ivy
275 :unwind #'swiper--cleanup
276 :re-builder #'swiper--re-builder
277 :history 'swiper-history))
279 (goto-char swiper--opoint)
280 (swiper--action res ivy-text)))))
282 (defun swiper--ensure-visible ()
283 "Remove overlays hiding point."
284 (let ((overlays (overlays-at (point)))
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)))))
291 (defvar swiper--overlays nil
294 (defun swiper--cleanup ()
295 "Clean up the overlays."
296 (while swiper--overlays
297 (delete-overlay (pop swiper--overlays)))
299 (goto-char (point-min))
300 (isearch-clean-overlays)))
302 (defun swiper--update-input-ivy ()
303 "Called when `ivy' input is updated."
306 (let* ((re (ivy--regex ivy-text))
308 (num (if (string-match "^[0-9]+" str)
309 (string-to-number (match-string 0 str))
311 (goto-char (point-min))
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)
322 (unless (and (>= (point) (window-start))
323 (<= (point) (window-end (ivy-state-window ivy-last) t)))
325 (swiper--add-overlays re))))
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))
340 (end (or end (save-excursion
343 (when (>= (length re) swiper-min-highlight)
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))
350 (while (<= i ivy--subexps)
351 (when (match-beginning i)
352 (let ((overlay (make-overlay (match-beginning i)
355 (cond ((zerop ivy--subexps)
360 (nth (1+ (mod (+ i 2) (1- (length 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)))
368 (defun swiper--action (x input)
369 "Goto line X and search for INPUT."
371 (user-error "No candidates")
372 (goto-char (point-min))
373 (forward-line (1- (read x)))
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")))))
382 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
383 (defun swiper-from-isearch ()
384 "Invoke `swiper' from isearch."
386 (let ((query (if isearch-regexp
388 (regexp-quote isearch-string))))
392 (defvar swiper-multi-buffers nil
393 "Store the current list of buffers.")
395 (defvar swiper-multi-candidates nil
396 "Store the list of candidates for `swiper-multi'.")
398 (defun swiper-multi-prompt ()
399 (format "Buffers (%s): "
400 (mapconcat #'identity swiper-multi-buffers ", ")))
402 (defun swiper-multi ()
403 "Select one or more buffers.
404 Run `swiper' for those buffers."
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))
415 (defun swiper-multi-action-1 (x)
416 (if (member x swiper-multi-buffers)
418 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
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
427 (let ((ww (window-width)))
428 (dolist (buf swiper-multi-buffers)
429 (with-current-buffer buf
430 (setq swiper-multi-candidates
434 (setq s (concat s " "))
435 (let ((len (length s)))
437 (1- len) len 'display
443 (length (buffer-name))
450 (swiper--candidates))
451 swiper-multi-candidates))))))
452 ((eq this-command 'ivy-call)
453 (delete-minibuffer-contents))))
455 (defun swiper-multi-action-2 (x)
456 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
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)))
463 (ivy--regex ivy-text)
464 (line-end-position) t)
465 (unless (eq ivy-exit 'done)
467 (swiper--add-overlays (ivy--regex ivy-text)))))))
471 ;;; swiper.el ends here