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