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