]> code.delx.au - gnu-emacs-elpa/blob - swiper.el
swiper.el: Add support for evil-jumper/backward
[gnu-emacs-elpa] / swiper.el
1 ;;; swiper.el --- Isearch with an overview. Oh, man! -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
7 ;; Version: 0.6.0
8 ;; Package-Requires: ((emacs "24.1"))
9 ;; Keywords: matching
10
11 ;; This file is part of GNU Emacs.
12
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)
16 ;; any later version.
17
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.
22
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27 ;;
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.
31 ;;
32 ;; It can double as a quick `regex-builder', although only single
33 ;; lines will be matched.
34 ;;
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).
39
40 ;;; Code:
41 (require 'ivy)
42
43 (defgroup swiper nil
44 "`isearch' with an overview."
45 :group 'matching
46 :prefix "swiper-")
47
48 (defface swiper-match-face-1
49 '((t (:inherit isearch-lazy-highlight-face)))
50 "The background face for `swiper' matches.")
51
52 (defface swiper-match-face-2
53 '((t (:inherit isearch)))
54 "Face for `swiper' matches modulo 1.")
55
56 (defface swiper-match-face-3
57 '((t (:inherit match)))
58 "Face for `swiper' matches modulo 2.")
59
60 (defface swiper-match-face-4
61 '((t (:inherit isearch-fail)))
62 "Face for `swiper' matches modulo 3.")
63
64 (define-obsolete-face-alias 'swiper-minibuffer-match-face-1
65 'ivy-minibuffer-match-face-1 "0.6.0")
66
67 (define-obsolete-face-alias 'swiper-minibuffer-match-face-2
68 'ivy-minibuffer-match-face-2 "0.6.0")
69
70 (define-obsolete-face-alias 'swiper-minibuffer-match-face-3
71 'ivy-minibuffer-match-face-3 "0.6.0")
72
73 (define-obsolete-face-alias 'swiper-minibuffer-match-face-4
74 'ivy-minibuffer-match-face-4 "0.6.0")
75
76 (defface swiper-line-face
77 '((t (:inherit highlight)))
78 "Face for current `swiper' line.")
79
80 (defcustom swiper-faces '(swiper-match-face-1
81 swiper-match-face-2
82 swiper-match-face-3
83 swiper-match-face-4)
84 "List of `swiper' faces for group matches.")
85
86 (defcustom swiper-min-highlight 2
87 "Only highlight matches for regexps at least this long."
88 :type 'integer)
89
90 (defvar swiper-map
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)
96 (define-key map (kbd "C-c C-f") 'swiper-toggle-face-matching)
97 map)
98 "Keymap for swiper.")
99
100 (defun swiper-query-replace ()
101 "Start `query-replace' with string to replace from last search string."
102 (interactive)
103 (if (null (window-minibuffer-p))
104 (user-error "Should only be called in the minibuffer through `swiper-map'")
105 (let* ((enable-recursive-minibuffers t)
106 (from (ivy--regex ivy-text))
107 (to (query-replace-read-to from "Query replace" t)))
108 (delete-minibuffer-contents)
109 (ivy-set-action (lambda (_)
110 (with-ivy-window
111 (move-beginning-of-line 1)
112 (perform-replace from to
113 t t nil))))
114 (swiper--cleanup)
115 (exit-minibuffer))))
116
117 (defvar avy-background)
118 (defvar avy-all-windows)
119 (defvar avy-style)
120 (defvar avy-keys)
121 (declare-function avy--regex-candidates "ext:avy")
122 (declare-function avy--process "ext:avy")
123 (declare-function avy--overlay-post "ext:avy")
124 (declare-function avy-action-goto "ext:avy")
125 (declare-function avy--done "ext:avy")
126 (declare-function avy--make-backgrounds "ext:avy")
127 (declare-function avy-window-list "ext:avy")
128 (declare-function avy-read "ext:avy")
129 (declare-function avy-read-de-bruijn "ext:avy")
130 (declare-function avy-tree "ext:avy")
131 (declare-function avy-push-mark "ext:avy")
132 (declare-function avy--remove-leading-chars "ext:avy")
133
134 ;;;###autoload
135 (defun swiper-avy ()
136 "Jump to one of the current swiper candidates."
137 (interactive)
138 (unless (string= ivy-text "")
139 (let* ((avy-all-windows nil)
140 (candidates (append
141 (with-ivy-window
142 (avy--regex-candidates
143 (ivy--regex ivy-text)))
144 (save-excursion
145 (save-restriction
146 (narrow-to-region (window-start) (window-end))
147 (goto-char (point-min))
148 (forward-line)
149 (let ((cands))
150 (while (< (point) (point-max))
151 (push (cons (1+ (point))
152 (selected-window))
153 cands)
154 (forward-line))
155 cands)))))
156 (candidate (unwind-protect
157 (prog2
158 (avy--make-backgrounds
159 (append (avy-window-list)
160 (list (ivy-state-window ivy-last))))
161 (if (eq avy-style 'de-bruijn)
162 (avy-read-de-bruijn
163 candidates avy-keys)
164 (avy-read (avy-tree candidates avy-keys)
165 #'avy--overlay-post
166 #'avy--remove-leading-chars))
167 (avy-push-mark))
168 (avy--done))))
169 (if (window-minibuffer-p (cdr candidate))
170 (progn
171 (ivy-set-index (- (line-number-at-pos (car candidate)) 2))
172 (ivy--exhibit)
173 (ivy-done)
174 (ivy-call))
175 (ivy-quit-and-run
176 (avy-action-goto (caar candidate)))))))
177
178 (declare-function mc/create-fake-cursor-at-point "ext:multiple-cursors-core")
179 (declare-function multiple-cursors-mode "ext:multiple-cursors-core")
180
181 ;;;###autoload
182 (defun swiper-mc ()
183 (interactive)
184 (unless (require 'multiple-cursors nil t)
185 (error "multiple-cursors isn't installed"))
186 (let ((cands (nreverse ivy--old-cands)))
187 (unless (string= ivy-text "")
188 (ivy-set-action
189 (lambda (_)
190 (let (cand)
191 (while (setq cand (pop cands))
192 (swiper--action cand)
193 (when cands
194 (mc/create-fake-cursor-at-point))))
195 (multiple-cursors-mode 1)))
196 (setq ivy-exit 'done)
197 (exit-minibuffer))))
198
199 (defun swiper-recenter-top-bottom (&optional arg)
200 "Call (`recenter-top-bottom' ARG)."
201 (interactive "P")
202 (with-ivy-window
203 (recenter-top-bottom arg)))
204
205 (defun swiper-font-lock-ensure ()
206 "Ensure the entired buffer is highlighted."
207 (unless (or (derived-mode-p 'magit-mode)
208 (bound-and-true-p magit-blame-mode)
209 (memq major-mode '(package-menu-mode
210 gnus-summary-mode
211 gnus-article-mode
212 gnus-group-mode
213 emms-playlist-mode
214 emms-stream-mode
215 erc-mode
216 org-agenda-mode
217 dired-mode
218 jabber-chat-mode
219 elfeed-search-mode
220 elfeed-show-mode
221 fundamental-mode
222 Man-mode
223 woman-mode
224 mu4e-view-mode
225 mu4e-headers-mode
226 help-mode
227 debbugs-gnu-mode
228 occur-mode
229 occur-edit-mode
230 bongo-mode
231 eww-mode
232 w3m-mode)))
233 (unless (> (buffer-size) 100000)
234 (if (fboundp 'font-lock-ensure)
235 (font-lock-ensure)
236 (with-no-warnings (font-lock-fontify-buffer))))))
237
238 (defvar swiper--format-spec ""
239 "Store the current candidates format spec.")
240
241 (defvar swiper--width nil
242 "Store the amount of digits needed for the longest line nubmer.")
243
244 (defvar swiper-use-visual-line nil
245 "When non-nil, use `line-move' instead of `forward-line'.")
246
247 (defun swiper--candidates ()
248 "Return a list of this buffer lines."
249 (setq swiper-use-visual-line
250 (and (not (eq major-mode 'org-mode))
251 visual-line-mode
252 (< (buffer-size) 20000)))
253 (let ((n-lines (count-lines (point-min) (point-max))))
254 (unless (zerop n-lines)
255 (setq swiper--width (1+ (floor (log n-lines 10))))
256 (setq swiper--format-spec
257 (format "%%-%dd " swiper--width))
258 (let ((line-number 0)
259 (advancer (if swiper-use-visual-line
260 (lambda (arg) (line-move arg t))
261 #'forward-line))
262 candidates)
263 (save-excursion
264 (goto-char (point-min))
265 (swiper-font-lock-ensure)
266 (while (< (point) (point-max))
267 (let ((str (concat " " (buffer-substring
268 (point)
269 (if swiper-use-visual-line
270 (save-excursion
271 (end-of-visual-line)
272 (point))
273 (line-end-position))))))
274 (put-text-property 0 1 'display
275 (format swiper--format-spec
276 (cl-incf line-number))
277 str)
278 (push str candidates))
279 (funcall advancer 1))
280 (nreverse candidates))))))
281
282 (defvar swiper--opoint 1
283 "The point when `swiper' starts.")
284
285 ;;;###autoload
286 (defun swiper (&optional initial-input)
287 "`isearch' with an overview.
288 When non-nil, INITIAL-INPUT is the initial search pattern."
289 (interactive)
290 (swiper--ivy initial-input))
291
292 (defvar swiper--anchor nil
293 "A line number to which the search should be anchored.")
294
295 (defvar swiper--len 0
296 "The last length of input for which an anchoring was made.")
297
298 (declare-function evil-jumper--set-jump "ext:evil-jumper")
299
300 (defun swiper--init ()
301 "Perform initialization common to both completion methods."
302 (setq swiper--opoint (point))
303 (setq swiper--len 0)
304 (setq swiper--anchor (line-number-at-pos))
305 (when (bound-and-true-p evil-jumper-mode)
306 (evil-jumper--set-jump)))
307
308 (defun swiper--re-builder (str)
309 "Transform STR into a swiper regex.
310 This is the regex used in the minibuffer, since the candidates
311 there have line numbers. In the buffer, `ivy--regex' should be used."
312 (cond
313 ((equal str "")
314 "")
315 ((equal str "^")
316 (setq ivy--subexps 0)
317 ".")
318 ((string-match "^\\^" str)
319 (setq ivy--old-re "")
320 (let ((re (ivy--regex-plus (substring str 1))))
321 (if (zerop ivy--subexps)
322 (prog1 (format "^ ?\\(%s\\)" re)
323 (setq ivy--subexps 1))
324 (format "^ %s" re))))
325 (t
326 (ivy--regex-plus str))))
327
328 (defvar swiper-history nil
329 "History for `swiper'.")
330
331 (defvar swiper-invocation-face nil
332 "The face at the point of invocation of `swiper'.")
333
334 (defun swiper--ivy (&optional initial-input)
335 "`isearch' with an overview using `ivy'.
336 When non-nil, INITIAL-INPUT is the initial search pattern."
337 (interactive)
338 (swiper--init)
339 (setq swiper-invocation-face
340 (plist-get (text-properties-at (point)) 'face))
341 (let ((candidates (swiper--candidates))
342 (preselect (buffer-substring-no-properties
343 (line-beginning-position)
344 (line-end-position)))
345 (minibuffer-allow-text-properties t))
346 (unwind-protect
347 (ivy-read
348 "Swiper: "
349 candidates
350 :initial-input initial-input
351 :keymap swiper-map
352 :preselect preselect
353 :require-match t
354 :update-fn #'swiper--update-input-ivy
355 :unwind #'swiper--cleanup
356 :action #'swiper--action
357 :re-builder #'swiper--re-builder
358 :history 'swiper-history
359 :caller 'swiper)
360 (when (null ivy-exit)
361 (goto-char swiper--opoint)))))
362
363 (defun swiper-toggle-face-matching ()
364 "Toggle matching only the candidates with `swiper-invocation-face'."
365 (interactive)
366 (setf (ivy-state-matcher ivy-last)
367 (if (ivy-state-matcher ivy-last)
368 nil
369 #'swiper--face-matcher))
370 (setq ivy--old-re nil))
371
372 (defun swiper--face-matcher (regexp candidates)
373 "Return REGEXP-matching CANDIDATES.
374 Matched candidates should have `swiper-invocation-face'."
375 (cl-remove-if-not
376 (lambda (x)
377 (and
378 (string-match regexp x)
379 (let ((s (match-string 0 x))
380 (i 0))
381 (while (and (< i (length s))
382 (text-property-any
383 i (1+ i)
384 'face swiper-invocation-face
385 s))
386 (cl-incf i))
387 (eq i (length s)))))
388 candidates))
389
390 (defun swiper--ensure-visible ()
391 "Remove overlays hiding point."
392 (let ((overlays (overlays-at (point)))
393 ov expose)
394 (while (setq ov (pop overlays))
395 (if (and (invisible-p (overlay-get ov 'invisible))
396 (setq expose (overlay-get ov 'isearch-open-invisible)))
397 (funcall expose ov)))))
398
399 (defvar swiper--overlays nil
400 "Store overlays.")
401
402 (defun swiper--cleanup ()
403 "Clean up the overlays."
404 (while swiper--overlays
405 (delete-overlay (pop swiper--overlays)))
406 (save-excursion
407 (goto-char (point-min))
408 (isearch-clean-overlays)))
409
410 (defun swiper--update-input-ivy ()
411 "Called when `ivy' input is updated."
412 (with-ivy-window
413 (swiper--cleanup)
414 (when (> (length ivy--current) 0)
415 (let* ((re (funcall ivy--regex-function ivy-text))
416 (re (if (stringp re) re (caar re)))
417 (str (get-text-property 0 'display ivy--current))
418 (num (if (string-match "^[0-9]+" str)
419 (string-to-number (match-string 0 str))
420 0)))
421 (goto-char (point-min))
422 (when (cl-plusp num)
423 (goto-char (point-min))
424 (if swiper-use-visual-line
425 (line-move (1- num))
426 (forward-line (1- num)))
427 (if (and (equal ivy-text "")
428 (>= swiper--opoint (line-beginning-position))
429 (<= swiper--opoint (line-end-position)))
430 (goto-char swiper--opoint)
431 (re-search-forward re (line-end-position) t))
432 (isearch-range-invisible (line-beginning-position)
433 (line-end-position))
434 (unless (and (>= (point) (window-start))
435 (<= (point) (window-end (ivy-state-window ivy-last) t)))
436 (recenter)))
437 (swiper--add-overlays re)))))
438
439 (defun swiper--add-overlays (re &optional beg end wnd)
440 "Add overlays for RE regexp in visible part of the current buffer.
441 BEG and END, when specified, are the point bounds.
442 WND, when specified is the window."
443 (setq wnd (or wnd (ivy-state-window ivy-last)))
444 (let ((ov (if visual-line-mode
445 (make-overlay
446 (save-excursion
447 (beginning-of-visual-line)
448 (point))
449 (save-excursion
450 (end-of-visual-line)
451 (point)))
452 (make-overlay
453 (line-beginning-position)
454 (1+ (line-end-position))))))
455 (overlay-put ov 'face 'swiper-line-face)
456 (overlay-put ov 'window wnd)
457 (push ov swiper--overlays)
458 (let* ((wh (window-height))
459 (beg (or beg (save-excursion
460 (forward-line (- wh))
461 (point))))
462 (end (or end (save-excursion
463 (forward-line wh)
464 (point)))))
465 (when (>= (length re) swiper-min-highlight)
466 (save-excursion
467 (goto-char beg)
468 ;; RE can become an invalid regexp
469 (while (and (ignore-errors (re-search-forward re end t))
470 (> (- (match-end 0) (match-beginning 0)) 0))
471 (let ((i 0))
472 (while (<= i ivy--subexps)
473 (when (match-beginning i)
474 (let ((overlay (make-overlay (match-beginning i)
475 (match-end i)))
476 (face
477 (cond ((zerop ivy--subexps)
478 (cadr swiper-faces))
479 ((zerop i)
480 (car swiper-faces))
481 (t
482 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
483 swiper-faces)))))
484 (push overlay swiper--overlays)
485 (overlay-put overlay 'face face)
486 (overlay-put overlay 'window wnd)
487 (overlay-put overlay 'priority i)))
488 (cl-incf i)))))))))
489
490 (defun swiper--action (x)
491 "Goto line X."
492 (if (null x)
493 (user-error "No candidates")
494 (with-ivy-window
495 (unless (equal (current-buffer)
496 (ivy-state-buffer ivy-last))
497 (switch-to-buffer (ivy-state-buffer ivy-last)))
498 (goto-char (point-min))
499 (funcall (if swiper-use-visual-line
500 #'line-move
501 #'forward-line)
502 (1- (read (get-text-property 0 'display x))))
503 (re-search-forward
504 (ivy--regex ivy-text) (line-end-position) t)
505 (swiper--ensure-visible)
506 (when (/= (point) swiper--opoint)
507 (unless (and transient-mark-mode mark-active)
508 (push-mark swiper--opoint t)
509 (message "Mark saved where search started"))))))
510
511 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
512 (defun swiper-from-isearch ()
513 "Invoke `swiper' from isearch."
514 (interactive)
515 (let ((query (if isearch-regexp
516 isearch-string
517 (regexp-quote isearch-string))))
518 (isearch-exit)
519 (swiper query)))
520
521 (defvar swiper-multi-buffers nil
522 "Store the current list of buffers.")
523
524 (defvar swiper-multi-candidates nil
525 "Store the list of candidates for `swiper-multi'.")
526
527 (defun swiper-multi-prompt ()
528 (format "Buffers (%s): "
529 (mapconcat #'identity swiper-multi-buffers ", ")))
530
531 (defun swiper-multi ()
532 "Select one or more buffers.
533 Run `swiper' for those buffers."
534 (interactive)
535 (setq swiper-multi-buffers nil)
536 (setq swiper-multi-candidates nil)
537 (ivy-read (swiper-multi-prompt)
538 'internal-complete-buffer
539 :action 'swiper-multi-action-1)
540 (ivy-read "Swiper: " swiper-multi-candidates
541 :action 'swiper-multi-action-2
542 :unwind #'swiper--cleanup
543 :caller 'swiper-multi))
544
545 (defun swiper-multi-action-1 (x)
546 (if (member x swiper-multi-buffers)
547 (progn
548 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
549 (unless (equal x "")
550 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
551 (let ((prompt (swiper-multi-prompt)))
552 (setf (ivy-state-prompt ivy-last) prompt)
553 (setq ivy--prompt (concat "%-4d " prompt)))
554 (cond ((memq this-command '(ivy-done
555 ivy-alt-done
556 ivy-immediate-done))
557 (let ((ww (window-width)))
558 (dolist (buf swiper-multi-buffers)
559 (with-current-buffer buf
560 (setq swiper-multi-candidates
561 (append
562 (mapcar
563 (lambda (s)
564 (setq s (concat s " "))
565 (let ((len (length s)))
566 (put-text-property
567 (1- len) len 'display
568 (concat
569 (make-string
570 (max
571 (- ww
572 (string-width s)
573 (length (buffer-name))
574 1)
575 0)
576 ?\ )
577 (buffer-name))
578 s)
579 s))
580 (swiper--candidates))
581 swiper-multi-candidates))))))
582 ((eq this-command 'ivy-call)
583 (delete-minibuffer-contents))))
584
585 (defun swiper-multi-action-2 (x)
586 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
587 (with-ivy-window
588 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
589 (switch-to-buffer (match-string 1 buf-space))
590 (goto-char (point-min))
591 (forward-line (1- (read x)))
592 (re-search-forward
593 (ivy--regex ivy-text)
594 (line-end-position) t)
595 (unless (eq ivy-exit 'done)
596 (swiper--cleanup)
597 (swiper--add-overlays (ivy--regex ivy-text)))))))
598
599 (provide 'swiper)
600
601 ;;; swiper.el ends here