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