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-line-face
65 '((t (:inherit highlight)))
66 "Face for current `swiper' line.")
68 (defcustom swiper-faces '(swiper-match-face-1
72 "List of `swiper' faces for group matches.")
74 (defcustom swiper-min-highlight 2
75 "Only highlight matches for regexps at least this long."
79 (let ((map (make-sparse-keymap)))
80 (define-key map (kbd "M-q") 'swiper-query-replace)
81 (define-key map (kbd "C-l") 'swiper-recenter-top-bottom)
82 (define-key map (kbd "C-'") 'swiper-avy)
86 (defun swiper-query-replace ()
87 "Start `query-replace' with string to replace from last search string."
89 (if (null (window-minibuffer-p))
90 (user-error "Should only be called in the minibuffer through `swiper-map'")
91 (let* ((enable-recursive-minibuffers t)
92 (from (ivy--regex ivy-text))
93 (to (query-replace-read-to from "Query replace" t)))
94 (delete-minibuffer-contents)
95 (ivy-set-action (lambda (_)
97 (move-beginning-of-line 1)
98 (perform-replace from to
103 (defvar avy-background)
104 (defvar avy-all-windows)
105 (declare-function avy--regex-candidates "ext:avy")
106 (declare-function avy--process "ext:avy")
107 (declare-function avy--overlay-post "ext:avy")
108 (declare-function avy-action-goto "ext:avy")
112 "Jump to one of the current swiper candidates."
114 (unless (string= ivy-text "")
116 (let* ((avy-all-windows nil)
118 (avy--regex-candidates
119 (ivy--regex ivy-text)))
122 (avy--process candidates #'avy--overlay-post)))
124 (avy-action-goto candidate))))))
126 (defun swiper-recenter-top-bottom (&optional arg)
127 "Call (`recenter-top-bottom' ARG)."
130 (recenter-top-bottom arg)))
132 (defun swiper-font-lock-ensure ()
133 "Ensure the entired buffer is highlighted."
134 (unless (or (derived-mode-p 'magit-mode)
135 (bound-and-true-p magit-blame-mode)
136 (memq major-mode '(package-menu-mode
140 emms-playlist-mode erc-mode
148 (unless (> (buffer-size) 100000)
149 (if (fboundp 'font-lock-ensure)
151 (with-no-warnings (font-lock-fontify-buffer))))))
153 (defvar swiper--format-spec ""
154 "Store the current candidates format spec.")
156 (defvar swiper--width nil
157 "Store the amount of digits needed for the longest line nubmer.")
159 (defun swiper--candidates ()
160 "Return a list of this buffer lines."
161 (let ((n-lines (count-lines (point-min) (point-max))))
162 (unless (zerop n-lines)
163 (setq swiper--width (1+ (floor (log n-lines 10))))
164 (setq swiper--format-spec
165 (format "%%-%dd %%s" swiper--width))
166 (let ((line-number 0)
169 (goto-char (point-min))
170 (swiper-font-lock-ensure)
171 (while (< (point) (point-max))
172 (push (format swiper--format-spec
173 (cl-incf line-number)
175 (line-beginning-position)
176 (line-end-position)))
179 (nreverse candidates))))))
181 (defvar swiper--opoint 1
182 "The point when `swiper' starts.")
185 (defun swiper (&optional initial-input)
186 "`isearch' with an overview.
187 When non-nil, INITIAL-INPUT is the initial search pattern."
189 (swiper--ivy initial-input))
191 (defvar swiper--anchor nil
192 "A line number to which the search should be anchored.")
194 (defvar swiper--len 0
195 "The last length of input for which an anchoring was made.")
197 (defun swiper--init ()
198 "Perform initialization common to both completion methods."
199 (setq swiper--opoint (point))
201 (setq swiper--anchor (line-number-at-pos)))
203 (defun swiper--re-builder (str)
204 "Transform STR into a swiper regex.
205 This is the regex used in the minibuffer, since the candidates
206 there have line numbers. In the buffer, `ivy--regex' should be used."
212 ((string-match "^\\^" str)
213 (setq ivy--old-re "")
214 (let ((re (ivy--regex-plus (substring str 1))))
215 (format "^[0-9][0-9 ]\\{%d\\}%s"
217 (if (zerop ivy--subexps)
218 (prog1 (format "\\(%s\\)" re)
219 (setq ivy--subexps 1))
222 (ivy--regex-plus str))))
224 (defvar swiper-history nil
225 "History for `swiper'.")
227 (defun swiper--ivy (&optional initial-input)
228 "`isearch' with an overview using `ivy'.
229 When non-nil, INITIAL-INPUT is the initial search pattern."
231 (unless (eq (length (help-function-arglist 'ivy-read)) 4)
232 (warn "You seem to be using the outdated stand-alone \"ivy\" package.
233 Please remove it and update the \"swiper\" package."))
235 (let ((candidates (swiper--candidates))
239 (buffer-substring-no-properties
240 (line-beginning-position)
241 (line-end-position))))
247 :initial-input initial-input
251 :update-fn #'swiper--update-input-ivy
252 :unwind #'swiper--cleanup
253 :re-builder #'swiper--re-builder
254 :history 'swiper-history))
256 (goto-char swiper--opoint)
257 (swiper--action res ivy-text)))))
259 (defun swiper--ensure-visible ()
260 "Remove overlays hiding point."
261 (let ((overlays (overlays-at (point)))
263 (while (setq ov (pop overlays))
264 (if (and (invisible-p (overlay-get ov 'invisible))
265 (setq expose (overlay-get ov 'isearch-open-invisible)))
266 (funcall expose ov)))))
268 (defvar swiper--overlays nil
271 (defun swiper--cleanup ()
272 "Clean up the overlays."
273 (while swiper--overlays
274 (delete-overlay (pop swiper--overlays)))
276 (goto-char (point-min))
277 (isearch-clean-overlays)))
279 (defun swiper--update-input-ivy ()
280 "Called when `ivy' input is updated."
283 (let* ((re (ivy--regex ivy-text))
285 (num (if (string-match "^[0-9]+" str)
286 (string-to-number (match-string 0 str))
288 (goto-char (point-min))
290 (goto-char (point-min))
291 (forward-line (1- num))
292 (if (and (equal ivy-text "")
293 (>= swiper--opoint (line-beginning-position))
294 (<= swiper--opoint (line-end-position)))
295 (goto-char swiper--opoint)
296 (re-search-forward re (line-end-position) t))
297 (isearch-range-invisible (line-beginning-position)
299 (unless (and (>= (point) (window-start))
300 (<= (point) (window-end (ivy-state-window ivy-last) t)))
302 (swiper--add-overlays re))))
304 (defun swiper--add-overlays (re &optional beg end)
305 "Add overlays for RE regexp in visible part of the current buffer.
306 BEG and END, when specified, are the point bounds."
307 (let ((ov (make-overlay
308 (line-beginning-position)
309 (1+ (line-end-position)))))
310 (overlay-put ov 'face 'swiper-line-face)
311 (overlay-put ov 'window (ivy-state-window ivy-last))
312 (push ov swiper--overlays)
313 (let* ((wh (window-height))
314 (beg (or beg (save-excursion
315 (forward-line (- wh))
317 (end (or end (save-excursion
320 (when (>= (length re) swiper-min-highlight)
323 ;; RE can become an invalid regexp
324 (while (and (ignore-errors (re-search-forward re end t))
325 (> (- (match-end 0) (match-beginning 0)) 0))
327 (while (<= i ivy--subexps)
328 (when (match-beginning i)
329 (let ((overlay (make-overlay (match-beginning i)
332 (cond ((zerop ivy--subexps)
337 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
339 (push overlay swiper--overlays)
340 (overlay-put overlay 'face face)
341 (overlay-put overlay 'window (ivy-state-window ivy-last))
342 (overlay-put overlay 'priority i)))
345 (defun swiper--action (x input)
346 "Goto line X and search for INPUT."
348 (user-error "No candidates")
349 (goto-char (point-min))
350 (forward-line (1- (read x)))
352 (ivy--regex input) (line-end-position) t)
353 (swiper--ensure-visible)
354 (when (/= (point) swiper--opoint)
355 (unless (and transient-mark-mode mark-active)
356 (push-mark swiper--opoint t)
357 (message "Mark saved where search started")))))
359 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
360 (defun swiper-from-isearch ()
361 "Invoke `swiper' from isearch."
363 (let ((query (if isearch-regexp
365 (regexp-quote isearch-string))))
371 ;;; swiper.el ends here