]> code.delx.au - gnu-emacs-elpa/blob - swiper.el
swiper.el (swiper-avy): Don't start on empty input
[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.4.1
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 (defface swiper-line-face
65 '((t (:inherit highlight)))
66 "Face for current `swiper' line.")
67
68 (defcustom swiper-faces '(swiper-match-face-1
69 swiper-match-face-2
70 swiper-match-face-3
71 swiper-match-face-4)
72 "List of `swiper' faces for group matches.")
73
74 (defcustom swiper-min-highlight 2
75 "Only highlight matches for regexps at least this long."
76 :type 'integer)
77
78 (defvar swiper-map
79 (let ((map (make-sparse-keymap)))
80 (define-key map (kbd "M-q") 'swiper-query-replace)
81 (define-key map (kbd "C-l") 'swiper-recenter-top-bottom)
82 (define-key map (kbd "C-'") 'swiper-avy)
83 map)
84 "Keymap for swiper.")
85
86 (defvar swiper--window nil
87 "Store the current window.")
88
89 (defun swiper-query-replace ()
90 "Start `query-replace' with string to replace from last search string."
91 (interactive)
92 (if (null (window-minibuffer-p))
93 (user-error "Should only be called in the minibuffer through `swiper-map'")
94 (let* ((enable-recursive-minibuffers t)
95 (from (ivy--regex ivy-text))
96 (to (query-replace-read-to from "Query replace" t)))
97 (delete-minibuffer-contents)
98 (ivy-set-action (lambda (_)
99 (with-selected-window swiper--window
100 (perform-replace from to
101 t t nil))))
102 (swiper--cleanup)
103 (exit-minibuffer))))
104
105 (defvar avy-background)
106 (declare-function avy--regex-candidates "ext:avy")
107 (declare-function avy--process "ext:avy")
108 (declare-function avy--overlay-post "ext:avy")
109 (declare-function avy--goto "ext:avy")
110
111 ;;;###autoload
112 (defun swiper-avy ()
113 "Jump to one of the current swiper candidates."
114 (interactive)
115 (unless (string= ivy-text "")
116 (with-selected-window (ivy-state-window ivy-last)
117 (let* ((avy-all-windows nil)
118 (candidates
119 (avy--regex-candidates
120 (ivy--regex ivy-text)))
121 (avy-background nil)
122 (candidate
123 (avy--process candidates #'avy--overlay-post)))
124 (ivy-quit-and-run
125 (avy--goto candidate))))))
126
127 (defun swiper-recenter-top-bottom (&optional arg)
128 "Call (`recenter-top-bottom' ARG) in `swiper--window'."
129 (interactive "P")
130 (with-selected-window swiper--window
131 (recenter-top-bottom arg)))
132
133 (defun swiper-font-lock-ensure ()
134 "Ensure the entired buffer is highlighted."
135 (unless (or (derived-mode-p 'magit-mode)
136 (memq major-mode '(package-menu-mode
137 gnus-summary-mode
138 gnus-article-mode
139 gnus-group-mode
140 emms-playlist-mode erc-mode
141 org-agenda-mode
142 dired-mode
143 jabber-chat-mode
144 elfeed-search-mode
145 fundamental-mode)))
146 (unless (> (buffer-size) 100000)
147 (if (fboundp 'font-lock-ensure)
148 (font-lock-ensure)
149 (with-no-warnings (font-lock-fontify-buffer))))))
150
151 (defvar swiper--format-spec ""
152 "Store the current candidates format spec.")
153
154 (defvar swiper--width nil
155 "Store the amount of digits needed for the longest line nubmer.")
156
157 (defun swiper--candidates ()
158 "Return a list of this buffer lines."
159 (let ((n-lines (count-lines (point-min) (point-max))))
160 (unless (zerop n-lines)
161 (setq swiper--width (1+ (floor (log n-lines 10))))
162 (setq swiper--format-spec
163 (format "%%-%dd %%s" swiper--width))
164 (let ((line-number 0)
165 candidates)
166 (save-excursion
167 (goto-char (point-min))
168 (swiper-font-lock-ensure)
169 (while (< (point) (point-max))
170 (push (format swiper--format-spec
171 (cl-incf line-number)
172 (buffer-substring
173 (line-beginning-position)
174 (line-end-position)))
175 candidates)
176 (forward-line 1))
177 (nreverse candidates))))))
178
179 (defvar swiper--opoint 1
180 "The point when `swiper' starts.")
181
182 ;;;###autoload
183 (defun swiper (&optional initial-input)
184 "`isearch' with an overview.
185 When non-nil, INITIAL-INPUT is the initial search pattern."
186 (interactive)
187 (swiper--ivy initial-input))
188
189 (defvar swiper--anchor nil
190 "A line number to which the search should be anchored.")
191
192 (defvar swiper--len 0
193 "The last length of input for which an anchoring was made.")
194
195 (defun swiper--init ()
196 "Perform initialization common to both completion methods."
197 (deactivate-mark)
198 (setq swiper--opoint (point))
199 (setq swiper--len 0)
200 (setq swiper--anchor (line-number-at-pos))
201 (setq swiper--window (selected-window)))
202
203 (defun swiper--re-builder (str)
204 "Transform STR into a swiper regex.
205 This is the regex used in the minibuffer, since the candidates
206 there have line numbers. In the buffer, `ivy--regex' should be used."
207 (cond
208 ((equal str "")
209 "")
210 ((equal str "^")
211 ".")
212 ((string-match "^\\^" str)
213 (setq ivy--old-re "")
214 (let ((re (ivy--regex-plus (substring str 1))))
215 (format "^[0-9][0-9 ]\\{%d\\}%s"
216 swiper--width
217 (if (zerop ivy--subexps)
218 (prog1 (format "\\(%s\\)" re)
219 (setq ivy--subexps 1))
220 re))))
221 (t
222 (ivy--regex-plus str))))
223
224 (defun swiper--ivy (&optional initial-input)
225 "`isearch' with an overview using `ivy'.
226 When non-nil, INITIAL-INPUT is the initial search pattern."
227 (interactive)
228 (unless (eq (length (help-function-arglist 'ivy-read)) 4)
229 (warn "You seem to be using the outdated stand-alone \"ivy\" package.
230 Please remove it and update the \"swiper\" package."))
231 (swiper--init)
232 (let ((candidates (swiper--candidates))
233 (preselect (format
234 swiper--format-spec
235 (line-number-at-pos)
236 (regexp-quote
237 (buffer-substring-no-properties
238 (line-beginning-position)
239 (line-end-position)))))
240 res)
241 (unwind-protect
242 (setq res (ivy-read
243 (replace-regexp-in-string
244 "%s" "pattern: " swiper--format-spec)
245 candidates
246 :initial-input initial-input
247 :keymap swiper-map
248 :preselect preselect
249 :require-match t
250 :update-fn #'swiper--update-input-ivy
251 :unwind #'swiper--cleanup
252 :re-builder #'swiper--re-builder))
253 (if (null ivy-exit)
254 (goto-char swiper--opoint)
255 (swiper--action res ivy-text)))))
256
257 (defun swiper--ensure-visible ()
258 "Remove overlays hiding point."
259 (let ((overlays (overlays-at (point)))
260 ov expose)
261 (while (setq ov (pop overlays))
262 (if (and (invisible-p (overlay-get ov 'invisible))
263 (setq expose (overlay-get ov 'isearch-open-invisible)))
264 (funcall expose ov)))))
265
266 (defvar swiper--overlays nil
267 "Store overlays.")
268
269 (defun swiper--cleanup ()
270 "Clean up the overlays."
271 (while swiper--overlays
272 (delete-overlay (pop swiper--overlays)))
273 (save-excursion
274 (goto-char (point-min))
275 (isearch-clean-overlays)))
276
277 (defun swiper--update-input-ivy ()
278 "Called when `ivy' input is updated."
279 (swiper--cleanup)
280 (let* ((re (ivy--regex ivy-text))
281 (str ivy--current)
282 (num (if (string-match "^[0-9]+" str)
283 (string-to-number (match-string 0 str))
284 0)))
285 (with-selected-window swiper--window
286 (goto-char (point-min))
287 (when (cl-plusp num)
288 (goto-char (point-min))
289 (forward-line (1- num))
290 (isearch-range-invisible (line-beginning-position)
291 (line-end-position))
292 (unless (and (>= (point) (window-start))
293 (<= (point) (window-end swiper--window t)))
294 (recenter)))
295 (swiper--add-overlays re))))
296
297 (defun swiper--add-overlays (re &optional beg end)
298 "Add overlays for RE regexp in visible part of the current buffer.
299 BEG and END, when specified, are the point bounds."
300 (let ((ov (make-overlay
301 (line-beginning-position)
302 (1+ (line-end-position)))))
303 (overlay-put ov 'face 'swiper-line-face)
304 (overlay-put ov 'window swiper--window)
305 (push ov swiper--overlays))
306 (let* ((wh (window-height))
307 (beg (or beg (save-excursion
308 (forward-line (- wh))
309 (point))))
310 (end (or end (save-excursion
311 (forward-line wh)
312 (point)))))
313 (when (>= (length re) swiper-min-highlight)
314 (save-excursion
315 (goto-char beg)
316 ;; RE can become an invalid regexp
317 (while (and (ignore-errors (re-search-forward re end t))
318 (> (- (match-end 0) (match-beginning 0)) 0))
319 (let ((i 0))
320 (while (<= i ivy--subexps)
321 (when (match-beginning i)
322 (let ((overlay (make-overlay (match-beginning i)
323 (match-end i)))
324 (face
325 (cond ((zerop ivy--subexps)
326 (cadr swiper-faces))
327 ((zerop i)
328 (car swiper-faces))
329 (t
330 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
331 swiper-faces)))))
332 (push overlay swiper--overlays)
333 (overlay-put overlay 'face face)
334 (overlay-put overlay 'window swiper--window)
335 (overlay-put overlay 'priority i)))
336 (cl-incf i))))))))
337
338 (defun swiper--action (x input)
339 "Goto line X and search for INPUT."
340 (if (null x)
341 (user-error "No candidates")
342 (goto-char (point-min))
343 (forward-line (1- (read x)))
344 (re-search-forward
345 (ivy--regex input) (line-end-position) t)
346 (swiper--ensure-visible)
347 (when (/= (point) swiper--opoint)
348 (unless (and transient-mark-mode mark-active)
349 (push-mark swiper--opoint t)
350 (message "Mark saved where search started")))))
351
352 (provide 'swiper)
353
354 ;;; swiper.el ends here