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."
76 (defcustom swiper-min-highlight 2
77 "Only highlight matches for regexps at least this long."
81 (let ((map (make-sparse-keymap)))
82 (define-key map (kbd "M-q") 'swiper-query-replace)
83 (define-key map (kbd "C-l") 'swiper-recenter-top-bottom)
84 (define-key map (kbd "C-'") 'swiper-avy)
85 (define-key map (kbd "C-7") 'swiper-mc)
86 (define-key map (kbd "C-c C-f") 'swiper-toggle-face-matching)
90 (defun swiper-query-replace ()
91 "Start `query-replace' with string to replace from last search string."
93 (if (null (window-minibuffer-p))
94 (user-error "Should only be called in the minibuffer through `swiper-map'")
95 (let* ((enable-recursive-minibuffers t)
96 (from (ivy--regex ivy-text))
97 (to (minibuffer-with-setup-hook
99 (setq minibuffer-default
100 (if (string-match "\\`\\\\_<\\(.*\\)\\\\_>\\'" ivy-text)
101 (match-string 1 ivy-text)
103 (read-from-minibuffer (format "Query replace %s with: " from)))))
105 (ivy-exit-with-action
108 (move-beginning-of-line 1)
109 (perform-replace from to
112 (defvar avy-background)
113 (defvar avy-all-windows)
116 (declare-function avy--regex-candidates "ext:avy")
117 (declare-function avy--process "ext:avy")
118 (declare-function avy--overlay-post "ext:avy")
119 (declare-function avy-action-goto "ext:avy")
120 (declare-function avy--done "ext:avy")
121 (declare-function avy--make-backgrounds "ext:avy")
122 (declare-function avy-window-list "ext:avy")
123 (declare-function avy-read "ext:avy")
124 (declare-function avy-read-de-bruijn "ext:avy")
125 (declare-function avy-tree "ext:avy")
126 (declare-function avy-push-mark "ext:avy")
127 (declare-function avy--remove-leading-chars "ext:avy")
131 "Jump to one of the current swiper candidates."
133 (unless (string= ivy-text "")
134 (let* ((avy-all-windows nil)
137 (avy--regex-candidates
138 (ivy--regex ivy-text)))
141 (narrow-to-region (window-start) (window-end))
142 (goto-char (point-min))
145 (while (< (point) (point-max))
146 (push (cons (1+ (point))
151 (candidate (unwind-protect
153 (avy--make-backgrounds
154 (append (avy-window-list)
155 (list (ivy-state-window ivy-last))))
156 (if (eq avy-style 'de-bruijn)
159 (avy-read (avy-tree candidates avy-keys)
161 #'avy--remove-leading-chars))
164 (if (window-minibuffer-p (cdr candidate))
166 (ivy-set-index (- (line-number-at-pos (car candidate)) 2))
171 (avy-action-goto (caar candidate)))))))
173 (declare-function mc/create-fake-cursor-at-point "ext:multiple-cursors-core")
174 (declare-function multiple-cursors-mode "ext:multiple-cursors-core")
179 (unless (require 'multiple-cursors nil t)
180 (error "multiple-cursors isn't installed"))
181 (let ((cands (nreverse ivy--old-cands)))
182 (unless (string= ivy-text "")
183 (ivy-exit-with-action
186 (while (setq cand (pop cands))
187 (swiper--action cand)
189 (mc/create-fake-cursor-at-point))))
190 (multiple-cursors-mode 1))))))
192 (defun swiper-recenter-top-bottom (&optional arg)
193 "Call (`recenter-top-bottom' ARG)."
196 (recenter-top-bottom arg)))
198 (defvar swiper-font-lock-exclude
229 "List of major-modes that are incompatible with font-lock-ensure.")
231 (defun swiper-font-lock-ensure-p ()
232 "Return non-nil if we should font-lock-ensure."
233 (or (derived-mode-p 'magit-mode)
234 (bound-and-true-p magit-blame-mode)
235 (memq major-mode swiper-font-lock-exclude)))
237 (defun swiper-font-lock-ensure ()
238 "Ensure the entired buffer is highlighted."
239 (unless (swiper-font-lock-ensure-p)
240 (unless (or (> (buffer-size) 100000) (null font-lock-mode))
241 (if (fboundp 'font-lock-ensure)
243 (with-no-warnings (font-lock-fontify-buffer))))))
245 (defvar swiper--format-spec ""
246 "Store the current candidates format spec.")
248 (defvar swiper--width nil
249 "Store the number of digits needed for the longest line nubmer.")
251 (defvar swiper-use-visual-line nil
252 "When non-nil, use `line-move' instead of `forward-line'.")
254 (declare-function outline-show-all "outline")
256 (defun swiper--candidates (&optional numbers-width)
257 "Return a list of this buffer lines.
259 NUMBERS-WIDTH, when specified, is used for width spec of line
260 numbers; replaces calculating the width from buffer line count."
261 (if (and visual-line-mode
262 ;; super-slow otherwise
263 (< (buffer-size) 20000))
265 (when (eq major-mode 'org-mode)
267 (if (fboundp 'outline-show-all)
271 (setq swiper-use-visual-line t))
272 (setq swiper-use-visual-line nil))
273 (let ((n-lines (count-lines (point-min) (point-max))))
274 (unless (zerop n-lines)
275 (setq swiper--width (or numbers-width
276 (1+ (floor (log n-lines 10)))))
277 (setq swiper--format-spec
278 (format "%%-%dd " swiper--width))
279 (let ((line-number 0)
280 (advancer (if swiper-use-visual-line
281 (lambda (arg) (line-move arg t))
285 (goto-char (point-min))
286 (swiper-font-lock-ensure)
287 (while (< (point) (point-max))
290 (replace-regexp-in-string
292 (if swiper-use-visual-line
295 (beginning-of-visual-line)
302 (line-end-position)))))))
303 (remove-text-properties 0 (length str) '(field) str)
304 (put-text-property 0 1 'display
305 (format swiper--format-spec
306 (cl-incf line-number))
308 (push str candidates))
309 (funcall advancer 1))
310 (nreverse candidates))))))
312 (defvar swiper--opoint 1
313 "The point when `swiper' starts.")
316 (defun swiper (&optional initial-input)
317 "`isearch' with an overview.
318 When non-nil, INITIAL-INPUT is the initial search pattern."
320 (swiper--ivy (swiper--candidates) initial-input))
322 (declare-function string-trim-right "subr-x")
324 (defun swiper-occur (&optional revert)
325 "Generate a custom occur buffer for `swiper'.
326 When REVERT is non-nil, regenerate the current *ivy-occur* buffer."
327 (let* ((buffer (ivy-state-buffer ivy-last))
330 (if (buffer-file-name buffer)
331 (file-name-nondirectory
332 (buffer-file-name buffer))
333 (buffer-name buffer)))
342 (get-text-property 0 'display s))
343 'face 'compilation-line-number)
347 (setq ivy--old-re nil)
348 (let ((ivy--regex-function 'swiper--re-builder))
350 (progn (string-match "\"\\(.*\\)\"" (buffer-name))
351 (match-string 1 (buffer-name)))
352 (with-current-buffer buffer
353 (swiper--candidates))))))))
354 (unless (eq major-mode 'ivy-occur-grep-mode)
355 (ivy-occur-grep-mode)
357 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
359 (insert (format "%d candidates:\n" (length cands)))
360 (ivy--occur-insert-lines
362 (lambda (cand) (concat "./" cand))
364 (goto-char (point-min))
367 (ivy-set-occur 'swiper 'swiper-occur)
369 (declare-function evil-jumper--set-jump "ext:evil-jumper")
371 (defvar swiper--current-line nil)
372 (defvar swiper--current-match-start nil)
374 (defun swiper--init ()
375 "Perform initialization common to both completion methods."
376 (setq swiper--current-line nil)
377 (setq swiper--current-match-start nil)
378 (setq swiper--opoint (point))
379 (when (bound-and-true-p evil-jumper-mode)
380 (evil-jumper--set-jump)))
382 (defun swiper--re-builder (str)
383 "Transform STR into a swiper regex.
384 This is the regex used in the minibuffer where candidates have
385 line numbers. For the buffer, use `ivy--regex' instead."
386 (replace-regexp-in-string
392 (setq ivy--subexps 0)
394 ((string-match "^\\^" str)
395 (setq ivy--old-re "")
396 (let ((re (ivy--regex-plus (substring str 1))))
397 (if (zerop ivy--subexps)
398 (prog1 (format "^ ?\\(%s\\)" re)
399 (setq ivy--subexps 1))
400 (format "^ %s" re))))
402 (ivy--regex-plus str)))))
404 (defvar swiper-history nil
405 "History for `swiper'.")
407 (defvar swiper-invocation-face nil
408 "The face at the point of invocation of `swiper'.")
410 (defun swiper--ivy (candidates &optional initial-input)
411 "Select one of CANDIDATES and move there.
412 When non-nil, INITIAL-INPUT is the initial search pattern."
415 (setq swiper-invocation-face
416 (plist-get (text-properties-at (point)) 'face))
418 (if swiper-use-visual-line
421 (save-excursion (beginning-of-visual-line) (point)))
422 (1- (line-number-at-pos))))
423 (minibuffer-allow-text-properties t)
431 :initial-input initial-input
435 :update-fn #'swiper--update-input-ivy
436 :unwind #'swiper--cleanup
437 :action #'swiper--action
438 :re-builder #'swiper--re-builder
439 :history 'swiper-history
443 (goto-char swiper--opoint)))))
445 (defun swiper-toggle-face-matching ()
446 "Toggle matching only the candidates with `swiper-invocation-face'."
448 (setf (ivy-state-matcher ivy-last)
449 (if (ivy-state-matcher ivy-last)
451 #'swiper--face-matcher))
452 (setq ivy--old-re nil))
454 (defun swiper--face-matcher (regexp candidates)
455 "Return REGEXP-matching CANDIDATES.
456 Matched candidates should have `swiper-invocation-face'."
460 (string-match regexp x)
461 (let ((s (match-string 0 x))
463 (while (and (< i (length s))
466 'face swiper-invocation-face
472 (defun swiper--ensure-visible ()
473 "Remove overlays hiding point."
474 (let ((overlays (overlays-at (1- (point))))
476 (while (setq ov (pop overlays))
477 (if (and (invisible-p (overlay-get ov 'invisible))
478 (setq expose (overlay-get ov 'isearch-open-invisible)))
479 (funcall expose ov)))))
481 (defvar swiper--overlays nil
484 (defun swiper--cleanup ()
485 "Clean up the overlays."
486 (while swiper--overlays
487 (delete-overlay (pop swiper--overlays)))
489 (goto-char (point-min))
490 (isearch-clean-overlays)))
492 (defun swiper--update-input-ivy ()
493 "Called when `ivy' input is updated."
496 (when (> (length ivy--current) 0)
497 (let* ((re (replace-regexp-in-string
499 (funcall ivy--regex-function ivy-text)))
500 (re (if (stringp re) re (caar re)))
501 (str (get-text-property 0 'display ivy--current))
502 (num (if (string-match "^[0-9]+" str)
503 (string-to-number (match-string 0 str))
505 (unless (eq this-command 'ivy-yank-word)
507 (unless (if swiper--current-line
508 (eq swiper--current-line num)
509 (eq (line-number-at-pos) num))
510 (goto-char (point-min))
511 (if swiper-use-visual-line
513 (forward-line (1- num))))
514 (if (and (equal ivy-text "")
515 (>= swiper--opoint (line-beginning-position))
516 (<= swiper--opoint (line-end-position)))
517 (goto-char swiper--opoint)
518 (if (eq swiper--current-line num)
519 (when swiper--current-match-start
520 (goto-char swiper--current-match-start))
521 (setq swiper--current-line num))
522 (when (re-search-forward re (line-end-position) t)
523 (setq swiper--current-match-start (match-beginning 0))))
524 (isearch-range-invisible (line-beginning-position)
526 (unless (and (>= (point) (window-start))
527 (<= (point) (window-end (ivy-state-window ivy-last) t)))
529 (swiper--add-overlays re)))))
531 (defun swiper--add-overlays (re &optional beg end wnd)
532 "Add overlays for RE regexp in visible part of the current buffer.
533 BEG and END, when specified, are the point bounds.
534 WND, when specified is the window."
535 (setq wnd (or wnd (ivy-state-window ivy-last)))
536 (let ((ov (if visual-line-mode
539 (beginning-of-visual-line)
545 (line-beginning-position)
546 (1+ (line-end-position))))))
547 (overlay-put ov 'face 'swiper-line-face)
548 (overlay-put ov 'window wnd)
549 (push ov swiper--overlays)
550 (let* ((wh (window-height))
551 (beg (or beg (save-excursion
552 (forward-line (- wh))
554 (end (or end (save-excursion
557 (when (>= (length re) swiper-min-highlight)
560 ;; RE can become an invalid regexp
561 (while (and (ignore-errors (re-search-forward re end t))
562 (> (- (match-end 0) (match-beginning 0)) 0))
564 (while (<= i ivy--subexps)
565 (when (match-beginning i)
566 (let ((overlay (make-overlay (match-beginning i)
569 (cond ((zerop ivy--subexps)
574 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
576 (push overlay swiper--overlays)
577 (overlay-put overlay 'face face)
578 (overlay-put overlay 'window wnd)
579 (overlay-put overlay 'priority i)))
582 (defun swiper--action (x)
584 (let ((ln (1- (read (or (get-text-property 0 'display x)
585 (and (string-match ":\\([0-9]+\\):.*\\'" x)
586 (match-string-no-properties 1 x))))))
587 (re (ivy--regex ivy-text)))
589 (user-error "No candidates")
591 (unless (equal (current-buffer)
592 (ivy-state-buffer ivy-last))
593 (switch-to-buffer (ivy-state-buffer ivy-last)))
594 (goto-char (point-min))
595 (funcall (if swiper-use-visual-line
599 (re-search-forward re (line-end-position) t)
600 (swiper--ensure-visible)
601 (when (/= (point) swiper--opoint)
602 (unless (and transient-mark-mode mark-active)
603 (when (eq ivy-exit 'done)
604 (push-mark swiper--opoint t)
605 (message "Mark saved where search started"))))
609 regexp-search-ring-max)))))
611 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
612 (defun swiper-from-isearch ()
613 "Invoke `swiper' from isearch."
615 (let ((query (if isearch-regexp
617 (regexp-quote isearch-string))))
621 (defvar swiper-multi-buffers nil
622 "Store the current list of buffers.")
624 (defvar swiper-multi-candidates nil
625 "Store the list of candidates for `swiper-multi'.")
627 (defun swiper-multi-prompt ()
628 (format "Buffers (%s): "
629 (mapconcat #'identity swiper-multi-buffers ", ")))
631 (defun swiper-multi ()
632 "Select one or more buffers.
633 Run `swiper' for those buffers."
635 (setq swiper-multi-buffers nil)
636 (ivy-read (swiper-multi-prompt)
637 'internal-complete-buffer
638 :action 'swiper-multi-action-1)
639 (ivy-read "Swiper: " swiper-multi-candidates
640 :action 'swiper-multi-action-2
641 :unwind #'swiper--cleanup
642 :caller 'swiper-multi))
645 "Run `swiper' for all opened buffers."
647 (ivy-read "Swiper: " (swiper--multi-candidates
651 :action 'swiper-multi-action-2
652 :unwind #'swiper--cleanup
653 :update-fn (lambda ()
654 (swiper-multi-action-2 ivy--current))
655 :caller 'swiper-multi))
657 (defun swiper--multi-candidates (buffers)
658 (let* ((ww (window-width))
660 (column-2 (apply #'max
663 (length (buffer-name b)))
665 (column-1 (- ww 4 column-2 1)))
666 (dolist (buf buffers)
667 (with-current-buffer buf
672 (setq s (concat (ivy--truncate-string s column-1) " "))
673 (let ((len (length s)))
675 (1- len) len 'display
678 (- ww (string-width s) (length (buffer-name)) 3)
683 (swiper--candidates 4))
688 (defun swiper-multi-action-1 (x)
689 (if (member x swiper-multi-buffers)
691 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
693 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
694 (let ((prompt (swiper-multi-prompt)))
695 (setf (ivy-state-prompt ivy-last) prompt)
696 (setq ivy--prompt (concat "%-4d " prompt)))
697 (cond ((memq this-command '(ivy-done
700 (setq swiper-multi-candidates
701 (swiper--multi-candidates
702 (mapcar #'get-buffer swiper-multi-buffers))))
703 ((eq this-command 'ivy-call)
704 (delete-minibuffer-contents))))
706 (defun swiper-multi-action-2 (x)
707 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
709 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
710 (switch-to-buffer (match-string 1 buf-space))
711 (goto-char (point-min))
712 (forward-line (1- (read (get-text-property 0 'display x))))
714 (ivy--regex ivy-text)
715 (line-end-position) t)
716 (unless (eq ivy-exit 'done)
718 (swiper--add-overlays (ivy--regex ivy-text)))))))
722 ;;; swiper.el ends here