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