]> code.delx.au - gnu-emacs-elpa/blob - packages/el-search/el-search.el
allow search wrapping
[gnu-emacs-elpa] / packages / el-search / el-search.el
1 ;;; el-search.el --- Expression based incremental search for emacs-lisp-mode -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc
4
5 ;; Author: Michael Heerdegen <michael_heerdegen@web.de>
6 ;; Maintainer: Michael Heerdegen <michael_heerdegen@web.de>
7 ;; Created: 29 Jul 2015
8 ;; Keywords: lisp
9 ;; Compatibility: GNU Emacs 25
10 ;; Version: 0.0.3
11 ;; Package-Requires: ((emacs "25"))
12
13
14 ;; This file is not part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29
30 ;;; Commentary:
31
32 ;; Introduction
33 ;; ============
34 ;;
35 ;;
36 ;; The main user entry point is the command `el-search-pattern'. It
37 ;; prompts for a `pcase' pattern and searches the current buffer for
38 ;; expressions that are matched by it when read. Point is put at the
39 ;; beginning of the expression found (unlike isearch).
40 ;;
41 ;; It doesn't matter how the code is actually formatted. Comments are
42 ;; ignored by the search, and strings are treated as objects, their
43 ;; contents are not being searched.
44 ;;
45 ;; Example 1: if you enter
46 ;;
47 ;; 97
48 ;;
49 ;; at the prompt, this will find any occurrence of the number 97 in
50 ;; the code, but not 977 or (+ 90 7) or "My string containing 97".
51 ;; But it will find anything `eq' to 97 after reading, e.g. #x61 or
52 ;; ?a.
53 ;;
54 ;;
55 ;; Example 2: If you enter the pattern
56 ;;
57 ;; `(defvar ,_)
58 ;;
59 ;; you search for all defvar forms that don't specify an init value.
60 ;;
61 ;; The following will search for defvar forms with a docstring whose
62 ;; first line is longer than 70 characters:
63 ;;
64 ;; `(defvar ,_ ,_
65 ;; ,(and s (guard (< 70 (length (car (split-string s "\n")))))))
66 ;;
67 ;;
68 ;; Convenience
69 ;; ===========
70 ;;
71 ;; For expression input, the minibuffer prompts here uses
72 ;; `emacs-lisp-mode'.
73 ;;
74 ;; When reading a search pattern in the minibuffer, the input is
75 ;; automatically wrapped into `(and expr ,(read input)). So, if you
76 ;; want to search a buffer for symbols that are defined in "cl-lib",
77 ;; you can use this pattern
78 ;;
79 ;; (guard (and (symbolp expr)
80 ;; (when-let ((file (symbol-file expr)))
81 ;; (string-match-p "cl-lib\\.elc?$" file))))
82 ;;
83 ;; without binding the variable `expr'.
84 ;;
85 ;;
86 ;; Replacing
87 ;; =========
88 ;;
89 ;; You can replace expressions with command `el-search-query-replace'.
90 ;; You are queried for a (pcase) pattern and a replacement expression.
91 ;; For each match of the pattern, the replacement expression is
92 ;; evaluated with the bindings created by the pcase matching in
93 ;; effect, and printed to produce the replacement string.
94 ;;
95 ;; Example: In some buffer you want to swap the two expressions at the
96 ;; places of the first two arguments in all calls of function `foo',
97 ;; so that e.g.
98 ;;
99 ;; (foo 'a (* 2 (+ 3 4)) t)
100 ;;
101 ;; becomes
102 ;;
103 ;; (foo (* 2 (+ 3 4)) 'a t).
104 ;;
105 ;; This will do it:
106 ;;
107 ;; M-x el-search-query-replace RET
108 ;; `(foo ,a ,b . ,rest) RET
109 ;; `(foo ,b ,a . ,rest) RET
110 ;;
111 ;; Type y to replace a match and go to the next one, r to replace
112 ;; without moving, SPC to go to the next match and ! to replace all
113 ;; remaining matches automatically. q quits. n is like SPC, so that
114 ;; y and n work like in isearch (meaning "yes" and "no") if you are
115 ;; used to that.
116 ;;
117 ;;
118 ;; Suggested key bindings
119 ;; ======================
120 ;;
121 ;; (define-key emacs-lisp-mode-map [(control ?S)] #'el-search-pattern)
122 ;; (define-key emacs-lisp-mode-map [(control ?%)] #'el-search-query-replace)
123 ;;
124 ;; (define-key isearch-mode-map [(control ?S)] #'el-search-search-from-isearch)
125 ;; (define-key isearch-mode-map [(control ?%)] #'el-search-replace-from-isearch)
126 ;;
127 ;; The bindings in `isearch-mode-map' let you conveniently switch to
128 ;; elisp searching from isearch.
129 ;;
130 ;;
131 ;; Bugs, Known Limitations
132 ;; =======================
133 ;;
134 ;; - Replacing: in some cases the reader syntax of forms
135 ;; is changing due to reading+printing. "Some" because we can treat
136 ;; that problem in most cases.
137 ;;
138 ;; - Similarly: Comments are normally preserved (where it makes
139 ;; sense). But when replacing like `(foo ,a ,b) -> `(foo ,b ,a)
140 ;;
141 ;; in a content like
142 ;;
143 ;; (foo
144 ;; a
145 ;; ;;a comment
146 ;; b)
147 ;;
148 ;; the comment will be lost.
149 ;;
150 ;;
151 ;; Acknowledgments
152 ;; ===============
153 ;;
154 ;; Thanks to Stefan Monnier for corrections and advice.
155 ;;
156 ;;
157 ;; TODO:
158 ;;
159 ;; - implement backward searching and wrapped searching
160 ;;
161 ;; - improve docstrings
162 ;;
163 ;; - add more examples
164 ;;
165 ;; - handle more reader syntaxes, e.g. #n, #n#
166 ;;
167 ;; - Implement sessions; add multi-file support based on iterators. A
168 ;; file list is read in (or the user can specify an iterator as a
169 ;; variable). The state in the current buffer is just (buffer
170 ;; . marker). Or should this be abstracted into an own lib? Could be
171 ;; named "files-session" or so.
172
173
174
175 ;;; Code:
176
177 ;;;; Requirements
178
179 (eval-when-compile
180 (require 'subr-x))
181
182 (require 'cl-lib)
183 (require 'elisp-mode)
184 (require 'thingatpt)
185
186
187 ;;;; Configuration stuff
188
189 (defgroup el-search nil
190 "Expression based search and replace for `emacs-lisp-mode'."
191 :group 'lisp)
192
193 (defcustom el-search-this-expression-identifier 'exp
194 "Name of the identifier referring to the whole expression.
195 The default value is `expr'. You can use this variable in the
196 search prompt to refer to value of the currently searched
197 expression."
198 :type 'symbol)
199
200 (defface el-search-match '((((background dark)) (:background "#0000A0"))
201 (t (:background "DarkSlateGray1")))
202 "Face for highlighting the current match.")
203
204
205 ;;;; Helpers
206
207 (defun el-search--print (expr)
208 (let ((print-quoted t)
209 (print-length nil)
210 (print-level nil))
211 (prin1-to-string expr)))
212
213 (defvar el-search-read-expression-map
214 (let ((map (make-sparse-keymap)))
215 (set-keymap-parent map read-expression-map)
216 (define-key map [(control ?g)] #'abort-recursive-edit)
217 (define-key map [up] nil)
218 (define-key map [down] nil)
219 (define-key map [(control meta backspace)] #'backward-kill-sexp)
220 (define-key map [(control ?S)] #'exit-minibuffer)
221 map)
222 "Map for reading input with `el-search-read-expression'.")
223
224 ;; $$$$$FIXME: this should be in Emacs! There is only a helper `read--expression'.
225 (defun el-search-read-expression (prompt &optional initial-contents hist default read)
226 "Read expression for `my-eval-expression'."
227 (minibuffer-with-setup-hook
228 (lambda ()
229 (emacs-lisp-mode)
230 (use-local-map el-search-read-expression-map)
231 (setq font-lock-mode t)
232 (funcall font-lock-function 1)
233 (backward-sexp)
234 (indent-sexp)
235 (goto-char (point-max)))
236 (read-from-minibuffer prompt initial-contents el-search-read-expression-map read
237 (or hist 'read-expression-history) default)))
238
239 (defun el-search--read-pattern (prompt &optional default read)
240 (el-search-read-expression
241 prompt el-search--initial-mb-contents 'el-search-history
242 (or default (when-let ((this-sexp (sexp-at-point)))
243 (concat "'" (el-search--print this-sexp))))
244 read))
245
246 (defun el-search--end-of-sexp ()
247 ;;Point must be at sexp beginning
248 (or (scan-sexps (point) 1) (point-max)))
249
250 (defun el-search--ensure-sexp-start ()
251 "Move point to the beginning of the next sexp if necessary.
252 Don't move if already at beginning of a sexp.
253 Point must not be inside a string or comment."
254 (let ((not-done t) res)
255 (while not-done
256 (let ((stop-here nil)
257 (looking-at-from-back (lambda (regexp n)
258 (save-excursion
259 (backward-char n)
260 (looking-at regexp)))))
261 (while (not stop-here)
262 (cond
263 ((eobp) (signal 'end-of-buffer nil))
264 ((looking-at (rx (and (* space) ";"))) (forward-line))
265 ((looking-at (rx (+ (or space "\n")))) (goto-char (match-end 0)))
266
267 ;; FIXME: can the rest be done more generically?
268 ((and (looking-at (rx (or (syntax symbol) (syntax word))))
269 (not (looking-at "\\_<"))
270 (not (funcall looking-at-from-back ",@" 2)))
271 (forward-symbol 1))
272 ((or (and (looking-at "'") (funcall looking-at-from-back "#" 1))
273 (and (looking-at "@") (funcall looking-at-from-back "," 1)))
274 (forward-char))
275 (t (setq stop-here t)))))
276 (condition-case nil
277 (progn
278 (setq res (save-excursion (read (current-buffer))))
279 (setq not-done nil))
280 (error (forward-char))))
281 res))
282
283 (defun el-search--matcher (pattern &rest body)
284 (let ((warning-suppress-log-types '((bytecomp))))
285 (byte-compile
286 `(lambda (expression)
287 (pcase expression
288 (,pattern ,@(or body (list t)))
289 (_ nil))))))
290
291 (defun el-search--match-p (matcher expression)
292 (funcall matcher expression))
293
294 (defun el-search--wrap-pattern (pattern)
295 `(and ,el-search-this-expression-identifier ,pattern))
296
297 (defun el-search--skip-expression (expression &optional read)
298 ;; Move forward at least one character. Don't move into a string or
299 ;; comment. Don't move further than the beginning of the next sexp.
300 ;; Try to move as far as possible. Point must be at the beginning
301 ;; of an expression.
302 ;; If there are positions where `read' would succeed, but that do
303 ;; not represent a valid sexp start, move past them (e.g. when
304 ;; before "#'" move past both characters).
305 ;;
306 ;; EXPRESSION must be the (read) expression at point, but when READ
307 ;; is non-nil, ignore the first argument and read the expression at
308 ;; point instead.
309 (when read (setq expression (save-excursion (read (current-buffer)))))
310 (cond
311 ((or (null expression)
312 (equal [] expression)
313 (not (or (listp expression) (vectorp expression))))
314 (goto-char (el-search--end-of-sexp)))
315 ((looking-at (rx (or ",@" "," "#'" "'")))
316 (goto-char (match-end 0)))
317 (t (forward-char))))
318
319 (defun el-search--search-pattern (pattern &optional noerror)
320 "Search elisp buffer with `pcase' PATTERN.
321 Set point to the beginning of the occurrence found and return
322 point. Optional second argument, if non-nil, means if fail just
323 return nil (no error)."
324 ;; For better performance we read complete top-level sexps and test
325 ;; for matches. We enter top-level expressions in the buffer text
326 ;; only when the test was successful.
327 (let ((matcher (el-search--matcher pattern)) (match-beg nil) (opoint (point)) current-expr)
328
329 ;; when inside a string or comment, move past it
330 (let ((syntax-here (syntax-ppss)))
331 (when (nth 3 syntax-here) ;inside a string
332 (goto-char (nth 8 syntax-here))
333 (forward-sexp))
334 (when (nth 4 syntax-here) ;inside a comment
335 (forward-line 1)
336 (while (and (not (eobp)) (looking-at (rx (and (* space) ";"))))
337 (forward-line 1))))
338
339 (if (catch 'no-match
340 (while (not match-beg)
341 (condition-case nil
342 (setq current-expr (el-search--ensure-sexp-start))
343 (end-of-buffer
344 (goto-char opoint)
345 (throw 'no-match t)))
346 (if (el-search--match-p matcher current-expr)
347 (setq match-beg (point)
348 opoint (point))
349 (el-search--skip-expression current-expr))))
350 (if noerror nil (signal 'end-of-buffer nil)))
351 match-beg))
352
353 (defun el-search--do-subsexps (pos do-fun &optional ret-fun bound)
354 ;; bound -> nil means till end of buffer
355 (save-excursion
356 (goto-char pos)
357 (condition-case nil
358 (while (< (point) (or bound (point-max)))
359 (let* ((this-sexp-end (save-excursion (thing-at-point--end-of-sexp) (point)))
360 (this-sexp-bounds (buffer-substring-no-properties (point) this-sexp-end)))
361 (funcall do-fun this-sexp-bounds this-sexp-end)
362 (el-search--skip-expression (read this-sexp-bounds))
363 (el-search--ensure-sexp-start)))
364 (end-of-buffer))
365 (when ret-fun (funcall ret-fun))))
366
367 (defun el-search--create-read-map (&optional pos)
368 (let ((mapping '()))
369 (el-search--do-subsexps
370 (or pos (point))
371 (lambda (sexp _) (push (cons (read sexp) sexp) mapping))
372 (lambda () (nreverse mapping))
373 (save-excursion (thing-at-point--end-of-sexp) (point)))))
374
375 (defun el-search--repair-replacement-layout (printed mapping)
376 (with-temp-buffer
377 (insert printed)
378 (el-search--do-subsexps
379 (point-min)
380 (lambda (sexp sexp-end)
381 (when-let ((old (cdr (assoc (read sexp) mapping))))
382 (delete-region (point) sexp-end)
383 (when (string-match-p "\n" old)
384 (unless (looking-back "^[[:space:]]*" (line-beginning-position))
385 (insert "\n"))
386 (unless (looking-at "[[:space:]\)]*$")
387 (insert "\n")
388 (backward-char)))
389 (insert old)))
390 (lambda () (buffer-substring (point-min) (point-max))))))
391
392
393 ;;;; Highlighting
394
395 (defvar-local el-search-hl-overlay nil)
396
397 (defvar el-search-keep-hl nil)
398
399 (defun el-search-hl-sexp-at-point ()
400 (let ((bounds (list (point) (el-search--end-of-sexp))))
401 (if (overlayp el-search-hl-overlay)
402 (apply #'move-overlay el-search-hl-overlay bounds)
403 (overlay-put (setq el-search-hl-overlay (apply #'make-overlay bounds))
404 'face 'el-search-match)))
405 (add-hook 'post-command-hook (el-search-hl-post-command-fun (current-buffer)) t))
406
407 (defun el-search-hl-remove ()
408 (when (overlayp el-search-hl-overlay)
409 (delete-overlay el-search-hl-overlay)))
410
411 (defun el-search-hl-post-command-fun (buf)
412 (lambda ()
413 (when (buffer-live-p buf)
414 (unless (or el-search-keep-hl
415 (eq this-command 'el-search-query-replace)
416 (eq this-command 'el-search-pattern))
417 (with-current-buffer buf
418 (el-search-hl-remove)
419 (remove-hook 'post-command-hook #'el-search-hl-post-command-fun t))))))
420
421
422 ;;;; Core functions
423
424 (defvar el-search-history '()
425 "List of input strings.")
426
427 (defvar el-search-success nil)
428 (defvar el-search-current-pattern nil)
429
430 ;;;###autoload
431 (defun el-search-pattern (pattern)
432 "Do incremental elisp search forward."
433 (interactive (list (if (eq this-command last-command)
434 el-search-current-pattern
435 (let ((pattern
436 (el-search--read-pattern "Find pcase pattern: "
437 (car el-search-history)
438 t)))
439 ;; A very common mistake: input "foo" instead of "'foo"
440 (when (and (symbolp pattern)
441 (not (eq pattern '_))
442 (or (not (boundp pattern))
443 (not (eq (symbol-value pattern) pattern))))
444 (error "Please don't forget the quote when searching for a symbol"))
445 (el-search--wrap-pattern pattern)))))
446 (setq this-command 'el-search-pattern) ;in case we come from isearch
447 (setq el-search-current-pattern pattern)
448 (let ((opoint (point)))
449 (when (eq this-command last-command)
450 (if el-search-success
451 (el-search--skip-expression nil t)
452 ;; wrap search
453 (goto-char (point-min))))
454 (setq el-search-success nil)
455 (when (condition-case nil
456 (el-search--search-pattern pattern)
457 (end-of-buffer (message "No match")
458 (goto-char opoint)
459 (el-search-hl-remove)
460 (ding)
461 nil))
462 (setq el-search-success t)
463 (el-search-hl-sexp-at-point)
464 (message "%s" (substitute-command-keys "Type \\[el-search-pattern] to repeat")))))
465
466 (defun el-search-search-and-replace-pattern (pattern replacement &optional mapping)
467 (let ((replace-all nil) (nbr-replaced 0) (nbr-skipped 0) (done nil)
468 (el-search-keep-hl t) (opoint (point))
469 (get-replacement (el-search--matcher pattern replacement)))
470 (unwind-protect
471 (while (and (not done) (el-search--search-pattern pattern t))
472 (setq opoint (point))
473 (unless replace-all (el-search-hl-sexp-at-point))
474 (let* ((read-mapping (el-search--create-read-map))
475 (region (list (point) (el-search--end-of-sexp)))
476 (substring (apply #'buffer-substring-no-properties region))
477 (expr (read substring))
478 (replaced-this nil)
479 (new-expr (funcall get-replacement expr))
480 (to-insert (el-search--repair-replacement-layout
481 (el-search--print new-expr) (append mapping read-mapping)))
482 (do-replace (lambda ()
483 (atomic-change-group
484 (apply #'delete-region region)
485 (let ((inhibit-message t)
486 (opoint (point)))
487 (insert to-insert)
488 (indent-region opoint (point))
489 (goto-char opoint)
490 (el-search-hl-sexp-at-point)))
491 (cl-incf nbr-replaced)
492 (setq replaced-this t))))
493 (if replace-all
494 (funcall do-replace)
495 (while (not (pcase (if replaced-this
496 (read-char-choice "[SPC ! q]" '(?\ ?! ?q ?n))
497 (read-char-choice
498 (concat "Replace this occurence"
499 (if (or (string-match-p "\n" to-insert)
500 (< 40 (length to-insert)))
501 "" (format " with `%s'" to-insert))
502 "? [y SPC r ! q]" )
503 '(?y ?n ?r ?\ ?! ?q)))
504 (?r (funcall do-replace)
505 nil)
506 (?y (funcall do-replace)
507 t)
508 ((or ?\ ?n)
509 (unless replaced-this (cl-incf nbr-skipped))
510 t)
511 (?! (unless replaced-this
512 (funcall do-replace))
513 (setq replace-all t)
514 t)
515 (?q (setq done t)
516 t)))))
517 (unless (or done (eobp)) (el-search--skip-expression nil t)))))
518 (el-search-hl-remove)
519 (goto-char opoint)
520 (message "Replaced %d matches%s"
521 nbr-replaced
522 (if (zerop nbr-skipped) ""
523 (format " (%d skipped)" nbr-skipped)))))
524
525 ;; We need a variable for the initial contents because we want to `call-interactively '
526 ;; `el-search-query-replace-read-args'
527 (defvar el-search--initial-mb-contents nil)
528
529 (defun el-search-query-replace-read-args ()
530 (barf-if-buffer-read-only)
531 (let* ((from (el-search--read-pattern "Replace from: "))
532 (to (let ((el-search--initial-mb-contents nil))
533 (el-search--read-pattern "Replace with result of evaluation of: " from))))
534 (list (el-search--wrap-pattern (read from)) (read to)
535 (with-temp-buffer
536 (insert to)
537 (el-search--create-read-map 1)))))
538
539 ;;;###autoload
540 (defun el-search-query-replace (from to &optional mapping)
541 "Replace some occurrences of FROM pattern with evaluated TO."
542 (interactive (el-search-query-replace-read-args))
543 (setq this-command 'el-search-query-replace) ;in case we come from isearch
544 (setq el-search-current-pattern from)
545 (barf-if-buffer-read-only)
546 (el-search-search-and-replace-pattern from to mapping))
547
548 (defun el-search--take-over-from-isearch ()
549 (let ((other-end isearch-other-end)
550 (input isearch-string))
551 (isearch-exit)
552 (when (and other-end (< other-end (point)))
553 (goto-char other-end))
554 input))
555
556 ;;;###autoload
557 (defun el-search-search-from-isearch ()
558 ;; FIXME: an interesting alternative would be to really integrate it
559 ;; with Isearch, using `isearch-search-fun-function'.
560 ;; Alas, this is not trivial if we want to transfer our optimizations.
561 (interactive)
562 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch))))
563 ;; use `call-interactively' so we get recorded in `extended-command-history'
564 (call-interactively #'el-search-pattern)))
565
566 ;;;###autoload
567 (defun el-search-replace-from-isearch ()
568 (interactive)
569 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch))))
570 (call-interactively #'el-search-query-replace)))
571
572
573
574 (provide 'el-search)
575 ;;; el-search.el ends here