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