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 (defvar swiper-font-lock-exclude
232 "List of major-modes that are incompatible with font-lock-ensure.")
234 (defun swiper-font-lock-ensure-p ()
235 "Return non-nil if we should font-lock-ensure."
236 (or (derived-mode-p 'magit-mode)
237 (bound-and-true-p magit-blame-mode)
238 (memq major-mode swiper-font-lock-exclude)))
240 (defun swiper-font-lock-ensure ()
241 "Ensure the entired buffer is highlighted."
242 (unless (swiper-font-lock-ensure-p)
243 (unless (> (buffer-size) 100000)
244 (if (fboundp 'font-lock-ensure)
246 (with-no-warnings (font-lock-fontify-buffer))))))
248 (defvar swiper--format-spec ""
249 "Store the current candidates format spec.")
251 (defvar swiper--width nil
252 "Store the amount of digits needed for the longest line nubmer.")
254 (defvar swiper-use-visual-line nil
255 "When non-nil, use `line-move' instead of `forward-line'.")
257 (declare-function outline-show-all "outline")
259 (defun swiper--candidates (&optional numbers-width)
260 "Return a list of this buffer lines.
262 NUMBERS-WIDTH, when specified, is used for line numbers width
263 spec, instead of calculating it as the log of the buffer line
265 (if (and visual-line-mode
266 ;; super-slow otherwise
267 (< (buffer-size) 20000))
269 (when (eq major-mode 'org-mode)
271 (if (fboundp 'outline-show-all)
275 (setq swiper-use-visual-line t))
276 (setq swiper-use-visual-line nil))
277 (let ((n-lines (count-lines (point-min) (point-max))))
278 (unless (zerop n-lines)
279 (setq swiper--width (or numbers-width
280 (1+ (floor (log n-lines 10)))))
281 (setq swiper--format-spec
282 (format "%%-%dd " swiper--width))
283 (let ((line-number 0)
284 (advancer (if swiper-use-visual-line
285 (lambda (arg) (line-move arg t))
289 (goto-char (point-min))
290 (swiper-font-lock-ensure)
291 (while (< (point) (point-max))
294 (replace-regexp-in-string
296 (if swiper-use-visual-line
299 (beginning-of-visual-line)
306 (line-end-position)))))))
307 (when (eq major-mode 'twittering-mode)
308 (remove-text-properties 0 (length str) '(field) str))
309 (put-text-property 0 1 'display
310 (format swiper--format-spec
311 (cl-incf line-number))
313 (push str candidates))
314 (funcall advancer 1))
315 (nreverse candidates))))))
317 (defvar swiper--opoint 1
318 "The point when `swiper' starts.")
321 (defun swiper (&optional initial-input)
322 "`isearch' with an overview.
323 When non-nil, INITIAL-INPUT is the initial search pattern."
325 (swiper--ivy initial-input))
327 (declare-function evil-jumper--set-jump "ext:evil-jumper")
329 (defvar swiper--current-line nil)
330 (defvar swiper--current-match-start nil)
332 (defun swiper--init ()
333 "Perform initialization common to both completion methods."
334 (setq swiper--current-line nil)
335 (setq swiper--current-match-start nil)
336 (setq swiper--opoint (point))
337 (when (bound-and-true-p evil-jumper-mode)
338 (evil-jumper--set-jump)))
340 (defun swiper--re-builder (str)
341 "Transform STR into a swiper regex.
342 This is the regex used in the minibuffer, since the candidates
343 there have line numbers. In the buffer, `ivy--regex' should be used."
348 (setq ivy--subexps 0)
350 ((string-match "^\\^" str)
351 (setq ivy--old-re "")
352 (let ((re (ivy--regex-plus (substring str 1))))
353 (if (zerop ivy--subexps)
354 (prog1 (format "^ ?\\(%s\\)" re)
355 (setq ivy--subexps 1))
356 (format "^ %s" re))))
358 (ivy--regex-plus str))))
360 (defvar swiper-history nil
361 "History for `swiper'.")
363 (defvar swiper-invocation-face nil
364 "The face at the point of invocation of `swiper'.")
366 (defun swiper--ivy (&optional initial-input)
367 "`isearch' with an overview using `ivy'.
368 When non-nil, INITIAL-INPUT is the initial search pattern."
371 (setq swiper-invocation-face
372 (plist-get (text-properties-at (point)) 'face))
373 (let ((candidates (swiper--candidates))
375 (if swiper-use-visual-line
378 (save-excursion (beginning-of-visual-line) (point)))
379 (1- (line-number-at-pos))))
380 (minibuffer-allow-text-properties t)
387 :initial-input initial-input
391 :update-fn #'swiper--update-input-ivy
392 :unwind #'swiper--cleanup
393 :action #'swiper--action
394 :re-builder #'swiper--re-builder
395 :history 'swiper-history
398 (goto-char swiper--opoint)))))
400 (defun swiper-toggle-face-matching ()
401 "Toggle matching only the candidates with `swiper-invocation-face'."
403 (setf (ivy-state-matcher ivy-last)
404 (if (ivy-state-matcher ivy-last)
406 #'swiper--face-matcher))
407 (setq ivy--old-re nil))
409 (defun swiper--face-matcher (regexp candidates)
410 "Return REGEXP-matching CANDIDATES.
411 Matched candidates should have `swiper-invocation-face'."
415 (string-match regexp x)
416 (let ((s (match-string 0 x))
418 (while (and (< i (length s))
421 'face swiper-invocation-face
427 (defun swiper--ensure-visible ()
428 "Remove overlays hiding point."
429 (let ((overlays (overlays-at (point)))
431 (while (setq ov (pop overlays))
432 (if (and (invisible-p (overlay-get ov 'invisible))
433 (setq expose (overlay-get ov 'isearch-open-invisible)))
434 (funcall expose ov)))))
436 (defvar swiper--overlays nil
439 (defun swiper--cleanup ()
440 "Clean up the overlays."
441 (while swiper--overlays
442 (delete-overlay (pop swiper--overlays)))
444 (goto-char (point-min))
445 (isearch-clean-overlays)))
447 (defun swiper--update-input-ivy ()
448 "Called when `ivy' input is updated."
451 (when (> (length ivy--current) 0)
452 (let* ((re (funcall ivy--regex-function ivy-text))
453 (re (if (stringp re) re (caar re)))
454 (str (get-text-property 0 'display ivy--current))
455 (num (if (string-match "^[0-9]+" str)
456 (string-to-number (match-string 0 str))
458 (unless (eq this-command 'ivy-yank-word)
460 (unless (if swiper--current-line
461 (eq swiper--current-line num)
462 (eq (line-number-at-pos) num))
463 (goto-char (point-min))
464 (if swiper-use-visual-line
466 (forward-line (1- num))))
467 (if (and (equal ivy-text "")
468 (>= swiper--opoint (line-beginning-position))
469 (<= swiper--opoint (line-end-position)))
470 (goto-char swiper--opoint)
471 (if (eq swiper--current-line num)
472 (when swiper--current-match-start
473 (goto-char swiper--current-match-start))
474 (setq swiper--current-line num))
475 (re-search-forward re (line-end-position) t)
476 (setq swiper--current-match-start (match-beginning 0)))
477 (isearch-range-invisible (line-beginning-position)
479 (unless (and (>= (point) (window-start))
480 (<= (point) (window-end (ivy-state-window ivy-last) t)))
482 (swiper--add-overlays re)))))
484 (defun swiper--add-overlays (re &optional beg end wnd)
485 "Add overlays for RE regexp in visible part of the current buffer.
486 BEG and END, when specified, are the point bounds.
487 WND, when specified is the window."
488 (setq wnd (or wnd (ivy-state-window ivy-last)))
489 (let ((ov (if visual-line-mode
492 (beginning-of-visual-line)
498 (line-beginning-position)
499 (1+ (line-end-position))))))
500 (overlay-put ov 'face 'swiper-line-face)
501 (overlay-put ov 'window wnd)
502 (push ov swiper--overlays)
503 (let* ((wh (window-height))
504 (beg (or beg (save-excursion
505 (forward-line (- wh))
507 (end (or end (save-excursion
510 (when (>= (length re) swiper-min-highlight)
513 ;; RE can become an invalid regexp
514 (while (and (ignore-errors (re-search-forward re end t))
515 (> (- (match-end 0) (match-beginning 0)) 0))
517 (while (<= i ivy--subexps)
518 (when (match-beginning i)
519 (let ((overlay (make-overlay (match-beginning i)
522 (cond ((zerop ivy--subexps)
527 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
529 (push overlay swiper--overlays)
530 (overlay-put overlay 'face face)
531 (overlay-put overlay 'window wnd)
532 (overlay-put overlay 'priority i)))
535 (defun swiper--action (x)
538 (user-error "No candidates")
540 (unless (equal (current-buffer)
541 (ivy-state-buffer ivy-last))
542 (switch-to-buffer (ivy-state-buffer ivy-last)))
543 (goto-char (point-min))
544 (funcall (if swiper-use-visual-line
547 (1- (read (get-text-property 0 'display x))))
549 (ivy--regex ivy-text) (line-end-position) t)
550 (swiper--ensure-visible)
551 (when (/= (point) swiper--opoint)
552 (unless (and transient-mark-mode mark-active)
553 (when (eq ivy-exit 'done)
554 (push-mark swiper--opoint t)
555 (message "Mark saved where search started")))))))
557 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
558 (defun swiper-from-isearch ()
559 "Invoke `swiper' from isearch."
561 (let ((query (if isearch-regexp
563 (regexp-quote isearch-string))))
567 (defvar swiper-multi-buffers nil
568 "Store the current list of buffers.")
570 (defvar swiper-multi-candidates nil
571 "Store the list of candidates for `swiper-multi'.")
573 (defun swiper-multi-prompt ()
574 (format "Buffers (%s): "
575 (mapconcat #'identity swiper-multi-buffers ", ")))
577 (defun swiper-multi ()
578 "Select one or more buffers.
579 Run `swiper' for those buffers."
581 (setq swiper-multi-buffers nil)
582 (ivy-read (swiper-multi-prompt)
583 'internal-complete-buffer
584 :action 'swiper-multi-action-1)
585 (ivy-read "Swiper: " swiper-multi-candidates
586 :action 'swiper-multi-action-2
587 :unwind #'swiper--cleanup
588 :caller 'swiper-multi))
591 "Run `swiper' for all opened buffers."
593 (ivy-read "Swiper: " (swiper--multi-candidates
597 :action 'swiper-multi-action-2
598 :unwind #'swiper--cleanup
599 :caller 'swiper-multi))
601 (defun swiper--multi-candidates (buffers)
602 (let* ((ww (window-width))
604 (column-2 (apply #'max
607 (length (buffer-name b)))
609 (column-1 (- ww 4 column-2 1)))
610 (dolist (buf buffers)
611 (with-current-buffer buf
616 (setq s (concat (ivy--truncate-string s column-1) " "))
617 (let ((len (length s)))
619 (1- len) len 'display
622 (- ww (string-width s) (length (buffer-name)) 3)
627 (swiper--candidates 4))
632 (defun swiper-multi-action-1 (x)
633 (if (member x swiper-multi-buffers)
635 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
637 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
638 (let ((prompt (swiper-multi-prompt)))
639 (setf (ivy-state-prompt ivy-last) prompt)
640 (setq ivy--prompt (concat "%-4d " prompt)))
641 (cond ((memq this-command '(ivy-done
644 (setq swiper-multi-candidates
645 (swiper--multi-candidates
646 (mapcar #'get-buffer swiper-multi-buffers))))
647 ((eq this-command 'ivy-call)
648 (delete-minibuffer-contents))))
650 (defun swiper-multi-action-2 (x)
651 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
653 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
654 (switch-to-buffer (match-string 1 buf-space))
655 (goto-char (point-min))
656 (forward-line (1- (read (get-text-property 0 'display x))))
658 (ivy--regex ivy-text)
659 (line-end-position) t)
660 (unless (eq ivy-exit 'done)
662 (swiper--add-overlays (ivy--regex ivy-text)))))))
666 ;;; swiper.el ends here