]> code.delx.au - gnu-emacs-elpa/blob - packages/el-search/el-search.el
Merge math-symbol-lists
[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.1.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 `el-search-pattern'. This command
37 ;; prompts for a `pcase' pattern and searches the current buffer for
38 ;; matching expressions by iteratively `read'ing buffer contents. For
39 ;; any match, point is put at the beginning of the expression found
40 ;; (unlike isearch which puts point at the end of matches).
41 ;;
42 ;; Why is it based on `pcase'? Because pattern matching (and the
43 ;; ability to combine destructuring and condition testing) is well
44 ;; suited for this task. In addition, pcase allows to add specialized
45 ;; pattern types and to combine them with other patterns in a natural
46 ;; and transparent way out of the box.
47 ;;
48 ;; It doesn't matter how the code is actually formatted. Comments are
49 ;; ignored, and strings are treated as atomic objects, their contents
50 ;; are not being searched.
51 ;;
52 ;;
53 ;; Example 1: if you enter
54 ;;
55 ;; 97
56 ;;
57 ;; at the prompt, this will find any occurrence of the number 97 in
58 ;; the code, but not 977 or (+ 90 7) or "My string containing 97".
59 ;; But it will find anything `eq' to 97 after reading, e.g. #x61 or
60 ;; ?a.
61 ;;
62 ;;
63 ;; Example 2: If you enter the pattern
64 ;;
65 ;; `(defvar ,_)
66 ;;
67 ;; you search for all defvar forms that don't specify an init value.
68 ;;
69 ;; The following will search for defvar forms with a docstring whose
70 ;; first line is longer than 70 characters:
71 ;;
72 ;; `(defvar ,_ ,_
73 ;; ,(and s (guard (< 70 (length (car (split-string s "\n")))))))
74 ;;
75 ;;
76 ;; When a search pattern is processed, the searched buffer is current
77 ;; with point at the beginning of the currently tested expression.
78 ;;
79 ;;
80 ;; Convenience
81 ;; ===========
82 ;;
83 ;; For pattern input, the minibuffer is put into `emacs-lisp-mode'.
84 ;;
85 ;; Any input PATTERN is silently transformed into (and exp PATTERN)
86 ;; so that you can always refer to the whole currently tested
87 ;; expression via the variable `exp'.
88 ;;
89 ;;
90 ;; Example 3:
91 ;;
92 ;; If you want to search a buffer for symbols that are defined in
93 ;; "cl-lib", you can use this pattern
94 ;;
95 ;; (guard (and (symbolp exp)
96 ;; (when-let ((file (symbol-file exp)))
97 ;; (string-match-p "cl-lib\\.elc?$" file))))
98 ;;
99 ;;
100 ;; ,----------------------------------------------------------------------
101 ;; | Q: "But I hate `pcase'! Can't we just do without?" |
102 ;; | |
103 ;; | A: Respect that you kept up until here! Just use (guard CODE), where|
104 ;; | CODE is any normal Elisp expression that returns non-nil when and |
105 ;; | only when you have a match. Use the variable `exp' to refer to |
106 ;; | the currently tested expression. Just like in the last example! |
107 ;; `----------------------------------------------------------------------
108 ;;
109 ;;
110 ;; It's cumbersome to write out the same complicated pattern
111 ;; constructs in the minibuffer again and again. You can define your
112 ;; own pcase pattern types for the purpose of el-search with
113 ;; `el-search-defpattern'. It is just like `pcase-defmacro', but the
114 ;; effect is limited to this package. See C-h f `el-search-pattern'
115 ;; for a list of predefined additional pattern forms.
116 ;;
117 ;;
118 ;; Replacing
119 ;; =========
120 ;;
121 ;; You can replace expressions with command `el-search-query-replace'.
122 ;; You are queried for a (pcase) pattern and a replacement expression.
123 ;; For each match of the pattern, the replacement expression is
124 ;; evaluated with the bindings created by the pcase matching in
125 ;; effect, and printed to produce the replacement string.
126 ;;
127 ;; Example: In some buffer you want to swap the two expressions at the
128 ;; places of the first two arguments in all calls of function `foo',
129 ;; so that e.g.
130 ;;
131 ;; (foo 'a (* 2 (+ 3 4)) t)
132 ;;
133 ;; becomes
134 ;;
135 ;; (foo (* 2 (+ 3 4)) 'a t).
136 ;;
137 ;; This will do it:
138 ;;
139 ;; M-x el-search-query-replace RET
140 ;; `(foo ,a ,b . ,rest) RET
141 ;; `(foo ,b ,a . ,rest) RET
142 ;;
143 ;; Type y to replace a match and go to the next one, r to replace
144 ;; without moving, SPC to go to the next match and ! to replace all
145 ;; remaining matches automatically. q quits. n is like SPC, so that
146 ;; y and n work like in isearch (meaning "yes" and "no") if you are
147 ;; used to that.
148 ;;
149 ;; It is possible to replace a match with multiple expressions using
150 ;; "splicing mode". When it is active, the replacement expression
151 ;; must evaluate to a list, and is spliced instead of inserted into
152 ;; the buffer for any replaced match. Use s to toggle splicing mode
153 ;; in a `el-search-query-replace' session.
154 ;;
155 ;;
156 ;; Suggested key bindings
157 ;; ======================
158 ;;
159 ;; (define-key emacs-lisp-mode-map [(control ?S)] #'el-search-pattern)
160 ;; (define-key emacs-lisp-mode-map [(control ?%)] #'el-search-query-replace)
161 ;;
162 ;; (define-key isearch-mode-map [(control ?S)] #'el-search-search-from-isearch)
163 ;; (define-key isearch-mode-map [(control ?%)] #'el-search-replace-from-isearch)
164 ;;
165 ;; The bindings in `isearch-mode-map' let you conveniently switch to
166 ;; elisp searching from isearch.
167 ;;
168 ;;
169 ;; Bugs, Known Limitations
170 ;; =======================
171 ;;
172 ;; - Replacing: in some cases the reader syntax of forms
173 ;; is changing due to reading+printing. "Some" because we can treat
174 ;; that problem in most cases.
175 ;;
176 ;; - Similarly: Comments are normally preserved (where it makes
177 ;; sense). But when replacing like `(foo ,a ,b) -> `(foo ,b ,a)
178 ;;
179 ;; in a content like
180 ;;
181 ;; (foo
182 ;; a
183 ;; ;;a comment
184 ;; b)
185 ;;
186 ;; the comment will be lost.
187 ;;
188 ;;
189 ;; Acknowledgments
190 ;; ===============
191 ;;
192 ;; Thanks to Stefan Monnier for corrections and advice.
193 ;;
194 ;;
195 ;; TODO:
196 ;;
197 ;; - When replacing like (progn A B C) -> A B C, the layout of the
198 ;; whole "group" A B C as a unit is lost. Instead of restoring layout
199 ;; as we do now (via "read mappings"), we could just make a backup of
200 ;; the original expression as a string, and use our search machinery
201 ;; to find occurrences in the replacement recursively.
202 ;;
203 ;; - detect infloops when replacing automatically (e.g. for 1 -> '(1))
204 ;;
205 ;; - implement backward searching
206 ;;
207 ;; - improve docstrings
208 ;;
209 ;; - handle more reader syntaxes, e.g. #n, #n#
210 ;;
211 ;; - Implement sessions; add multi-file support based on iterators. A
212 ;; file list is read in (or the user can specify an iterator as a
213 ;; variable). The state in the current buffer is just (buffer
214 ;; . marker). Or should this be abstracted into an own lib? Could
215 ;; be named "files-session" or so.
216
217
218
219 ;;; Code:
220
221 ;;;; Requirements
222
223 (eval-when-compile
224 (require 'subr-x))
225
226 (require 'cl-lib)
227 (require 'elisp-mode)
228 (require 'thingatpt)
229 (require 'help-fns) ;el-search--make-docstring
230
231
232 ;;;; Configuration stuff
233
234 (defgroup el-search nil
235 "Expression based search and replace for `emacs-lisp-mode'."
236 :group 'lisp)
237
238 (defcustom el-search-this-expression-identifier 'exp
239 "Identifier referring to the current expression in pattern input.
240 When entering a PATTERN in an interactive \"el-search\" command,
241 the pattern actually used will be
242
243 `(and ,el-search-this-expression-identifier ,pattern)
244
245 The default value is `exp'."
246 :type 'symbol)
247
248 (defface el-search-match '((((background dark)) (:background "#0000A0"))
249 (t (:background "DarkSlateGray3")))
250 "Face for highlighting the current match.")
251
252 (defface el-search-other-match '((((background dark)) (:background "#202060"))
253 (t (:background "DarkSlateGray1")))
254 "Face for highlighting the other matches.")
255
256
257 ;;;; Helpers
258
259 (defun el-search--print (expr)
260 (let ((print-quoted t)
261 (print-length nil)
262 (print-level nil))
263 (prin1-to-string expr)))
264
265 (defvar el-search-read-expression-map
266 (let ((map (make-sparse-keymap)))
267 (set-keymap-parent map read-expression-map)
268 (define-key map [(control ?g)] #'abort-recursive-edit)
269 (define-key map [up] nil)
270 (define-key map [down] nil)
271 (define-key map [(control meta backspace)] #'backward-kill-sexp)
272 (define-key map [(control ?S)] #'exit-minibuffer)
273 map)
274 "Map for reading input with `el-search-read-expression'.")
275
276 (defun el-search--setup-minibuffer ()
277 (emacs-lisp-mode)
278 (use-local-map el-search-read-expression-map)
279 (setq font-lock-mode t)
280 (funcall font-lock-function 1)
281 (backward-sexp)
282 (indent-sexp)
283 (goto-char (point-max))
284 (when-let ((this-sexp (with-current-buffer (window-buffer (minibuffer-selected-window))
285 (thing-at-point 'sexp))))
286 (let ((more-defaults (list (concat "'" this-sexp))))
287 (setq-local minibuffer-default-add-function
288 (lambda () (if (listp minibuffer-default)
289 (append minibuffer-default more-defaults)
290 (cons minibuffer-default more-defaults)))))))
291
292 ;; $$$$$FIXME: this should be in Emacs! There is only a helper `read--expression'.
293 (defun el-search-read-expression (prompt &optional initial-contents hist default read)
294 "Read expression for `my-eval-expression'."
295 (minibuffer-with-setup-hook #'el-search--setup-minibuffer
296 (read-from-minibuffer prompt initial-contents el-search-read-expression-map read
297 (or hist 'read-expression-history) default)))
298
299 (defvar el-search--initial-mb-contents nil)
300
301 (defun el-search--read-pattern (prompt &optional default read)
302 (let ((input (el-search-read-expression
303 prompt el-search--initial-mb-contents 'el-search-history default read)))
304 (if (or read (not (string= input ""))) input (car el-search-history))))
305
306 (defun el-search--end-of-sexp ()
307 ;;Point must be at sexp beginning
308 (or (scan-sexps (point) 1) (point-max)))
309
310 (defun el-search--ensure-sexp-start ()
311 "Move point to the beginning of the next sexp if necessary.
312 Don't move if already at beginning of a sexp.
313 Point must not be inside a string or comment."
314 (let ((not-done t) res)
315 (while not-done
316 (let ((stop-here nil)
317 (looking-at-from-back (lambda (regexp n)
318 (save-excursion
319 (backward-char n)
320 (looking-at regexp)))))
321 (while (not stop-here)
322 (cond
323 ((eobp) (signal 'end-of-buffer nil))
324 ((looking-at (rx (and (* space) ";"))) (forward-line))
325 ((looking-at (rx (+ (or space "\n")))) (goto-char (match-end 0)))
326
327 ;; FIXME: can the rest be done more generically?
328 ((and (looking-at (rx (or (syntax symbol) (syntax word))))
329 (not (looking-at "\\_<"))
330 (not (funcall looking-at-from-back ",@" 2)))
331 (forward-symbol 1))
332 ((or (and (looking-at "'") (funcall looking-at-from-back "#" 1))
333 (and (looking-at "@") (funcall looking-at-from-back "," 1)))
334 (forward-char))
335 (t (setq stop-here t)))))
336 (condition-case nil
337 (progn
338 (setq res (save-excursion (read (current-buffer))))
339 (setq not-done nil))
340 (error (forward-char))))
341 res))
342
343 (defvar el-search--pcase-macros '()
344 "List of additional \"el-search\" pcase macros.")
345
346 (defun el-search--make-docstring ()
347 ;; code mainly from `pcase--make-docstring'
348 (let* ((main (documentation (symbol-function 'el-search-pattern) 'raw))
349 (ud (help-split-fundoc main 'pcase)))
350 (with-temp-buffer
351 (insert (or (cdr ud) main))
352 (mapc
353 (pcase-lambda (`(,symbol . ,fun))
354 (when-let ((doc (documentation fun)))
355 (insert "\n\n\n-- ")
356 (setq doc (help-fns--signature symbol doc fun fun nil))
357 (insert "\n" (or doc "Not documented."))))
358 (reverse el-search--pcase-macros))
359 (let ((combined-doc (buffer-string)))
360 (if ud (help-add-fundoc-usage combined-doc (car ud)) combined-doc)))))
361
362 (put 'el-search-pattern 'function-documentation '(el-search--make-docstring))
363
364 (defmacro el-search-defpattern (name args &rest body)
365 "Like `pcase-defmacro', but limited to el-search patterns.
366 The semantics is exactly that of `pcase-defmacro', but the scope
367 of the definitions is limited to \"el-search\"."
368 (declare (indent 2) (debug defun))
369 `(setf (alist-get ',name el-search--pcase-macros)
370 (lambda ,args ,@body)))
371
372
373 (defmacro el-search--with-additional-pcase-macros (&rest body)
374 `(cl-letf ,(mapcar (pcase-lambda (`(,symbol . ,fun))
375 `((get ',symbol 'pcase-macroexpander) #',fun))
376 el-search--pcase-macros)
377 ,@body))
378
379 (defun el-search--matcher (pattern &rest body)
380 (eval ;use `eval' to allow for user defined pattern types at run time
381 (let ((expression (make-symbol "expression")))
382 `(el-search--with-additional-pcase-macros
383 (let ((byte-compile-debug t) ;make undefined pattern types raise an error
384 (warning-suppress-log-types '((bytecomp)))
385 (pcase--dontwarn-upats (cons '_ pcase--dontwarn-upats)))
386 (byte-compile (lambda (,expression)
387 (pcase ,expression
388 (,pattern ,@(or body (list t)))
389 (_ nil)))))))))
390
391 (defun el-search--match-p (matcher expression)
392 (funcall matcher expression))
393
394 (defun el-search--wrap-pattern (pattern)
395 `(and ,el-search-this-expression-identifier ,pattern))
396
397 (defun el-search--skip-expression (expression &optional read)
398 ;; Move forward at least one character. Don't move into a string or
399 ;; comment. Don't move further than the beginning of the next sexp.
400 ;; Try to move as far as possible. Point must be at the beginning
401 ;; of an expression.
402 ;; If there are positions where `read' would succeed, but that do
403 ;; not represent a valid sexp start, move past them (e.g. when
404 ;; before "#'" move past both characters).
405 ;;
406 ;; EXPRESSION must be the (read) expression at point, but when READ
407 ;; is non-nil, ignore the first argument and read the expression at
408 ;; point instead.
409 (when read (setq expression (save-excursion (read (current-buffer)))))
410 (cond
411 ((or (null expression)
412 (equal [] expression)
413 (not (or (listp expression) (vectorp expression))))
414 (goto-char (el-search--end-of-sexp)))
415 ((looking-at (rx (or ",@" "," "#'" "'")))
416 (goto-char (match-end 0)))
417 (t (forward-char))))
418
419 (defun el-search--search-pattern-1 (matcher &optional noerror)
420 (let ((match-beg nil) (opoint (point)) current-expr)
421
422 ;; when inside a string or comment, move past it
423 (let ((syntax-here (syntax-ppss)))
424 (when (nth 3 syntax-here) ;inside a string
425 (goto-char (nth 8 syntax-here))
426 (forward-sexp))
427 (when (nth 4 syntax-here) ;inside a comment
428 (forward-line 1)
429 (while (and (not (eobp)) (looking-at (rx (and (* space) ";"))))
430 (forward-line 1))))
431
432 (if (catch 'no-match
433 (while (not match-beg)
434 (condition-case nil
435 (setq current-expr (el-search--ensure-sexp-start))
436 (end-of-buffer
437 (goto-char opoint)
438 (throw 'no-match t)))
439 (if (el-search--match-p matcher current-expr)
440 (setq match-beg (point)
441 opoint (point))
442 (el-search--skip-expression current-expr))))
443 (if noerror nil (signal 'end-of-buffer nil)))
444 match-beg))
445
446 (defun el-search--search-pattern (pattern &optional noerror)
447 "Search elisp buffer with `pcase' PATTERN.
448 Set point to the beginning of the occurrence found and return
449 point. Optional second argument, if non-nil, means if fail just
450 return nil (no error)."
451 (el-search--search-pattern-1 (el-search--matcher pattern) noerror))
452
453 (defun el-search--do-subsexps (pos do-fun &optional ret-fun bound)
454 ;; In current buffer, for any expression start between POS and BOUND
455 ;; or (point-max), in order, call two argument function DO-FUN with
456 ;; the current sexp string and the ending position of the current
457 ;; sexp. When done, with RET-FUN given, call it with no args and
458 ;; return the result; else, return nil.
459 (save-excursion
460 (goto-char pos)
461 (condition-case nil
462 (while (< (point) (or bound (point-max)))
463 (let* ((this-sexp-end (save-excursion (thing-at-point--end-of-sexp) (point)))
464 (this-sexp-string (buffer-substring-no-properties (point) this-sexp-end)))
465 (funcall do-fun this-sexp-string this-sexp-end)
466 (el-search--skip-expression (read this-sexp-string))
467 (el-search--ensure-sexp-start)))
468 (end-of-buffer))
469 (when ret-fun (funcall ret-fun))))
470
471 (defun el-search--create-read-map (&optional pos)
472 (let ((mapping '()))
473 (el-search--do-subsexps
474 (or pos (point))
475 (lambda (sexp _) (push (cons (read sexp) sexp) mapping))
476 (lambda () (nreverse mapping))
477 (save-excursion (thing-at-point--end-of-sexp) (point)))))
478
479 (defun el-search--repair-replacement-layout (printed mapping)
480 (with-temp-buffer
481 (insert printed)
482 (el-search--do-subsexps
483 (point-min)
484 (lambda (sexp sexp-end)
485 (when-let ((old (cdr (assoc (read sexp) mapping))))
486 (delete-region (point) sexp-end)
487 (when (string-match-p "\n" old)
488 (unless (looking-back "^[[:space:]]*" (line-beginning-position))
489 (insert "\n"))
490 (unless (looking-at "[[:space:]\)]*$")
491 (insert "\n")
492 (backward-char)))
493 (save-excursion (insert old))))
494 (lambda () (buffer-substring (point-min) (point-max))))))
495
496 (defun el-search--check-pattern-args (type args predicate &optional message)
497 "Check whether all ARGS fulfill PREDICATE.
498 Raise an error if not. TYPE and optional argument MESSAGE are
499 used to construct the error message."
500 (mapc (lambda (arg)
501 (unless (funcall predicate arg)
502 (error (concat "Pattern `%S': "
503 (or message (format "argument doesn't fulfill %S" predicate))
504 ": %S")
505 type arg)))
506 args))
507
508
509 ;;;; Additional pattern type definitions
510
511 (defun el-search--split (matcher1 matcher2 list)
512 "Helper for the append pattern type.
513
514 When a splitting of LIST into two lists L1, L2 exist so that Li
515 is matched by MATCHERi, return (L1 L2) for such Li, else return
516 nil."
517 (let ((try-match (lambda (list1 list2)
518 (when (and (el-search--match-p matcher1 list1)
519 (el-search--match-p matcher2 list2))
520 (list list1 list2))))
521 (list1 list) (list2 '()) (match nil))
522 ;; don't use recursion, this could hit `max-lisp-eval-depth'
523 (while (and (not (setq match (funcall try-match list1 list2)))
524 (consp list1))
525 (let ((last-list1 (last list1)))
526 (if-let ((cdr-last-list1 (cdr last-list1)))
527 ;; list1 is a dotted list. Then list2 must be empty.
528 (progn (setcdr last-list1 nil)
529 (setq list2 cdr-last-list1))
530 (setq list1 (butlast list1 1)
531 list2 (cons (car last-list1) list2)))))
532 match))
533
534 (el-search-defpattern append (&rest patterns)
535 "Matches any list factorable into lists matched by PATTERNS in order.
536
537 PATTERNS is a list of patterns P1..Pn. Match any list L for that
538 lists L1..Ln exist that are matched by P1..Pn in order and L is
539 equal to the concatenation of L1..Ln. Ln is allowed to be no
540 list.
541
542 When different ways of matching are possible, it is unspecified
543 which one is chosen.
544
545 Example: the pattern
546
547 (append '(1 2 3) x (app car-safe 7))
548
549 matches the list (1 2 3 4 5 6 7 8 9) and binds `x' to (4 5 6)."
550 (if (null patterns)
551 '(pred null)
552 (pcase-let ((`(,pattern . ,more-patterns) patterns))
553 (cond
554 ((null more-patterns) pattern)
555 ((null (cdr more-patterns))
556 `(and (pred listp)
557 (app ,(apply-partially #'el-search--split
558 (el-search--matcher pattern)
559 (el-search--matcher (car more-patterns)))
560 (,'\` ((,'\, ,pattern)
561 (,'\, ,(car more-patterns)))))))
562 (t `(append ,pattern (append ,@more-patterns)))))))
563
564 (el-search-defpattern string (&rest regexps)
565 "Matches any string that is matched by all REGEXPS."
566 (el-search--check-pattern-args 'string regexps #'stringp)
567 (let ((string (make-symbol "string"))
568 (regexp (make-symbol "regexp")))
569 `(and (pred stringp)
570 (pred (lambda (,string)
571 (cl-every
572 (lambda (,regexp) (string-match-p ,regexp ,string))
573 (list ,@regexps)))))))
574
575 (el-search-defpattern symbol (&rest regexps)
576 "Matches any symbol whose name is matched by all REGEXPS."
577 (el-search--check-pattern-args 'symbol regexps #'stringp)
578 `(and (pred symbolp)
579 (app symbol-name (string ,@regexps))))
580
581 (defun el-search--contains-p (matcher exp)
582 "Return non-nil when tree EXP contains a match for MATCHER.
583 Recurse on all types of sequences. In the positive case the
584 return value is (t elt), where ELT is a matching element found in
585 EXP."
586 (if (el-search--match-p matcher exp)
587 (list t exp)
588 (and (sequencep exp)
589 (let ((try-match (apply-partially #'el-search--contains-p matcher)))
590 (if (consp exp)
591 (or (funcall try-match (car exp))
592 (funcall try-match (cdr exp)))
593 (cl-some try-match exp))))))
594
595 (el-search-defpattern contains (&rest patterns)
596 "Matches trees that contain a match for all PATTERNs.
597 Searches any tree of sequences recursively for matches. Objects
598 of any kind matched by all PATTERNs are also matched.
599
600 Example: (contains (string \"H\") 17) matches ((\"Hallo\") x (5 [1 17]))"
601 (cond
602 ((null patterns) '_)
603 ((null (cdr patterns))
604 (let ((pattern (car patterns)))
605 `(app ,(apply-partially #'el-search--contains-p (el-search--matcher pattern))
606 (,'\` (t (,'\, ,pattern))))))
607 (t `(and ,@(mapcar (lambda (pattern) `(contains ,pattern)) patterns)))))
608
609 (el-search-defpattern not (pattern)
610 "Matches any object that is not matched by PATTERN."
611 `(app ,(apply-partially #'el-search--match-p (el-search--matcher pattern))
612 (pred not)))
613
614 (defun el-search--match-symbol-file (regexp symbol)
615 (when-let ((symbol-file (and (symbolp symbol)
616 (symbol-file symbol))))
617 (string-match-p
618 (if (symbolp regexp) (concat "\\`" (symbol-name regexp) "\\'") regexp)
619 (file-name-sans-extension (file-name-nondirectory symbol-file)))))
620
621 (el-search-defpattern source (regexp)
622 "Matches any symbol whose `symbol-file' is matched by REGEXP.
623
624 This pattern matches when the object is a symbol for that
625 `symbol-file' returns a (non-nil) FILE-NAME that fulfills
626 (string-match-p REGEXP (file-name-sans-extension
627 (file-name-nondirectory FILENAME)))
628
629 REGEXP can also be a symbol, in which case
630
631 (concat \"^\" (symbol-name regexp) \"$\")
632
633 is used as regular expression."
634 (el-search--check-pattern-args 'source (list regexp) #'stringp)
635 `(pred (el-search--match-symbol-file ,regexp)))
636
637 (defun el-search--match-key-sequence (keys expr)
638 (when-let ((expr-keys (pcase expr
639 ((or (pred stringp) (pred vectorp)) expr)
640 (`(kbd ,(and (pred stringp) string)) (ignore-errors (kbd string))))))
641 (apply #'equal
642 (mapcar (lambda (keys) (ignore-errors (key-description keys)))
643 (list keys expr-keys)))))
644
645 (el-search-defpattern keys (key-sequence)
646 "Matches descriptions of the KEY-SEQUENCE.
647 KEY-SEQUENCE is a string or vector representing a key sequence,
648 or an expression of the form (kbd STRING).
649
650 Match any description of the same key sequence in any of these
651 formats.
652
653 Example: the pattern
654
655 (keys (kbd \"C-s\"))
656
657 matches any of these expressions:
658
659 \"\\C-s\"
660 \"\C-s\"
661 (kbd \"C-s\")
662 [(control ?s)]"
663 (when (eq (car-safe key-sequence) 'kbd)
664 (setq key-sequence (kbd (cadr key-sequence))))
665 (el-search--check-pattern-args 'keys (list key-sequence) (lambda (x) (or (stringp x) (vectorp x)))
666 "argument not a string or vector")
667 `(pred (el-search--match-key-sequence ,key-sequence)))
668
669 (defun el-search--s (expr)
670 (cond
671 ((symbolp expr) `(or (symbol ,(symbol-name expr))
672 (,'\` (,'quote (,'\, (symbol ,(symbol-name expr)))))
673 (,'\` (,'function (,'\, (symbol ,(symbol-name expr)))))))
674 ((stringp expr) `(string ,expr))
675 (t expr)))
676
677 (el-search-defpattern l (&rest lpats)
678 "Alternative pattern type for matching lists.
679 Match any list with subsequent elements matched by all LPATS in
680 order.
681
682 The idea is to be able to search for pieces of code (i.e. lists)
683 with very brief input by using a specialized syntax.
684
685 An LPAT can take the following forms:
686
687 SYMBOL Matches any symbol S matched by SYMBOL's name interpreted
688 as a regexp. Matches also 'S and #'S for any such S.
689 STRING Matches any string matched by STRING interpreted as a
690 regexp
691 _ Matches any list element
692 __ Matches any number of list elements (including zero)
693 ^ Matches zero elements, but only at the beginning of a list
694 $ Matches zero elements, but only at the end of a list
695 PAT Anything else is interpreted as a normal pcase pattern, and
696 matches one list element matched by it
697
698 ^ is only valid as the first, $ as the last of the LPATS.
699
700 Example: To match defuns that contain \"hl\" in their name and
701 have at least one mandatory, but also optional arguments, you
702 could use this pattern:
703
704 (l ^ 'defun hl (l _ &optional))"
705 (let ((match-start nil) (match-end nil))
706 (when (eq (car-safe lpats) '^)
707 (setq match-start t)
708 (cl-callf cdr lpats))
709 (when (eq (car-safe (last lpats)) '$)
710 (setq match-end t)
711 (cl-callf butlast lpats 1))
712 `(append ,@(if match-start '() '(_))
713 ,@(mapcar
714 (lambda (elt)
715 (pcase elt
716 ('__ '_)
717 ('_ '`(,_))
718 ('_? '(or '() `(,_))) ;FIXME: useful - document? or should we provide a (? PAT)
719 ;thing?
720 (_ `(,'\` ((,'\, ,(el-search--s elt)))))))
721 lpats)
722 ,@(if match-end '() '(_)))))
723
724
725 ;;;; Highlighting
726
727 (defvar-local el-search-hl-overlay nil)
728
729 (defvar-local el-search-hl-other-overlays '())
730
731 (defvar el-search-keep-hl nil)
732
733 (defun el-search-hl-sexp (&optional bounds)
734 (let ((bounds (or bounds
735 (list (point) (el-search--end-of-sexp)))))
736 (if (overlayp el-search-hl-overlay)
737 (apply #'move-overlay el-search-hl-overlay bounds)
738 (overlay-put (setq el-search-hl-overlay (apply #'make-overlay bounds))
739 'face 'el-search-match))
740 (overlay-put el-search-hl-overlay 'priority 1002))
741 (add-hook 'post-command-hook #'el-search-hl-post-command-fun t t))
742
743 (defun el-search--hl-other-matches-1 (pattern from to)
744 (mapc #'delete-overlay el-search-hl-other-overlays)
745 (setq el-search-hl-other-overlays '())
746 (let ((matcher (el-search--matcher pattern))
747 this-match-beg this-match-end
748 (done nil))
749 (save-excursion
750 (goto-char from)
751 (while (not done)
752 (setq this-match-beg (el-search--search-pattern-1 matcher t))
753 (if (not this-match-beg)
754 (setq done t)
755 (goto-char this-match-beg)
756 (setq this-match-end (el-search--end-of-sexp))
757 (let ((ov (make-overlay this-match-beg this-match-end)))
758 (overlay-put ov 'face 'el-search-other-match)
759 (overlay-put ov 'priority 1001)
760 (push ov el-search-hl-other-overlays)
761 (goto-char this-match-end)
762 (when (>= (point) to) (setq done t))))))))
763
764 (defun el-search-hl-other-matches (pattern)
765 "Highlight all matches visible in the selected window."
766 (el-search--hl-other-matches-1 pattern
767 (save-excursion
768 (goto-char (window-start))
769 (beginning-of-defun-raw)
770 (point))
771 (window-end))
772 (add-hook 'window-scroll-functions #'el-search--after-scroll t t))
773
774 (defun el-search--after-scroll (_win start)
775 (el-search--hl-other-matches-1 el-search-current-pattern
776 (save-excursion
777 (goto-char start)
778 (beginning-of-defun-raw)
779 (point))
780 (window-end nil t)))
781
782 (defun el-search-hl-remove ()
783 (when (overlayp el-search-hl-overlay)
784 (delete-overlay el-search-hl-overlay))
785 (remove-hook 'window-scroll-functions #'el-search--after-scroll t)
786 (mapc #'delete-overlay el-search-hl-other-overlays)
787 (setq el-search-hl-other-overlays '()))
788
789 (defun el-search-hl-post-command-fun ()
790 (unless (or el-search-keep-hl
791 (eq this-command 'el-search-query-replace)
792 (eq this-command 'el-search-pattern))
793 (el-search-hl-remove)
794 (remove-hook 'post-command-hook 'el-search-hl-post-command-fun t)))
795
796
797 ;;;; Core functions
798
799 (defvar el-search-history '()
800 "List of input strings.")
801
802 (defvar el-search-success nil)
803 (defvar el-search-current-pattern nil)
804
805 ;;;###autoload
806 (defun el-search-pattern (pattern)
807 "Start new or resume last elisp search.
808
809 Search current buffer for expressions that are matched by `pcase'
810 PATTERN. Use `read' to transform buffer contents into
811 expressions.
812
813
814 Additional `pcase' pattern types to be used with this command can
815 be defined with `el-search-defpattern'.
816
817 The following additional pattern types are currently defined:"
818 (interactive (list (if (and (eq this-command last-command)
819 el-search-success)
820 el-search-current-pattern
821 (let ((pattern
822 (el-search--read-pattern "Find pcase pattern: "
823 (car el-search-history)
824 t)))
825 ;; A very common mistake: input "foo" instead of "'foo"
826 (when (and (symbolp pattern)
827 (not (eq pattern '_))
828 (or (not (boundp pattern))
829 (not (eq (symbol-value pattern) pattern))))
830 (error "Please don't forget the quote when searching for a symbol"))
831 (el-search--wrap-pattern pattern)))))
832 (setq this-command 'el-search-pattern) ;in case we come from isearch
833 (setq el-search-current-pattern pattern)
834 (let ((opoint (point)))
835 (when (and (eq this-command last-command) el-search-success)
836 (el-search--skip-expression nil t))
837 (setq el-search-success nil)
838 (when (condition-case nil
839 (el-search--search-pattern pattern)
840 (end-of-buffer (message "No match")
841 (goto-char opoint)
842 (el-search-hl-remove)
843 (ding)
844 nil))
845 (setq el-search-success t)
846 (el-search-hl-sexp)
847 (unless (eq this-command last-command)
848 (el-search-hl-other-matches pattern)))))
849
850 (defvar el-search-search-and-replace-help-string
851 "\
852 y Replace this match and move to the next.
853 SPC or n Skip this match and move to the next.
854 r Replace this match but don't move.
855 ! Replace all remaining matches automatically.
856 q Quit. To resume, use e.g. `repeat-complex-command'.
857 ? Show this help.
858 s Toggle splicing mode. When splicing mode is
859 on (default off), the replacement expression must
860 evaluate to a list, and the result is spliced into the
861 buffer, instead of just inserted.
862
863 Hit any key to proceed."
864 "Help string for ? in `el-search-query-replace'.")
865
866 (defun el-search-search-and-replace-pattern (pattern replacement &optional mapping splice)
867 (let ((replace-all nil) (nbr-replaced 0) (nbr-skipped 0) (done nil)
868 (el-search-keep-hl t) (opoint (point))
869 (get-replacement (el-search--matcher pattern replacement)))
870 (unwind-protect
871 (while (and (not done) (el-search--search-pattern pattern t))
872 (setq opoint (point))
873 (unless replace-all
874 (el-search-hl-sexp)
875 (unless (eq this-command last-command)
876 (el-search-hl-other-matches pattern)))
877 (let* ((read-mapping (el-search--create-read-map))
878 (region (list (point) (el-search--end-of-sexp)))
879 (substring (apply #'buffer-substring-no-properties region))
880 (expr (read substring))
881 (replaced-this nil)
882 (new-expr (funcall get-replacement expr))
883 (get-replacement-string
884 (lambda () (if (and splice (not (listp new-expr)))
885 (error "Expression to splice in is an atom")
886 (el-search--repair-replacement-layout
887 (if splice
888 (mapconcat #'el-search--print new-expr " ")
889 (el-search--print new-expr))
890 (append mapping read-mapping)))))
891 (to-insert (funcall get-replacement-string))
892 (do-replace (lambda ()
893 (atomic-change-group
894 (apply #'delete-region region)
895 (let ((inhibit-message t)
896 (opoint (point)))
897 (insert to-insert)
898 (indent-region opoint (point))
899 (el-search-hl-sexp (list opoint (point)))
900 (goto-char opoint)))
901 (cl-incf nbr-replaced)
902 (setq replaced-this t))))
903 (if replace-all
904 (funcall do-replace)
905 (while (not (pcase (if replaced-this
906 (read-char-choice "[SPC ! q] (? for help)"
907 '(?\ ?! ?q ?n ??))
908 (read-char-choice
909 (concat "Replace this occurrence"
910 (if (or (string-match-p "\n" to-insert)
911 (< 40 (length to-insert)))
912 "" (format " with `%s'" to-insert))
913 "? "
914 (if splice "{splice} " "")
915 "[y SPC r ! s q] (? for help)" )
916 '(?y ?n ?r ?\ ?! ?q ?s ??)))
917 (?r (funcall do-replace)
918 nil)
919 (?y (funcall do-replace)
920 t)
921 ((or ?\ ?n)
922 (unless replaced-this (cl-incf nbr-skipped))
923 t)
924 (?! (unless replaced-this
925 (funcall do-replace))
926 (setq replace-all t)
927 t)
928 (?s (cl-callf not splice)
929 (setq to-insert (funcall get-replacement-string))
930 nil)
931 (?q (setq done t)
932 t)
933 (?? (ignore (read-char el-search-search-and-replace-help-string))
934 nil)))))
935 (unless (or done (eobp)) (el-search--skip-expression nil t)))))
936 (el-search-hl-remove)
937 (goto-char opoint)
938 (message "Replaced %d matches%s"
939 nbr-replaced
940 (if (zerop nbr-skipped) ""
941 (format " (%d skipped)" nbr-skipped)))))
942
943 (defun el-search-query-replace-read-args ()
944 (barf-if-buffer-read-only)
945 (let* ((from (el-search--read-pattern "Replace from: "))
946 (to (let ((el-search--initial-mb-contents nil))
947 (el-search--read-pattern "Replace with result of evaluation of: " from))))
948 (list (el-search--wrap-pattern (read from)) (read to)
949 (with-temp-buffer
950 (insert to)
951 (el-search--create-read-map 1)))))
952
953 ;;;###autoload
954 (defun el-search-query-replace (from to &optional mapping)
955 "Replace some occurrences of FROM pattern with evaluated TO."
956 (interactive (el-search-query-replace-read-args))
957 (setq this-command 'el-search-query-replace) ;in case we come from isearch
958 (setq el-search-current-pattern from)
959 (barf-if-buffer-read-only)
960 (el-search-search-and-replace-pattern from to mapping))
961
962 (defun el-search--take-over-from-isearch (&optional goto-left-end)
963 (let ((other-end (and goto-left-end isearch-other-end))
964 (input isearch-string))
965 (isearch-exit)
966 (when (and other-end (< other-end (point)))
967 (goto-char other-end))
968 input))
969
970 ;;;###autoload
971 (defun el-search-search-from-isearch ()
972 ;; FIXME: an interesting alternative would be to really integrate it
973 ;; with Isearch, using `isearch-search-fun-function'.
974 ;; Alas, this is not trivial if we want to transfer our optimizations.
975 (interactive)
976 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch))))
977 ;; use `call-interactively' so we get recorded in `extended-command-history'
978 (call-interactively #'el-search-pattern)))
979
980 ;;;###autoload
981 (defun el-search-replace-from-isearch ()
982 (interactive)
983 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch t))))
984 (call-interactively #'el-search-query-replace)))
985
986
987
988 (provide 'el-search)
989 ;;; el-search.el ends here