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