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")
177 "Create a fake cursor for each `swiper' candidate."
179 (unless (require 'multiple-cursors nil t)
180 (error "multiple-cursors isn't installed"))
181 (unless (window-minibuffer-p)
182 (error "Call me only from `swiper'"))
183 (let ((cands (nreverse ivy--old-cands)))
184 (unless (string= ivy-text "")
185 (ivy-exit-with-action
188 (while (setq cand (pop cands))
189 (swiper--action cand)
191 (mc/create-fake-cursor-at-point))))
192 (multiple-cursors-mode 1))))))
194 (defun swiper-recenter-top-bottom (&optional arg)
195 "Call (`recenter-top-bottom' ARG)."
198 (recenter-top-bottom arg)))
200 (defvar swiper-font-lock-exclude
231 "List of major-modes that are incompatible with font-lock-ensure.")
233 (defun swiper-font-lock-ensure-p ()
234 "Return non-nil if we should font-lock-ensure."
235 (or (derived-mode-p 'magit-mode)
236 (bound-and-true-p magit-blame-mode)
237 (memq major-mode swiper-font-lock-exclude)))
239 (defun swiper-font-lock-ensure ()
240 "Ensure the entired buffer is highlighted."
241 (unless (swiper-font-lock-ensure-p)
242 (unless (or (> (buffer-size) 100000) (null font-lock-mode))
243 (if (fboundp 'font-lock-ensure)
245 (with-no-warnings (font-lock-fontify-buffer))))))
247 (defvar swiper--format-spec ""
248 "Store the current candidates format spec.")
250 (defvar swiper--width nil
251 "Store the number of digits needed for the longest line nubmer.")
253 (defvar swiper-use-visual-line nil
254 "When non-nil, use `line-move' instead of `forward-line'.")
256 (declare-function outline-show-all "outline")
258 (defun swiper--candidates (&optional numbers-width)
259 "Return a list of this buffer lines.
261 NUMBERS-WIDTH, when specified, is used for width spec of line
262 numbers; replaces calculating the width from buffer line count."
263 (if (and visual-line-mode
264 ;; super-slow otherwise
265 (< (buffer-size) 20000))
267 (when (eq major-mode 'org-mode)
269 (if (fboundp 'outline-show-all)
273 (setq swiper-use-visual-line t))
274 (setq swiper-use-visual-line nil))
275 (let ((n-lines (count-lines (point-min) (point-max))))
276 (unless (zerop n-lines)
277 (setq swiper--width (or numbers-width
278 (1+ (floor (log n-lines 10)))))
279 (setq swiper--format-spec
280 (format "%%-%dd " swiper--width))
281 (let ((line-number 0)
282 (advancer (if swiper-use-visual-line
283 (lambda (arg) (line-move arg t))
287 (goto-char (point-min))
288 (swiper-font-lock-ensure)
289 (while (< (point) (point-max))
292 (replace-regexp-in-string
294 (if swiper-use-visual-line
297 (beginning-of-visual-line)
304 (line-end-position)))))))
305 (remove-text-properties 0 (length str) '(field) str)
306 (put-text-property 0 1 'display
307 (format swiper--format-spec
308 (cl-incf line-number))
310 (push str candidates))
311 (funcall advancer 1))
312 (nreverse candidates))))))
314 (defvar swiper--opoint 1
315 "The point when `swiper' starts.")
318 (defun swiper (&optional initial-input)
319 "`isearch' with an overview.
320 When non-nil, INITIAL-INPUT is the initial search pattern."
322 (swiper--ivy (swiper--candidates) initial-input))
324 (declare-function string-trim-right "subr-x")
326 (defun swiper-occur (&optional revert)
327 "Generate a custom occur buffer for `swiper'.
328 When REVERT is non-nil, regenerate the current *ivy-occur* buffer."
329 (let* ((buffer (ivy-state-buffer ivy-last))
332 (if (buffer-file-name buffer)
333 (file-name-nondirectory
334 (buffer-file-name buffer))
335 (buffer-name buffer)))
344 (get-text-property 0 'display s))
345 'face 'compilation-line-number)
349 (setq ivy--old-re nil)
350 (let ((ivy--regex-function 'swiper--re-builder))
352 (progn (string-match "\"\\(.*\\)\"" (buffer-name))
353 (match-string 1 (buffer-name)))
354 (with-current-buffer buffer
355 (swiper--candidates))))))))
356 (unless (eq major-mode 'ivy-occur-grep-mode)
357 (ivy-occur-grep-mode)
359 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
361 (insert (format "%d candidates:\n" (length cands)))
362 (ivy--occur-insert-lines
364 (lambda (cand) (concat "./" cand))
366 (goto-char (point-min))
369 (ivy-set-occur 'swiper 'swiper-occur)
371 (declare-function evil-jumper--set-jump "ext:evil-jumper")
373 (defvar swiper--current-line nil)
374 (defvar swiper--current-match-start nil)
376 (defun swiper--init ()
377 "Perform initialization common to both completion methods."
378 (setq swiper--current-line nil)
379 (setq swiper--current-match-start nil)
380 (setq swiper--opoint (point))
381 (when (bound-and-true-p evil-jumper-mode)
382 (evil-jumper--set-jump)))
384 (defun swiper--re-builder (str)
385 "Transform STR into a swiper regex.
386 This is the regex used in the minibuffer where candidates have
387 line numbers. For the buffer, use `ivy--regex' instead."
388 (replace-regexp-in-string
394 (setq ivy--subexps 0)
396 ((string-match "^\\^" str)
397 (setq ivy--old-re "")
398 (let ((re (ivy--regex-plus (substring str 1))))
399 (if (zerop ivy--subexps)
400 (prog1 (format "^ ?\\(%s\\)" re)
401 (setq ivy--subexps 1))
402 (format "^ %s" re))))
404 (ivy--regex-plus str)))))
406 (defvar swiper-history nil
407 "History for `swiper'.")
409 (defvar swiper-invocation-face nil
410 "The face at the point of invocation of `swiper'.")
412 (defun swiper--ivy (candidates &optional initial-input)
413 "Select one of CANDIDATES and move there.
414 When non-nil, INITIAL-INPUT is the initial search pattern."
417 (setq swiper-invocation-face
418 (plist-get (text-properties-at (point)) 'face))
420 (if swiper-use-visual-line
423 (save-excursion (beginning-of-visual-line) (point)))
424 (1- (line-number-at-pos))))
425 (minibuffer-allow-text-properties t)
433 :initial-input initial-input
437 :update-fn #'swiper--update-input-ivy
438 :unwind #'swiper--cleanup
439 :action #'swiper--action
440 :re-builder #'swiper--re-builder
441 :history 'swiper-history
445 (goto-char swiper--opoint)))))
447 (defun swiper-toggle-face-matching ()
448 "Toggle matching only the candidates with `swiper-invocation-face'."
450 (setf (ivy-state-matcher ivy-last)
451 (if (ivy-state-matcher ivy-last)
453 #'swiper--face-matcher))
454 (setq ivy--old-re nil))
456 (defun swiper--face-matcher (regexp candidates)
457 "Return REGEXP-matching CANDIDATES.
458 Matched candidates should have `swiper-invocation-face'."
462 (string-match regexp x)
463 (let ((s (match-string 0 x))
465 (while (and (< i (length s))
468 'face swiper-invocation-face
474 (defun swiper--ensure-visible ()
475 "Remove overlays hiding point."
476 (let ((overlays (overlays-at (1- (point))))
478 (while (setq ov (pop overlays))
479 (if (and (invisible-p (overlay-get ov 'invisible))
480 (setq expose (overlay-get ov 'isearch-open-invisible)))
481 (funcall expose ov)))))
483 (defvar swiper--overlays nil
486 (defun swiper--cleanup ()
487 "Clean up the overlays."
488 (while swiper--overlays
489 (delete-overlay (pop swiper--overlays)))
491 (goto-char (point-min))
492 (isearch-clean-overlays)))
494 (defun swiper--update-input-ivy ()
495 "Called when `ivy' input is updated."
498 (when (> (length ivy--current) 0)
499 (let* ((re (replace-regexp-in-string
501 (funcall ivy--regex-function ivy-text)))
502 (re (if (stringp re) re (caar re)))
503 (str (get-text-property 0 'display ivy--current))
504 (num (if (string-match "^[0-9]+" str)
505 (string-to-number (match-string 0 str))
507 (unless (eq this-command 'ivy-yank-word)
509 (unless (if swiper--current-line
510 (eq swiper--current-line num)
511 (eq (line-number-at-pos) num))
512 (goto-char (point-min))
513 (if swiper-use-visual-line
515 (forward-line (1- num))))
516 (if (and (equal ivy-text "")
517 (>= swiper--opoint (line-beginning-position))
518 (<= swiper--opoint (line-end-position)))
519 (goto-char swiper--opoint)
520 (if (eq swiper--current-line num)
521 (when swiper--current-match-start
522 (goto-char swiper--current-match-start))
523 (setq swiper--current-line num))
524 (when (re-search-forward re (line-end-position) t)
525 (setq swiper--current-match-start (match-beginning 0))))
526 (isearch-range-invisible (line-beginning-position)
528 (unless (and (>= (point) (window-start))
529 (<= (point) (window-end (ivy-state-window ivy-last) t)))
531 (swiper--add-overlays re)))))
533 (defun swiper--add-overlays (re &optional beg end wnd)
534 "Add overlays for RE regexp in visible part of the current buffer.
535 BEG and END, when specified, are the point bounds.
536 WND, when specified is the window."
537 (setq wnd (or wnd (ivy-state-window ivy-last)))
538 (let ((ov (if visual-line-mode
541 (beginning-of-visual-line)
547 (line-beginning-position)
548 (1+ (line-end-position))))))
549 (overlay-put ov 'face 'swiper-line-face)
550 (overlay-put ov 'window wnd)
551 (push ov swiper--overlays)
552 (let* ((wh (window-height))
553 (beg (or beg (save-excursion
554 (forward-line (- wh))
556 (end (or end (save-excursion
559 (when (>= (length re) swiper-min-highlight)
562 ;; RE can become an invalid regexp
563 (while (and (ignore-errors (re-search-forward re end t))
564 (> (- (match-end 0) (match-beginning 0)) 0))
566 (while (<= i ivy--subexps)
567 (when (match-beginning i)
568 (let ((overlay (make-overlay (match-beginning i)
571 (cond ((zerop ivy--subexps)
576 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
578 (push overlay swiper--overlays)
579 (overlay-put overlay 'face face)
580 (overlay-put overlay 'window wnd)
581 (overlay-put overlay 'priority i)))
584 (defun swiper--action (x)
586 (let ((ln (1- (read (or (get-text-property 0 'display x)
587 (and (string-match ":\\([0-9]+\\):.*\\'" x)
588 (match-string-no-properties 1 x))))))
589 (re (ivy--regex ivy-text)))
591 (user-error "No candidates")
593 (unless (equal (current-buffer)
594 (ivy-state-buffer ivy-last))
595 (switch-to-buffer (ivy-state-buffer ivy-last)))
596 (goto-char (point-min))
597 (funcall (if swiper-use-visual-line
601 (re-search-forward re (line-end-position) t)
602 (swiper--ensure-visible)
603 (when (/= (point) swiper--opoint)
604 (unless (and transient-mark-mode mark-active)
605 (when (eq ivy-exit 'done)
606 (push-mark swiper--opoint t)
607 (message "Mark saved where search started"))))
611 regexp-search-ring-max)))))
613 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
614 (defun swiper-from-isearch ()
615 "Invoke `swiper' from isearch."
617 (let ((query (if isearch-regexp
619 (regexp-quote isearch-string))))
623 (defvar swiper-multi-buffers nil
624 "Store the current list of buffers.")
626 (defvar swiper-multi-candidates nil
627 "Store the list of candidates for `swiper-multi'.")
629 (defun swiper-multi-prompt ()
630 (format "Buffers (%s): "
631 (mapconcat #'identity swiper-multi-buffers ", ")))
633 (defun swiper-multi ()
634 "Select one or more buffers.
635 Run `swiper' for those buffers."
637 (setq swiper-multi-buffers nil)
638 (ivy-read (swiper-multi-prompt)
639 'internal-complete-buffer
640 :action 'swiper-multi-action-1)
641 (ivy-read "Swiper: " swiper-multi-candidates
642 :action 'swiper-multi-action-2
643 :unwind #'swiper--cleanup
644 :caller 'swiper-multi))
647 "Run `swiper' for all opened buffers."
649 (ivy-read "Swiper: " (swiper--multi-candidates
653 :action 'swiper-multi-action-2
654 :unwind #'swiper--cleanup
655 :update-fn (lambda ()
656 (swiper-multi-action-2 ivy--current))
657 :caller 'swiper-multi))
659 (defun swiper--multi-candidates (buffers)
660 (let* ((ww (window-width))
662 (column-2 (apply #'max
665 (length (buffer-name b)))
667 (column-1 (- ww 4 column-2 1)))
668 (dolist (buf buffers)
669 (with-current-buffer buf
674 (setq s (concat (ivy--truncate-string s column-1) " "))
675 (let ((len (length s)))
677 (1- len) len 'display
681 (- ww (string-width s) (length (buffer-name)) 3))
686 (swiper--candidates 4))
691 (defun swiper-multi-action-1 (x)
692 (if (member x swiper-multi-buffers)
694 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
696 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
697 (let ((prompt (swiper-multi-prompt)))
698 (setf (ivy-state-prompt ivy-last) prompt)
699 (setq ivy--prompt (concat "%-4d " prompt)))
700 (cond ((memq this-command '(ivy-done
703 (setq swiper-multi-candidates
704 (swiper--multi-candidates
705 (mapcar #'get-buffer swiper-multi-buffers))))
706 ((eq this-command 'ivy-call)
707 (delete-minibuffer-contents))))
709 (defun swiper-multi-action-2 (x)
710 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
712 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
713 (switch-to-buffer (match-string 1 buf-space))
714 (goto-char (point-min))
715 (forward-line (1- (read (get-text-property 0 'display x))))
717 (ivy--regex ivy-text)
718 (line-end-position) t)
719 (unless (eq ivy-exit 'done)
721 (swiper--add-overlays (ivy--regex ivy-text)))))))
725 ;;; swiper.el ends here