]> code.delx.au - gnu-emacs-elpa/blob - swiper.el
Fix up visual-line-mode limitation logic
[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 (let* ((avy-all-windows nil)
145 (candidates (append
146 (with-ivy-window
147 (avy--regex-candidates
148 (ivy--regex ivy-text)))
149 (save-excursion
150 (save-restriction
151 (narrow-to-region (window-start) (window-end))
152 (goto-char (point-min))
153 (forward-line)
154 (let ((cands))
155 (while (< (point) (point-max))
156 (push (cons (1+ (point))
157 (selected-window))
158 cands)
159 (forward-line))
160 cands)))))
161 (candidate (unwind-protect
162 (prog2
163 (avy--make-backgrounds
164 (append (avy-window-list)
165 (list (ivy-state-window ivy-last))))
166 (if (eq avy-style 'de-bruijn)
167 (avy-read-de-bruijn
168 candidates avy-keys)
169 (avy-read (avy-tree candidates avy-keys)
170 #'avy--overlay-post
171 #'avy--remove-leading-chars))
172 (avy-push-mark))
173 (avy--done))))
174 (if (window-minibuffer-p (cdr candidate))
175 (progn
176 (ivy-set-index (- (line-number-at-pos (car candidate)) 2))
177 (ivy--exhibit)
178 (ivy-done)
179 (ivy-call))
180 (ivy-quit-and-run
181 (avy-action-goto (caar candidate)))))))
182
183 (defun swiper-recenter-top-bottom (&optional arg)
184 "Call (`recenter-top-bottom' ARG)."
185 (interactive "P")
186 (with-ivy-window
187 (recenter-top-bottom arg)))
188
189 (defun swiper-font-lock-ensure ()
190 "Ensure the entired buffer is highlighted."
191 (unless (or (derived-mode-p 'magit-mode)
192 (bound-and-true-p magit-blame-mode)
193 (memq major-mode '(package-menu-mode
194 gnus-summary-mode
195 gnus-article-mode
196 gnus-group-mode
197 emms-playlist-mode erc-mode
198 org-agenda-mode
199 dired-mode
200 jabber-chat-mode
201 elfeed-search-mode
202 fundamental-mode
203 Man-mode
204 woman-mode
205 mu4e-view-mode
206 mu4e-headers-mode)))
207 (unless (> (buffer-size) 100000)
208 (if (fboundp 'font-lock-ensure)
209 (font-lock-ensure)
210 (with-no-warnings (font-lock-fontify-buffer))))))
211
212 (defvar swiper--format-spec ""
213 "Store the current candidates format spec.")
214
215 (defvar swiper--width nil
216 "Store the amount of digits needed for the longest line nubmer.")
217
218 (defvar swiper-use-visual-line nil
219 "When non-nil, use `line-move' instead of `forward-line'.")
220
221 (defun swiper--candidates ()
222 "Return a list of this buffer lines."
223 (setq swiper-use-visual-line
224 (and (not (eq major-mode 'org-mode))
225 visual-line-mode
226 (< (buffer-size) 20000)))
227 (let ((n-lines (count-lines (point-min) (point-max))))
228 (unless (zerop n-lines)
229 (setq swiper--width (1+ (floor (log n-lines 10))))
230 (setq swiper--format-spec
231 (format "%%-%dd " swiper--width))
232 (let ((line-number 0)
233 (advancer (if swiper-use-visual-line
234 (lambda (arg) (line-move arg t))
235 #'forward-line))
236 candidates)
237 (save-excursion
238 (goto-char (point-min))
239 (swiper-font-lock-ensure)
240 (while (< (point) (point-max))
241 (let ((str (concat " " (buffer-substring
242 (point)
243 (if swiper-use-visual-line
244 (save-excursion
245 (end-of-visual-line)
246 (point))
247 (line-end-position))))))
248 (put-text-property 0 1 'display
249 (format swiper--format-spec
250 (cl-incf line-number))
251 str)
252 (push str candidates))
253 (funcall advancer 1))
254 (nreverse candidates))))))
255
256 (defvar swiper--opoint 1
257 "The point when `swiper' starts.")
258
259 ;;;###autoload
260 (defun swiper (&optional initial-input)
261 "`isearch' with an overview.
262 When non-nil, INITIAL-INPUT is the initial search pattern."
263 (interactive)
264 (swiper--ivy initial-input))
265
266 (defvar swiper--anchor nil
267 "A line number to which the search should be anchored.")
268
269 (defvar swiper--len 0
270 "The last length of input for which an anchoring was made.")
271
272 (defun swiper--init ()
273 "Perform initialization common to both completion methods."
274 (setq swiper--opoint (point))
275 (setq swiper--len 0)
276 (setq swiper--anchor (line-number-at-pos)))
277
278 (defun swiper--re-builder (str)
279 "Transform STR into a swiper regex.
280 This is the regex used in the minibuffer, since the candidates
281 there have line numbers. In the buffer, `ivy--regex' should be used."
282 (cond
283 ((equal str "")
284 "")
285 ((equal str "^")
286 ".")
287 ((string-match "^\\^" str)
288 (setq ivy--old-re "")
289 (let ((re (ivy--regex-plus (substring str 1))))
290 (format "^[0-9][0-9 ]\\{%d\\}%s"
291 swiper--width
292 (if (zerop ivy--subexps)
293 (prog1 (format "\\(%s\\)" re)
294 (setq ivy--subexps 1))
295 re))))
296 (t
297 (ivy--regex-plus str))))
298
299 (defvar swiper-history nil
300 "History for `swiper'.")
301
302 (defun swiper--ivy (&optional initial-input)
303 "`isearch' with an overview using `ivy'.
304 When non-nil, INITIAL-INPUT is the initial search pattern."
305 (interactive)
306 (swiper--init)
307 (let ((candidates (swiper--candidates))
308 (preselect (buffer-substring-no-properties
309 (line-beginning-position)
310 (line-end-position)))
311 (minibuffer-allow-text-properties t)
312 res)
313 (unwind-protect
314 (setq res (ivy-read
315 "Swiper: "
316 candidates
317 :initial-input initial-input
318 :keymap swiper-map
319 :preselect preselect
320 :require-match t
321 :update-fn #'swiper--update-input-ivy
322 :unwind #'swiper--cleanup
323 :re-builder #'swiper--re-builder
324 :history 'swiper-history))
325 (if (null ivy-exit)
326 (goto-char swiper--opoint)
327 (swiper--action res ivy-text)))))
328
329 (defun swiper--ensure-visible ()
330 "Remove overlays hiding point."
331 (let ((overlays (overlays-at (point)))
332 ov expose)
333 (while (setq ov (pop overlays))
334 (if (and (invisible-p (overlay-get ov 'invisible))
335 (setq expose (overlay-get ov 'isearch-open-invisible)))
336 (funcall expose ov)))))
337
338 (defvar swiper--overlays nil
339 "Store overlays.")
340
341 (defun swiper--cleanup ()
342 "Clean up the overlays."
343 (while swiper--overlays
344 (delete-overlay (pop swiper--overlays)))
345 (save-excursion
346 (goto-char (point-min))
347 (isearch-clean-overlays)))
348
349 (defun swiper--update-input-ivy ()
350 "Called when `ivy' input is updated."
351 (with-ivy-window
352 (swiper--cleanup)
353 (when (> (length ivy--current) 0)
354 (let* ((re (funcall ivy--regex-function ivy-text))
355 (re (if (stringp re) re (caar re)))
356 (str (get-text-property 0 'display ivy--current))
357 (num (if (string-match "^[0-9]+" str)
358 (string-to-number (match-string 0 str))
359 0)))
360 (goto-char (point-min))
361 (when (cl-plusp num)
362 (goto-char (point-min))
363 (if swiper-use-visual-line
364 (line-move (1- num))
365 (forward-line (1- num)))
366 (if (and (equal ivy-text "")
367 (>= swiper--opoint (line-beginning-position))
368 (<= swiper--opoint (line-end-position)))
369 (goto-char swiper--opoint)
370 (re-search-forward re (line-end-position) t))
371 (isearch-range-invisible (line-beginning-position)
372 (line-end-position))
373 (unless (and (>= (point) (window-start))
374 (<= (point) (window-end (ivy-state-window ivy-last) t)))
375 (recenter)))
376 (swiper--add-overlays re)))))
377
378 (defun swiper--add-overlays (re &optional beg end)
379 "Add overlays for RE regexp in visible part of the current buffer.
380 BEG and END, when specified, are the point bounds."
381 (let ((ov (if visual-line-mode
382 (make-overlay
383 (save-excursion
384 (beginning-of-visual-line)
385 (point))
386 (save-excursion
387 (end-of-visual-line)
388 (point)))
389 (make-overlay
390 (line-beginning-position)
391 (1+ (line-end-position))))))
392 (overlay-put ov 'face 'swiper-line-face)
393 (overlay-put ov 'window (ivy-state-window ivy-last))
394 (push ov swiper--overlays)
395 (let* ((wh (window-height))
396 (beg (or beg (save-excursion
397 (forward-line (- wh))
398 (point))))
399 (end (or end (save-excursion
400 (forward-line wh)
401 (point)))))
402 (when (>= (length re) swiper-min-highlight)
403 (save-excursion
404 (goto-char beg)
405 ;; RE can become an invalid regexp
406 (while (and (ignore-errors (re-search-forward re end t))
407 (> (- (match-end 0) (match-beginning 0)) 0))
408 (let ((i 0))
409 (while (<= i ivy--subexps)
410 (when (match-beginning i)
411 (let ((overlay (make-overlay (match-beginning i)
412 (match-end i)))
413 (face
414 (cond ((zerop ivy--subexps)
415 (cadr swiper-faces))
416 ((zerop i)
417 (car swiper-faces))
418 (t
419 (nth (1+ (mod (+ i 2) (1- (length swiper-faces))))
420 swiper-faces)))))
421 (push overlay swiper--overlays)
422 (overlay-put overlay 'face face)
423 (overlay-put overlay 'window (ivy-state-window ivy-last))
424 (overlay-put overlay 'priority i)))
425 (cl-incf i)))))))))
426
427 (defun swiper--action (x input)
428 "Goto line X and search for INPUT."
429 (if (null x)
430 (user-error "No candidates")
431 (goto-char (point-min))
432 (funcall (if swiper-use-visual-line
433 #'line-move
434 #'forward-line)
435 (1- (read (get-text-property 0 'display x))))
436 (re-search-forward
437 (ivy--regex input) (line-end-position) t)
438 (swiper--ensure-visible)
439 (when (/= (point) swiper--opoint)
440 (unless (and transient-mark-mode mark-active)
441 (push-mark swiper--opoint t)
442 (message "Mark saved where search started")))))
443
444 ;; (define-key isearch-mode-map (kbd "C-o") 'swiper-from-isearch)
445 (defun swiper-from-isearch ()
446 "Invoke `swiper' from isearch."
447 (interactive)
448 (let ((query (if isearch-regexp
449 isearch-string
450 (regexp-quote isearch-string))))
451 (isearch-exit)
452 (swiper query)))
453
454 (defvar swiper-multi-buffers nil
455 "Store the current list of buffers.")
456
457 (defvar swiper-multi-candidates nil
458 "Store the list of candidates for `swiper-multi'.")
459
460 (defun swiper-multi-prompt ()
461 (format "Buffers (%s): "
462 (mapconcat #'identity swiper-multi-buffers ", ")))
463
464 (defun swiper-multi ()
465 "Select one or more buffers.
466 Run `swiper' for those buffers."
467 (interactive)
468 (setq swiper-multi-buffers nil)
469 (setq swiper-multi-candidates nil)
470 (ivy-read (swiper-multi-prompt)
471 'internal-complete-buffer
472 :action 'swiper-multi-action-1)
473 (ivy-read "Swiper: " swiper-multi-candidates
474 :action 'swiper-multi-action-2
475 :unwind #'swiper--cleanup))
476
477 (defun swiper-multi-action-1 (x)
478 (if (member x swiper-multi-buffers)
479 (progn
480 (setq swiper-multi-buffers (delete x swiper-multi-buffers)))
481 (unless (equal x "")
482 (setq swiper-multi-buffers (append swiper-multi-buffers (list x)))))
483 (let ((prompt (swiper-multi-prompt)))
484 (setf (ivy-state-prompt ivy-last) prompt)
485 (setq ivy--prompt (concat "%-4d " prompt)))
486 (cond ((memq this-command '(ivy-done
487 ivy-alt-done
488 ivy-immediate-done))
489 (let ((ww (window-width)))
490 (dolist (buf swiper-multi-buffers)
491 (with-current-buffer buf
492 (setq swiper-multi-candidates
493 (append
494 (mapcar
495 (lambda (s)
496 (setq s (concat s " "))
497 (let ((len (length s)))
498 (put-text-property
499 (1- len) len 'display
500 (concat
501 (make-string
502 (max
503 (- ww
504 (string-width s)
505 (length (buffer-name))
506 1)
507 0)
508 ?\ )
509 (buffer-name))
510 s)
511 s))
512 (swiper--candidates))
513 swiper-multi-candidates))))))
514 ((eq this-command 'ivy-call)
515 (delete-minibuffer-contents))))
516
517 (defun swiper-multi-action-2 (x)
518 (let ((buf-space (get-text-property (1- (length x)) 'display x)))
519 (with-ivy-window
520 (when (string-match "\\` *\\([^ ]+\\)\\'" buf-space)
521 (switch-to-buffer (match-string 1 buf-space))
522 (goto-char (point-min))
523 (forward-line (1- (read x)))
524 (re-search-forward
525 (ivy--regex ivy-text)
526 (line-end-position) t)
527 (unless (eq ivy-exit 'done)
528 (swiper--cleanup)
529 (swiper--add-overlays (ivy--regex ivy-text)))))))
530
531 (provide 'swiper)
532
533 ;;; swiper.el ends here