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