]> code.delx.au - gnu-emacs-elpa/blob - swiper.el
swiper.el (swiper-font-lock-ensure): Add bongo-playlist-mode
[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.7.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 bongo-playlist-mode
229 eww-mode
230 twittering-mode
231 vc-dir-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 (declare-function outline-show-all "outline")
248
249 (defun swiper--candidates (&optional numbers-width)
250 "Return a list of this buffer lines.
251
252 NUMBERS-WIDTH, when specified, is used for line numbers width
253 spec, instead of calculating it as the log of the buffer line
254 count."
255 (if (and visual-line-mode
256 ;; super-slow otherwise
257 (< (buffer-size) 20000))
258 (progn
259 (when (eq major-mode 'org-mode)
260 (require 'outline)
261 (if (fboundp 'outline-show-all)
262 (outline-show-all)
263 (with-no-warnings
264 (show-all))))
265 (setq swiper-use-visual-line t))
266 (setq swiper-use-visual-line nil))
267 (let ((n-lines (count-lines (point-min) (point-max))))
268 (unless (zerop n-lines)
269 (setq swiper--width (or numbers-width
270 (1+ (floor (log n-lines 10)))))
271 (setq swiper--format-spec
272 (format "%%-%dd " swiper--width))
273 (let ((line-number 0)
274 (advancer (if swiper-use-visual-line
275 (lambda (arg) (line-move arg t))
276 #'forward-line))
277 candidates)
278 (save-excursion
279 (goto-char (point-min))
280 (swiper-font-lock-ensure)
281 (while (< (point) (point-max))
282 (let ((str (concat
283 " "
284 (replace-regexp-in-string
285 "\t" " "
286 (if swiper-use-visual-line
287 (buffer-substring
288 (save-excursion
289 (beginning-of-visual-line)
290 (point))
291 (save-excursion
292 (end-of-visual-line)
293 (point)))
294 (buffer-substring
295 (point)
296 (line-end-position)))))))
297 (when (eq major-mode 'twittering-mode)
298 (remove-text-properties 0 (length str) '(field) str))
299 (put-text-property 0 1 'display
300 (format swiper--format-spec
301 (cl-incf line-number))
302 str)
303 (push str candidates))
304 (funcall advancer 1))
305 (nreverse candidates))))))
306
307 (defvar swiper--opoint 1
308 "The point when `swiper' starts.")
309
310 ;;;###autoload
311 (defun swiper (&optional initial-input)
312 "`isearch' with an overview.
313 When non-nil, INITIAL-INPUT is the initial search pattern."
314 (interactive)
315 (swiper--ivy initial-input))
316
317 (declare-function evil-jumper--set-jump "ext:evil-jumper")
318
319 (defvar swiper--current-line nil)
320 (defvar swiper--current-match-start nil)
321
322 (defun swiper--init ()
323 "Perform initialization common to both completion methods."
324 (setq swiper--current-line nil)
325 (setq swiper--current-match-start nil)
326 (setq swiper--opoint (point))
327 (when (bound-and-true-p evil-jumper-mode)
328 (evil-jumper--set-jump)))
329
330 (defun swiper--re-builder (str)
331 "Transform STR into a swiper regex.
332 This is the regex used in the minibuffer, since the candidates
333 there have line numbers. In the buffer, `ivy--regex' should be used."
334 (cond
335 ((equal str "")
336 "")
337 ((equal str "^")
338 (setq ivy--subexps 0)
339 ".")
340 ((string-match "^\\^" str)
341 (setq ivy--old-re "")
342 (let ((re (ivy--regex-plus (substring str 1))))
343 (if (zerop ivy--subexps)
344 (prog1 (format "^ ?\\(%s\\)" re)
345 (setq ivy--subexps 1))
346 (format "^ %s" re))))
347 (t
348 (ivy--regex-plus str))))
349
350 (defvar swiper-history nil
351 "History for `swiper'.")
352
353 (defvar swiper-invocation-face nil
354 "The face at the point of invocation of `swiper'.")
355
356 (defun swiper--ivy (&optional initial-input)
357 "`isearch' with an overview using `ivy'.
358 When non-nil, INITIAL-INPUT is the initial search pattern."
359 (interactive)
360 (swiper--init)
361 (setq swiper-invocation-face
362 (plist-get (text-properties-at (point)) 'face))
363 (let ((candidates (swiper--candidates))
364 (preselect
365 (if swiper-use-visual-line
366 (count-screen-lines
367 (point-min)
368 (save-excursion (beginning-of-visual-line) (point)))
369 (1- (line-number-at-pos))))
370 (minibuffer-allow-text-properties t)
371 res)
372 (unwind-protect
373 (setq res
374 (ivy-read
375 "Swiper: "
376 candidates
377 :initial-input initial-input
378 :keymap swiper-map
379 :preselect preselect
380 :require-match t
381 :update-fn #'swiper--update-input-ivy
382 :unwind #'swiper--cleanup
383 :action #'swiper--action
384 :re-builder #'swiper--re-builder
385 :history 'swiper-history
386 :caller 'swiper))
387 (unless res
388 (goto-char swiper--opoint)))))
389
390 (defun swiper-toggle-face-matching ()
391 "Toggle matching only the candidates with `swiper-invocation-face'."
392 (interactive)
393 (setf (ivy-state-matcher ivy-last)
394 (if (ivy-state-matcher ivy-last)
395 nil
396 #'swiper--face-matcher))
397 (setq ivy--old-re nil))
398
399 (defun swiper--face-matcher (regexp candidates)
400 "Return REGEXP-matching CANDIDATES.
401 Matched candidates should have `swiper-invocation-face'."
402 (cl-remove-if-not
403 (lambda (x)
404 (and
405 (string-match regexp x)
406 (let ((s (match-string 0 x))
407 (i 0))
408 (while (and (< i (length s))
409 (text-property-any
410 i (1+ i)
411 'face swiper-invocation-face
412 s))
413 (cl-incf i))
414 (eq i (length s)))))
415 candidates))
416
417 (defun swiper--ensure-visible ()
418 "Remove overlays hiding point."
419 (let ((overlays (overlays-at (point)))
420 ov expose)
421 (while (setq ov (pop overlays))
422 (if (and (invisible-p (overlay-get ov 'invisible))
423 (setq expose (overlay-get ov 'isearch-open-invisible)))
424 (funcall expose ov)))))
425
426 (defvar swiper--overlays nil
427 "Store overlays.")
428
429 (defun swiper--cleanup ()
430 "Clean up the overlays."
431 (while swiper--overlays
432 (delete-overlay (pop swiper--overlays)))
433 (save-excursion
434 (goto-char (point-min))
435 (isearch-clean-overlays)))
436
437 (defun swiper--update-input-ivy ()
438 "Called when `ivy' input is updated."
439 (with-ivy-window
440 (swiper--cleanup)
441 (when (> (length ivy--current) 0)
442 (let* ((re (funcall ivy--regex-function ivy-text))
443 (re (if (stringp re) re (caar re)))
444 (str (get-text-property 0 'display ivy--current))
445 (num (if (string-match "^[0-9]+" str)
446 (string-to-number (match-string 0 str))
447 0)))
448 (unless (eq this-command 'ivy-yank-word)
449 (when (cl-plusp num)
450 (unless (if swiper--current-line
451 (eq swiper--current-line num)
452 (eq (line-number-at-pos) num))
453 (goto-char (point-min))
454 (if swiper-use-visual-line
455 (line-move (1- num))
456 (forward-line (1- num))))
457 (if (and (equal ivy-text "")
458 (>= swiper--opoint (line-beginning-position))
459 (<= swiper--opoint (line-end-position)))
460 (goto-char swiper--opoint)
461 (if (eq swiper--current-line num)
462 (when swiper--current-match-start
463 (goto-char swiper--current-match-start))
464 (setq swiper--current-line num))
465 (re-search-forward re (line-end-position) t)
466 (setq swiper--current-match-start (match-beginning 0)))
467 (isearch-range-invisible (line-beginning-position)
468 (line-end-position))
469 (unless (and (>= (point) (window-start))
470 (<= (point) (window-end (ivy-state-window ivy-last) t)))
471 (recenter))))
472 (swiper--add-overlays re)))))
473
474 (defun swiper--add-overlays (re &optional beg end wnd)
475 "Add overlays for RE regexp in visible part of the current buffer.
476 BEG and END, when specified, are the point bounds.
477 WND, when specified is the window."
478 (setq wnd (or wnd (ivy-state-window ivy-last)))
479 (let ((ov (if visual-line-mode
480 (make-overlay
481 (save-excursion
482 (beginning-of-visual-line)
483 (point))
484 (save-excursion
485 (end-of-visual-line)
486 (point)))
487 (make-overlay
488 (line-beginning-position)
489 (1+ (line-end-position))))))
490 (overlay-put ov 'face 'swiper-line-face)
491 (overlay-put ov 'window wnd)
492 (push ov swiper--overlays)
493 (let* ((wh (window-height))
494 (beg (or beg (save-excursion
495 (forward-line (- wh))
496 (point))))
497 (end (or end (save-excursion
498 (forward-line wh)
499 (point)))))
500 (when (>= (length re) swiper-min-highlight)
501 (save-excursion
502 (goto-char beg)
503 ;; RE can become an invalid regexp
504 (while (and (ignore-errors (re-search-forward re end t))
505 (> (- (match-end 0) (match-beginning 0)) 0))
506 (let ((i 0))
507 (while (<= i ivy--subexps)
508 (when (match-beginning i)
509 (let ((overlay (make-overlay (match-beginning i)
510 (match-end i)))
511 (face
512 (cond ((zerop ivy--subexps)
513 (cadr swiper-faces))
514 ((zerop i)
515 (car swiper-faces))
516 (t
517 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
518 swiper-faces)))))
519 (push overlay swiper--overlays)
520 (overlay-put overlay 'face face)
521 (overlay-put overlay 'window wnd)
522 (overlay-put overlay 'priority i)))
523 (cl-incf i)))))))))
524
525 (defun swiper--action (x)
526 "Goto line X."
527 (if (null x)
528 (user-error "No candidates")
529 (with-ivy-window
530 (unless (equal (current-buffer)
531 (ivy-state-buffer ivy-last))
532 (switch-to-buffer (ivy-state-buffer ivy-last)))
533 (goto-char (point-min))
534 (funcall (if swiper-use-visual-line
535 #'line-move
536 #'forward-line)
537 (1- (read (get-text-property 0 'display x))))
538 (re-search-forward
539 (ivy--regex ivy-text) (line-end-position) t)
540 (swiper--ensure-visible)
541 (when (/= (point) swiper--opoint)
542 (unless (and transient-mark-mode mark-active)
543 (when (eq ivy-exit 'done)
544 (push-mark swiper--opoint t)
545 (message "Mark saved where search started")))))))
546
547 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
548 (defun swiper-from-isearch ()
549 "Invoke `swiper' from isearch."
550 (interactive)
551 (let ((query (if isearch-regexp
552 isearch-string
553 (regexp-quote isearch-string))))
554 (isearch-exit)
555 (swiper query)))
556
557 (defvar swiper-multi-buffers nil
558 "Store the current list of buffers.")
559
560 (defvar swiper-multi-candidates nil
561 "Store the list of candidates for `swiper-multi'.")
562
563 (defun swiper-multi-prompt ()
564 (format "Buffers (%s): "
565 (mapconcat #'identity swiper-multi-buffers ", ")))
566
567 (defun swiper-multi ()
568 "Select one or more buffers.
569 Run `swiper' for those buffers."
570 (interactive)
571 (setq swiper-multi-buffers nil)
572 (ivy-read (swiper-multi-prompt)
573 'internal-complete-buffer
574 :action 'swiper-multi-action-1)
575 (ivy-read "Swiper: " swiper-multi-candidates
576 :action 'swiper-multi-action-2
577 :unwind #'swiper--cleanup
578 :caller 'swiper-multi))
579
580 (defun swiper-all ()
581 "Run `swiper' for all opened buffers."
582 (interactive)
583 (ivy-read "Swiper: " (swiper--multi-candidates
584 (cl-remove-if-not
585 #'buffer-file-name
586 (buffer-list)))
587 :action 'swiper-multi-action-2
588 :unwind #'swiper--cleanup
589 :caller 'swiper-multi))
590
591 (defun swiper--multi-candidates (buffers)
592 (let* ((ww (window-width))
593 (res nil)
594 (column-2 (apply #'max
595 (mapcar
596 (lambda (b)
597 (length (buffer-name b)))
598 buffers)))
599 (column-1 (- ww 4 column-2 1)))
600 (dolist (buf buffers)
601 (with-current-buffer buf
602 (setq res
603 (append
604 (mapcar
605 (lambda (s)
606 (setq s (concat (ivy--truncate-string s column-1) " "))
607 (let ((len (length s)))
608 (put-text-property
609 (1- len) len 'display
610 (concat
611 (make-string
612 (- ww (string-width s) (length (buffer-name)) 3)
613 ?\ )
614 (buffer-name))
615 s)
616 s))
617 (swiper--candidates 4))
618 res))
619 nil))
620 res))
621
622 (defun swiper-multi-action-1 (x)
623 (if (member x swiper-multi-buffers)
624 (progn
625 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
626 (unless (equal x "")
627 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
628 (let ((prompt (swiper-multi-prompt)))
629 (setf (ivy-state-prompt ivy-last) prompt)
630 (setq ivy--prompt (concat "%-4d " prompt)))
631 (cond ((memq this-command '(ivy-done
632 ivy-alt-done
633 ivy-immediate-done))
634 (setq swiper-multi-candidates
635 (swiper--multi-candidates
636 (mapcar #'get-buffer swiper-multi-buffers))))
637 ((eq this-command 'ivy-call)
638 (delete-minibuffer-contents))))
639
640 (defun swiper-multi-action-2 (x)
641 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
642 (with-ivy-window
643 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
644 (switch-to-buffer (match-string 1 buf-space))
645 (goto-char (point-min))
646 (forward-line (1- (read (get-text-property 0 'display x))))
647 (re-search-forward
648 (ivy--regex ivy-text)
649 (line-end-position) t)
650 (unless (eq ivy-exit 'done)
651 (swiper--cleanup)
652 (swiper--add-overlays (ivy--regex ivy-text)))))))
653
654 (provide 'swiper)
655
656 ;;; swiper.el ends here