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 (query-replace-read-to from "Query replace" t)))
102 (move-beginning-of-line 1)
103 (perform-replace from to
106 (defvar avy-background)
107 (defvar avy-all-windows)
110 (declare-function avy--regex-candidates "ext:avy")
111 (declare-function avy--process "ext:avy")
112 (declare-function avy--overlay-post "ext:avy")
113 (declare-function avy-action-goto "ext:avy")
114 (declare-function avy--done "ext:avy")
115 (declare-function avy--make-backgrounds "ext:avy")
116 (declare-function avy-window-list "ext:avy")
117 (declare-function avy-read "ext:avy")
118 (declare-function avy-read-de-bruijn "ext:avy")
119 (declare-function avy-tree "ext:avy")
120 (declare-function avy-push-mark "ext:avy")
121 (declare-function avy--remove-leading-chars "ext:avy")
125 "Jump to one of the current swiper candidates."
127 (unless (string= ivy-text "")
128 (let* ((avy-all-windows nil)
131 (avy--regex-candidates
132 (ivy--regex ivy-text)))
135 (narrow-to-region (window-start) (window-end))
136 (goto-char (point-min))
139 (while (< (point) (point-max))
140 (push (cons (1+ (point))
145 (candidate (unwind-protect
147 (avy--make-backgrounds
148 (append (avy-window-list)
149 (list (ivy-state-window ivy-last))))
150 (if (eq avy-style 'de-bruijn)
153 (avy-read (avy-tree candidates avy-keys)
155 #'avy--remove-leading-chars))
158 (if (window-minibuffer-p (cdr candidate))
160 (ivy-set-index (- (line-number-at-pos (car candidate)) 2))
165 (avy-action-goto (caar candidate)))))))
167 (declare-function mc/create-fake-cursor-at-point "ext:multiple-cursors-core")
168 (declare-function multiple-cursors-mode "ext:multiple-cursors-core")
173 (unless (require 'multiple-cursors nil t)
174 (error "multiple-cursors isn't installed"))
175 (let ((cands (nreverse ivy--old-cands)))
176 (unless (string= ivy-text "")
177 (ivy-exit-with-action
180 (while (setq cand (pop cands))
181 (swiper--action cand)
183 (mc/create-fake-cursor-at-point))))
184 (multiple-cursors-mode 1))))))
186 (defun swiper-recenter-top-bottom (&optional arg)
187 "Call (`recenter-top-bottom' ARG)."
190 (recenter-top-bottom arg)))
192 (defvar swiper-font-lock-exclude
223 "List of major-modes that are incompatible with font-lock-ensure.")
225 (defun swiper-font-lock-ensure-p ()
226 "Return non-nil if we should font-lock-ensure."
227 (or (derived-mode-p 'magit-mode)
228 (bound-and-true-p magit-blame-mode)
229 (memq major-mode swiper-font-lock-exclude)))
231 (defun swiper-font-lock-ensure ()
232 "Ensure the entired buffer is highlighted."
233 (unless (swiper-font-lock-ensure-p)
234 (unless (or (> (buffer-size) 100000) (null font-lock-mode))
235 (if (fboundp 'font-lock-ensure)
237 (with-no-warnings (font-lock-fontify-buffer))))))
239 (defvar swiper--format-spec ""
240 "Store the current candidates format spec.")
242 (defvar swiper--width nil
243 "Store the number of digits needed for the longest line nubmer.")
245 (defvar swiper-use-visual-line nil
246 "When non-nil, use `line-move' instead of `forward-line'.")
248 (declare-function outline-show-all "outline")
250 (defun swiper--candidates (&optional numbers-width)
251 "Return a list of this buffer lines.
253 NUMBERS-WIDTH, when specified, is used for width spec of line
254 numbers; replaces calculating the width from buffer line count."
255 (if (and visual-line-mode
256 ;; super-slow otherwise
257 (< (buffer-size) 20000))
259 (when (eq major-mode 'org-mode)
261 (if (fboundp 'outline-show-all)
265 (setq swiper-use-visual-line t))
266 (setq swiper-use-visual-line nil))
267 (let ((n-lines (count-lines (point-min) (point-max))))
268 (unless (zerop n-lines)
269 (setq swiper--width (or numbers-width
270 (1+ (floor (log n-lines 10)))))
271 (setq swiper--format-spec
272 (format "%%-%dd " swiper--width))
273 (let ((line-number 0)
274 (advancer (if swiper-use-visual-line
275 (lambda (arg) (line-move arg t))
279 (goto-char (point-min))
280 (swiper-font-lock-ensure)
281 (while (< (point) (point-max))
284 (replace-regexp-in-string
286 (if swiper-use-visual-line
289 (beginning-of-visual-line)
296 (line-end-position)))))))
297 (when (eq major-mode 'twittering-mode)
298 (remove-text-properties 0 (length str) '(field) str))
299 (put-text-property 0 1 'display
300 (format swiper--format-spec
301 (cl-incf line-number))
303 (push str candidates))
304 (funcall advancer 1))
305 (nreverse candidates))))))
307 (defvar swiper--opoint 1
308 "The point when `swiper' starts.")
311 (defun swiper (&optional initial-input)
312 "`isearch' with an overview.
313 When non-nil, INITIAL-INPUT is the initial search pattern."
315 (swiper--ivy (swiper--candidates) initial-input))
317 (declare-function string-trim-right "subr-x")
319 (defun swiper-occur ()
320 "Generate a custom occur buffer for `swiper'."
321 (let* ((fname (propertize
323 (file-name-nondirectory
325 (ivy-state-buffer ivy-last))))
334 (get-text-property 0 'display s))
335 'face 'compilation-line-number)
338 (unless (eq major-mode 'ivy-occur-grep-mode)
339 (ivy-occur-grep-mode)
341 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
343 (insert (format "%d candidates:\n" (length cands)))
344 (ivy--occur-insert-lines
346 (lambda (cand) (concat "./" cand))
349 (ivy-set-occur 'swiper 'swiper-occur)
351 (declare-function evil-jumper--set-jump "ext:evil-jumper")
353 (defvar swiper--current-line nil)
354 (defvar swiper--current-match-start nil)
356 (defun swiper--init ()
357 "Perform initialization common to both completion methods."
358 (setq swiper--current-line nil)
359 (setq swiper--current-match-start nil)
360 (setq swiper--opoint (point))
361 (when (bound-and-true-p evil-jumper-mode)
362 (evil-jumper--set-jump)))
364 (defun swiper--re-builder (str)
365 "Transform STR into a swiper regex.
366 This is the regex used in the minibuffer where candidates have
367 line numbers. For the buffer, use `ivy--regex' instead."
368 (replace-regexp-in-string
374 (setq ivy--subexps 0)
376 ((string-match "^\\^" str)
377 (setq ivy--old-re "")
378 (let ((re (ivy--regex-plus (substring str 1))))
379 (if (zerop ivy--subexps)
380 (prog1 (format "^ ?\\(%s\\)" re)
381 (setq ivy--subexps 1))
382 (format "^ %s" re))))
384 (ivy--regex-plus str)))))
386 (defvar swiper-history nil
387 "History for `swiper'.")
389 (defvar swiper-invocation-face nil
390 "The face at the point of invocation of `swiper'.")
392 (defun swiper--ivy (candidates &optional initial-input)
393 "Select one of CANDIDATES and move there.
394 When non-nil, INITIAL-INPUT is the initial search pattern."
397 (setq swiper-invocation-face
398 (plist-get (text-properties-at (point)) 'face))
400 (if swiper-use-visual-line
403 (save-excursion (beginning-of-visual-line) (point)))
404 (1- (line-number-at-pos))))
405 (minibuffer-allow-text-properties t)
413 :initial-input initial-input
417 :update-fn #'swiper--update-input-ivy
418 :unwind #'swiper--cleanup
419 :action #'swiper--action
420 :re-builder #'swiper--re-builder
421 :history 'swiper-history
425 (goto-char swiper--opoint)))))
427 (defun swiper-toggle-face-matching ()
428 "Toggle matching only the candidates with `swiper-invocation-face'."
430 (setf (ivy-state-matcher ivy-last)
431 (if (ivy-state-matcher ivy-last)
433 #'swiper--face-matcher))
434 (setq ivy--old-re nil))
436 (defun swiper--face-matcher (regexp candidates)
437 "Return REGEXP-matching CANDIDATES.
438 Matched candidates should have `swiper-invocation-face'."
442 (string-match regexp x)
443 (let ((s (match-string 0 x))
445 (while (and (< i (length s))
448 'face swiper-invocation-face
454 (defun swiper--ensure-visible ()
455 "Remove overlays hiding point."
456 (let ((overlays (overlays-at (1- (point))))
458 (while (setq ov (pop overlays))
459 (if (and (invisible-p (overlay-get ov 'invisible))
460 (setq expose (overlay-get ov 'isearch-open-invisible)))
461 (funcall expose ov)))))
463 (defvar swiper--overlays nil
466 (defun swiper--cleanup ()
467 "Clean up the overlays."
468 (while swiper--overlays
469 (delete-overlay (pop swiper--overlays)))
471 (goto-char (point-min))
472 (isearch-clean-overlays)))
474 (defun swiper--update-input-ivy ()
475 "Called when `ivy' input is updated."
478 (when (> (length ivy--current) 0)
479 (let* ((re (replace-regexp-in-string
481 (funcall ivy--regex-function ivy-text)))
482 (re (if (stringp re) re (caar re)))
483 (str (get-text-property 0 'display ivy--current))
484 (num (if (string-match "^[0-9]+" str)
485 (string-to-number (match-string 0 str))
487 (unless (eq this-command 'ivy-yank-word)
489 (unless (if swiper--current-line
490 (eq swiper--current-line num)
491 (eq (line-number-at-pos) num))
492 (goto-char (point-min))
493 (if swiper-use-visual-line
495 (forward-line (1- num))))
496 (if (and (equal ivy-text "")
497 (>= swiper--opoint (line-beginning-position))
498 (<= swiper--opoint (line-end-position)))
499 (goto-char swiper--opoint)
500 (if (eq swiper--current-line num)
501 (when swiper--current-match-start
502 (goto-char swiper--current-match-start))
503 (setq swiper--current-line num))
504 (when (re-search-forward re (line-end-position) t)
505 (setq swiper--current-match-start (match-beginning 0))))
506 (isearch-range-invisible (line-beginning-position)
508 (unless (and (>= (point) (window-start))
509 (<= (point) (window-end (ivy-state-window ivy-last) t)))
511 (swiper--add-overlays re)))))
513 (defun swiper--add-overlays (re &optional beg end wnd)
514 "Add overlays for RE regexp in visible part of the current buffer.
515 BEG and END, when specified, are the point bounds.
516 WND, when specified is the window."
517 (setq wnd (or wnd (ivy-state-window ivy-last)))
518 (let ((ov (if visual-line-mode
521 (beginning-of-visual-line)
527 (line-beginning-position)
528 (1+ (line-end-position))))))
529 (overlay-put ov 'face 'swiper-line-face)
530 (overlay-put ov 'window wnd)
531 (push ov swiper--overlays)
532 (let* ((wh (window-height))
533 (beg (or beg (save-excursion
534 (forward-line (- wh))
536 (end (or end (save-excursion
539 (when (>= (length re) swiper-min-highlight)
542 ;; RE can become an invalid regexp
543 (while (and (ignore-errors (re-search-forward re end t))
544 (> (- (match-end 0) (match-beginning 0)) 0))
546 (while (<= i ivy--subexps)
547 (when (match-beginning i)
548 (let ((overlay (make-overlay (match-beginning i)
551 (cond ((zerop ivy--subexps)
556 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
558 (push overlay swiper--overlays)
559 (overlay-put overlay 'face face)
560 (overlay-put overlay 'window wnd)
561 (overlay-put overlay 'priority i)))
564 (defun swiper--action (x)
566 (let ((ln (1- (read (or (get-text-property 0 'display x)
567 (and (string-match ":\\([0-9]+\\):.*\\'" x)
568 (match-string-no-properties 1 x))))))
569 (re (ivy--regex ivy-text)))
571 (user-error "No candidates")
573 (unless (equal (current-buffer)
574 (ivy-state-buffer ivy-last))
575 (switch-to-buffer (ivy-state-buffer ivy-last)))
576 (goto-char (point-min))
577 (funcall (if swiper-use-visual-line
581 (re-search-forward re (line-end-position) t)
582 (swiper--ensure-visible)
583 (when (/= (point) swiper--opoint)
584 (unless (and transient-mark-mode mark-active)
585 (when (eq ivy-exit 'done)
586 (push-mark swiper--opoint t)
587 (message "Mark saved where search started"))))
591 regexp-search-ring-max)))))
593 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
594 (defun swiper-from-isearch ()
595 "Invoke `swiper' from isearch."
597 (let ((query (if isearch-regexp
599 (regexp-quote isearch-string))))
603 (defvar swiper-multi-buffers nil
604 "Store the current list of buffers.")
606 (defvar swiper-multi-candidates nil
607 "Store the list of candidates for `swiper-multi'.")
609 (defun swiper-multi-prompt ()
610 (format "Buffers (%s): "
611 (mapconcat #'identity swiper-multi-buffers ", ")))
613 (defun swiper-multi ()
614 "Select one or more buffers.
615 Run `swiper' for those buffers."
617 (setq swiper-multi-buffers nil)
618 (ivy-read (swiper-multi-prompt)
619 'internal-complete-buffer
620 :action 'swiper-multi-action-1)
621 (ivy-read "Swiper: " swiper-multi-candidates
622 :action 'swiper-multi-action-2
623 :unwind #'swiper--cleanup
624 :caller 'swiper-multi))
627 "Run `swiper' for all opened buffers."
629 (ivy-read "Swiper: " (swiper--multi-candidates
633 :action 'swiper-multi-action-2
634 :unwind #'swiper--cleanup
635 :update-fn (lambda ()
636 (swiper-multi-action-2 ivy--current))
637 :caller 'swiper-multi))
639 (defun swiper--multi-candidates (buffers)
640 (let* ((ww (window-width))
642 (column-2 (apply #'max
645 (length (buffer-name b)))
647 (column-1 (- ww 4 column-2 1)))
648 (dolist (buf buffers)
649 (with-current-buffer buf
654 (setq s (concat (ivy--truncate-string s column-1) " "))
655 (let ((len (length s)))
657 (1- len) len 'display
660 (- ww (string-width s) (length (buffer-name)) 3)
665 (swiper--candidates 4))
670 (defun swiper-multi-action-1 (x)
671 (if (member x swiper-multi-buffers)
673 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
675 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
676 (let ((prompt (swiper-multi-prompt)))
677 (setf (ivy-state-prompt ivy-last) prompt)
678 (setq ivy--prompt (concat "%-4d " prompt)))
679 (cond ((memq this-command '(ivy-done
682 (setq swiper-multi-candidates
683 (swiper--multi-candidates
684 (mapcar #'get-buffer swiper-multi-buffers))))
685 ((eq this-command 'ivy-call)
686 (delete-minibuffer-contents))))
688 (defun swiper-multi-action-2 (x)
689 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
691 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
692 (switch-to-buffer (match-string 1 buf-space))
693 (goto-char (point-min))
694 (forward-line (1- (read (get-text-property 0 'display x))))
696 (ivy--regex ivy-text)
697 (line-end-position) t)
698 (unless (eq ivy-exit 'done)
700 (swiper--add-overlays (ivy--regex ivy-text)))))))
704 ;;; swiper.el ends here