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