]> code.delx.au - gnu-emacs-elpa/blob - swiper.el
swiper.el (swiper--ivy): Use minibuffer-allow-text-properties
[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.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-minibuffer-match-face-1
65 '((((class color) (background light))
66 :background "#d3d3d3")
67 (((class color) (background dark))
68 :background "#555555"))
69 "The background face for `swiper' minibuffer matches."
70 :group 'function-args-faces)
71
72 (defface swiper-minibuffer-match-face-2
73 '((((class color) (background light))
74 :background "#e99ce8" :weight bold)
75 (((class color) (background dark))
76 :background "#777777" :weight bold))
77 "Face for `swiper' minibuffer matches modulo 1.")
78
79 (defface swiper-minibuffer-match-face-3
80 '((((class color) (background light))
81 :background "#bbbbff" :weight bold)
82 (((class color) (background dark))
83 :background "#7777ff" :weight bold))
84 "Face for `swiper' minibuffer matches modulo 2.")
85
86 (defface swiper-minibuffer-match-face-4
87 '((((class color) (background light))
88 :background "#ffbbff" :weight bold)
89 (((class color) (background dark))
90 :background "#8a498a" :weight bold))
91 "Face for `swiper' minibuffer matches modulo 3.")
92
93 (defface swiper-line-face
94 '((t (:inherit highlight)))
95 "Face for current `swiper' line.")
96
97 (defcustom swiper-faces '(swiper-match-face-1
98 swiper-match-face-2
99 swiper-match-face-3
100 swiper-match-face-4)
101 "List of `swiper' faces for group matches.")
102
103 (defcustom swiper-min-highlight 2
104 "Only highlight matches for regexps at least this long."
105 :type 'integer)
106
107 (defvar swiper-map
108 (let ((map (make-sparse-keymap)))
109 (define-key map (kbd "M-q") 'swiper-query-replace)
110 (define-key map (kbd "C-l") 'swiper-recenter-top-bottom)
111 (define-key map (kbd "C-'") 'swiper-avy)
112 map)
113 "Keymap for swiper.")
114
115 (defun swiper-query-replace ()
116 "Start `query-replace' with string to replace from last search string."
117 (interactive)
118 (if (null (window-minibuffer-p))
119 (user-error "Should only be called in the minibuffer through `swiper-map'")
120 (let* ((enable-recursive-minibuffers t)
121 (from (ivy--regex ivy-text))
122 (to (query-replace-read-to from "Query replace" t)))
123 (delete-minibuffer-contents)
124 (ivy-set-action (lambda (_)
125 (with-ivy-window
126 (move-beginning-of-line 1)
127 (perform-replace from to
128 t t nil))))
129 (swiper--cleanup)
130 (exit-minibuffer))))
131
132 (defvar avy-background)
133 (defvar avy-all-windows)
134 (declare-function avy--regex-candidates "ext:avy")
135 (declare-function avy--process "ext:avy")
136 (declare-function avy--overlay-post "ext:avy")
137 (declare-function avy-action-goto "ext:avy")
138
139 ;;;###autoload
140 (defun swiper-avy ()
141 "Jump to one of the current swiper candidates."
142 (interactive)
143 (unless (string= ivy-text "")
144 (with-ivy-window
145 (let* ((avy-all-windows nil)
146 (candidates
147 (avy--regex-candidates
148 (ivy--regex ivy-text)))
149 (avy-background nil)
150 (candidate
151 (avy--process candidates #'avy--overlay-post)))
152 (ivy-quit-and-run
153 (avy-action-goto candidate))))))
154
155 (defun swiper-recenter-top-bottom (&optional arg)
156 "Call (`recenter-top-bottom' ARG)."
157 (interactive "P")
158 (with-ivy-window
159 (recenter-top-bottom arg)))
160
161 (defun swiper-font-lock-ensure ()
162 "Ensure the entired buffer is highlighted."
163 (unless (or (derived-mode-p 'magit-mode)
164 (bound-and-true-p magit-blame-mode)
165 (memq major-mode '(package-menu-mode
166 gnus-summary-mode
167 gnus-article-mode
168 gnus-group-mode
169 emms-playlist-mode erc-mode
170 org-agenda-mode
171 dired-mode
172 jabber-chat-mode
173 elfeed-search-mode
174 fundamental-mode
175 Man-mode
176 woman-mode)))
177 (unless (> (buffer-size) 100000)
178 (if (fboundp 'font-lock-ensure)
179 (font-lock-ensure)
180 (with-no-warnings (font-lock-fontify-buffer))))))
181
182 (defvar swiper--format-spec ""
183 "Store the current candidates format spec.")
184
185 (defvar swiper--width nil
186 "Store the amount of digits needed for the longest line nubmer.")
187
188 (defun swiper--candidates ()
189 "Return a list of this buffer lines."
190 (let ((n-lines (count-lines (point-min) (point-max))))
191 (unless (zerop n-lines)
192 (setq swiper--width (1+ (floor (log n-lines 10))))
193 (setq swiper--format-spec
194 (format "%%-%dd " swiper--width))
195 (let ((line-number 0)
196 candidates)
197 (save-excursion
198 (goto-char (point-min))
199 (swiper-font-lock-ensure)
200 (while (< (point) (point-max))
201 (let ((str (concat " " (buffer-substring
202 (line-beginning-position)
203 (line-end-position)))))
204 (put-text-property 0 1 'display
205 (format swiper--format-spec
206 (cl-incf line-number))
207 str)
208 (push str candidates))
209 (forward-line 1))
210 (nreverse candidates))))))
211
212 (defvar swiper--opoint 1
213 "The point when `swiper' starts.")
214
215 ;;;###autoload
216 (defun swiper (&optional initial-input)
217 "`isearch' with an overview.
218 When non-nil, INITIAL-INPUT is the initial search pattern."
219 (interactive)
220 (swiper--ivy initial-input))
221
222 (defvar swiper--anchor nil
223 "A line number to which the search should be anchored.")
224
225 (defvar swiper--len 0
226 "The last length of input for which an anchoring was made.")
227
228 (defun swiper--init ()
229 "Perform initialization common to both completion methods."
230 (setq swiper--opoint (point))
231 (setq swiper--len 0)
232 (setq swiper--anchor (line-number-at-pos)))
233
234 (defun swiper--re-builder (str)
235 "Transform STR into a swiper regex.
236 This is the regex used in the minibuffer, since the candidates
237 there have line numbers. In the buffer, `ivy--regex' should be used."
238 (cond
239 ((equal str "")
240 "")
241 ((equal str "^")
242 ".")
243 ((string-match "^\\^" str)
244 (setq ivy--old-re "")
245 (let ((re (ivy--regex-plus (substring str 1))))
246 (format "^[0-9][0-9 ]\\{%d\\}%s"
247 swiper--width
248 (if (zerop ivy--subexps)
249 (prog1 (format "\\(%s\\)" re)
250 (setq ivy--subexps 1))
251 re))))
252 (t
253 (ivy--regex-plus str))))
254
255 (defvar swiper-history nil
256 "History for `swiper'.")
257
258 (defun swiper--ivy (&optional initial-input)
259 "`isearch' with an overview using `ivy'.
260 When non-nil, INITIAL-INPUT is the initial search pattern."
261 (interactive)
262 (unless (eq (length (help-function-arglist 'ivy-read)) 4)
263 (warn "You seem to be using the outdated stand-alone \"ivy\" package.
264 Please remove it and update the \"swiper\" package."))
265 (swiper--init)
266 (let ((candidates (swiper--candidates))
267 (preselect (buffer-substring-no-properties
268 (line-beginning-position)
269 (line-end-position)))
270 (minibuffer-allow-text-properties t)
271 res)
272 (unwind-protect
273 (setq res (ivy-read
274 "Swiper: "
275 candidates
276 :initial-input initial-input
277 :keymap swiper-map
278 :preselect preselect
279 :require-match t
280 :update-fn #'swiper--update-input-ivy
281 :unwind #'swiper--cleanup
282 :re-builder #'swiper--re-builder
283 :history 'swiper-history))
284 (if (null ivy-exit)
285 (goto-char swiper--opoint)
286 (swiper--action res ivy-text)))))
287
288 (defun swiper--ensure-visible ()
289 "Remove overlays hiding point."
290 (let ((overlays (overlays-at (point)))
291 ov expose)
292 (while (setq ov (pop overlays))
293 (if (and (invisible-p (overlay-get ov 'invisible))
294 (setq expose (overlay-get ov 'isearch-open-invisible)))
295 (funcall expose ov)))))
296
297 (defvar swiper--overlays nil
298 "Store overlays.")
299
300 (defun swiper--cleanup ()
301 "Clean up the overlays."
302 (while swiper--overlays
303 (delete-overlay (pop swiper--overlays)))
304 (save-excursion
305 (goto-char (point-min))
306 (isearch-clean-overlays)))
307
308 (defun swiper--update-input-ivy ()
309 "Called when `ivy' input is updated."
310 (with-ivy-window
311 (swiper--cleanup)
312 (when (> (length ivy--current) 0)
313 (let* ((re (funcall ivy--regex-function ivy-text))
314 (re (if (stringp re) re (caar re)))
315 (str (get-text-property 0 'display ivy--current))
316 (num (if (string-match "^[0-9]+" str)
317 (string-to-number (match-string 0 str))
318 0)))
319 (goto-char (point-min))
320 (when (cl-plusp num)
321 (goto-char (point-min))
322 (forward-line (1- num))
323 (if (and (equal ivy-text "")
324 (>= swiper--opoint (line-beginning-position))
325 (<= swiper--opoint (line-end-position)))
326 (goto-char swiper--opoint)
327 (re-search-forward re (line-end-position) t))
328 (isearch-range-invisible (line-beginning-position)
329 (line-end-position))
330 (unless (and (>= (point) (window-start))
331 (<= (point) (window-end (ivy-state-window ivy-last) t)))
332 (recenter)))
333 (swiper--add-overlays re)))))
334
335 (defun swiper--add-overlays (re &optional beg end)
336 "Add overlays for RE regexp in visible part of the current buffer.
337 BEG and END, when specified, are the point bounds."
338 (let ((ov (make-overlay
339 (line-beginning-position)
340 (1+ (line-end-position)))))
341 (overlay-put ov 'face 'swiper-line-face)
342 (overlay-put ov 'window (ivy-state-window ivy-last))
343 (push ov swiper--overlays)
344 (let* ((wh (window-height))
345 (beg (or beg (save-excursion
346 (forward-line (- wh))
347 (point))))
348 (end (or end (save-excursion
349 (forward-line wh)
350 (point)))))
351 (when (>= (length re) swiper-min-highlight)
352 (save-excursion
353 (goto-char beg)
354 ;; RE can become an invalid regexp
355 (while (and (ignore-errors (re-search-forward re end t))
356 (> (- (match-end 0) (match-beginning 0)) 0))
357 (let ((i 0))
358 (while (<= i ivy--subexps)
359 (when (match-beginning i)
360 (let ((overlay (make-overlay (match-beginning i)
361 (match-end i)))
362 (face
363 (cond ((zerop ivy--subexps)
364 (cadr swiper-faces))
365 ((zerop i)
366 (car swiper-faces))
367 (t
368 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
369 swiper-faces)))))
370 (push overlay swiper--overlays)
371 (overlay-put overlay 'face face)
372 (overlay-put overlay 'window (ivy-state-window ivy-last))
373 (overlay-put overlay 'priority i)))
374 (cl-incf i)))))))))
375
376 (defun swiper--action (x input)
377 "Goto line X and search for INPUT."
378 (if (null x)
379 (user-error "No candidates")
380 (goto-char (point-min))
381 (forward-line (1- (read (get-text-property 0 'display x))))
382 (re-search-forward
383 (ivy--regex input) (line-end-position) t)
384 (swiper--ensure-visible)
385 (when (/= (point) swiper--opoint)
386 (unless (and transient-mark-mode mark-active)
387 (push-mark swiper--opoint t)
388 (message "Mark saved where search started")))))
389
390 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
391 (defun swiper-from-isearch ()
392 "Invoke `swiper' from isearch."
393 (interactive)
394 (let ((query (if isearch-regexp
395 isearch-string
396 (regexp-quote isearch-string))))
397 (isearch-exit)
398 (swiper query)))
399
400 (defvar swiper-multi-buffers nil
401 "Store the current list of buffers.")
402
403 (defvar swiper-multi-candidates nil
404 "Store the list of candidates for `swiper-multi'.")
405
406 (defun swiper-multi-prompt ()
407 (format "Buffers (%s): "
408 (mapconcat #'identity swiper-multi-buffers ", ")))
409
410 (defun swiper-multi ()
411 "Select one or more buffers.
412 Run `swiper' for those buffers."
413 (interactive)
414 (setq swiper-multi-buffers nil)
415 (setq swiper-multi-candidates nil)
416 (ivy-read (swiper-multi-prompt)
417 'internal-complete-buffer
418 :action 'swiper-multi-action-1)
419 (ivy-read "Swiper: " swiper-multi-candidates
420 :action 'swiper-multi-action-2
421 :unwind #'swiper--cleanup))
422
423 (defun swiper-multi-action-1 (x)
424 (if (member x swiper-multi-buffers)
425 (progn
426 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
427 (unless (equal x "")
428 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
429 (let ((prompt (swiper-multi-prompt)))
430 (setf (ivy-state-prompt ivy-last) prompt)
431 (setq ivy--prompt (concat "%-4d " prompt)))
432 (cond ((memq this-command '(ivy-done
433 ivy-alt-done
434 ivy-immediate-done))
435 (let ((ww (window-width)))
436 (dolist (buf swiper-multi-buffers)
437 (with-current-buffer buf
438 (setq swiper-multi-candidates
439 (append
440 (mapcar
441 (lambda (s)
442 (setq s (concat s " "))
443 (let ((len (length s)))
444 (put-text-property
445 (1- len) len 'display
446 (concat
447 (make-string
448 (max
449 (- ww
450 (string-width s)
451 (length (buffer-name))
452 1)
453 0)
454 ?\ )
455 (buffer-name))
456 s)
457 s))
458 (swiper--candidates))
459 swiper-multi-candidates))))))
460 ((eq this-command 'ivy-call)
461 (delete-minibuffer-contents))))
462
463 (defun swiper-multi-action-2 (x)
464 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
465 (with-ivy-window
466 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
467 (switch-to-buffer (match-string 1 buf-space))
468 (goto-char (point-min))
469 (forward-line (1- (read x)))
470 (re-search-forward
471 (ivy--regex ivy-text)
472 (line-end-position) t)
473 (unless (eq ivy-exit 'done)
474 (swiper--cleanup)
475 (swiper--add-overlays (ivy--regex ivy-text)))))))
476
477 (provide 'swiper)
478
479 ;;; swiper.el ends here