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 "")
145 (let* ((avy-all-windows nil)
147 (avy--regex-candidates
148 (ivy--regex ivy-text)))
151 (avy--process candidates #'avy--overlay-post)))
153 (avy-action-goto candidate))))))
155 (defun swiper-recenter-top-bottom (&optional arg)
156 "Call (`recenter-top-bottom' ARG)."
159 (recenter-top-bottom arg)))
161 (defun swiper-font-lock-ensure ()
162 "Ensure the entired buffer is highlighted."
163 (unless (or (derived-mode-p 'magit-mode)
164 (bound-and-true-p magit-blame-mode)
165 (memq major-mode '(package-menu-mode
169 emms-playlist-mode erc-mode
179 (unless (> (buffer-size) 100000)
180 (if (fboundp 'font-lock-ensure)
182 (with-no-warnings (font-lock-fontify-buffer))))))
184 (defvar swiper--format-spec ""
185 "Store the current candidates format spec.")
187 (defvar swiper--width nil
188 "Store the amount of digits needed for the longest line nubmer.")
190 (defun swiper--candidates ()
191 "Return a list of this buffer lines."
192 (let ((n-lines (count-lines (point-min) (point-max))))
193 (unless (zerop n-lines)
194 (setq swiper--width (1+ (floor (log n-lines 10))))
195 (setq swiper--format-spec
196 (format "%%-%dd " swiper--width))
197 (let ((line-number 0)
200 (goto-char (point-min))
201 (swiper-font-lock-ensure)
202 (while (< (point) (point-max))
203 (let ((str (concat " " (buffer-substring
204 (line-beginning-position)
205 (line-end-position)))))
206 (put-text-property 0 1 'display
207 (format swiper--format-spec
208 (cl-incf line-number))
210 (push str candidates))
212 (nreverse candidates))))))
214 (defvar swiper--opoint 1
215 "The point when `swiper' starts.")
218 (defun swiper (&optional initial-input)
219 "`isearch' with an overview.
220 When non-nil, INITIAL-INPUT is the initial search pattern."
222 (swiper--ivy initial-input))
224 (defvar swiper--anchor nil
225 "A line number to which the search should be anchored.")
227 (defvar swiper--len 0
228 "The last length of input for which an anchoring was made.")
230 (defun swiper--init ()
231 "Perform initialization common to both completion methods."
232 (setq swiper--opoint (point))
234 (setq swiper--anchor (line-number-at-pos)))
236 (defun swiper--re-builder (str)
237 "Transform STR into a swiper regex.
238 This is the regex used in the minibuffer, since the candidates
239 there have line numbers. In the buffer, `ivy--regex' should be used."
245 ((string-match "^\\^" str)
246 (setq ivy--old-re "")
247 (let ((re (ivy--regex-plus (substring str 1))))
248 (format "^[0-9][0-9 ]\\{%d\\}%s"
250 (if (zerop ivy--subexps)
251 (prog1 (format "\\(%s\\)" re)
252 (setq ivy--subexps 1))
255 (ivy--regex-plus str))))
257 (defvar swiper-history nil
258 "History for `swiper'.")
260 (defun swiper--ivy (&optional initial-input)
261 "`isearch' with an overview using `ivy'.
262 When non-nil, INITIAL-INPUT is the initial search pattern."
265 (let ((candidates (swiper--candidates))
266 (preselect (buffer-substring-no-properties
267 (line-beginning-position)
268 (line-end-position)))
269 (minibuffer-allow-text-properties t)
275 :initial-input initial-input
279 :update-fn #'swiper--update-input-ivy
280 :unwind #'swiper--cleanup
281 :re-builder #'swiper--re-builder
282 :history 'swiper-history))
284 (goto-char swiper--opoint)
285 (swiper--action res ivy-text)))))
287 (defun swiper--ensure-visible ()
288 "Remove overlays hiding point."
289 (let ((overlays (overlays-at (point)))
291 (while (setq ov (pop overlays))
292 (if (and (invisible-p (overlay-get ov 'invisible))
293 (setq expose (overlay-get ov 'isearch-open-invisible)))
294 (funcall expose ov)))))
296 (defvar swiper--overlays nil
299 (defun swiper--cleanup ()
300 "Clean up the overlays."
301 (while swiper--overlays
302 (delete-overlay (pop swiper--overlays)))
304 (goto-char (point-min))
305 (isearch-clean-overlays)))
307 (defun swiper--update-input-ivy ()
308 "Called when `ivy' input is updated."
311 (when (> (length ivy--current) 0)
312 (let* ((re (funcall ivy--regex-function ivy-text))
313 (re (if (stringp re) re (caar re)))
314 (str (get-text-property 0 'display ivy--current))
315 (num (if (string-match "^[0-9]+" str)
316 (string-to-number (match-string 0 str))
318 (goto-char (point-min))
320 (goto-char (point-min))
321 (forward-line (1- num))
322 (if (and (equal ivy-text "")
323 (>= swiper--opoint (line-beginning-position))
324 (<= swiper--opoint (line-end-position)))
325 (goto-char swiper--opoint)
326 (re-search-forward re (line-end-position) t))
327 (isearch-range-invisible (line-beginning-position)
329 (unless (and (>= (point) (window-start))
330 (<= (point) (window-end (ivy-state-window ivy-last) t)))
332 (swiper--add-overlays re)))))
334 (defun swiper--add-overlays (re &optional beg end)
335 "Add overlays for RE regexp in visible part of the current buffer.
336 BEG and END, when specified, are the point bounds."
337 (let ((ov (make-overlay
338 (line-beginning-position)
339 (1+ (line-end-position)))))
340 (overlay-put ov 'face 'swiper-line-face)
341 (overlay-put ov 'window (ivy-state-window ivy-last))
342 (push ov swiper--overlays)
343 (let* ((wh (window-height))
344 (beg (or beg (save-excursion
345 (forward-line (- wh))
347 (end (or end (save-excursion
350 (when (>= (length re) swiper-min-highlight)
353 ;; RE can become an invalid regexp
354 (while (and (ignore-errors (re-search-forward re end t))
355 (> (- (match-end 0) (match-beginning 0)) 0))
357 (while (<= i ivy--subexps)
358 (when (match-beginning i)
359 (let ((overlay (make-overlay (match-beginning i)
362 (cond ((zerop ivy--subexps)
367 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
369 (push overlay swiper--overlays)
370 (overlay-put overlay 'face face)
371 (overlay-put overlay 'window (ivy-state-window ivy-last))
372 (overlay-put overlay 'priority i)))
375 (defun swiper--action (x input)
376 "Goto line X and search for INPUT."
378 (user-error "No candidates")
379 (goto-char (point-min))
380 (forward-line (1- (read (get-text-property 0 'display x))))
382 (ivy--regex input) (line-end-position) t)
383 (swiper--ensure-visible)
384 (when (/= (point) swiper--opoint)
385 (unless (and transient-mark-mode mark-active)
386 (push-mark swiper--opoint t)
387 (message "Mark saved where search started")))))
389 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
390 (defun swiper-from-isearch ()
391 "Invoke `swiper' from isearch."
393 (let ((query (if isearch-regexp
395 (regexp-quote isearch-string))))
399 (defvar swiper-multi-buffers nil
400 "Store the current list of buffers.")
402 (defvar swiper-multi-candidates nil
403 "Store the list of candidates for `swiper-multi'.")
405 (defun swiper-multi-prompt ()
406 (format "Buffers (%s): "
407 (mapconcat #'identity swiper-multi-buffers ", ")))
409 (defun swiper-multi ()
410 "Select one or more buffers.
411 Run `swiper' for those buffers."
413 (setq swiper-multi-buffers nil)
414 (setq swiper-multi-candidates nil)
415 (ivy-read (swiper-multi-prompt)
416 'internal-complete-buffer
417 :action 'swiper-multi-action-1)
418 (ivy-read "Swiper: " swiper-multi-candidates
419 :action 'swiper-multi-action-2
420 :unwind #'swiper--cleanup))
422 (defun swiper-multi-action-1 (x)
423 (if (member x swiper-multi-buffers)
425 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
427 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
428 (let ((prompt (swiper-multi-prompt)))
429 (setf (ivy-state-prompt ivy-last) prompt)
430 (setq ivy--prompt (concat "%-4d " prompt)))
431 (cond ((memq this-command '(ivy-done
434 (let ((ww (window-width)))
435 (dolist (buf swiper-multi-buffers)
436 (with-current-buffer buf
437 (setq swiper-multi-candidates
441 (setq s (concat s " "))
442 (let ((len (length s)))
444 (1- len) len 'display
450 (length (buffer-name))
457 (swiper--candidates))
458 swiper-multi-candidates))))))
459 ((eq this-command 'ivy-call)
460 (delete-minibuffer-contents))))
462 (defun swiper-multi-action-2 (x)
463 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
465 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
466 (switch-to-buffer (match-string 1 buf-space))
467 (goto-char (point-min))
468 (forward-line (1- (read x)))
470 (ivy--regex ivy-text)
471 (line-end-position) t)
472 (unless (eq ivy-exit 'done)
474 (swiper--add-overlays (ivy--regex ivy-text)))))))
478 ;;; swiper.el ends here