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