1 ;;; el-search.el --- Expression based incremental search for emacs-lisp-mode -*- lexical-binding: t -*-
3 ;; Copyright (C) 2015 Free Software Foundation, Inc
5 ;; Author: Michael Heerdegen <michael_heerdegen@web.de>
6 ;; Maintainer: Michael Heerdegen <michael_heerdegen@web.de>
7 ;; Created: 29 Jul 2015
9 ;; Compatibility: GNU Emacs 25
11 ;; Package-Requires: ((emacs "25"))
14 ;; This file is not part of GNU Emacs.
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.
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.
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/>.
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).
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.
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.
53 ;; Example 1: if you enter
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
63 ;; Example 2: If you enter the pattern
67 ;; you search for all defvar forms that don't specify an init value.
69 ;; The following will search for defvar forms with a docstring whose
70 ;; first line is longer than 70 characters:
73 ;; ,(and s (guard (< 70 (length (car (split-string s "\n")))))))
76 ;; When a search pattern is processed, the searched buffer is current
77 ;; with point at the beginning of the currently tested expression.
83 ;; For pattern input, the minibuffer is put into `emacs-lisp-mode'.
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'.
92 ;; If you want to search a buffer for symbols that are defined in
93 ;; "cl-lib", you can use this pattern
95 ;; (guard (and (symbolp exp)
96 ;; (when-let ((file (symbol-file exp)))
97 ;; (string-match-p "cl-lib\\.elc?$" file))))
100 ;; ,----------------------------------------------------------------------
101 ;; | Q: "But I hate `pcase'! Can't we just do without?" |
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 ;; `----------------------------------------------------------------------
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.
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.
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',
131 ;; (foo 'a (* 2 (+ 3 4)) t)
135 ;; (foo (* 2 (+ 3 4)) 'a t).
139 ;; M-x el-search-query-replace RET
140 ;; `(foo ,a ,b . ,rest) RET
141 ;; `(foo ,b ,a . ,rest) RET
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
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.
156 ;; Suggested key bindings
157 ;; ======================
159 ;; (define-key emacs-lisp-mode-map [(control ?S)] #'el-search-pattern)
160 ;; (define-key emacs-lisp-mode-map [(control ?%)] #'el-search-query-replace)
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)
165 ;; The bindings in `isearch-mode-map' let you conveniently switch to
166 ;; "el-search" searching from isearch.
169 ;; Bugs, Known Limitations
170 ;; =======================
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.
176 ;; - Similarly: Comments are normally preserved (where it makes
177 ;; sense). But when replacing like `(foo ,a ,b) -> `(foo ,b ,a)
186 ;; the comment will be lost.
188 ;; FIXME: when we have resumable sessions, pause and warn about this case.
194 ;; Thanks to Stefan Monnier for corrections and advice.
199 ;; - implement backward searching
201 ;; - Make `el-search-pattern' accept an &optional limit, at least for
202 ;; the non-interactive use case?
204 ;; - improve docstrings
206 ;; - handle more reader syntaxes, e.g. #n, #n#
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.
224 (require 'elisp-mode)
226 (require 'help-fns) ;el-search--make-docstring
229 ;;;; Configuration stuff
231 (defgroup el-search nil
232 "Expression based search and replace for `emacs-lisp-mode'."
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
240 `(and ,el-search-this-expression-identifier ,pattern)
242 The default value is `exp'."
245 (defface el-search-match '((((background dark)) (:background "#0000A0"))
246 (t (:background "DarkSlateGray3")))
247 "Face for highlighting the current match.")
249 (defface el-search-other-match '((((background dark)) (:background "#202060"))
250 (t (:background "DarkSlateGray1")))
251 "Face for highlighting the other matches.")
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.
261 If nil, the value of `case-fold-search' is decisive."
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).
276 is then equivalent to
280 When this option is off, the first form would just signal an
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)))
293 (string-match-p regexp string)))
295 (defun el-search--pp-to-string (expr)
296 (let ((print-length nil)
298 (pp-to-string expr)))
300 (defvar el-search-read-expression-map
301 (let ((map (make-sparse-keymap)))
302 (set-keymap-parent map read-expression-map)
303 (define-key map [(control ?g)] #'abort-recursive-edit)
304 (define-key map [up] nil)
305 (define-key map [down] nil)
306 (define-key map [(control meta backspace)] #'backward-kill-sexp)
307 (define-key map [(control ?S)] #'exit-minibuffer)
309 "Map for reading input with `el-search-read-expression'.")
311 (defun el-search--setup-minibuffer ()
313 (use-local-map el-search-read-expression-map)
314 (setq font-lock-mode t)
315 (funcall font-lock-function 1)
316 (goto-char (minibuffer-prompt-end))
317 (when (looking-at ".*\n")
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)))))))
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)))
335 (defvar el-search-history '()
336 "List of search input strings.")
338 (defvar el-search-query-replace-history '()
339 "List of input strings from `el-search-query-replace'.")
341 (defvar el-search--initial-mb-contents nil)
343 (defun el-search--read-pattern (prompt &optional default read histvar)
344 (cl-callf or histvar 'el-search-history)
345 (let ((input (el-search-read-expression
346 prompt el-search--initial-mb-contents histvar default read)))
347 (if (or read (not (string= input ""))) input (car (symbol-value histvar)))))
349 (defun el-search--end-of-sexp ()
350 ;;Point must be at sexp beginning
351 (or (scan-sexps (point) 1) (point-max)))
353 (defun el-search--ensure-sexp-start ()
354 "Move point to the next sexp beginning position.
355 Don't move if already at beginning of a sexp. Point must not be
356 inside a string or comment. `read' the expression at that point
358 ;; This doesn't catch end-of-buffer to keep the return value non-ambiguous
359 (let ((not-done t) res)
361 (let ((stop-here nil)
362 (looking-at-from-back (lambda (regexp n)
366 (looking-at regexp))))))
367 (while (not stop-here)
369 ((eobp) (signal 'end-of-buffer nil))
370 ((looking-at (rx (and (* space) ";"))) (forward-line))
371 ((looking-at (rx (+ (or space "\n")))) (goto-char (match-end 0)))
373 ;; FIXME: can the rest be done more generically?
374 ((and (looking-at (rx (or (syntax symbol) (syntax word))))
375 (not (looking-at "\\_<"))
376 (not (funcall looking-at-from-back ",@" 2)))
378 ((or (and (looking-at "'") (funcall looking-at-from-back "#" 1))
379 (and (looking-at "@") (funcall looking-at-from-back "," 1)))
381 (t (setq stop-here t)))))
384 (setq res (save-excursion (read (current-buffer))))
386 (error (forward-char))))
389 (defvar el-search--pcase-macros '()
390 "List of additional \"el-search\" pcase macros.")
392 (defun el-search--make-docstring ()
393 ;; code mainly from `pcase--make-docstring'
394 (let* ((main (documentation (symbol-function 'el-search-pattern) 'raw))
395 (ud (help-split-fundoc main 'pcase)))
397 (insert (or (cdr ud) main))
399 (pcase-lambda (`(,symbol . ,fun))
400 (when-let ((doc (documentation fun)))
402 (setq doc (help-fns--signature symbol doc fun fun nil))
403 (insert "\n" (or doc "Not documented."))))
404 (reverse el-search--pcase-macros))
405 (let ((combined-doc (buffer-string)))
406 (if ud (help-add-fundoc-usage combined-doc (car ud)) combined-doc)))))
408 (put 'el-search-pattern 'function-documentation '(el-search--make-docstring))
410 (defmacro el-search-defpattern (name args &rest body)
411 "Like `pcase-defmacro', but limited to el-search patterns.
412 The semantics is exactly that of `pcase-defmacro', but the scope
413 of the definitions is limited to \"el-search\"."
414 (declare (indent 2) (debug defun))
415 `(setf (alist-get ',name el-search--pcase-macros)
416 (lambda ,args ,@body)))
418 (defun el-search--macroexpand-1 (pattern)
419 "Expand \"el-search\" PATTERN.
420 This is like `pcase--macroexpand', but expands only patterns
421 defined with `el-search-defpattern' and performs only one
424 Return PATTERN if this pattern type was not defined with
425 `el-search-defpattern'."
426 (if-let ((expander (alist-get (car-safe pattern) el-search--pcase-macros)))
427 (apply expander (cdr pattern))
430 (defmacro el-search--with-additional-pcase-macros (&rest body)
431 `(cl-letf ,(mapcar (pcase-lambda (`(,symbol . ,fun))
432 `((get ',symbol 'pcase-macroexpander) #',fun))
433 el-search--pcase-macros)
436 (defun el-search--matcher (pattern &rest body)
437 (eval ;use `eval' to allow for user defined pattern types at run time
438 (let ((expression (make-symbol "expression")))
439 `(el-search--with-additional-pcase-macros
440 (let ((byte-compile-debug t) ;make undefined pattern types raise an error
441 (warning-suppress-log-types '((bytecomp)))
442 (pcase--dontwarn-upats (cons '_ pcase--dontwarn-upats)))
443 (byte-compile (lambda (,expression)
445 (,pattern ,@(or body (list t)))
448 (defun el-search--match-p (matcher expression)
449 (funcall matcher expression))
451 (defun el-search--wrap-pattern (pattern)
452 `(and ,el-search-this-expression-identifier ,pattern))
454 (defun el-search--skip-expression (expression &optional read)
455 ;; Move forward at least one character. Don't move into a string or
456 ;; comment. Don't move further than the beginning of the next sexp.
457 ;; Try to move as far as possible. Point must be at the beginning
459 ;; If there are positions where `read' would succeed, but that do
460 ;; not represent a valid sexp start, move past them (e.g. when
461 ;; before "#'" move past both characters).
463 ;; EXPRESSION must be the (read) expression at point, but when READ
464 ;; is non-nil, ignore the first argument and read the expression at
466 (when read (setq expression (save-excursion (read (current-buffer)))))
468 ((or (null expression)
469 (equal [] expression)
470 (not (or (listp expression) (vectorp expression))))
471 (goto-char (el-search--end-of-sexp)))
472 ((looking-at (rx (or ",@" "," "#'" "'")))
473 (goto-char (match-end 0)))
476 (defun el-search--search-pattern-1 (matcher &optional noerror)
477 (let ((match-beg nil) (opoint (point)) current-expr)
479 ;; when inside a string or comment, move past it
480 (let ((syntax-here (syntax-ppss)))
481 (when (nth 3 syntax-here) ;inside a string
482 (goto-char (nth 8 syntax-here))
484 (when (nth 4 syntax-here) ;inside a comment
486 (while (and (not (eobp)) (looking-at (rx (and (* space) ";"))))
490 (while (not match-beg)
492 (setq current-expr (el-search--ensure-sexp-start))
495 (throw 'no-match t)))
496 (if (el-search--match-p matcher current-expr)
497 (setq match-beg (point)
499 (el-search--skip-expression current-expr))))
500 (if noerror nil (signal 'end-of-buffer nil)))
503 (defun el-search--search-pattern (pattern &optional noerror)
504 "Search elisp buffer with `pcase' PATTERN.
505 Set point to the beginning of the occurrence found and return
506 point. Optional second argument, if non-nil, means if fail just
507 return nil (no error)."
508 (el-search--search-pattern-1 (el-search--matcher pattern) noerror))
510 (defun el-search--format-replacement (replacement original replace-expr-input splice)
511 ;; Return a printed representation of REPLACEMENT. Try to reuse the
512 ;; layout of subexpressions shared with the original (replaced)
513 ;; expression and the replace expression.
514 (if (and splice (not (listp replacement)))
515 (error "Expression to splice in is an atom")
516 (let ((orig-buffer (generate-new-buffer "orig-expr")))
517 (with-current-buffer orig-buffer
520 (when replace-expr-input (insert "\n\n" replace-expr-input)))
525 (mapconcat #'el-search--pp-to-string replacement " ")
526 (el-search--pp-to-string replacement)))
528 (let (start this-sexp end orig-match-start orig-match-end done)
529 (while (and (< (point) (point-max))
533 this-sexp (read (current-buffer))
536 (end-of-buffer nil)))
537 (setq done nil orig-match-start nil)
538 (with-current-buffer orig-buffer
540 (if (el-search--search-pattern `',this-sexp t)
541 (setq orig-match-start (point)
542 orig-match-end (progn (forward-sexp) (point)))
544 ;; find out whether we have a sequence of equal expressions
545 (while (and (not done)
547 (progn (setq this-sexp (read (current-buffer))) t)
548 ((invalid-read-syntax end-of-buffer end-of-file) nil)))
549 (if (with-current-buffer orig-buffer
551 (if (not (equal this-sexp (read (current-buffer))))
553 (setq orig-match-end (point))
555 ((invalid-read-syntax end-of-buffer end-of-file) nil)))
559 (let ((match (with-current-buffer orig-buffer
560 (buffer-substring-no-properties orig-match-start
562 (delete-region start end)
564 (when (string-match-p "\n" match)
565 (unless (looking-back "^[[:space:]\(]*" (line-beginning-position))
567 (unless (looking-at "[[:space:]\)]*$")
572 (el-search--skip-expression nil t))
574 (el-search--ensure-sexp-start)
575 (end-of-buffer (goto-char (point-max))))))
576 (delete-trailing-whitespace (point-min) (point-max)) ;FIXME: this should not be necessary
577 (let ((result (buffer-substring (point-min) (point-max))))
578 (if (equal replacement (read result))
580 (error "Error in `el-search--format-replacement' - please make a bug report"))))
581 (kill-buffer orig-buffer)))))
583 (defun el-search--check-pattern-args (type args predicate &optional message)
584 "Check whether all ARGS fulfill PREDICATE.
585 Raise an error if not. The string arguments TYPE and optional
586 MESSAGE are used to construct the error message."
588 (unless (funcall predicate arg)
589 (error (concat "Pattern `%s': "
590 (or message (format "argument doesn't fulfill %S" predicate))
595 (defvar el-search-current-pattern nil)
597 (defvar el-search-success nil)
600 ;;;; Additional pattern type definitions
602 (defun el-search--split (matcher1 matcher2 list)
603 "Helper for the append pattern type.
605 When a splitting of LIST into two lists L1, L2 exist so that Li
606 is matched by MATCHERi, return (L1 L2) for such Li, else return
608 (let ((try-match (lambda (list1 list2)
609 (when (and (el-search--match-p matcher1 list1)
610 (el-search--match-p matcher2 list2))
611 (list list1 list2))))
612 (list1 list) (list2 '()) (match nil))
613 ;; don't use recursion, this could hit `max-lisp-eval-depth'
614 (while (and (not (setq match (funcall try-match list1 list2)))
616 (let ((last-list1 (last list1)))
617 (if-let ((cdr-last-list1 (cdr last-list1)))
618 ;; list1 is a dotted list. Then list2 must be empty.
619 (progn (setcdr last-list1 nil)
620 (setq list2 cdr-last-list1))
621 (setq list1 (butlast list1 1)
622 list2 (cons (car last-list1) list2)))))
625 (el-search-defpattern append (&rest patterns)
626 "Matches any list factorable into lists matched by PATTERNS in order.
628 PATTERNS is a list of patterns P1..Pn. Match any list L for that
629 lists L1..Ln exist that are matched by P1..Pn in order and L is
630 equal to the concatenation of L1..Ln. Ln is allowed to be no
633 When different ways of matching are possible, it is unspecified
638 (append '(1 2 3) x (app car-safe 7))
640 matches the list (1 2 3 4 5 6 7 8 9) and binds `x' to (4 5 6)."
643 (pcase-let ((`(,pattern . ,more-patterns) patterns))
645 ((null more-patterns) pattern)
646 ((null (cdr more-patterns))
648 (app ,(apply-partially #'el-search--split
649 (el-search--matcher pattern)
650 (el-search--matcher (car more-patterns)))
651 (,'\` ((,'\, ,pattern)
652 (,'\, ,(car more-patterns)))))))
653 (t `(append ,pattern (append ,@more-patterns)))))))
655 (defun el-search--stringish-p (thing)
656 (or (stringp thing) (and el-search-use-sloppy-strings (symbolp thing))))
658 (el-search-defpattern string (&rest regexps)
659 "Matches any string that is matched by all REGEXPS."
660 (el-search--check-pattern-args "string" regexps #'el-search--stringish-p
661 "Argument not a string")
663 ,@(mapcar (lambda (thing) `(pred (el-search--smart-string-match-p
664 ,(if (symbolp thing) (symbol-name thing) thing))))
667 (el-search-defpattern symbol (&rest regexps)
668 "Matches any symbol whose name is matched by all REGEXPS."
669 (el-search--check-pattern-args "symbol" regexps #'el-search--stringish-p
670 "Argument not a string")
672 (app symbol-name (string ,@regexps))))
674 (defun el-search--contains-p (matcher exp)
675 "Return non-nil when tree EXP contains a match for MATCHER.
676 Recurse on all types of sequences. In the positive case the
677 return value is (t elt), where ELT is a matching element found in
679 (if (el-search--match-p matcher exp)
682 (let ((try-match (apply-partially #'el-search--contains-p matcher)))
684 (or (funcall try-match (car exp))
685 (funcall try-match (cdr exp)))
686 (cl-some try-match exp))))))
688 (el-search-defpattern contains (&rest patterns)
689 "Matches trees that contain a match for all PATTERNs.
690 Searches any tree of sequences recursively for matches. Objects
691 of any kind matched by all PATTERNs are also matched.
693 Example: (contains (string \"H\") 17) matches ((\"Hallo\") x (5 [1 17]))"
696 ((null (cdr patterns))
697 (let ((pattern (car patterns)))
698 `(app ,(apply-partially #'el-search--contains-p (el-search--matcher pattern))
699 (,'\` (t (,'\, ,pattern))))))
700 (t `(and ,@(mapcar (lambda (pattern) `(contains ,pattern)) patterns)))))
702 (el-search-defpattern not (pattern)
703 "Matches any object that is not matched by PATTERN."
704 `(app ,(apply-partially #'el-search--match-p (el-search--matcher pattern))
707 (defun el-search--match-symbol-file (regexp symbol)
708 (when-let ((symbol-file (and (symbolp symbol)
709 (symbol-file symbol))))
710 (el-search--smart-string-match-p
711 (if (symbolp regexp) (concat "\\`" (symbol-name regexp) "\\'") regexp)
712 (file-name-sans-extension (file-name-nondirectory symbol-file)))))
714 (el-search-defpattern source (regexp)
715 "Matches any symbol whose `symbol-file' is matched by REGEXP.
717 This pattern matches when the object is a symbol for that
718 `symbol-file' returns a (non-nil) FILE-NAME that fulfills
719 (string-match-p REGEXP (file-name-sans-extension
720 (file-name-nondirectory FILENAME)))
722 REGEXP can also be a symbol, in which case
724 (concat \"^\" (symbol-name regexp) \"$\")
726 is used as regular expression."
727 (el-search--check-pattern-args "source" (list regexp) #'el-search--stringish-p
728 "Argument not a string")
729 `(pred (el-search--match-symbol-file ,(if (symbolp regexp) (symbol-name regexp) regexp))))
731 (defun el-search--match-key-sequence (keys expr)
732 (when-let ((expr-keys (pcase expr
733 ((or (pred stringp) (pred vectorp)) expr)
734 (`(kbd ,(and (pred stringp) string)) (ignore-errors (kbd string))))))
736 (mapcar (lambda (keys) (ignore-errors (key-description keys)))
737 (list keys expr-keys)))))
739 (el-search-defpattern keys (key-sequence)
740 "Matches descriptions of the KEY-SEQUENCE.
741 KEY-SEQUENCE is a string or vector representing a key sequence,
742 or an expression of the form (kbd STRING).
744 Match any description of the same key sequence in any of these
751 matches any of these expressions:
757 (when (eq (car-safe key-sequence) 'kbd)
758 (setq key-sequence (kbd (cadr key-sequence))))
759 (el-search--check-pattern-args "keys" (list key-sequence) (lambda (x) (or (stringp x) (vectorp x)))
760 "argument not a string or vector")
761 `(pred (el-search--match-key-sequence ,key-sequence)))
763 (defun el-search--transform-nontrivial-lpat (expr)
765 ((symbolp expr) `(or (symbol ,(symbol-name expr))
766 (,'\` (,'quote (,'\, (symbol ,(symbol-name expr)))))
767 (,'\` (,'function (,'\, (symbol ,(symbol-name expr)))))))
768 ((stringp expr) `(string ,expr))
771 (el-search-defpattern l (&rest lpats)
772 "Alternative pattern type for matching lists.
773 Match any list with subsequent elements matched by all LPATS in
776 The idea is to be able to search for pieces of code (i.e. lists)
777 with very brief input by using a specialized syntax.
779 An LPAT can take the following forms:
781 SYMBOL Matches any symbol S matched by SYMBOL's name interpreted
782 as a regexp. Matches also 'S and #'S for any such S.
783 STRING Matches any string matched by STRING interpreted as a
785 _ Matches any list element
786 __ Matches any number of list elements (including zero)
787 ^ Matches zero elements, but only at the beginning of a list
788 $ Matches zero elements, but only at the end of a list
789 PAT Anything else is interpreted as a normal pcase pattern, and
790 matches one list element matched by it
792 ^ is only valid as the first, $ as the last of the LPATS.
794 Example: To match defuns that contain \"hl\" in their name and
795 have at least one mandatory, but also optional arguments, you
796 could use this pattern:
798 (l ^ 'defun hl (l _ &optional))"
799 (let ((match-start nil) (match-end nil))
800 (when (eq (car-safe lpats) '^)
802 (cl-callf cdr lpats))
803 (when (eq (car-safe (last lpats)) '$)
805 (cl-callf butlast lpats 1))
806 `(append ,@(if match-start '() '(_))
812 ('_? '(or '() `(,_))) ;FIXME: useful - document? or should we provide a (? PAT)
814 (_ `(,'\` ((,'\, ,(el-search--transform-nontrivial-lpat elt)))))))
816 ,@(if match-end '() '(_)))))
818 (el-search-defpattern char-prop (property)
819 "Matches the object if completely covered with PROPERTY.
820 This pattern matches the object if its representation in the
821 search buffer is completely covered with the character property
824 This pattern always tests the complete expression in the search
825 buffer, it is not possible to test subexpressions calculated in
827 `(guard (and (get-char-property (point) ',property)
828 ,(macroexp-let2 nil limit '(scan-sexps (point) 1)
829 `(= (next-single-char-property-change
830 (point) ',property nil ,limit)
833 (el-search-defpattern includes-prop (property)
834 "Matches the object if partly covered with PROPERTY.
835 This pattern matches the object if its representation in the
836 search buffer is partly covered with the character property
839 This pattern always tests the complete expression in the search
840 buffer, it is not possible to test subexpressions calculated in
842 `(guard (or (get-char-property (point) ',property)
843 ,(macroexp-let2 nil limit '(scan-sexps (point) 1)
844 `(not (= (next-single-char-property-change
845 (point) ',property nil ,limit)
848 (el-search-defpattern change ()
849 "Matches the object if it is part of a change.
850 This is equivalent to (char-prop diff-hl-hunk).
852 You need `diff-hl-mode' turned on, provided by the library
853 \"diff-hl\" available in Gnu Elpa."
854 (or (bound-and-true-p diff-hl-mode)
855 (error "diff-hl-mode not enabled"))
856 '(char-prop diff-hl-hunk))
858 (el-search-defpattern changed ()
859 "Matches the object if it contains a change.
860 This is equivalent to (includes-prop diff-hl-hunk).
862 You need `diff-hl-mode' turned on, provided by the library
863 \"diff-hl\" available in Gnu Elpa."
864 (or (bound-and-true-p diff-hl-mode)
865 (error "diff-hl-mode not enabled"))
866 '(includes-prop diff-hl-hunk))
871 (defvar-local el-search-hl-overlay nil)
873 (defvar-local el-search-hl-other-overlays '())
875 (defvar el-search-keep-hl nil)
877 (defun el-search-hl-sexp (&optional bounds)
878 (let ((bounds (or bounds
879 (list (point) (el-search--end-of-sexp)))))
880 (if (overlayp el-search-hl-overlay)
881 (apply #'move-overlay el-search-hl-overlay bounds)
882 (overlay-put (setq el-search-hl-overlay (apply #'make-overlay bounds))
883 'face 'el-search-match))
884 (overlay-put el-search-hl-overlay 'priority 1002))
885 (add-hook 'post-command-hook #'el-search-hl-post-command-fun t t))
887 (defun el-search--hl-other-matches-1 (pattern from to)
888 (mapc #'delete-overlay el-search-hl-other-overlays)
889 (setq el-search-hl-other-overlays '())
890 (let ((matcher (el-search--matcher pattern))
891 this-match-beg this-match-end
896 (setq this-match-beg (el-search--search-pattern-1 matcher t))
897 (if (not this-match-beg)
899 (goto-char this-match-beg)
900 (setq this-match-end (el-search--end-of-sexp))
901 (let ((ov (make-overlay this-match-beg this-match-end)))
902 (overlay-put ov 'face 'el-search-other-match)
903 (overlay-put ov 'priority 1001)
904 (push ov el-search-hl-other-overlays)
905 (goto-char this-match-end)
906 (when (>= (point) to) (setq done t))))))))
908 (defun el-search-hl-other-matches (pattern)
909 "Highlight all matches visible in the selected window."
910 (el-search--hl-other-matches-1 pattern
912 (goto-char (window-start))
913 (beginning-of-defun-raw)
916 (add-hook 'window-scroll-functions #'el-search--after-scroll t t))
918 (defun el-search--after-scroll (_win start)
919 (el-search--hl-other-matches-1 el-search-current-pattern
922 (beginning-of-defun-raw)
926 (defun el-search-hl-remove ()
927 (when (overlayp el-search-hl-overlay)
928 (delete-overlay el-search-hl-overlay))
929 (remove-hook 'window-scroll-functions #'el-search--after-scroll t)
930 (mapc #'delete-overlay el-search-hl-other-overlays)
931 (setq el-search-hl-other-overlays '()))
933 (defun el-search-hl-post-command-fun ()
934 (unless (or el-search-keep-hl
935 (eq this-command 'el-search-query-replace)
936 (eq this-command 'el-search-pattern))
937 (el-search-hl-remove)
938 (remove-hook 'post-command-hook 'el-search-hl-post-command-fun t)))
944 (defun el-search-pattern (pattern &optional no-error)
945 "Start new or resume last elisp search.
947 Search current buffer for expressions that are matched by `pcase'
948 PATTERN. Use `read' to transform buffer contents into
952 Additional `pcase' pattern types to be used with this command can
953 be defined with `el-search-defpattern'.
955 The following additional pattern types are currently defined:"
956 (interactive (list (if (and (eq this-command last-command)
958 el-search-current-pattern
960 (el-search--read-pattern "Find pcase pattern: "
961 (car el-search-history)
963 ;; A very common mistake: input "foo" instead of "'foo"
964 (when (and (symbolp pattern)
965 (not (eq pattern '_))
966 (or (not (boundp pattern))
967 (not (eq (symbol-value pattern) pattern))))
968 (error "Please don't forget the quote when searching for a symbol"))
969 (el-search--wrap-pattern pattern)))))
970 (if (not (called-interactively-p 'any))
971 (el-search--search-pattern pattern no-error)
972 (setq this-command 'el-search-pattern) ;in case we come from isearch
973 (setq el-search-current-pattern pattern)
974 (let ((opoint (point)))
975 (when (and (eq this-command last-command) el-search-success)
976 (el-search--skip-expression nil t))
977 (setq el-search-success nil)
978 (when (condition-case nil
979 (el-search--search-pattern pattern)
980 (end-of-buffer (message "No match")
982 (el-search-hl-remove)
985 (setq el-search-success t)
987 (unless (eq this-command last-command)
988 (el-search-hl-other-matches pattern))))))
990 (defvar el-search-search-and-replace-help-string
992 y Replace this match and move to the next.
993 SPC or n Skip this match and move to the next.
994 r Replace this match but don't move.
995 ! Replace all remaining matches automatically.
996 q Quit. To resume, use e.g. `repeat-complex-command'.
998 s Toggle splicing mode. When splicing mode is
999 on (default off), the replacement expression must
1000 evaluate to a list, and the result is spliced into the
1001 buffer, instead of just inserted.
1003 Hit any key to proceed."
1004 "Help string for ? in `el-search-query-replace'.")
1006 (defun el-search--search-and-replace-pattern (pattern replacement &optional splice to-input-string)
1007 (let ((replace-all nil) (nbr-replaced 0) (nbr-skipped 0) (done nil)
1008 (el-search-keep-hl t) (opoint (point))
1009 (get-replacement (el-search--matcher pattern replacement))
1010 (skip-matches-in-replacement 'ask))
1012 (while (and (not done) (el-search--search-pattern pattern t))
1013 (setq opoint (point))
1016 (unless (eq this-command last-command)
1017 (el-search-hl-other-matches pattern)))
1018 (let* ((region (list (point) (el-search--end-of-sexp)))
1019 (original-text (apply #'buffer-substring-no-properties region))
1020 (expr (read original-text))
1022 (new-expr (funcall get-replacement expr))
1023 (get-replacement-string
1024 (lambda () (el-search--format-replacement new-expr original-text to-input-string splice)))
1025 (to-insert (funcall get-replacement-string))
1026 (replacement-contains-another-match
1031 (el-search--skip-expression new-expr)
1033 (progn (el-search--ensure-sexp-start)
1034 (el-search--search-pattern pattern t))
1035 (end-of-buffer nil))))
1036 (do-replace (lambda ()
1037 (atomic-change-group
1038 (apply #'delete-region region)
1039 (let ((inhibit-message t)
1042 (indent-region opoint (point))
1043 (el-search-hl-sexp (list opoint (point)))
1044 (goto-char opoint)))
1045 (cl-incf nbr-replaced)
1046 (setq replaced-this t))))
1048 (funcall do-replace)
1049 (while (not (pcase (if replaced-this
1050 (read-char-choice "[SPC ! q] (? for help)"
1051 '(?\ ?! ?q ?\C-g ?n ??))
1053 (concat "Replace this occurrence"
1054 (if (or (string-match-p "\n" to-insert)
1055 (< 40 (length to-insert)))
1056 "" (format " with `%s'" to-insert))
1058 (if splice "{splice} " "")
1059 "[y SPC r ! s q] (? for help)" )
1060 '(?y ?n ?r ?\ ?! ?q ?\C-g ?s ??)))
1061 (?r (funcall do-replace)
1063 (?y (funcall do-replace)
1066 (unless replaced-this (cl-incf nbr-skipped))
1068 (?! (unless replaced-this
1069 (funcall do-replace))
1070 (setq replace-all t)
1072 (?s (cl-callf not splice)
1073 (setq to-insert (funcall get-replacement-string))
1078 (?? (ignore (read-char el-search-search-and-replace-help-string))
1080 (unless (or done (eobp))
1082 ((not (and replaced-this replacement-contains-another-match))
1083 (el-search--skip-expression nil t))
1084 ((eq skip-matches-in-replacement 'ask)
1085 (if (setq skip-matches-in-replacement
1086 (yes-or-no-p "Match in replacement - always skip? "))
1088 (el-search--skip-expression nil t)
1090 (setq replace-all nil)
1091 (message "Falling back to interactive mode")
1093 (skip-matches-in-replacement (forward-sexp))
1095 (el-search--skip-expression nil t)
1096 (message "Replacement contains another match%s"
1097 (if replace-all " - falling back to interactive mode" ""))
1098 (setq replace-all nil)
1100 (el-search-hl-remove)
1102 (message "Replaced %d matches%s"
1104 (if (zerop nbr-skipped) ""
1105 (format " (%d skipped)" nbr-skipped)))))
1107 (defun el-search-query-replace--read-args ()
1108 (barf-if-buffer-read-only)
1109 (let ((from-input (el-search--read-pattern "Query replace pattern: " nil nil
1110 'el-search-query-replace-history))
1117 (skip-chars-forward " \t\n
\f")
1118 ;; FIXME: maybe more sanity tests here...
1119 (if (not (looking-at "->"))
1120 (setq from from-input
1121 to (let ((el-search--initial-mb-contents nil))
1122 (el-search--read-pattern "Replace with result of evaluation of: " from)))
1126 (setq from (buffer-substring 1 (point)))
1127 (skip-chars-forward " \t\n
\f")
1128 (setq to (buffer-substring (point) (progn (forward-sexp) (point))))))
1129 (unless (and el-search-query-replace-history
1130 (not (string= from from-input))
1131 (string= from-input (car el-search-query-replace-history)))
1132 (push (format "%s -> %s" from to) ;FIXME: add line break when FROM or TO is multiline?
1133 el-search-query-replace-history))
1134 (list (el-search--wrap-pattern (read from)) (read to) to)))
1137 (defun el-search-query-replace (from-pattern to-expr &optional textual-to)
1138 "Replace some matches of \"el-search\" pattern FROM-PATTERN.
1140 TO-EXPR is an Elisp expression that is evaluated repeatedly for
1141 each match with bindings created in FROM-PATTERN in effect to
1142 produce a replacement expression. Operate from point
1145 As each match is found, the user must type a character saying
1146 what to do with it. For directions, type ? at that time.
1148 As an alternative to enter FROM-PATTERN and TO-EXPR separately,
1149 you can also give an input of the form
1151 FROM-PATTERN -> TO-EXPR
1153 to the first prompt and specify both expressions at once. This
1154 format is also used for history entries."
1155 (interactive (el-search-query-replace--read-args))
1156 (setq this-command 'el-search-query-replace) ;in case we come from isearch
1157 (setq el-search-current-pattern from-pattern)
1158 (barf-if-buffer-read-only)
1159 (el-search--search-and-replace-pattern from-pattern to-expr nil textual-to))
1161 (defun el-search--take-over-from-isearch (&optional goto-left-end)
1162 (let ((other-end (and goto-left-end isearch-other-end))
1163 (input isearch-string))
1165 (when (and other-end (< other-end (point)))
1166 (goto-char other-end))
1170 (defun el-search-search-from-isearch ()
1171 ;; FIXME: an interesting alternative would be to really integrate it
1172 ;; with Isearch, using `isearch-search-fun-function'.
1173 ;; Alas, this is not trivial if we want to transfer our optimizations.
1175 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch))))
1176 ;; use `call-interactively' so we get recorded in `extended-command-history'
1177 (call-interactively #'el-search-pattern)))
1180 (defun el-search-replace-from-isearch ()
1182 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch t))))
1183 (call-interactively #'el-search-query-replace)))
1187 (provide 'el-search)
1188 ;;; el-search.el ends here