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