]> code.delx.au - gnu-emacs-elpa/blob - swiper.el
swiper.el: Use show-all if outline-show-all isn't there
[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 (swiper--cleanup)
109 (ivy-exit-with-action
110 (lambda (_)
111 (with-ivy-window
112 (move-beginning-of-line 1)
113 (perform-replace from to
114 t t nil)))))))
115
116 (defvar avy-background)
117 (defvar avy-all-windows)
118 (defvar avy-style)
119 (defvar avy-keys)
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")
132
133 ;;;###autoload
134 (defun swiper-avy ()
135 "Jump to one of the current swiper candidates."
136 (interactive)
137 (unless (string= ivy-text "")
138 (let* ((avy-all-windows nil)
139 (candidates (append
140 (with-ivy-window
141 (avy--regex-candidates
142 (ivy--regex ivy-text)))
143 (save-excursion
144 (save-restriction
145 (narrow-to-region (window-start) (window-end))
146 (goto-char (point-min))
147 (forward-line)
148 (let ((cands))
149 (while (< (point) (point-max))
150 (push (cons (1+ (point))
151 (selected-window))
152 cands)
153 (forward-line))
154 cands)))))
155 (candidate (unwind-protect
156 (prog2
157 (avy--make-backgrounds
158 (append (avy-window-list)
159 (list (ivy-state-window ivy-last))))
160 (if (eq avy-style 'de-bruijn)
161 (avy-read-de-bruijn
162 candidates avy-keys)
163 (avy-read (avy-tree candidates avy-keys)
164 #'avy--overlay-post
165 #'avy--remove-leading-chars))
166 (avy-push-mark))
167 (avy--done))))
168 (if (window-minibuffer-p (cdr candidate))
169 (progn
170 (ivy-set-index (- (line-number-at-pos (car candidate)) 2))
171 (ivy--exhibit)
172 (ivy-done)
173 (ivy-call))
174 (ivy-quit-and-run
175 (avy-action-goto (caar candidate)))))))
176
177 (declare-function mc/create-fake-cursor-at-point "ext:multiple-cursors-core")
178 (declare-function multiple-cursors-mode "ext:multiple-cursors-core")
179
180 ;;;###autoload
181 (defun swiper-mc ()
182 (interactive)
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 "")
187 (ivy-exit-with-action
188 (lambda (_)
189 (let (cand)
190 (while (setq cand (pop cands))
191 (swiper--action cand)
192 (when cands
193 (mc/create-fake-cursor-at-point))))
194 (multiple-cursors-mode 1))))))
195
196 (defun swiper-recenter-top-bottom (&optional arg)
197 "Call (`recenter-top-bottom' ARG)."
198 (interactive "P")
199 (with-ivy-window
200 (recenter-top-bottom arg)))
201
202 (defun swiper-font-lock-ensure ()
203 "Ensure the entired buffer is highlighted."
204 (unless (or (derived-mode-p 'magit-mode)
205 (bound-and-true-p magit-blame-mode)
206 (memq major-mode '(package-menu-mode
207 gnus-summary-mode
208 gnus-article-mode
209 gnus-group-mode
210 emms-playlist-mode
211 emms-stream-mode
212 erc-mode
213 org-agenda-mode
214 dired-mode
215 jabber-chat-mode
216 elfeed-search-mode
217 elfeed-show-mode
218 fundamental-mode
219 Man-mode
220 woman-mode
221 mu4e-view-mode
222 mu4e-headers-mode
223 help-mode
224 debbugs-gnu-mode
225 occur-mode
226 occur-edit-mode
227 bongo-mode
228 eww-mode
229 twittering-mode
230 w3m-mode)))
231 (unless (> (buffer-size) 100000)
232 (if (fboundp 'font-lock-ensure)
233 (font-lock-ensure)
234 (with-no-warnings (font-lock-fontify-buffer))))))
235
236 (defvar swiper--format-spec ""
237 "Store the current candidates format spec.")
238
239 (defvar swiper--width nil
240 "Store the amount of digits needed for the longest line nubmer.")
241
242 (defvar swiper-use-visual-line nil
243 "When non-nil, use `line-move' instead of `forward-line'.")
244
245 (declare-function outline-show-all "outline")
246
247 (defun swiper--candidates (&optional numbers-width)
248 "Return a list of this buffer lines.
249
250 NUMBERS-WIDTH, when specified, is used for line numbers width
251 spec, instead of calculating it as the log of the buffer line
252 count."
253 (if (and visual-line-mode
254 ;; super-slow otherwise
255 (< (buffer-size) 20000))
256 (progn
257 (when (eq major-mode 'org-mode)
258 (require 'outline)
259 (if (fboundp 'outline-show-all)
260 (outline-show-all)
261 (show-all)))
262 (setq swiper-use-visual-line t))
263 (setq swiper-use-visual-line nil))
264 (let ((n-lines (count-lines (point-min) (point-max))))
265 (unless (zerop n-lines)
266 (setq swiper--width (or numbers-width
267 (1+ (floor (log n-lines 10)))))
268 (setq swiper--format-spec
269 (format "%%-%dd " swiper--width))
270 (let ((line-number 0)
271 (advancer (if swiper-use-visual-line
272 (lambda (arg) (line-move arg t))
273 #'forward-line))
274 candidates)
275 (save-excursion
276 (goto-char (point-min))
277 (swiper-font-lock-ensure)
278 (while (< (point) (point-max))
279 (let ((str (concat
280 " "
281 (replace-regexp-in-string
282 "\t" " "
283 (buffer-substring
284 (point)
285 (if swiper-use-visual-line
286 (save-excursion
287 (end-of-visual-line)
288 (point))
289 (line-end-position)))))))
290 (when (eq major-mode 'twittering-mode)
291 (remove-text-properties 0 (length str) '(field) str))
292 (put-text-property 0 1 'display
293 (format swiper--format-spec
294 (cl-incf line-number))
295 str)
296 (push str candidates))
297 (funcall advancer 1))
298 (nreverse candidates))))))
299
300 (defvar swiper--opoint 1
301 "The point when `swiper' starts.")
302
303 ;;;###autoload
304 (defun swiper (&optional initial-input)
305 "`isearch' with an overview.
306 When non-nil, INITIAL-INPUT is the initial search pattern."
307 (interactive)
308 (swiper--ivy initial-input))
309
310 (declare-function evil-jumper--set-jump "ext:evil-jumper")
311
312 (defun swiper--init ()
313 "Perform initialization common to both completion methods."
314 (setq swiper--opoint (point))
315 (when (bound-and-true-p evil-jumper-mode)
316 (evil-jumper--set-jump)))
317
318 (defun swiper--re-builder (str)
319 "Transform STR into a swiper regex.
320 This is the regex used in the minibuffer, since the candidates
321 there have line numbers. In the buffer, `ivy--regex' should be used."
322 (cond
323 ((equal str "")
324 "")
325 ((equal str "^")
326 (setq ivy--subexps 0)
327 ".")
328 ((string-match "^\\^" str)
329 (setq ivy--old-re "")
330 (let ((re (ivy--regex-plus (substring str 1))))
331 (if (zerop ivy--subexps)
332 (prog1 (format "^ ?\\(%s\\)" re)
333 (setq ivy--subexps 1))
334 (format "^ %s" re))))
335 (t
336 (ivy--regex-plus str))))
337
338 (defvar swiper-history nil
339 "History for `swiper'.")
340
341 (defvar swiper-invocation-face nil
342 "The face at the point of invocation of `swiper'.")
343
344 (defun swiper--ivy (&optional initial-input)
345 "`isearch' with an overview using `ivy'.
346 When non-nil, INITIAL-INPUT is the initial search pattern."
347 (interactive)
348 (swiper--init)
349 (setq swiper-invocation-face
350 (plist-get (text-properties-at (point)) 'face))
351 (let ((candidates (swiper--candidates))
352 (preselect
353 (if swiper-use-visual-line
354 (count-screen-lines
355 (point-min)
356 (save-excursion (beginning-of-visual-line) (point)))
357 (1- (line-number-at-pos))))
358 (minibuffer-allow-text-properties t)
359 res)
360 (unwind-protect
361 (setq res
362 (ivy-read
363 "Swiper: "
364 candidates
365 :initial-input initial-input
366 :keymap swiper-map
367 :preselect preselect
368 :require-match t
369 :update-fn #'swiper--update-input-ivy
370 :unwind #'swiper--cleanup
371 :action #'swiper--action
372 :re-builder #'swiper--re-builder
373 :history 'swiper-history
374 :caller 'swiper))
375 (unless res
376 (goto-char swiper--opoint)))))
377
378 (defun swiper-toggle-face-matching ()
379 "Toggle matching only the candidates with `swiper-invocation-face'."
380 (interactive)
381 (setf (ivy-state-matcher ivy-last)
382 (if (ivy-state-matcher ivy-last)
383 nil
384 #'swiper--face-matcher))
385 (setq ivy--old-re nil))
386
387 (defun swiper--face-matcher (regexp candidates)
388 "Return REGEXP-matching CANDIDATES.
389 Matched candidates should have `swiper-invocation-face'."
390 (cl-remove-if-not
391 (lambda (x)
392 (and
393 (string-match regexp x)
394 (let ((s (match-string 0 x))
395 (i 0))
396 (while (and (< i (length s))
397 (text-property-any
398 i (1+ i)
399 'face swiper-invocation-face
400 s))
401 (cl-incf i))
402 (eq i (length s)))))
403 candidates))
404
405 (defun swiper--ensure-visible ()
406 "Remove overlays hiding point."
407 (let ((overlays (overlays-at (point)))
408 ov expose)
409 (while (setq ov (pop overlays))
410 (if (and (invisible-p (overlay-get ov 'invisible))
411 (setq expose (overlay-get ov 'isearch-open-invisible)))
412 (funcall expose ov)))))
413
414 (defvar swiper--overlays nil
415 "Store overlays.")
416
417 (defun swiper--cleanup ()
418 "Clean up the overlays."
419 (while swiper--overlays
420 (delete-overlay (pop swiper--overlays)))
421 (save-excursion
422 (goto-char (point-min))
423 (isearch-clean-overlays)))
424
425 (defun swiper--update-input-ivy ()
426 "Called when `ivy' input is updated."
427 (with-ivy-window
428 (swiper--cleanup)
429 (when (> (length ivy--current) 0)
430 (let* ((re (funcall ivy--regex-function ivy-text))
431 (re (if (stringp re) re (caar re)))
432 (str (get-text-property 0 'display ivy--current))
433 (num (if (string-match "^[0-9]+" str)
434 (string-to-number (match-string 0 str))
435 0)))
436 (goto-char (point-min))
437 (when (cl-plusp num)
438 (goto-char (point-min))
439 (if swiper-use-visual-line
440 (line-move (1- num))
441 (forward-line (1- num)))
442 (if (and (equal ivy-text "")
443 (>= swiper--opoint (line-beginning-position))
444 (<= swiper--opoint (line-end-position)))
445 (goto-char swiper--opoint)
446 (re-search-forward re (line-end-position) t))
447 (isearch-range-invisible (line-beginning-position)
448 (line-end-position))
449 (unless (and (>= (point) (window-start))
450 (<= (point) (window-end (ivy-state-window ivy-last) t)))
451 (recenter)))
452 (swiper--add-overlays re)))))
453
454 (defun swiper--add-overlays (re &optional beg end wnd)
455 "Add overlays for RE regexp in visible part of the current buffer.
456 BEG and END, when specified, are the point bounds.
457 WND, when specified is the window."
458 (setq wnd (or wnd (ivy-state-window ivy-last)))
459 (let ((ov (if visual-line-mode
460 (make-overlay
461 (save-excursion
462 (beginning-of-visual-line)
463 (point))
464 (save-excursion
465 (end-of-visual-line)
466 (point)))
467 (make-overlay
468 (line-beginning-position)
469 (1+ (line-end-position))))))
470 (overlay-put ov 'face 'swiper-line-face)
471 (overlay-put ov 'window wnd)
472 (push ov swiper--overlays)
473 (let* ((wh (window-height))
474 (beg (or beg (save-excursion
475 (forward-line (- wh))
476 (point))))
477 (end (or end (save-excursion
478 (forward-line wh)
479 (point)))))
480 (when (>= (length re) swiper-min-highlight)
481 (save-excursion
482 (goto-char beg)
483 ;; RE can become an invalid regexp
484 (while (and (ignore-errors (re-search-forward re end t))
485 (> (- (match-end 0) (match-beginning 0)) 0))
486 (let ((i 0))
487 (while (<= i ivy--subexps)
488 (when (match-beginning i)
489 (let ((overlay (make-overlay (match-beginning i)
490 (match-end i)))
491 (face
492 (cond ((zerop ivy--subexps)
493 (cadr swiper-faces))
494 ((zerop i)
495 (car swiper-faces))
496 (t
497 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
498 swiper-faces)))))
499 (push overlay swiper--overlays)
500 (overlay-put overlay 'face face)
501 (overlay-put overlay 'window wnd)
502 (overlay-put overlay 'priority i)))
503 (cl-incf i)))))))))
504
505 (defun swiper--action (x)
506 "Goto line X."
507 (if (null x)
508 (user-error "No candidates")
509 (with-ivy-window
510 (unless (equal (current-buffer)
511 (ivy-state-buffer ivy-last))
512 (switch-to-buffer (ivy-state-buffer ivy-last)))
513 (goto-char (point-min))
514 (funcall (if swiper-use-visual-line
515 #'line-move
516 #'forward-line)
517 (1- (read (get-text-property 0 'display x))))
518 (re-search-forward
519 (ivy--regex ivy-text) (line-end-position) t)
520 (swiper--ensure-visible)
521 (when (/= (point) swiper--opoint)
522 (unless (and transient-mark-mode mark-active)
523 (when (eq ivy-exit 'done)
524 (push-mark swiper--opoint t)
525 (message "Mark saved where search started")))))))
526
527 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
528 (defun swiper-from-isearch ()
529 "Invoke `swiper' from isearch."
530 (interactive)
531 (let ((query (if isearch-regexp
532 isearch-string
533 (regexp-quote isearch-string))))
534 (isearch-exit)
535 (swiper query)))
536
537 (defvar swiper-multi-buffers nil
538 "Store the current list of buffers.")
539
540 (defvar swiper-multi-candidates nil
541 "Store the list of candidates for `swiper-multi'.")
542
543 (defun swiper-multi-prompt ()
544 (format "Buffers (%s): "
545 (mapconcat #'identity swiper-multi-buffers ", ")))
546
547 (defun swiper-multi ()
548 "Select one or more buffers.
549 Run `swiper' for those buffers."
550 (interactive)
551 (setq swiper-multi-buffers nil)
552 (ivy-read (swiper-multi-prompt)
553 'internal-complete-buffer
554 :action 'swiper-multi-action-1)
555 (ivy-read "Swiper: " swiper-multi-candidates
556 :action 'swiper-multi-action-2
557 :unwind #'swiper--cleanup
558 :caller 'swiper-multi))
559
560 (defun swiper-all ()
561 "Run `swiper' for all opened buffers."
562 (interactive)
563 (ivy-read "Swiper: " (swiper--multi-candidates
564 (cl-remove-if-not
565 #'buffer-file-name
566 (buffer-list)))
567 :action 'swiper-multi-action-2
568 :unwind #'swiper--cleanup
569 :caller 'swiper-multi))
570
571 (defun swiper--multi-candidates (buffers)
572 (let* ((ww (window-width))
573 (res nil)
574 (column-2 (apply #'max
575 (mapcar
576 (lambda (b)
577 (length (buffer-name b)))
578 buffers)))
579 (column-1 (- ww 4 column-2 1)))
580 (dolist (buf buffers)
581 (with-current-buffer buf
582 (setq res
583 (append
584 (mapcar
585 (lambda (s)
586 (setq s (concat (ivy--truncate-string s column-1) " "))
587 (let ((len (length s)))
588 (put-text-property
589 (1- len) len 'display
590 (concat
591 (make-string
592 (- ww (string-width s) (length (buffer-name)) 3)
593 ?\ )
594 (buffer-name))
595 s)
596 s))
597 (swiper--candidates 4))
598 res))
599 nil))
600 res))
601
602 (defun swiper-multi-action-1 (x)
603 (if (member x swiper-multi-buffers)
604 (progn
605 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
606 (unless (equal x "")
607 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
608 (let ((prompt (swiper-multi-prompt)))
609 (setf (ivy-state-prompt ivy-last) prompt)
610 (setq ivy--prompt (concat "%-4d " prompt)))
611 (cond ((memq this-command '(ivy-done
612 ivy-alt-done
613 ivy-immediate-done))
614 (setq swiper-multi-candidates
615 (swiper--multi-candidates
616 (mapcar #'get-buffer swiper-multi-buffers))))
617 ((eq this-command 'ivy-call)
618 (delete-minibuffer-contents))))
619
620 (defun swiper-multi-action-2 (x)
621 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
622 (with-ivy-window
623 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
624 (switch-to-buffer (match-string 1 buf-space))
625 (goto-char (point-min))
626 (forward-line (1- (read (get-text-property 0 'display x))))
627 (re-search-forward
628 (ivy--regex ivy-text)
629 (line-end-position) t)
630 (unless (eq ivy-exit 'done)
631 (swiper--cleanup)
632 (swiper--add-overlays (ivy--regex ivy-text)))))))
633
634 (provide 'swiper)
635
636 ;;; swiper.el ends here