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)
99 (defun swiper-query-replace ()
100 "Start `query-replace' with string to replace from last search string."
102 (if (null (window-minibuffer-p))
103 (user-error "Should only be called in the minibuffer through `swiper-map'")
104 (let* ((enable-recursive-minibuffers t)
105 (from (ivy--regex ivy-text))
106 (to (query-replace-read-to from "Query replace" t)))
107 (delete-minibuffer-contents)
108 (ivy-set-action (lambda (_)
110 (move-beginning-of-line 1)
111 (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 "")
190 (while (setq cand (pop cands))
191 (swiper--action cand)
193 (mc/create-fake-cursor-at-point))))
194 (multiple-cursors-mode 1)))
195 (setq ivy-exit 'done)
198 (defun swiper-recenter-top-bottom (&optional arg)
199 "Call (`recenter-top-bottom' ARG)."
202 (recenter-top-bottom arg)))
204 (defun swiper-font-lock-ensure ()
205 "Ensure the entired buffer is highlighted."
206 (unless (or (derived-mode-p 'magit-mode)
207 (bound-and-true-p magit-blame-mode)
208 (memq major-mode '(package-menu-mode
227 (unless (> (buffer-size) 100000)
228 (if (fboundp 'font-lock-ensure)
230 (with-no-warnings (font-lock-fontify-buffer))))))
232 (defvar swiper--format-spec ""
233 "Store the current candidates format spec.")
235 (defvar swiper--width nil
236 "Store the amount of digits needed for the longest line nubmer.")
238 (defvar swiper-use-visual-line nil
239 "When non-nil, use `line-move' instead of `forward-line'.")
241 (defun swiper--candidates ()
242 "Return a list of this buffer lines."
243 (setq swiper-use-visual-line
244 (and (not (eq major-mode 'org-mode))
246 (< (buffer-size) 20000)))
247 (let ((n-lines (count-lines (point-min) (point-max))))
248 (unless (zerop n-lines)
249 (setq swiper--width (1+ (floor (log n-lines 10))))
250 (setq swiper--format-spec
251 (format "%%-%dd " swiper--width))
252 (let ((line-number 0)
253 (advancer (if swiper-use-visual-line
254 (lambda (arg) (line-move arg t))
258 (goto-char (point-min))
259 (swiper-font-lock-ensure)
260 (while (< (point) (point-max))
261 (let ((str (concat " " (buffer-substring
263 (if swiper-use-visual-line
267 (line-end-position))))))
268 (put-text-property 0 1 'display
269 (format swiper--format-spec
270 (cl-incf line-number))
272 (push str candidates))
273 (funcall advancer 1))
274 (nreverse candidates))))))
276 (defvar swiper--opoint 1
277 "The point when `swiper' starts.")
280 (defun swiper (&optional initial-input)
281 "`isearch' with an overview.
282 When non-nil, INITIAL-INPUT is the initial search pattern."
284 (swiper--ivy initial-input))
286 (defvar swiper--anchor nil
287 "A line number to which the search should be anchored.")
289 (defvar swiper--len 0
290 "The last length of input for which an anchoring was made.")
292 (defun swiper--init ()
293 "Perform initialization common to both completion methods."
294 (setq swiper--opoint (point))
296 (setq swiper--anchor (line-number-at-pos)))
298 (defun swiper--re-builder (str)
299 "Transform STR into a swiper regex.
300 This is the regex used in the minibuffer, since the candidates
301 there have line numbers. In the buffer, `ivy--regex' should be used."
306 (setq ivy--subexps 0)
308 ((string-match "^\\^" str)
309 (setq ivy--old-re "")
310 (let ((re (ivy--regex-plus (substring str 1))))
311 (if (zerop ivy--subexps)
312 (prog1 (format "^ ?\\(%s\\)" re)
313 (setq ivy--subexps 1))
314 (format "^ %s" re))))
316 (ivy--regex-plus str))))
318 (defvar swiper-history nil
319 "History for `swiper'.")
321 (defun swiper--ivy (&optional initial-input)
322 "`isearch' with an overview using `ivy'.
323 When non-nil, INITIAL-INPUT is the initial search pattern."
326 (let ((candidates (swiper--candidates))
327 (preselect (buffer-substring-no-properties
328 (line-beginning-position)
329 (line-end-position)))
330 (minibuffer-allow-text-properties t))
335 :initial-input initial-input
339 :update-fn #'swiper--update-input-ivy
340 :unwind #'swiper--cleanup
341 :action #'swiper--action
342 :re-builder #'swiper--re-builder
343 :history 'swiper-history
345 (when (null ivy-exit)
346 (goto-char swiper--opoint)))))
348 (defun swiper--ensure-visible ()
349 "Remove overlays hiding point."
350 (let ((overlays (overlays-at (point)))
352 (while (setq ov (pop overlays))
353 (if (and (invisible-p (overlay-get ov 'invisible))
354 (setq expose (overlay-get ov 'isearch-open-invisible)))
355 (funcall expose ov)))))
357 (defvar swiper--overlays nil
360 (defun swiper--cleanup ()
361 "Clean up the overlays."
362 (while swiper--overlays
363 (delete-overlay (pop swiper--overlays)))
365 (goto-char (point-min))
366 (isearch-clean-overlays)))
368 (defun swiper--update-input-ivy ()
369 "Called when `ivy' input is updated."
372 (when (> (length ivy--current) 0)
373 (let* ((re (funcall ivy--regex-function ivy-text))
374 (re (if (stringp re) re (caar re)))
375 (str (get-text-property 0 'display ivy--current))
376 (num (if (string-match "^[0-9]+" str)
377 (string-to-number (match-string 0 str))
379 (goto-char (point-min))
381 (goto-char (point-min))
382 (if swiper-use-visual-line
384 (forward-line (1- num)))
385 (if (and (equal ivy-text "")
386 (>= swiper--opoint (line-beginning-position))
387 (<= swiper--opoint (line-end-position)))
388 (goto-char swiper--opoint)
389 (re-search-forward re (line-end-position) t))
390 (isearch-range-invisible (line-beginning-position)
392 (unless (and (>= (point) (window-start))
393 (<= (point) (window-end (ivy-state-window ivy-last) t)))
395 (swiper--add-overlays re)))))
397 (defun swiper--add-overlays (re &optional beg end)
398 "Add overlays for RE regexp in visible part of the current buffer.
399 BEG and END, when specified, are the point bounds."
400 (let ((ov (if visual-line-mode
403 (beginning-of-visual-line)
409 (line-beginning-position)
410 (1+ (line-end-position))))))
411 (overlay-put ov 'face 'swiper-line-face)
412 (overlay-put ov 'window (ivy-state-window ivy-last))
413 (push ov swiper--overlays)
414 (let* ((wh (window-height))
415 (beg (or beg (save-excursion
416 (forward-line (- wh))
418 (end (or end (save-excursion
421 (when (>= (length re) swiper-min-highlight)
424 ;; RE can become an invalid regexp
425 (while (and (ignore-errors (re-search-forward re end t))
426 (> (- (match-end 0) (match-beginning 0)) 0))
428 (while (<= i ivy--subexps)
429 (when (match-beginning i)
430 (let ((overlay (make-overlay (match-beginning i)
433 (cond ((zerop ivy--subexps)
438 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
440 (push overlay swiper--overlays)
441 (overlay-put overlay 'face face)
442 (overlay-put overlay 'window (ivy-state-window ivy-last))
443 (overlay-put overlay 'priority i)))
446 (defun swiper--action (x)
449 (user-error "No candidates")
451 (unless (equal (current-buffer)
452 (ivy-state-buffer ivy-last))
453 (switch-to-buffer (ivy-state-buffer ivy-last)))
454 (goto-char (point-min))
455 (funcall (if swiper-use-visual-line
458 (1- (read (get-text-property 0 'display x))))
460 (ivy--regex ivy-text) (line-end-position) t)
461 (swiper--ensure-visible)
462 (when (/= (point) swiper--opoint)
463 (unless (and transient-mark-mode mark-active)
464 (push-mark swiper--opoint t)
465 (message "Mark saved where search started"))))))
467 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
468 (defun swiper-from-isearch ()
469 "Invoke `swiper' from isearch."
471 (let ((query (if isearch-regexp
473 (regexp-quote isearch-string))))
477 (defvar swiper-multi-buffers nil
478 "Store the current list of buffers.")
480 (defvar swiper-multi-candidates nil
481 "Store the list of candidates for `swiper-multi'.")
483 (defun swiper-multi-prompt ()
484 (format "Buffers (%s): "
485 (mapconcat #'identity swiper-multi-buffers ", ")))
487 (defun swiper-multi ()
488 "Select one or more buffers.
489 Run `swiper' for those buffers."
491 (setq swiper-multi-buffers nil)
492 (setq swiper-multi-candidates nil)
493 (ivy-read (swiper-multi-prompt)
494 'internal-complete-buffer
495 :action 'swiper-multi-action-1)
496 (ivy-read "Swiper: " swiper-multi-candidates
497 :action 'swiper-multi-action-2
498 :unwind #'swiper--cleanup
499 :caller 'swiper-multi))
501 (defun swiper-multi-action-1 (x)
502 (if (member x swiper-multi-buffers)
504 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
506 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
507 (let ((prompt (swiper-multi-prompt)))
508 (setf (ivy-state-prompt ivy-last) prompt)
509 (setq ivy--prompt (concat "%-4d " prompt)))
510 (cond ((memq this-command '(ivy-done
513 (let ((ww (window-width)))
514 (dolist (buf swiper-multi-buffers)
515 (with-current-buffer buf
516 (setq swiper-multi-candidates
520 (setq s (concat s " "))
521 (let ((len (length s)))
523 (1- len) len 'display
529 (length (buffer-name))
536 (swiper--candidates))
537 swiper-multi-candidates))))))
538 ((eq this-command 'ivy-call)
539 (delete-minibuffer-contents))))
541 (defun swiper-multi-action-2 (x)
542 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
544 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
545 (switch-to-buffer (match-string 1 buf-space))
546 (goto-char (point-min))
547 (forward-line (1- (read x)))
549 (ivy--regex ivy-text)
550 (line-end-position) t)
551 (unless (eq ivy-exit 'done)
553 (swiper--add-overlays (ivy--regex ivy-text)))))))
557 ;;; swiper.el ends here