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