]> code.delx.au - gnu-emacs-elpa/blob - packages/el-search/el-search.el
use uninterned symbol in `el-search--matcher'
[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 "Name of the identifier referring to the current expression.
240 The default value is `exp'. You can use this name in the search
241 prompt to refer to the value of the currently tested expression."
242 :type 'symbol)
243
244 (defface el-search-match '((((background dark)) (:background "#0000A0"))
245 (t (:background "DarkSlateGray3")))
246 "Face for highlighting the current match.")
247
248 (defface el-search-other-match '((((background dark)) (:background "#202060"))
249 (t (:background "DarkSlateGray1")))
250 "Face for highlighting the other matches.")
251
252
253 ;;;; Helpers
254
255 (defun el-search--print (expr)
256 (let ((print-quoted t)
257 (print-length nil)
258 (print-level nil))
259 (prin1-to-string expr)))
260
261 (defvar el-search-read-expression-map
262 (let ((map (make-sparse-keymap)))
263 (set-keymap-parent map read-expression-map)
264 (define-key map [(control ?g)] #'abort-recursive-edit)
265 (define-key map [up] nil)
266 (define-key map [down] nil)
267 (define-key map [(control meta backspace)] #'backward-kill-sexp)
268 (define-key map [(control ?S)] #'exit-minibuffer)
269 map)
270 "Map for reading input with `el-search-read-expression'.")
271
272 ;; $$$$$FIXME: this should be in Emacs! There is only a helper `read--expression'.
273 (defun el-search-read-expression (prompt &optional initial-contents hist default read)
274 "Read expression for `my-eval-expression'."
275 (minibuffer-with-setup-hook
276 (lambda ()
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 (read-from-minibuffer prompt initial-contents el-search-read-expression-map read
285 (or hist 'read-expression-history) default)))
286
287 (defvar el-search--initial-mb-contents nil)
288
289 (defun el-search--read-pattern (prompt &optional default read)
290 (let ((this-sexp (sexp-at-point)))
291 (minibuffer-with-setup-hook
292 (lambda ()
293 (when this-sexp
294 (let ((more-defaults (list (concat "'" (el-search--print this-sexp)))))
295 (setq-local minibuffer-default-add-function
296 (lambda () (if (listp minibuffer-default)
297 (append minibuffer-default more-defaults)
298 (cons minibuffer-default more-defaults)))))))
299 (el-search-read-expression
300 prompt el-search--initial-mb-contents 'el-search-history default read))))
301
302 (defun el-search--end-of-sexp ()
303 ;;Point must be at sexp beginning
304 (or (scan-sexps (point) 1) (point-max)))
305
306 (defun el-search--ensure-sexp-start ()
307 "Move point to the beginning of the next sexp if necessary.
308 Don't move if already at beginning of a sexp.
309 Point must not be inside a string or comment."
310 (let ((not-done t) res)
311 (while not-done
312 (let ((stop-here nil)
313 (looking-at-from-back (lambda (regexp n)
314 (save-excursion
315 (backward-char n)
316 (looking-at regexp)))))
317 (while (not stop-here)
318 (cond
319 ((eobp) (signal 'end-of-buffer nil))
320 ((looking-at (rx (and (* space) ";"))) (forward-line))
321 ((looking-at (rx (+ (or space "\n")))) (goto-char (match-end 0)))
322
323 ;; FIXME: can the rest be done more generically?
324 ((and (looking-at (rx (or (syntax symbol) (syntax word))))
325 (not (looking-at "\\_<"))
326 (not (funcall looking-at-from-back ",@" 2)))
327 (forward-symbol 1))
328 ((or (and (looking-at "'") (funcall looking-at-from-back "#" 1))
329 (and (looking-at "@") (funcall looking-at-from-back "," 1)))
330 (forward-char))
331 (t (setq stop-here t)))))
332 (condition-case nil
333 (progn
334 (setq res (save-excursion (read (current-buffer))))
335 (setq not-done nil))
336 (error (forward-char))))
337 res))
338
339 (defvar el-search--pcase-macros '()
340 "List of additional \"el-search\" pcase macros.")
341
342 (defun el-search--make-docstring ()
343 ;; code mainly from `pcase--make-docstring'
344 (let* ((main (documentation (symbol-function 'el-search-pattern) 'raw))
345 (ud (help-split-fundoc main 'pcase)))
346 (with-temp-buffer
347 (insert (or (cdr ud) main))
348 (mapc
349 (pcase-lambda (`(,symbol . ,fun))
350 (when-let ((doc (documentation fun)))
351 (insert "\n\n\n-- ")
352 (setq doc (help-fns--signature symbol doc fun fun nil))
353 (insert "\n" (or doc "Not documented."))))
354 (reverse el-search--pcase-macros))
355 (let ((combined-doc (buffer-string)))
356 (if ud (help-add-fundoc-usage combined-doc (car ud)) combined-doc)))))
357
358 (put 'el-search-pattern 'function-documentation '(el-search--make-docstring))
359
360 (defmacro el-search-defpattern (name args &rest body)
361 "Like `pcase-defmacro', but limited to el-search patterns.
362 The semantics is exactly that of `pcase-defmacro', but the scope
363 of the definitions is limited to \"el-search\"."
364 (declare (indent 2) (debug defun))
365 `(setf (alist-get ',name el-search--pcase-macros)
366 (lambda ,args ,@body)))
367
368
369 (defmacro el-search--with-additional-pcase-macros (&rest body)
370 `(cl-letf ,(mapcar (pcase-lambda (`(,symbol . ,fun))
371 `((get ',symbol 'pcase-macroexpander) #',fun))
372 el-search--pcase-macros)
373 ,@body))
374
375 (defun el-search--matcher (pattern &rest body)
376 (eval ;use `eval' to allow for user defined pattern types at run time
377 (let ((expression (make-symbol "expression")))
378 `(el-search--with-additional-pcase-macros
379 (let ((byte-compile-debug t) ;make undefined pattern types raise an error
380 (warning-suppress-log-types '((bytecomp)))
381 (pcase--dontwarn-upats (cons '_ pcase--dontwarn-upats)))
382 (byte-compile (lambda (,expression)
383 (pcase ,expression
384 (,pattern ,@(or body (list t)))
385 (_ nil)))))))))
386
387 (defun el-search--match-p (matcher expression)
388 (funcall matcher expression))
389
390 (defun el-search--wrap-pattern (pattern)
391 `(and ,el-search-this-expression-identifier ,pattern))
392
393 (defun el-search--skip-expression (expression &optional read)
394 ;; Move forward at least one character. Don't move into a string or
395 ;; comment. Don't move further than the beginning of the next sexp.
396 ;; Try to move as far as possible. Point must be at the beginning
397 ;; of an expression.
398 ;; If there are positions where `read' would succeed, but that do
399 ;; not represent a valid sexp start, move past them (e.g. when
400 ;; before "#'" move past both characters).
401 ;;
402 ;; EXPRESSION must be the (read) expression at point, but when READ
403 ;; is non-nil, ignore the first argument and read the expression at
404 ;; point instead.
405 (when read (setq expression (save-excursion (read (current-buffer)))))
406 (cond
407 ((or (null expression)
408 (equal [] expression)
409 (not (or (listp expression) (vectorp expression))))
410 (goto-char (el-search--end-of-sexp)))
411 ((looking-at (rx (or ",@" "," "#'" "'")))
412 (goto-char (match-end 0)))
413 (t (forward-char))))
414
415 (defun el-search--search-pattern-1 (matcher &optional noerror)
416 (let ((match-beg nil) (opoint (point)) current-expr)
417
418 ;; when inside a string or comment, move past it
419 (let ((syntax-here (syntax-ppss)))
420 (when (nth 3 syntax-here) ;inside a string
421 (goto-char (nth 8 syntax-here))
422 (forward-sexp))
423 (when (nth 4 syntax-here) ;inside a comment
424 (forward-line 1)
425 (while (and (not (eobp)) (looking-at (rx (and (* space) ";"))))
426 (forward-line 1))))
427
428 (if (catch 'no-match
429 (while (not match-beg)
430 (condition-case nil
431 (setq current-expr (el-search--ensure-sexp-start))
432 (end-of-buffer
433 (goto-char opoint)
434 (throw 'no-match t)))
435 (if (el-search--match-p matcher current-expr)
436 (setq match-beg (point)
437 opoint (point))
438 (el-search--skip-expression current-expr))))
439 (if noerror nil (signal 'end-of-buffer nil)))
440 match-beg))
441
442 (defun el-search--search-pattern (pattern &optional noerror)
443 "Search elisp buffer with `pcase' PATTERN.
444 Set point to the beginning of the occurrence found and return
445 point. Optional second argument, if non-nil, means if fail just
446 return nil (no error)."
447 (el-search--search-pattern-1 (el-search--matcher pattern) noerror))
448
449 (defun el-search--do-subsexps (pos do-fun &optional ret-fun bound)
450 ;; In current buffer, for any expression start between POS and BOUND
451 ;; or (point-max), in order, call two argument function DO-FUN with
452 ;; the current sexp string and the ending position of the current
453 ;; sexp. When done, with RET-FUN given, call it with no args and
454 ;; return the result; else, return nil.
455 (save-excursion
456 (goto-char pos)
457 (condition-case nil
458 (while (< (point) (or bound (point-max)))
459 (let* ((this-sexp-end (save-excursion (thing-at-point--end-of-sexp) (point)))
460 (this-sexp-string (buffer-substring-no-properties (point) this-sexp-end)))
461 (funcall do-fun this-sexp-string this-sexp-end)
462 (el-search--skip-expression (read this-sexp-string))
463 (el-search--ensure-sexp-start)))
464 (end-of-buffer))
465 (when ret-fun (funcall ret-fun))))
466
467 (defun el-search--create-read-map (&optional pos)
468 (let ((mapping '()))
469 (el-search--do-subsexps
470 (or pos (point))
471 (lambda (sexp _) (push (cons (read sexp) sexp) mapping))
472 (lambda () (nreverse mapping))
473 (save-excursion (thing-at-point--end-of-sexp) (point)))))
474
475 (defun el-search--repair-replacement-layout (printed mapping)
476 (with-temp-buffer
477 (insert printed)
478 (el-search--do-subsexps
479 (point-min)
480 (lambda (sexp sexp-end)
481 (when-let ((old (cdr (assoc (read sexp) mapping))))
482 (delete-region (point) sexp-end)
483 (when (string-match-p "\n" old)
484 (unless (looking-back "^[[:space:]]*" (line-beginning-position))
485 (insert "\n"))
486 (unless (looking-at "[[:space:]\)]*$")
487 (insert "\n")
488 (backward-char)))
489 (save-excursion (insert old))))
490 (lambda () (buffer-substring (point-min) (point-max))))))
491
492 (defun el-search--check-pattern-args (type args predicate &optional message)
493 "Check whether all ARGS fulfill PREDICATE.
494 Raise an error if not. TYPE and optional argument MESSAGE are
495 used to construct the error message."
496 (mapc (lambda (arg)
497 (unless (funcall predicate arg)
498 (error (concat "Pattern `%S': "
499 (or message (format "argument doesn't fulfill %S" predicate))
500 ": %S")
501 type arg)))
502 args))
503
504
505 ;;;; Additional pattern type definitions
506
507 (defun el-search--split (matcher1 matcher2 list)
508 "Helper for the append pattern type.
509
510 When a splitting of LIST into two lists L1, L2 exist so that Li
511 is matched by MATCHERi, return (L1 L2) for such Li, else return
512 nil."
513 (let ((try-match (lambda (list1 list2)
514 (when (and (el-search--match-p matcher1 list1)
515 (el-search--match-p matcher2 list2))
516 (list list1 list2))))
517 (list1 list) (list2 '()) (match nil))
518 ;; don't use recursion, this could hit `max-lisp-eval-depth'
519 (while (and (not (setq match (funcall try-match list1 list2)))
520 (consp list1))
521 (let ((last-list1 (last list1)))
522 (if-let ((cdr-last-list1 (cdr last-list1)))
523 ;; list1 is a dotted list. Then list2 must be empty.
524 (progn (setcdr last-list1 nil)
525 (setq list2 cdr-last-list1))
526 (setq list1 (butlast list1 1)
527 list2 (cons (car last-list1) list2)))))
528 match))
529
530 (el-search-defpattern append (&rest patterns)
531 "Matches any list factorable into lists matched by PATTERNS in order.
532
533 PATTERNS is a list of patterns P1..Pn. Match any list L for that
534 lists L1..Ln exist that are matched by P1..Pn in order and L is
535 equal to the concatenation of L1..Ln. Ln is allowed to be no
536 list.
537
538 When different ways of matching are possible, it is unspecified
539 which one is chosen.
540
541 Example: the pattern
542
543 (append '(1 2 3) x (app car-safe 7))
544
545 matches the list (1 2 3 4 5 6 7 8 9) and binds `x' to (4 5 6)."
546 (if (null patterns)
547 '(pred null)
548 (pcase-let ((`(,pattern . ,more-patterns) patterns))
549 (cond
550 ((null more-patterns) pattern)
551 ((null (cdr more-patterns))
552 `(and (pred listp)
553 (app ,(apply-partially #'el-search--split
554 (el-search--matcher pattern)
555 (el-search--matcher (car more-patterns)))
556 (,'\` ((,'\, ,pattern)
557 (,'\, ,(car more-patterns)))))))
558 (t `(append ,pattern (append ,@more-patterns)))))))
559
560 (el-search-defpattern string (&rest regexps)
561 "Matches any string that is matched by all REGEXPS."
562 (el-search--check-pattern-args 'string regexps #'stringp)
563 (let ((string (make-symbol "string"))
564 (regexp (make-symbol "regexp")))
565 `(and (pred stringp)
566 (pred (lambda (,string)
567 (cl-every
568 (lambda (,regexp) (string-match-p ,regexp ,string))
569 (list ,@regexps)))))))
570
571 (el-search-defpattern symbol (&rest regexps)
572 "Matches any symbol whose name is matched by all REGEXPS."
573 (el-search--check-pattern-args 'symbol regexps #'stringp)
574 `(and (pred symbolp)
575 (app symbol-name (string ,@regexps))))
576
577 (defun el-search--contains-p (matcher exp)
578 "Return non-nil when tree EXP contains a match for MATCHER.
579 Recurse on all types of sequences. In the positive case the
580 return value is (t elt), where ELT is a matching element found in
581 EXP."
582 (if (el-search--match-p matcher exp)
583 (list t exp)
584 (and (sequencep exp)
585 (let ((try-match (apply-partially #'el-search--contains-p matcher)))
586 (if (consp exp)
587 (or (funcall try-match (car exp))
588 (funcall try-match (cdr exp)))
589 (cl-some try-match exp))))))
590
591 (el-search-defpattern contains (&rest patterns)
592 "Matches trees that contain a match for all PATTERNs.
593 Searches any tree of sequences recursively for matches. Objects
594 of any kind matched by all PATTERNs are also matched.
595
596 Example: (contains (string \"H\") 17) matches ((\"Hallo\") x (5 [1 17]))"
597 (cond
598 ((null patterns) '_)
599 ((null (cdr patterns))
600 (let ((pattern (car patterns)))
601 `(app ,(apply-partially #'el-search--contains-p (el-search--matcher pattern))
602 (,'\` (t (,'\, ,pattern))))))
603 (t `(and ,@(mapcar (lambda (pattern) `(contains ,pattern)) patterns)))))
604
605 (el-search-defpattern not (pattern)
606 "Matches any object that is not matched by PATTERN."
607 `(app ,(apply-partially #'el-search--match-p (el-search--matcher pattern))
608 (pred not)))
609
610 (defun el-search--match-symbol-file (regexp symbol)
611 (when-let ((symbol-file (and (symbolp symbol)
612 (symbol-file symbol))))
613 (string-match-p
614 (if (symbolp regexp) (concat "\\`" (symbol-name regexp) "\\'") regexp)
615 (file-name-sans-extension (file-name-nondirectory symbol-file)))))
616
617 (el-search-defpattern source (regexp)
618 "Matches any symbol whose `symbol-file' is matched by REGEXP.
619
620 This pattern matches when the object is a symbol for that
621 `symbol-file' returns a (non-nil) FILE-NAME that fulfills
622 (string-match-p REGEXP (file-name-sans-extension
623 (file-name-nondirectory FILENAME)))
624
625 REGEXP can also be a symbol, in which case
626
627 (concat \"^\" (symbol-name regexp) \"$\")
628
629 is used as regular expression."
630 (el-search--check-pattern-args 'source (list regexp) #'stringp)
631 `(pred (el-search--match-symbol-file ,regexp)))
632
633 (defun el-search--match-key-sequence (keys expr)
634 (when-let ((expr-keys (pcase expr
635 ((or (pred stringp) (pred vectorp)) expr)
636 (`(kbd ,(and (pred stringp) string)) (ignore-errors (kbd string))))))
637 (apply #'equal
638 (mapcar (lambda (keys) (ignore-errors (key-description keys)))
639 (list keys expr-keys)))))
640
641 (el-search-defpattern keys (key-sequence)
642 "Matches descriptions of the KEY-SEQUENCE.
643 KEY-SEQUENCE is a string or vector representing a key sequence,
644 or an expression of the form (kbd STRING).
645
646 Match any description of the same key sequence in any of these
647 formats.
648
649 Example: the pattern
650
651 (keys (kbd \"C-s\"))
652
653 matches any of these expressions:
654
655 \"\\C-s\"
656 \"\C-s\"
657 (kbd \"C-s\")
658 [(control ?s)]"
659 (when (eq (car-safe key-sequence) 'kbd)
660 (setq key-sequence (kbd (cadr key-sequence))))
661 (el-search--check-pattern-args 'keys (list key-sequence) (lambda (x) (or (stringp x) (vectorp x)))
662 "argument not a string or vector")
663 `(pred (el-search--match-key-sequence ,key-sequence)))
664
665 (defun el-search--s (expr)
666 (cond
667 ((symbolp expr) `(symbol ,(symbol-name expr)))
668 ((stringp expr) `(string ,expr))
669 (t expr)))
670
671 (el-search-defpattern l (&rest lpats)
672 "Alternative pattern type for matching lists.
673 Match any list with subsequent elements matched by all LPATS in
674 order.
675
676 The idea is to be able to search for pieces of code (i.e. lists)
677 with very brief input by using a specialized syntax.
678
679 An LPAT can take the following forms:
680
681 SYMBOL Matches any symbol matched by SYMBOL's name interpreted as
682 a regexp
683 STRING Matches any string matched by STRING interpreted as a
684 regexp
685 _ Matches any list element
686 __ Matches any number of list elements (including zero)
687 ^ Matches zero elements, but only at the beginning of a list
688 $ Matches zero elements, but only at the end of a list
689 PAT Anything else is interpreted as a normal pcase pattern, and
690 matches one list element matched by it
691
692 ^ is only valid as the first, $ as the last of the LPATS.
693
694 Example: To match defuns that contain \"hl\" in their name and
695 have at least one mandatory, but also optional arguments, you
696 could use this pattern:
697
698 (l ^ 'defun hl (l _ &optional))"
699 (let ((match-start nil) (match-end nil))
700 (when (eq (car-safe lpats) '^)
701 (setq match-start t)
702 (cl-callf cdr lpats))
703 (when (eq (car-safe (last lpats)) '$)
704 (setq match-end t)
705 (cl-callf butlast lpats 1))
706 `(append ,@(if match-start '() '(_))
707 ,@(mapcar
708 (lambda (elt)
709 (pcase elt
710 ('__ '_)
711 ('_ '`(,_))
712 ('_? '(or '() `(,_))) ;FIXME: useful - document? or should we provide a (? PAT)
713 ;thing?
714 (_ `(,'\` ((,'\, ,(el-search--s elt)))))))
715 lpats)
716 ,@(if match-end '() '(_)))))
717
718
719 ;;;; Highlighting
720
721 (defvar-local el-search-hl-overlay nil)
722
723 (defvar-local el-search-hl-other-overlays '())
724
725 (defvar el-search-keep-hl nil)
726
727 (defun el-search-hl-sexp (&optional bounds)
728 (let ((bounds (or bounds
729 (list (point) (el-search--end-of-sexp)))))
730 (if (overlayp el-search-hl-overlay)
731 (apply #'move-overlay el-search-hl-overlay bounds)
732 (overlay-put (setq el-search-hl-overlay (apply #'make-overlay bounds))
733 'face 'el-search-match))
734 (overlay-put el-search-hl-overlay 'priority 1002))
735 (add-hook 'post-command-hook #'el-search-hl-post-command-fun t t))
736
737 (defun el-search--hl-other-matches-1 (pattern from to)
738 (mapc #'delete-overlay el-search-hl-other-overlays)
739 (setq el-search-hl-other-overlays '())
740 (let ((matcher (el-search--matcher pattern))
741 this-match-beg this-match-end
742 (done nil))
743 (save-excursion
744 (goto-char from)
745 (while (not done)
746 (setq this-match-beg (el-search--search-pattern-1 matcher t))
747 (if (not this-match-beg)
748 (setq done t)
749 (goto-char this-match-beg)
750 (setq this-match-end (el-search--end-of-sexp))
751 (let ((ov (make-overlay this-match-beg this-match-end)))
752 (overlay-put ov 'face 'el-search-other-match)
753 (overlay-put ov 'priority 1001)
754 (push ov el-search-hl-other-overlays)
755 (goto-char this-match-end)
756 (when (>= (point) to) (setq done t))))))))
757
758 (defun el-search-hl-other-matches (pattern)
759 "Highlight all matches visible in the selected window."
760 (el-search--hl-other-matches-1 pattern
761 (save-excursion
762 (goto-char (window-start))
763 (beginning-of-defun-raw)
764 (point))
765 (window-end))
766 (add-hook 'window-scroll-functions #'el-search--after-scroll t t))
767
768 (defun el-search--after-scroll (_win start)
769 (el-search--hl-other-matches-1 el-search-current-pattern
770 (save-excursion
771 (goto-char start)
772 (beginning-of-defun-raw)
773 (point))
774 (window-end nil t)))
775
776 (defun el-search-hl-remove ()
777 (when (overlayp el-search-hl-overlay)
778 (delete-overlay el-search-hl-overlay))
779 (remove-hook 'window-scroll-functions #'el-search--after-scroll t)
780 (mapc #'delete-overlay el-search-hl-other-overlays)
781 (setq el-search-hl-other-overlays '()))
782
783 (defun el-search-hl-post-command-fun ()
784 (unless (or el-search-keep-hl
785 (eq this-command 'el-search-query-replace)
786 (eq this-command 'el-search-pattern))
787 (el-search-hl-remove)
788 (remove-hook 'post-command-hook 'el-search-hl-post-command-fun t)))
789
790
791 ;;;; Core functions
792
793 (defvar el-search-history '()
794 "List of input strings.")
795
796 (defvar el-search-success nil)
797 (defvar el-search-current-pattern nil)
798
799 ;;;###autoload
800 (defun el-search-pattern (pattern)
801 "Start new or resume last elisp search.
802
803 Search current buffer for expressions that are matched by `pcase'
804 PATTERN. Use `read' to transform buffer contents into
805 expressions.
806
807
808 Additional `pcase' pattern types to be used with this command can
809 be defined with `el-search-defpattern'.
810
811 The following additional pattern types are currently defined:"
812 (interactive (list (if (and (eq this-command last-command)
813 el-search-success)
814 el-search-current-pattern
815 (let ((pattern
816 (el-search--read-pattern "Find pcase pattern: "
817 (car el-search-history)
818 t)))
819 ;; A very common mistake: input "foo" instead of "'foo"
820 (when (and (symbolp pattern)
821 (not (eq pattern '_))
822 (or (not (boundp pattern))
823 (not (eq (symbol-value pattern) pattern))))
824 (error "Please don't forget the quote when searching for a symbol"))
825 (el-search--wrap-pattern pattern)))))
826 (setq this-command 'el-search-pattern) ;in case we come from isearch
827 (setq el-search-current-pattern pattern)
828 (let ((opoint (point)))
829 (when (and (eq this-command last-command) el-search-success)
830 (el-search--skip-expression nil t))
831 (setq el-search-success nil)
832 (when (condition-case nil
833 (el-search--search-pattern pattern)
834 (end-of-buffer (message "No match")
835 (goto-char opoint)
836 (el-search-hl-remove)
837 (ding)
838 nil))
839 (setq el-search-success t)
840 (el-search-hl-sexp)
841 (unless (eq this-command last-command)
842 (el-search-hl-other-matches pattern)))))
843
844 (defvar el-search-search-and-replace-help-string
845 "\
846 y Replace this match and move to the next.
847 SPC or n Skip this match and move to the next.
848 r Replace this match but don't move.
849 ! Replace all remaining matches automatically.
850 q Quit. To resume, use e.g. `repeat-complex-command'.
851 ? Show this help.
852 s Toggle splicing mode. When splicing mode is
853 on (default off), the replacement expression must
854 evaluate to a list, and the result is spliced into the
855 buffer, instead of just inserted.
856
857 Hit any key to proceed."
858 "Help string for ? in `el-search-query-replace'.")
859
860 (defun el-search-search-and-replace-pattern (pattern replacement &optional mapping splice)
861 (let ((replace-all nil) (nbr-replaced 0) (nbr-skipped 0) (done nil)
862 (el-search-keep-hl t) (opoint (point))
863 (get-replacement (el-search--matcher pattern replacement)))
864 (unwind-protect
865 (while (and (not done) (el-search--search-pattern pattern t))
866 (setq opoint (point))
867 (unless replace-all
868 (el-search-hl-sexp)
869 (unless (eq this-command last-command)
870 (el-search-hl-other-matches pattern)))
871 (let* ((read-mapping (el-search--create-read-map))
872 (region (list (point) (el-search--end-of-sexp)))
873 (substring (apply #'buffer-substring-no-properties region))
874 (expr (read substring))
875 (replaced-this nil)
876 (new-expr (funcall get-replacement expr))
877 (get-replacement-string
878 (lambda () (if (and splice (not (listp new-expr)))
879 (error "Expression to splice in is an atom")
880 (el-search--repair-replacement-layout
881 (if splice
882 (mapconcat #'el-search--print new-expr " ")
883 (el-search--print new-expr))
884 (append mapping read-mapping)))))
885 (to-insert (funcall get-replacement-string))
886 (do-replace (lambda ()
887 (atomic-change-group
888 (apply #'delete-region region)
889 (let ((inhibit-message t)
890 (opoint (point)))
891 (insert to-insert)
892 (indent-region opoint (point))
893 (el-search-hl-sexp (list opoint (point)))
894 (goto-char opoint)))
895 (cl-incf nbr-replaced)
896 (setq replaced-this t))))
897 (if replace-all
898 (funcall do-replace)
899 (while (not (pcase (if replaced-this
900 (read-char-choice "[SPC ! q] (? for help)"
901 '(?\ ?! ?q ?n ??))
902 (read-char-choice
903 (concat "Replace this occurrence"
904 (if (or (string-match-p "\n" to-insert)
905 (< 40 (length to-insert)))
906 "" (format " with `%s'" to-insert))
907 "? "
908 (if splice "{splice} " "")
909 "[y SPC r ! s q] (? for help)" )
910 '(?y ?n ?r ?\ ?! ?q ?s ??)))
911 (?r (funcall do-replace)
912 nil)
913 (?y (funcall do-replace)
914 t)
915 ((or ?\ ?n)
916 (unless replaced-this (cl-incf nbr-skipped))
917 t)
918 (?! (unless replaced-this
919 (funcall do-replace))
920 (setq replace-all t)
921 t)
922 (?s (cl-callf not splice)
923 (setq to-insert (funcall get-replacement-string))
924 nil)
925 (?q (setq done t)
926 t)
927 (?? (ignore (read-char el-search-search-and-replace-help-string))
928 nil)))))
929 (unless (or done (eobp)) (el-search--skip-expression nil t)))))
930 (el-search-hl-remove)
931 (goto-char opoint)
932 (message "Replaced %d matches%s"
933 nbr-replaced
934 (if (zerop nbr-skipped) ""
935 (format " (%d skipped)" nbr-skipped)))))
936
937 (defun el-search-query-replace-read-args ()
938 (barf-if-buffer-read-only)
939 (let* ((from (el-search--read-pattern "Replace from: "))
940 (to (let ((el-search--initial-mb-contents nil))
941 (el-search--read-pattern "Replace with result of evaluation of: " from))))
942 (list (el-search--wrap-pattern (read from)) (read to)
943 (with-temp-buffer
944 (insert to)
945 (el-search--create-read-map 1)))))
946
947 ;;;###autoload
948 (defun el-search-query-replace (from to &optional mapping)
949 "Replace some occurrences of FROM pattern with evaluated TO."
950 (interactive (el-search-query-replace-read-args))
951 (setq this-command 'el-search-query-replace) ;in case we come from isearch
952 (setq el-search-current-pattern from)
953 (barf-if-buffer-read-only)
954 (el-search-search-and-replace-pattern from to mapping))
955
956 (defun el-search--take-over-from-isearch (&optional goto-left-end)
957 (let ((other-end (and goto-left-end isearch-other-end))
958 (input isearch-string))
959 (isearch-exit)
960 (when (and other-end (< other-end (point)))
961 (goto-char other-end))
962 input))
963
964 ;;;###autoload
965 (defun el-search-search-from-isearch ()
966 ;; FIXME: an interesting alternative would be to really integrate it
967 ;; with Isearch, using `isearch-search-fun-function'.
968 ;; Alas, this is not trivial if we want to transfer our optimizations.
969 (interactive)
970 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch))))
971 ;; use `call-interactively' so we get recorded in `extended-command-history'
972 (call-interactively #'el-search-pattern)))
973
974 ;;;###autoload
975 (defun el-search-replace-from-isearch ()
976 (interactive)
977 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch t))))
978 (call-interactively #'el-search-query-replace)))
979
980
981
982 (provide 'el-search)
983 ;;; el-search.el ends here