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 (define-obsolete-face-alias 'swiper-minibuffer-match-face-1
65 'ivy-minibuffer-match-face-1 "0.6.0")
67 (define-obsolete-face-alias 'swiper-minibuffer-match-face-2
68 'ivy-minibuffer-match-face-2 "0.6.0")
70 (define-obsolete-face-alias 'swiper-minibuffer-match-face-3
71 'ivy-minibuffer-match-face-3 "0.6.0")
73 (define-obsolete-face-alias 'swiper-minibuffer-match-face-4
74 'ivy-minibuffer-match-face-4 "0.6.0")
76 (defface swiper-line-face
77 '((t (:inherit highlight)))
78 "Face for current `swiper' line.")
80 (defcustom swiper-faces '(swiper-match-face-1
84 "List of `swiper' faces for group matches.")
86 (defcustom swiper-min-highlight 2
87 "Only highlight matches for regexps at least this long."
91 (let ((map (make-sparse-keymap)))
92 (define-key map (kbd "M-q") 'swiper-query-replace)
93 (define-key map (kbd "C-l") 'swiper-recenter-top-bottom)
94 (define-key map (kbd "C-'") 'swiper-avy)
95 (define-key map (kbd "C-7") 'swiper-mc)
96 (define-key map (kbd "C-c C-f") 'swiper-toggle-face-matching)
100 (defun swiper-query-replace ()
101 "Start `query-replace' with string to replace from last search string."
103 (if (null (window-minibuffer-p))
104 (user-error "Should only be called in the minibuffer through `swiper-map'")
105 (let* ((enable-recursive-minibuffers t)
106 (from (ivy--regex ivy-text))
107 (to (query-replace-read-to from "Query replace" t)))
109 (ivy-exit-with-action
112 (move-beginning-of-line 1)
113 (perform-replace from to
116 (defvar avy-background)
117 (defvar avy-all-windows)
120 (declare-function avy--regex-candidates "ext:avy")
121 (declare-function avy--process "ext:avy")
122 (declare-function avy--overlay-post "ext:avy")
123 (declare-function avy-action-goto "ext:avy")
124 (declare-function avy--done "ext:avy")
125 (declare-function avy--make-backgrounds "ext:avy")
126 (declare-function avy-window-list "ext:avy")
127 (declare-function avy-read "ext:avy")
128 (declare-function avy-read-de-bruijn "ext:avy")
129 (declare-function avy-tree "ext:avy")
130 (declare-function avy-push-mark "ext:avy")
131 (declare-function avy--remove-leading-chars "ext:avy")
135 "Jump to one of the current swiper candidates."
137 (unless (string= ivy-text "")
138 (let* ((avy-all-windows nil)
141 (avy--regex-candidates
142 (ivy--regex ivy-text)))
145 (narrow-to-region (window-start) (window-end))
146 (goto-char (point-min))
149 (while (< (point) (point-max))
150 (push (cons (1+ (point))
155 (candidate (unwind-protect
157 (avy--make-backgrounds
158 (append (avy-window-list)
159 (list (ivy-state-window ivy-last))))
160 (if (eq avy-style 'de-bruijn)
163 (avy-read (avy-tree candidates avy-keys)
165 #'avy--remove-leading-chars))
168 (if (window-minibuffer-p (cdr candidate))
170 (ivy-set-index (- (line-number-at-pos (car candidate)) 2))
175 (avy-action-goto (caar candidate)))))))
177 (declare-function mc/create-fake-cursor-at-point "ext:multiple-cursors-core")
178 (declare-function multiple-cursors-mode "ext:multiple-cursors-core")
183 (unless (require 'multiple-cursors nil t)
184 (error "multiple-cursors isn't installed"))
185 (let ((cands (nreverse ivy--old-cands)))
186 (unless (string= ivy-text "")
187 (ivy-exit-with-action
190 (while (setq cand (pop cands))
191 (swiper--action cand)
193 (mc/create-fake-cursor-at-point))))
194 (multiple-cursors-mode 1))))))
196 (defun swiper-recenter-top-bottom (&optional arg)
197 "Call (`recenter-top-bottom' ARG)."
200 (recenter-top-bottom arg)))
202 (defun swiper-font-lock-ensure ()
203 "Ensure the entired buffer is highlighted."
204 (unless (or (derived-mode-p 'magit-mode)
205 (bound-and-true-p magit-blame-mode)
206 (memq major-mode '(package-menu-mode
230 (unless (> (buffer-size) 100000)
231 (if (fboundp 'font-lock-ensure)
233 (with-no-warnings (font-lock-fontify-buffer))))))
235 (defvar swiper--format-spec ""
236 "Store the current candidates format spec.")
238 (defvar swiper--width nil
239 "Store the amount of digits needed for the longest line nubmer.")
241 (defvar swiper-use-visual-line nil
242 "When non-nil, use `line-move' instead of `forward-line'.")
244 (declare-function outline-show-all "outline")
246 (defun swiper--candidates (&optional numbers-width)
247 "Return a list of this buffer lines.
249 NUMBERS-WIDTH, when specified, is used for line numbers width
250 spec, instead of calculating it as the log of the buffer line
252 (if (and visual-line-mode
253 ;; super-slow otherwise
254 (< (buffer-size) 20000))
256 (when (eq major-mode 'org-mode)
258 (setq swiper-use-visual-line t))
259 (setq swiper-use-visual-line nil))
260 (let ((n-lines (count-lines (point-min) (point-max))))
261 (unless (zerop n-lines)
262 (setq swiper--width (or numbers-width
263 (1+ (floor (log n-lines 10)))))
264 (setq swiper--format-spec
265 (format "%%-%dd " swiper--width))
266 (let ((line-number 0)
267 (advancer (if swiper-use-visual-line
268 (lambda (arg) (line-move arg t))
272 (goto-char (point-min))
273 (swiper-font-lock-ensure)
274 (while (< (point) (point-max))
277 (replace-regexp-in-string
281 (if swiper-use-visual-line
285 (line-end-position)))))))
286 (put-text-property 0 1 'display
287 (format swiper--format-spec
288 (cl-incf line-number))
290 (push str candidates))
291 (funcall advancer 1))
292 (nreverse candidates))))))
294 (defvar swiper--opoint 1
295 "The point when `swiper' starts.")
298 (defun swiper (&optional initial-input)
299 "`isearch' with an overview.
300 When non-nil, INITIAL-INPUT is the initial search pattern."
302 (swiper--ivy initial-input))
304 (declare-function evil-jumper--set-jump "ext:evil-jumper")
306 (defun swiper--init ()
307 "Perform initialization common to both completion methods."
308 (setq swiper--opoint (point))
309 (when (bound-and-true-p evil-jumper-mode)
310 (evil-jumper--set-jump)))
312 (defun swiper--re-builder (str)
313 "Transform STR into a swiper regex.
314 This is the regex used in the minibuffer, since the candidates
315 there have line numbers. In the buffer, `ivy--regex' should be used."
320 (setq ivy--subexps 0)
322 ((string-match "^\\^" str)
323 (setq ivy--old-re "")
324 (let ((re (ivy--regex-plus (substring str 1))))
325 (if (zerop ivy--subexps)
326 (prog1 (format "^ ?\\(%s\\)" re)
327 (setq ivy--subexps 1))
328 (format "^ %s" re))))
330 (ivy--regex-plus str))))
332 (defvar swiper-history nil
333 "History for `swiper'.")
335 (defvar swiper-invocation-face nil
336 "The face at the point of invocation of `swiper'.")
338 (defun swiper--ivy (&optional initial-input)
339 "`isearch' with an overview using `ivy'.
340 When non-nil, INITIAL-INPUT is the initial search pattern."
343 (setq swiper-invocation-face
344 (plist-get (text-properties-at (point)) 'face))
345 (let ((candidates (swiper--candidates))
347 (if swiper-use-visual-line
350 (save-excursion (beginning-of-visual-line) (point)))
351 (1- (line-number-at-pos))))
352 (minibuffer-allow-text-properties t))
357 :initial-input initial-input
361 :update-fn #'swiper--update-input-ivy
362 :unwind #'swiper--cleanup
363 :action #'swiper--action
364 :re-builder #'swiper--re-builder
365 :history 'swiper-history
367 (when (null ivy-exit)
368 (goto-char swiper--opoint)))))
370 (defun swiper-toggle-face-matching ()
371 "Toggle matching only the candidates with `swiper-invocation-face'."
373 (setf (ivy-state-matcher ivy-last)
374 (if (ivy-state-matcher ivy-last)
376 #'swiper--face-matcher))
377 (setq ivy--old-re nil))
379 (defun swiper--face-matcher (regexp candidates)
380 "Return REGEXP-matching CANDIDATES.
381 Matched candidates should have `swiper-invocation-face'."
385 (string-match regexp x)
386 (let ((s (match-string 0 x))
388 (while (and (< i (length s))
391 'face swiper-invocation-face
397 (defun swiper--ensure-visible ()
398 "Remove overlays hiding point."
399 (let ((overlays (overlays-at (point)))
401 (while (setq ov (pop overlays))
402 (if (and (invisible-p (overlay-get ov 'invisible))
403 (setq expose (overlay-get ov 'isearch-open-invisible)))
404 (funcall expose ov)))))
406 (defvar swiper--overlays nil
409 (defun swiper--cleanup ()
410 "Clean up the overlays."
411 (while swiper--overlays
412 (delete-overlay (pop swiper--overlays)))
414 (goto-char (point-min))
415 (isearch-clean-overlays)))
417 (defun swiper--update-input-ivy ()
418 "Called when `ivy' input is updated."
421 (when (> (length ivy--current) 0)
422 (let* ((re (funcall ivy--regex-function ivy-text))
423 (re (if (stringp re) re (caar re)))
424 (str (get-text-property 0 'display ivy--current))
425 (num (if (string-match "^[0-9]+" str)
426 (string-to-number (match-string 0 str))
428 (goto-char (point-min))
430 (goto-char (point-min))
431 (if swiper-use-visual-line
433 (forward-line (1- num)))
434 (if (and (equal ivy-text "")
435 (>= swiper--opoint (line-beginning-position))
436 (<= swiper--opoint (line-end-position)))
437 (goto-char swiper--opoint)
438 (re-search-forward re (line-end-position) t))
439 (isearch-range-invisible (line-beginning-position)
441 (unless (and (>= (point) (window-start))
442 (<= (point) (window-end (ivy-state-window ivy-last) t)))
444 (swiper--add-overlays re)))))
446 (defun swiper--add-overlays (re &optional beg end wnd)
447 "Add overlays for RE regexp in visible part of the current buffer.
448 BEG and END, when specified, are the point bounds.
449 WND, when specified is the window."
450 (setq wnd (or wnd (ivy-state-window ivy-last)))
451 (let ((ov (if visual-line-mode
454 (beginning-of-visual-line)
460 (line-beginning-position)
461 (1+ (line-end-position))))))
462 (overlay-put ov 'face 'swiper-line-face)
463 (overlay-put ov 'window wnd)
464 (push ov swiper--overlays)
465 (let* ((wh (window-height))
466 (beg (or beg (save-excursion
467 (forward-line (- wh))
469 (end (or end (save-excursion
472 (when (>= (length re) swiper-min-highlight)
475 ;; RE can become an invalid regexp
476 (while (and (ignore-errors (re-search-forward re end t))
477 (> (- (match-end 0) (match-beginning 0)) 0))
479 (while (<= i ivy--subexps)
480 (when (match-beginning i)
481 (let ((overlay (make-overlay (match-beginning i)
484 (cond ((zerop ivy--subexps)
489 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
491 (push overlay swiper--overlays)
492 (overlay-put overlay 'face face)
493 (overlay-put overlay 'window wnd)
494 (overlay-put overlay 'priority i)))
497 (defun swiper--action (x)
500 (user-error "No candidates")
502 (unless (equal (current-buffer)
503 (ivy-state-buffer ivy-last))
504 (switch-to-buffer (ivy-state-buffer ivy-last)))
505 (goto-char (point-min))
506 (funcall (if swiper-use-visual-line
509 (1- (read (get-text-property 0 'display x))))
511 (ivy--regex ivy-text) (line-end-position) t)
512 (swiper--ensure-visible)
513 (when (/= (point) swiper--opoint)
514 (unless (and transient-mark-mode mark-active)
515 (push-mark swiper--opoint t)
516 (message "Mark saved where search started"))))))
518 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
519 (defun swiper-from-isearch ()
520 "Invoke `swiper' from isearch."
522 (let ((query (if isearch-regexp
524 (regexp-quote isearch-string))))
528 (defvar swiper-multi-buffers nil
529 "Store the current list of buffers.")
531 (defvar swiper-multi-candidates nil
532 "Store the list of candidates for `swiper-multi'.")
534 (defun swiper-multi-prompt ()
535 (format "Buffers (%s): "
536 (mapconcat #'identity swiper-multi-buffers ", ")))
538 (defun swiper-multi ()
539 "Select one or more buffers.
540 Run `swiper' for those buffers."
542 (setq swiper-multi-buffers nil)
543 (ivy-read (swiper-multi-prompt)
544 'internal-complete-buffer
545 :action 'swiper-multi-action-1)
546 (ivy-read "Swiper: " swiper-multi-candidates
547 :action 'swiper-multi-action-2
548 :unwind #'swiper--cleanup
549 :caller 'swiper-multi))
552 "Run `swiper' for all opened buffers."
554 (ivy-read "Swiper: " (swiper--multi-candidates
558 :action 'swiper-multi-action-2
559 :unwind #'swiper--cleanup
560 :caller 'swiper-multi))
562 (defun swiper--multi-candidates (buffers)
563 (let* ((ww (window-width))
565 (column-2 (apply #'max
568 (length (buffer-name b)))
570 (column-1 (- ww 4 column-2 1)))
571 (dolist (buf buffers)
572 (with-current-buffer buf
577 (setq s (concat (ivy--truncate-string s column-1) " "))
578 (let ((len (length s)))
580 (1- len) len 'display
583 (- ww (string-width s) (length (buffer-name)) 3)
588 (swiper--candidates 4))
593 (defun swiper-multi-action-1 (x)
594 (if (member x swiper-multi-buffers)
596 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
598 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
599 (let ((prompt (swiper-multi-prompt)))
600 (setf (ivy-state-prompt ivy-last) prompt)
601 (setq ivy--prompt (concat "%-4d " prompt)))
602 (cond ((memq this-command '(ivy-done
605 (setq swiper-multi-candidates
606 (swiper--multi-candidates
607 (mapcar #'get-buffer swiper-multi-buffers))))
608 ((eq this-command 'ivy-call)
609 (delete-minibuffer-contents))))
611 (defun swiper-multi-action-2 (x)
612 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
614 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
615 (switch-to-buffer (match-string 1 buf-space))
616 (goto-char (point-min))
617 (forward-line (1- (read (get-text-property 0 'display x))))
619 (ivy--regex ivy-text)
620 (line-end-position) t)
621 (unless (eq ivy-exit 'done)
623 (swiper--add-overlays (ivy--regex ivy-text)))))))
627 ;;; swiper.el ends here