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 (defun swiper--candidates (&optional numbers-width)
245 "Return a list of this buffer lines.
247 NUMBERS-WIDTH, when specified, is used for line numbers width
248 spec, instead of calculating it as the log of the buffer line
250 (if (and visual-line-mode
251 ;; super-slow otherwise
252 (< (buffer-size) 20000))
254 (when (eq major-mode 'org-mode)
256 (setq swiper-use-visual-line t))
257 (setq swiper-use-visual-line nil))
258 (let ((n-lines (count-lines (point-min) (point-max))))
259 (unless (zerop n-lines)
260 (setq swiper--width (or numbers-width
261 (1+ (floor (log n-lines 10)))))
262 (setq swiper--format-spec
263 (format "%%-%dd " swiper--width))
264 (let ((line-number 0)
265 (advancer (if swiper-use-visual-line
266 (lambda (arg) (line-move arg t))
270 (goto-char (point-min))
271 (swiper-font-lock-ensure)
272 (while (< (point) (point-max))
275 (replace-regexp-in-string
279 (if swiper-use-visual-line
283 (line-end-position)))))))
284 (put-text-property 0 1 'display
285 (format swiper--format-spec
286 (cl-incf line-number))
288 (push str candidates))
289 (funcall advancer 1))
290 (nreverse candidates))))))
292 (defvar swiper--opoint 1
293 "The point when `swiper' starts.")
296 (defun swiper (&optional initial-input)
297 "`isearch' with an overview.
298 When non-nil, INITIAL-INPUT is the initial search pattern."
300 (swiper--ivy initial-input))
302 (declare-function evil-jumper--set-jump "ext:evil-jumper")
304 (defun swiper--init ()
305 "Perform initialization common to both completion methods."
306 (setq swiper--opoint (point))
307 (when (bound-and-true-p evil-jumper-mode)
308 (evil-jumper--set-jump)))
310 (defun swiper--re-builder (str)
311 "Transform STR into a swiper regex.
312 This is the regex used in the minibuffer, since the candidates
313 there have line numbers. In the buffer, `ivy--regex' should be used."
318 (setq ivy--subexps 0)
320 ((string-match "^\\^" str)
321 (setq ivy--old-re "")
322 (let ((re (ivy--regex-plus (substring str 1))))
323 (if (zerop ivy--subexps)
324 (prog1 (format "^ ?\\(%s\\)" re)
325 (setq ivy--subexps 1))
326 (format "^ %s" re))))
328 (ivy--regex-plus str))))
330 (defvar swiper-history nil
331 "History for `swiper'.")
333 (defvar swiper-invocation-face nil
334 "The face at the point of invocation of `swiper'.")
336 (defun swiper--ivy (&optional initial-input)
337 "`isearch' with an overview using `ivy'.
338 When non-nil, INITIAL-INPUT is the initial search pattern."
341 (setq swiper-invocation-face
342 (plist-get (text-properties-at (point)) 'face))
343 (let ((candidates (swiper--candidates))
345 (if swiper-use-visual-line
348 (save-excursion (beginning-of-visual-line) (point)))
349 (1- (line-number-at-pos))))
350 (minibuffer-allow-text-properties t))
355 :initial-input initial-input
359 :update-fn #'swiper--update-input-ivy
360 :unwind #'swiper--cleanup
361 :action #'swiper--action
362 :re-builder #'swiper--re-builder
363 :history 'swiper-history
365 (when (null ivy-exit)
366 (goto-char swiper--opoint)))))
368 (defun swiper-toggle-face-matching ()
369 "Toggle matching only the candidates with `swiper-invocation-face'."
371 (setf (ivy-state-matcher ivy-last)
372 (if (ivy-state-matcher ivy-last)
374 #'swiper--face-matcher))
375 (setq ivy--old-re nil))
377 (defun swiper--face-matcher (regexp candidates)
378 "Return REGEXP-matching CANDIDATES.
379 Matched candidates should have `swiper-invocation-face'."
383 (string-match regexp x)
384 (let ((s (match-string 0 x))
386 (while (and (< i (length s))
389 'face swiper-invocation-face
395 (defun swiper--ensure-visible ()
396 "Remove overlays hiding point."
397 (let ((overlays (overlays-at (point)))
399 (while (setq ov (pop overlays))
400 (if (and (invisible-p (overlay-get ov 'invisible))
401 (setq expose (overlay-get ov 'isearch-open-invisible)))
402 (funcall expose ov)))))
404 (defvar swiper--overlays nil
407 (defun swiper--cleanup ()
408 "Clean up the overlays."
409 (while swiper--overlays
410 (delete-overlay (pop swiper--overlays)))
412 (goto-char (point-min))
413 (isearch-clean-overlays)))
415 (defun swiper--update-input-ivy ()
416 "Called when `ivy' input is updated."
419 (when (> (length ivy--current) 0)
420 (let* ((re (funcall ivy--regex-function ivy-text))
421 (re (if (stringp re) re (caar re)))
422 (str (get-text-property 0 'display ivy--current))
423 (num (if (string-match "^[0-9]+" str)
424 (string-to-number (match-string 0 str))
426 (goto-char (point-min))
428 (goto-char (point-min))
429 (if swiper-use-visual-line
431 (forward-line (1- num)))
432 (if (and (equal ivy-text "")
433 (>= swiper--opoint (line-beginning-position))
434 (<= swiper--opoint (line-end-position)))
435 (goto-char swiper--opoint)
436 (re-search-forward re (line-end-position) t))
437 (isearch-range-invisible (line-beginning-position)
439 (unless (and (>= (point) (window-start))
440 (<= (point) (window-end (ivy-state-window ivy-last) t)))
442 (swiper--add-overlays re)))))
444 (defun swiper--add-overlays (re &optional beg end wnd)
445 "Add overlays for RE regexp in visible part of the current buffer.
446 BEG and END, when specified, are the point bounds.
447 WND, when specified is the window."
448 (setq wnd (or wnd (ivy-state-window ivy-last)))
449 (let ((ov (if visual-line-mode
452 (beginning-of-visual-line)
458 (line-beginning-position)
459 (1+ (line-end-position))))))
460 (overlay-put ov 'face 'swiper-line-face)
461 (overlay-put ov 'window wnd)
462 (push ov swiper--overlays)
463 (let* ((wh (window-height))
464 (beg (or beg (save-excursion
465 (forward-line (- wh))
467 (end (or end (save-excursion
470 (when (>= (length re) swiper-min-highlight)
473 ;; RE can become an invalid regexp
474 (while (and (ignore-errors (re-search-forward re end t))
475 (> (- (match-end 0) (match-beginning 0)) 0))
477 (while (<= i ivy--subexps)
478 (when (match-beginning i)
479 (let ((overlay (make-overlay (match-beginning i)
482 (cond ((zerop ivy--subexps)
487 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
489 (push overlay swiper--overlays)
490 (overlay-put overlay 'face face)
491 (overlay-put overlay 'window wnd)
492 (overlay-put overlay 'priority i)))
495 (defun swiper--action (x)
498 (user-error "No candidates")
500 (unless (equal (current-buffer)
501 (ivy-state-buffer ivy-last))
502 (switch-to-buffer (ivy-state-buffer ivy-last)))
503 (goto-char (point-min))
504 (funcall (if swiper-use-visual-line
507 (1- (read (get-text-property 0 'display x))))
509 (ivy--regex ivy-text) (line-end-position) t)
510 (swiper--ensure-visible)
511 (when (/= (point) swiper--opoint)
512 (unless (and transient-mark-mode mark-active)
513 (push-mark swiper--opoint t)
514 (message "Mark saved where search started"))))))
516 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
517 (defun swiper-from-isearch ()
518 "Invoke `swiper' from isearch."
520 (let ((query (if isearch-regexp
522 (regexp-quote isearch-string))))
526 (defvar swiper-multi-buffers nil
527 "Store the current list of buffers.")
529 (defvar swiper-multi-candidates nil
530 "Store the list of candidates for `swiper-multi'.")
532 (defun swiper-multi-prompt ()
533 (format "Buffers (%s): "
534 (mapconcat #'identity swiper-multi-buffers ", ")))
536 (defun swiper-multi ()
537 "Select one or more buffers.
538 Run `swiper' for those buffers."
540 (setq swiper-multi-buffers nil)
541 (ivy-read (swiper-multi-prompt)
542 'internal-complete-buffer
543 :action 'swiper-multi-action-1)
544 (ivy-read "Swiper: " swiper-multi-candidates
545 :action 'swiper-multi-action-2
546 :unwind #'swiper--cleanup
547 :caller 'swiper-multi))
550 "Run `swiper' for all opened buffers."
552 (ivy-read "Swiper: " (swiper--multi-candidates
556 :action 'swiper-multi-action-2
557 :unwind #'swiper--cleanup
558 :caller 'swiper-multi))
560 (defun swiper--multi-candidates (buffers)
561 (let* ((ww (window-width))
563 (column-2 (apply #'max
566 (length (buffer-name b)))
568 (column-1 (- ww 4 column-2 1)))
569 (dolist (buf buffers)
570 (with-current-buffer buf
575 (setq s (concat (ivy--truncate-string s column-1) " "))
576 (let ((len (length s)))
578 (1- len) len 'display
581 (- ww (string-width s) (length (buffer-name)) 3)
586 (swiper--candidates 4))
591 (defun swiper-multi-action-1 (x)
592 (if (member x swiper-multi-buffers)
594 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
596 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
597 (let ((prompt (swiper-multi-prompt)))
598 (setf (ivy-state-prompt ivy-last) prompt)
599 (setq ivy--prompt (concat "%-4d " prompt)))
600 (cond ((memq this-command '(ivy-done
603 (setq swiper-multi-candidates
604 (swiper--multi-candidates
605 (mapcar #'get-buffer swiper-multi-buffers))))
606 ((eq this-command 'ivy-call)
607 (delete-minibuffer-contents))))
609 (defun swiper-multi-action-2 (x)
610 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
612 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
613 (switch-to-buffer (match-string 1 buf-space))
614 (goto-char (point-min))
615 (forward-line (1- (read (get-text-property 0 'display x))))
617 (ivy--regex ivy-text)
618 (line-end-position) t)
619 (unless (eq ivy-exit 'done)
621 (swiper--add-overlays (ivy--regex ivy-text)))))))
625 ;;; swiper.el ends here