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