]> code.delx.au - gnu-emacs-elpa/blob - swiper.el
swiper.el (swiper--add-overlays): Take extra WND arg
[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 map)
97 "Keymap for swiper.")
98
99 (defun swiper-query-replace ()
100 "Start `query-replace' with string to replace from last search string."
101 (interactive)
102 (if (null (window-minibuffer-p))
103 (user-error "Should only be called in the minibuffer through `swiper-map'")
104 (let* ((enable-recursive-minibuffers t)
105 (from (ivy--regex ivy-text))
106 (to (query-replace-read-to from "Query replace" t)))
107 (delete-minibuffer-contents)
108 (ivy-set-action (lambda (_)
109 (with-ivy-window
110 (move-beginning-of-line 1)
111 (perform-replace from to
112 t t nil))))
113 (swiper--cleanup)
114 (exit-minibuffer))))
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-set-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 (setq ivy-exit 'done)
196 (exit-minibuffer))))
197
198 (defun swiper-recenter-top-bottom (&optional arg)
199 "Call (`recenter-top-bottom' ARG)."
200 (interactive "P")
201 (with-ivy-window
202 (recenter-top-bottom arg)))
203
204 (defun swiper-font-lock-ensure ()
205 "Ensure the entired buffer is highlighted."
206 (unless (or (derived-mode-p 'magit-mode)
207 (bound-and-true-p magit-blame-mode)
208 (memq major-mode '(package-menu-mode
209 gnus-summary-mode
210 gnus-article-mode
211 gnus-group-mode
212 emms-playlist-mode
213 emms-stream-mode
214 erc-mode
215 org-agenda-mode
216 dired-mode
217 jabber-chat-mode
218 elfeed-search-mode
219 elfeed-show-mode
220 fundamental-mode
221 Man-mode
222 woman-mode
223 mu4e-view-mode
224 mu4e-headers-mode
225 help-mode
226 debbugs-gnu-mode
227 w3m-mode)))
228 (unless (> (buffer-size) 100000)
229 (if (fboundp 'font-lock-ensure)
230 (font-lock-ensure)
231 (with-no-warnings (font-lock-fontify-buffer))))))
232
233 (defvar swiper--format-spec ""
234 "Store the current candidates format spec.")
235
236 (defvar swiper--width nil
237 "Store the amount of digits needed for the longest line nubmer.")
238
239 (defvar swiper-use-visual-line nil
240 "When non-nil, use `line-move' instead of `forward-line'.")
241
242 (defun swiper--candidates ()
243 "Return a list of this buffer lines."
244 (setq swiper-use-visual-line
245 (and (not (eq major-mode 'org-mode))
246 visual-line-mode
247 (< (buffer-size) 20000)))
248 (let ((n-lines (count-lines (point-min) (point-max))))
249 (unless (zerop n-lines)
250 (setq swiper--width (1+ (floor (log n-lines 10))))
251 (setq swiper--format-spec
252 (format "%%-%dd " swiper--width))
253 (let ((line-number 0)
254 (advancer (if swiper-use-visual-line
255 (lambda (arg) (line-move arg t))
256 #'forward-line))
257 candidates)
258 (save-excursion
259 (goto-char (point-min))
260 (swiper-font-lock-ensure)
261 (while (< (point) (point-max))
262 (let ((str (concat " " (buffer-substring
263 (point)
264 (if swiper-use-visual-line
265 (save-excursion
266 (end-of-visual-line)
267 (point))
268 (line-end-position))))))
269 (put-text-property 0 1 'display
270 (format swiper--format-spec
271 (cl-incf line-number))
272 str)
273 (push str candidates))
274 (funcall advancer 1))
275 (nreverse candidates))))))
276
277 (defvar swiper--opoint 1
278 "The point when `swiper' starts.")
279
280 ;;;###autoload
281 (defun swiper (&optional initial-input)
282 "`isearch' with an overview.
283 When non-nil, INITIAL-INPUT is the initial search pattern."
284 (interactive)
285 (swiper--ivy initial-input))
286
287 (defvar swiper--anchor nil
288 "A line number to which the search should be anchored.")
289
290 (defvar swiper--len 0
291 "The last length of input for which an anchoring was made.")
292
293 (defun swiper--init ()
294 "Perform initialization common to both completion methods."
295 (setq swiper--opoint (point))
296 (setq swiper--len 0)
297 (setq swiper--anchor (line-number-at-pos)))
298
299 (defun swiper--re-builder (str)
300 "Transform STR into a swiper regex.
301 This is the regex used in the minibuffer, since the candidates
302 there have line numbers. In the buffer, `ivy--regex' should be used."
303 (cond
304 ((equal str "")
305 "")
306 ((equal str "^")
307 (setq ivy--subexps 0)
308 ".")
309 ((string-match "^\\^" str)
310 (setq ivy--old-re "")
311 (let ((re (ivy--regex-plus (substring str 1))))
312 (if (zerop ivy--subexps)
313 (prog1 (format "^ ?\\(%s\\)" re)
314 (setq ivy--subexps 1))
315 (format "^ %s" re))))
316 (t
317 (ivy--regex-plus str))))
318
319 (defvar swiper-history nil
320 "History for `swiper'.")
321
322 (defun swiper--ivy (&optional initial-input)
323 "`isearch' with an overview using `ivy'.
324 When non-nil, INITIAL-INPUT is the initial search pattern."
325 (interactive)
326 (swiper--init)
327 (let ((candidates (swiper--candidates))
328 (preselect (buffer-substring-no-properties
329 (line-beginning-position)
330 (line-end-position)))
331 (minibuffer-allow-text-properties t))
332 (unwind-protect
333 (ivy-read
334 "Swiper: "
335 candidates
336 :initial-input initial-input
337 :keymap swiper-map
338 :preselect preselect
339 :require-match t
340 :update-fn #'swiper--update-input-ivy
341 :unwind #'swiper--cleanup
342 :action #'swiper--action
343 :re-builder #'swiper--re-builder
344 :history 'swiper-history
345 :caller 'swiper)
346 (when (null ivy-exit)
347 (goto-char swiper--opoint)))))
348
349 (defun swiper--ensure-visible ()
350 "Remove overlays hiding point."
351 (let ((overlays (overlays-at (point)))
352 ov expose)
353 (while (setq ov (pop overlays))
354 (if (and (invisible-p (overlay-get ov 'invisible))
355 (setq expose (overlay-get ov 'isearch-open-invisible)))
356 (funcall expose ov)))))
357
358 (defvar swiper--overlays nil
359 "Store overlays.")
360
361 (defun swiper--cleanup ()
362 "Clean up the overlays."
363 (while swiper--overlays
364 (delete-overlay (pop swiper--overlays)))
365 (save-excursion
366 (goto-char (point-min))
367 (isearch-clean-overlays)))
368
369 (defun swiper--update-input-ivy ()
370 "Called when `ivy' input is updated."
371 (with-ivy-window
372 (swiper--cleanup)
373 (when (> (length ivy--current) 0)
374 (let* ((re (funcall ivy--regex-function ivy-text))
375 (re (if (stringp re) re (caar re)))
376 (str (get-text-property 0 'display ivy--current))
377 (num (if (string-match "^[0-9]+" str)
378 (string-to-number (match-string 0 str))
379 0)))
380 (goto-char (point-min))
381 (when (cl-plusp num)
382 (goto-char (point-min))
383 (if swiper-use-visual-line
384 (line-move (1- num))
385 (forward-line (1- num)))
386 (if (and (equal ivy-text "")
387 (>= swiper--opoint (line-beginning-position))
388 (<= swiper--opoint (line-end-position)))
389 (goto-char swiper--opoint)
390 (re-search-forward re (line-end-position) t))
391 (isearch-range-invisible (line-beginning-position)
392 (line-end-position))
393 (unless (and (>= (point) (window-start))
394 (<= (point) (window-end (ivy-state-window ivy-last) t)))
395 (recenter)))
396 (swiper--add-overlays re)))))
397
398 (defun swiper--add-overlays (re &optional beg end wnd)
399 "Add overlays for RE regexp in visible part of the current buffer.
400 BEG and END, when specified, are the point bounds.
401 WND, when specified is the window."
402 (setq wnd (or wnd (ivy-state-window ivy-last)))
403 (let ((ov (if visual-line-mode
404 (make-overlay
405 (save-excursion
406 (beginning-of-visual-line)
407 (point))
408 (save-excursion
409 (end-of-visual-line)
410 (point)))
411 (make-overlay
412 (line-beginning-position)
413 (1+ (line-end-position))))))
414 (overlay-put ov 'face 'swiper-line-face)
415 (overlay-put ov 'window wnd)
416 (push ov swiper--overlays)
417 (let* ((wh (window-height))
418 (beg (or beg (save-excursion
419 (forward-line (- wh))
420 (point))))
421 (end (or end (save-excursion
422 (forward-line wh)
423 (point)))))
424 (when (>= (length re) swiper-min-highlight)
425 (save-excursion
426 (goto-char beg)
427 ;; RE can become an invalid regexp
428 (while (and (ignore-errors (re-search-forward re end t))
429 (> (- (match-end 0) (match-beginning 0)) 0))
430 (let ((i 0))
431 (while (<= i ivy--subexps)
432 (when (match-beginning i)
433 (let ((overlay (make-overlay (match-beginning i)
434 (match-end i)))
435 (face
436 (cond ((zerop ivy--subexps)
437 (cadr swiper-faces))
438 ((zerop i)
439 (car swiper-faces))
440 (t
441 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
442 swiper-faces)))))
443 (push overlay swiper--overlays)
444 (overlay-put overlay 'face face)
445 (overlay-put overlay 'window wnd)
446 (overlay-put overlay 'priority i)))
447 (cl-incf i)))))))))
448
449 (defun swiper--action (x)
450 "Goto line X."
451 (if (null x)
452 (user-error "No candidates")
453 (with-ivy-window
454 (unless (equal (current-buffer)
455 (ivy-state-buffer ivy-last))
456 (switch-to-buffer (ivy-state-buffer ivy-last)))
457 (goto-char (point-min))
458 (funcall (if swiper-use-visual-line
459 #'line-move
460 #'forward-line)
461 (1- (read (get-text-property 0 'display x))))
462 (re-search-forward
463 (ivy--regex ivy-text) (line-end-position) t)
464 (swiper--ensure-visible)
465 (when (/= (point) swiper--opoint)
466 (unless (and transient-mark-mode mark-active)
467 (push-mark swiper--opoint t)
468 (message "Mark saved where search started"))))))
469
470 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
471 (defun swiper-from-isearch ()
472 "Invoke `swiper' from isearch."
473 (interactive)
474 (let ((query (if isearch-regexp
475 isearch-string
476 (regexp-quote isearch-string))))
477 (isearch-exit)
478 (swiper query)))
479
480 (defvar swiper-multi-buffers nil
481 "Store the current list of buffers.")
482
483 (defvar swiper-multi-candidates nil
484 "Store the list of candidates for `swiper-multi'.")
485
486 (defun swiper-multi-prompt ()
487 (format "Buffers (%s): "
488 (mapconcat #'identity swiper-multi-buffers ", ")))
489
490 (defun swiper-multi ()
491 "Select one or more buffers.
492 Run `swiper' for those buffers."
493 (interactive)
494 (setq swiper-multi-buffers nil)
495 (setq swiper-multi-candidates nil)
496 (ivy-read (swiper-multi-prompt)
497 'internal-complete-buffer
498 :action 'swiper-multi-action-1)
499 (ivy-read "Swiper: " swiper-multi-candidates
500 :action 'swiper-multi-action-2
501 :unwind #'swiper--cleanup
502 :caller 'swiper-multi))
503
504 (defun swiper-multi-action-1 (x)
505 (if (member x swiper-multi-buffers)
506 (progn
507 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
508 (unless (equal x "")
509 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
510 (let ((prompt (swiper-multi-prompt)))
511 (setf (ivy-state-prompt ivy-last) prompt)
512 (setq ivy--prompt (concat "%-4d " prompt)))
513 (cond ((memq this-command '(ivy-done
514 ivy-alt-done
515 ivy-immediate-done))
516 (let ((ww (window-width)))
517 (dolist (buf swiper-multi-buffers)
518 (with-current-buffer buf
519 (setq swiper-multi-candidates
520 (append
521 (mapcar
522 (lambda (s)
523 (setq s (concat s " "))
524 (let ((len (length s)))
525 (put-text-property
526 (1- len) len 'display
527 (concat
528 (make-string
529 (max
530 (- ww
531 (string-width s)
532 (length (buffer-name))
533 1)
534 0)
535 ?\ )
536 (buffer-name))
537 s)
538 s))
539 (swiper--candidates))
540 swiper-multi-candidates))))))
541 ((eq this-command 'ivy-call)
542 (delete-minibuffer-contents))))
543
544 (defun swiper-multi-action-2 (x)
545 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
546 (with-ivy-window
547 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
548 (switch-to-buffer (match-string 1 buf-space))
549 (goto-char (point-min))
550 (forward-line (1- (read x)))
551 (re-search-forward
552 (ivy--regex ivy-text)
553 (line-end-position) t)
554 (unless (eq ivy-exit 'done)
555 (swiper--cleanup)
556 (swiper--add-overlays (ivy--regex ivy-text)))))))
557
558 (provide 'swiper)
559
560 ;;; swiper.el ends here