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.")
74 (defcustom swiper-min-highlight 2
75 "Only highlight matches for regexps at least this long."
79 (let ((map (make-sparse-keymap)))
80 (define-key map (kbd "M-q") 'swiper-query-replace)
81 (define-key map (kbd "C-l") 'swiper-recenter-top-bottom)
82 (define-key map (kbd "C-'") 'swiper-avy)
83 (define-key map (kbd "C-7") 'swiper-mc)
84 (define-key map (kbd "C-c C-f") 'swiper-toggle-face-matching)
88 (defun swiper-query-replace ()
89 "Start `query-replace' with string to replace from last search string."
91 (if (null (window-minibuffer-p))
92 (user-error "Should only be called in the minibuffer through `swiper-map'")
93 (let* ((enable-recursive-minibuffers t)
94 (from (ivy--regex ivy-text))
95 (to (query-replace-read-to from "Query replace" t)))
100 (move-beginning-of-line 1)
101 (perform-replace from to
104 (defvar avy-background)
105 (defvar avy-all-windows)
108 (declare-function avy--regex-candidates "ext:avy")
109 (declare-function avy--process "ext:avy")
110 (declare-function avy--overlay-post "ext:avy")
111 (declare-function avy-action-goto "ext:avy")
112 (declare-function avy--done "ext:avy")
113 (declare-function avy--make-backgrounds "ext:avy")
114 (declare-function avy-window-list "ext:avy")
115 (declare-function avy-read "ext:avy")
116 (declare-function avy-read-de-bruijn "ext:avy")
117 (declare-function avy-tree "ext:avy")
118 (declare-function avy-push-mark "ext:avy")
119 (declare-function avy--remove-leading-chars "ext:avy")
123 "Jump to one of the current swiper candidates."
125 (unless (string= ivy-text "")
126 (let* ((avy-all-windows nil)
129 (avy--regex-candidates
130 (ivy--regex ivy-text)))
133 (narrow-to-region (window-start) (window-end))
134 (goto-char (point-min))
137 (while (< (point) (point-max))
138 (push (cons (1+ (point))
143 (candidate (unwind-protect
145 (avy--make-backgrounds
146 (append (avy-window-list)
147 (list (ivy-state-window ivy-last))))
148 (if (eq avy-style 'de-bruijn)
151 (avy-read (avy-tree candidates avy-keys)
153 #'avy--remove-leading-chars))
156 (if (window-minibuffer-p (cdr candidate))
158 (ivy-set-index (- (line-number-at-pos (car candidate)) 2))
163 (avy-action-goto (caar candidate)))))))
165 (declare-function mc/create-fake-cursor-at-point "ext:multiple-cursors-core")
166 (declare-function multiple-cursors-mode "ext:multiple-cursors-core")
171 (unless (require 'multiple-cursors nil t)
172 (error "multiple-cursors isn't installed"))
173 (let ((cands (nreverse ivy--old-cands)))
174 (unless (string= ivy-text "")
175 (ivy-exit-with-action
178 (while (setq cand (pop cands))
179 (swiper--action cand)
181 (mc/create-fake-cursor-at-point))))
182 (multiple-cursors-mode 1))))))
184 (defun swiper-recenter-top-bottom (&optional arg)
185 "Call (`recenter-top-bottom' ARG)."
188 (recenter-top-bottom arg)))
190 (defvar swiper-font-lock-exclude
221 "List of major-modes that are incompatible with font-lock-ensure.")
223 (defun swiper-font-lock-ensure-p ()
224 "Return non-nil if we should font-lock-ensure."
225 (or (derived-mode-p 'magit-mode)
226 (bound-and-true-p magit-blame-mode)
227 (memq major-mode swiper-font-lock-exclude)))
229 (defun swiper-font-lock-ensure ()
230 "Ensure the entired buffer is highlighted."
231 (unless (swiper-font-lock-ensure-p)
232 (unless (or (> (buffer-size) 100000) (null font-lock-mode))
233 (if (fboundp 'font-lock-ensure)
235 (with-no-warnings (font-lock-fontify-buffer))))))
237 (defvar swiper--format-spec ""
238 "Store the current candidates format spec.")
240 (defvar swiper--width nil
241 "Store the number of digits needed for the longest line nubmer.")
243 (defvar swiper-use-visual-line nil
244 "When non-nil, use `line-move' instead of `forward-line'.")
246 (declare-function outline-show-all "outline")
248 (defun swiper--candidates (&optional numbers-width)
249 "Return a list of this buffer lines.
251 NUMBERS-WIDTH, when specified, is used for width spec of line
252 numbers; replaces calculating the width from buffer line count."
253 (if (and visual-line-mode
254 ;; super-slow otherwise
255 (< (buffer-size) 20000))
257 (when (eq major-mode 'org-mode)
259 (if (fboundp 'outline-show-all)
263 (setq swiper-use-visual-line t))
264 (setq swiper-use-visual-line nil))
265 (let ((n-lines (count-lines (point-min) (point-max))))
266 (unless (zerop n-lines)
267 (setq swiper--width (or numbers-width
268 (1+ (floor (log n-lines 10)))))
269 (setq swiper--format-spec
270 (format "%%-%dd " swiper--width))
271 (let ((line-number 0)
272 (advancer (if swiper-use-visual-line
273 (lambda (arg) (line-move arg t))
277 (goto-char (point-min))
278 (swiper-font-lock-ensure)
279 (while (< (point) (point-max))
282 (replace-regexp-in-string
284 (if swiper-use-visual-line
287 (beginning-of-visual-line)
294 (line-end-position)))))))
295 (when (eq major-mode 'twittering-mode)
296 (remove-text-properties 0 (length str) '(field) str))
297 (put-text-property 0 1 'display
298 (format swiper--format-spec
299 (cl-incf line-number))
301 (push str candidates))
302 (funcall advancer 1))
303 (nreverse candidates))))))
305 (defvar swiper--opoint 1
306 "The point when `swiper' starts.")
309 (defun swiper (&optional initial-input)
310 "`isearch' with an overview.
311 When non-nil, INITIAL-INPUT is the initial search pattern."
313 (swiper--ivy (swiper--candidates) initial-input))
315 (declare-function string-trim-right "subr-x")
317 (defun swiper-occur ()
318 "Generate a custom occur buffer for `swiper'."
319 (ivy-occur-grep-mode)
321 (let* ((fname (propertize
323 (file-name-nondirectory
333 (get-text-property 0 'display s))
334 'face 'compilation-line-number)
337 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
339 (insert (format "%d candidates:\n" (length cands)))
340 (ivy--occur-insert-lines
342 (lambda (cand) (concat "./" cand))
345 (ivy-set-occur 'swiper 'swiper-occur)
347 (declare-function evil-jumper--set-jump "ext:evil-jumper")
349 (defvar swiper--current-line nil)
350 (defvar swiper--current-match-start nil)
352 (defun swiper--init ()
353 "Perform initialization common to both completion methods."
354 (setq swiper--current-line nil)
355 (setq swiper--current-match-start nil)
356 (setq swiper--opoint (point))
357 (when (bound-and-true-p evil-jumper-mode)
358 (evil-jumper--set-jump)))
360 (defun swiper--re-builder (str)
361 "Transform STR into a swiper regex.
362 This is the regex used in the minibuffer where candidates have
363 line numbers. For the buffer, use `ivy--regex' instead."
364 (replace-regexp-in-string
370 (setq ivy--subexps 0)
372 ((string-match "^\\^" str)
373 (setq ivy--old-re "")
374 (let ((re (ivy--regex-plus (substring str 1))))
375 (if (zerop ivy--subexps)
376 (prog1 (format "^ ?\\(%s\\)" re)
377 (setq ivy--subexps 1))
378 (format "^ %s" re))))
380 (ivy--regex-plus str)))))
382 (defvar swiper-history nil
383 "History for `swiper'.")
385 (defvar swiper-invocation-face nil
386 "The face at the point of invocation of `swiper'.")
388 (defun swiper--ivy (candidates &optional initial-input)
389 "Select one of CANDIDATES and move there.
390 When non-nil, INITIAL-INPUT is the initial search pattern."
393 (setq swiper-invocation-face
394 (plist-get (text-properties-at (point)) 'face))
396 (if swiper-use-visual-line
399 (save-excursion (beginning-of-visual-line) (point)))
400 (1- (line-number-at-pos))))
401 (minibuffer-allow-text-properties t)
409 :initial-input initial-input
413 :update-fn #'swiper--update-input-ivy
414 :unwind #'swiper--cleanup
415 :action #'swiper--action
416 :re-builder #'swiper--re-builder
417 :history 'swiper-history
421 (goto-char swiper--opoint)))))
423 (defun swiper-toggle-face-matching ()
424 "Toggle matching only the candidates with `swiper-invocation-face'."
426 (setf (ivy-state-matcher ivy-last)
427 (if (ivy-state-matcher ivy-last)
429 #'swiper--face-matcher))
430 (setq ivy--old-re nil))
432 (defun swiper--face-matcher (regexp candidates)
433 "Return REGEXP-matching CANDIDATES.
434 Matched candidates should have `swiper-invocation-face'."
438 (string-match regexp x)
439 (let ((s (match-string 0 x))
441 (while (and (< i (length s))
444 'face swiper-invocation-face
450 (defun swiper--ensure-visible ()
451 "Remove overlays hiding point."
452 (let ((overlays (overlays-at (point)))
454 (while (setq ov (pop overlays))
455 (if (and (invisible-p (overlay-get ov 'invisible))
456 (setq expose (overlay-get ov 'isearch-open-invisible)))
457 (funcall expose ov)))))
459 (defvar swiper--overlays nil
462 (defun swiper--cleanup ()
463 "Clean up the overlays."
464 (while swiper--overlays
465 (delete-overlay (pop swiper--overlays)))
467 (goto-char (point-min))
468 (isearch-clean-overlays)))
470 (defun swiper--update-input-ivy ()
471 "Called when `ivy' input is updated."
474 (when (> (length ivy--current) 0)
475 (let* ((re (replace-regexp-in-string
477 (funcall ivy--regex-function ivy-text)))
478 (re (if (stringp re) re (caar re)))
479 (str (get-text-property 0 'display ivy--current))
480 (num (if (string-match "^[0-9]+" str)
481 (string-to-number (match-string 0 str))
483 (unless (eq this-command 'ivy-yank-word)
485 (unless (if swiper--current-line
486 (eq swiper--current-line num)
487 (eq (line-number-at-pos) num))
488 (goto-char (point-min))
489 (if swiper-use-visual-line
491 (forward-line (1- num))))
492 (if (and (equal ivy-text "")
493 (>= swiper--opoint (line-beginning-position))
494 (<= swiper--opoint (line-end-position)))
495 (goto-char swiper--opoint)
496 (if (eq swiper--current-line num)
497 (when swiper--current-match-start
498 (goto-char swiper--current-match-start))
499 (setq swiper--current-line num))
500 (when (re-search-forward re (line-end-position) t)
501 (setq swiper--current-match-start (match-beginning 0))))
502 (isearch-range-invisible (line-beginning-position)
504 (unless (and (>= (point) (window-start))
505 (<= (point) (window-end (ivy-state-window ivy-last) t)))
507 (swiper--add-overlays re)))))
509 (defun swiper--add-overlays (re &optional beg end wnd)
510 "Add overlays for RE regexp in visible part of the current buffer.
511 BEG and END, when specified, are the point bounds.
512 WND, when specified is the window."
513 (setq wnd (or wnd (ivy-state-window ivy-last)))
514 (let ((ov (if visual-line-mode
517 (beginning-of-visual-line)
523 (line-beginning-position)
524 (1+ (line-end-position))))))
525 (overlay-put ov 'face 'swiper-line-face)
526 (overlay-put ov 'window wnd)
527 (push ov swiper--overlays)
528 (let* ((wh (window-height))
529 (beg (or beg (save-excursion
530 (forward-line (- wh))
532 (end (or end (save-excursion
535 (when (>= (length re) swiper-min-highlight)
538 ;; RE can become an invalid regexp
539 (while (and (ignore-errors (re-search-forward re end t))
540 (> (- (match-end 0) (match-beginning 0)) 0))
542 (while (<= i ivy--subexps)
543 (when (match-beginning i)
544 (let ((overlay (make-overlay (match-beginning i)
547 (cond ((zerop ivy--subexps)
552 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
554 (push overlay swiper--overlays)
555 (overlay-put overlay 'face face)
556 (overlay-put overlay 'window wnd)
557 (overlay-put overlay 'priority i)))
560 (defun swiper--action (x)
562 (let ((ln (1- (read (if (memq this-command '(ivy-occur-press))
563 (when (string-match ":\\([0-9]+\\):.*\\'" x)
564 (match-string-no-properties 1 x))
565 (get-text-property 0 'display x)))))
566 (re (ivy--regex ivy-text)))
568 (user-error "No candidates")
570 (unless (equal (current-buffer)
571 (ivy-state-buffer ivy-last))
572 (switch-to-buffer (ivy-state-buffer ivy-last)))
573 (goto-char (point-min))
574 (funcall (if swiper-use-visual-line
578 (re-search-forward re (line-end-position) t)
579 (swiper--ensure-visible)
580 (when (/= (point) swiper--opoint)
581 (unless (and transient-mark-mode mark-active)
582 (when (eq ivy-exit 'done)
583 (push-mark swiper--opoint t)
584 (message "Mark saved where search started"))))
588 regexp-search-ring-max)))))
590 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
591 (defun swiper-from-isearch ()
592 "Invoke `swiper' from isearch."
594 (let ((query (if isearch-regexp
596 (regexp-quote isearch-string))))
600 (defvar swiper-multi-buffers nil
601 "Store the current list of buffers.")
603 (defvar swiper-multi-candidates nil
604 "Store the list of candidates for `swiper-multi'.")
606 (defun swiper-multi-prompt ()
607 (format "Buffers (%s): "
608 (mapconcat #'identity swiper-multi-buffers ", ")))
610 (defun swiper-multi ()
611 "Select one or more buffers.
612 Run `swiper' for those buffers."
614 (setq swiper-multi-buffers nil)
615 (ivy-read (swiper-multi-prompt)
616 'internal-complete-buffer
617 :action 'swiper-multi-action-1)
618 (ivy-read "Swiper: " swiper-multi-candidates
619 :action 'swiper-multi-action-2
620 :unwind #'swiper--cleanup
621 :caller 'swiper-multi))
624 "Run `swiper' for all opened buffers."
626 (ivy-read "Swiper: " (swiper--multi-candidates
630 :action 'swiper-multi-action-2
631 :unwind #'swiper--cleanup
632 :caller 'swiper-multi))
634 (defun swiper--multi-candidates (buffers)
635 (let* ((ww (window-width))
637 (column-2 (apply #'max
640 (length (buffer-name b)))
642 (column-1 (- ww 4 column-2 1)))
643 (dolist (buf buffers)
644 (with-current-buffer buf
649 (setq s (concat (ivy--truncate-string s column-1) " "))
650 (let ((len (length s)))
652 (1- len) len 'display
655 (- ww (string-width s) (length (buffer-name)) 3)
660 (swiper--candidates 4))
665 (defun swiper-multi-action-1 (x)
666 (if (member x swiper-multi-buffers)
668 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
670 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
671 (let ((prompt (swiper-multi-prompt)))
672 (setf (ivy-state-prompt ivy-last) prompt)
673 (setq ivy--prompt (concat "%-4d " prompt)))
674 (cond ((memq this-command '(ivy-done
677 (setq swiper-multi-candidates
678 (swiper--multi-candidates
679 (mapcar #'get-buffer swiper-multi-buffers))))
680 ((eq this-command 'ivy-call)
681 (delete-minibuffer-contents))))
683 (defun swiper-multi-action-2 (x)
684 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
686 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
687 (switch-to-buffer (match-string 1 buf-space))
688 (goto-char (point-min))
689 (forward-line (1- (read (get-text-property 0 'display x))))
691 (ivy--regex ivy-text)
692 (line-end-position) t)
693 (unless (eq ivy-exit 'done)
695 (swiper--add-overlays (ivy--regex ivy-text)))))))
699 ;;; swiper.el ends here