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