]> code.delx.au - gnu-emacs-elpa/blob - packages/el-search/el-search.el
el-search: new pattern type `append'
[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.2
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 ;; Example 3:
81 ;;
82 ;; I can be useful to use (guard EXP) patterns for side effects (note:
83 ;; this only works when applied to the top level expression).
84 ;;
85 ;; The following pattern will search for symbols defined in any
86 ;; library whose name starts with "cl". As a side effect, it prints
87 ;; the current line number, whether we have a macro or a function, and
88 ;; the defining file in the echo area for each match:
89 ;;
90 ;; (and (pred symbolp)
91 ;; (let file (symbol-file exp))
92 ;; (guard file)
93 ;; (let lib-name (file-name-sans-extension
94 ;; (file-name-nondirectory file)))
95 ;; (guard (string-match-p "^cl" lib-name))
96 ;; (or (and (pred macrop) (let type "macro "))
97 ;; (and (pred functionp) (let type "function "))
98 ;; (let type ""))
99 ;; (guard (message "Line %d: %s`%S' (from \"%s\")"
100 ;; (line-number-at-pos)
101 ;; type
102 ;; exp
103 ;; lib-name)))
104 ;;
105 ;; `message' never returns nil, so the last `guard' always "matches".
106 ;;
107 ;;
108 ;; Convenience
109 ;; ===========
110 ;;
111 ;; For pattern input, the minibuffer is put into `emacs-lisp-mode'.
112 ;;
113 ;; Any input PATTERN is silently transformed into (and exp PATTERN)
114 ;; so that you can always refer to the whole currently tested
115 ;; expression via the variable `exp'.
116 ;;
117 ;; Example 4:
118 ;;
119 ;; If you want to search a buffer for symbols that are defined in
120 ;; "cl-lib", you can use this pattern
121 ;;
122 ;; (guard (and (symbolp exp)
123 ;; (when-let ((file (symbol-file exp)))
124 ;; (string-match-p "cl-lib\\.elc?$" file))))
125 ;;
126 ;;
127 ;; ,----------------------------------------------------------------------
128 ;; | Q: "But I hate `pcase'! Can't we just do without?" |
129 ;; | |
130 ;; | A: Respect that you kept up until here! Just use (guard CODE), where|
131 ;; | CODE is any normal Elisp expression that returns non-nil when and |
132 ;; | only when you have a match. Use the variable `exp' to refer to |
133 ;; | the currently tested expression. Just like in the last example! |
134 ;; `----------------------------------------------------------------------
135 ;;
136 ;;
137 ;; It's cumbersome to write out the same complicated pattern
138 ;; constructs in the minibuffer again and again. You can define your
139 ;; own pcase pattern types for the purpose of el-search with
140 ;; `el-search-defpattern'. It is just like `pcase-defmacro', but the
141 ;; effect is limited to this package. See C-h f `el-search-pattern'
142 ;; for a list of predefined additional pattern forms.
143 ;;
144 ;;
145 ;; Replacing
146 ;; =========
147 ;;
148 ;; You can replace expressions with command `el-search-query-replace'.
149 ;; You are queried for a (pcase) pattern and a replacement expression.
150 ;; For each match of the pattern, the replacement expression is
151 ;; evaluated with the bindings created by the pcase matching in
152 ;; effect, and printed to produce the replacement string.
153 ;;
154 ;; Example: In some buffer you want to swap the two expressions at the
155 ;; places of the first two arguments in all calls of function `foo',
156 ;; so that e.g.
157 ;;
158 ;; (foo 'a (* 2 (+ 3 4)) t)
159 ;;
160 ;; becomes
161 ;;
162 ;; (foo (* 2 (+ 3 4)) 'a t).
163 ;;
164 ;; This will do it:
165 ;;
166 ;; M-x el-search-query-replace RET
167 ;; `(foo ,a ,b . ,rest) RET
168 ;; `(foo ,b ,a . ,rest) RET
169 ;;
170 ;; Type y to replace a match and go to the next one, r to replace
171 ;; without moving, SPC to go to the next match and ! to replace all
172 ;; remaining matches automatically. q quits. n is like SPC, so that
173 ;; y and n work like in isearch (meaning "yes" and "no") if you are
174 ;; used to that.
175 ;;
176 ;; It is possible to replace a match with multiple expressions using
177 ;; "splicing mode". When it is active, the replacement expression
178 ;; must evaluate to a list, and is spliced instead of inserted into
179 ;; the buffer for any replaced match. Use s to toggle splicing mode
180 ;; in a `el-search-query-replace' session.
181 ;;
182 ;;
183 ;; Suggested key bindings
184 ;; ======================
185 ;;
186 ;; (define-key emacs-lisp-mode-map [(control ?S)] #'el-search-pattern)
187 ;; (define-key emacs-lisp-mode-map [(control ?%)] #'el-search-query-replace)
188 ;;
189 ;; (define-key isearch-mode-map [(control ?S)] #'el-search-search-from-isearch)
190 ;; (define-key isearch-mode-map [(control ?%)] #'el-search-replace-from-isearch)
191 ;;
192 ;; The bindings in `isearch-mode-map' let you conveniently switch to
193 ;; elisp searching from isearch.
194 ;;
195 ;;
196 ;; Bugs, Known Limitations
197 ;; =======================
198 ;;
199 ;; - Replacing: in some cases the reader syntax of forms
200 ;; is changing due to reading+printing. "Some" because we can treat
201 ;; that problem in most cases.
202 ;;
203 ;; - Similarly: Comments are normally preserved (where it makes
204 ;; sense). But when replacing like `(foo ,a ,b) -> `(foo ,b ,a)
205 ;;
206 ;; in a content like
207 ;;
208 ;; (foo
209 ;; a
210 ;; ;;a comment
211 ;; b)
212 ;;
213 ;; the comment will be lost.
214 ;;
215 ;;
216 ;; Acknowledgments
217 ;; ===============
218 ;;
219 ;; Thanks to Stefan Monnier for corrections and advice.
220 ;;
221 ;;
222 ;; TODO:
223 ;;
224 ;; - When replacing like (progn A B C) -> A B C, the layout of the
225 ;; whole "group" A B C as a unit is lost. Instead of restoring layout
226 ;; as we do now (via "read mappings"), we could just make a backup of
227 ;; the original expression as a string, and use our search machinery
228 ;; to find occurrences in the replacement recursively.
229 ;;
230 ;; - detect infloops when replacing automatically (e.g. for 1 -> '(1))
231 ;;
232 ;; - highlight matches around point in a timer
233 ;;
234 ;; - implement backward searching
235 ;;
236 ;; - improve docstrings
237 ;;
238 ;; - handle more reader syntaxes, e.g. #n, #n#
239 ;;
240 ;; - Implement sessions; add multi-file support based on iterators. A
241 ;; file list is read in (or the user can specify an iterator as a
242 ;; variable). The state in the current buffer is just (buffer
243 ;; . marker). Or should this be abstracted into an own lib? Could
244 ;; be named "files-session" or so.
245
246
247
248 ;;; Code:
249
250 ;;;; Requirements
251
252 (eval-when-compile
253 (require 'subr-x))
254
255 (require 'cl-lib)
256 (require 'elisp-mode)
257 (require 'thingatpt)
258 (require 'help-fns) ;el-search--make-docstring
259
260
261 ;;;; Configuration stuff
262
263 (defgroup el-search nil
264 "Expression based search and replace for `emacs-lisp-mode'."
265 :group 'lisp)
266
267 (defcustom el-search-this-expression-identifier 'exp
268 "Name of the identifier referring to the current expression.
269 The default value is `exp'. You can use this name in the search
270 prompt to refer to the value of the currently tested expression."
271 :type 'symbol)
272
273 (defface el-search-match '((((background dark)) (:background "#0000A0"))
274 (t (:background "DarkSlateGray1")))
275 "Face for highlighting the current match.")
276
277
278 ;;;; Helpers
279
280 (defun el-search--print (expr)
281 (let ((print-quoted t)
282 (print-length nil)
283 (print-level nil))
284 (prin1-to-string expr)))
285
286 (defvar el-search-read-expression-map
287 (let ((map (make-sparse-keymap)))
288 (set-keymap-parent map read-expression-map)
289 (define-key map [(control ?g)] #'abort-recursive-edit)
290 (define-key map [up] nil)
291 (define-key map [down] nil)
292 (define-key map [(control meta backspace)] #'backward-kill-sexp)
293 (define-key map [(control ?S)] #'exit-minibuffer)
294 map)
295 "Map for reading input with `el-search-read-expression'.")
296
297 ;; $$$$$FIXME: this should be in Emacs! There is only a helper `read--expression'.
298 (defun el-search-read-expression (prompt &optional initial-contents hist default read)
299 "Read expression for `my-eval-expression'."
300 (minibuffer-with-setup-hook
301 (lambda ()
302 (emacs-lisp-mode)
303 (use-local-map el-search-read-expression-map)
304 (setq font-lock-mode t)
305 (funcall font-lock-function 1)
306 (backward-sexp)
307 (indent-sexp)
308 (goto-char (point-max)))
309 (read-from-minibuffer prompt initial-contents el-search-read-expression-map read
310 (or hist 'read-expression-history) default)))
311
312 (defvar el-search--initial-mb-contents nil)
313
314 (defun el-search--read-pattern (prompt &optional default read)
315 (let ((this-sexp (sexp-at-point)))
316 (minibuffer-with-setup-hook
317 (lambda ()
318 (when this-sexp
319 (let ((more-defaults (list (concat "'" (el-search--print this-sexp)))))
320 (setq-local minibuffer-default-add-function
321 (lambda () (if (listp minibuffer-default)
322 (append minibuffer-default more-defaults)
323 (cons minibuffer-default more-defaults)))))))
324 (el-search-read-expression
325 prompt el-search--initial-mb-contents 'el-search-history default read))))
326
327 (defun el-search--end-of-sexp ()
328 ;;Point must be at sexp beginning
329 (or (scan-sexps (point) 1) (point-max)))
330
331 (defun el-search--ensure-sexp-start ()
332 "Move point to the beginning of the next sexp if necessary.
333 Don't move if already at beginning of a sexp.
334 Point must not be inside a string or comment."
335 (let ((not-done t) res)
336 (while not-done
337 (let ((stop-here nil)
338 (looking-at-from-back (lambda (regexp n)
339 (save-excursion
340 (backward-char n)
341 (looking-at regexp)))))
342 (while (not stop-here)
343 (cond
344 ((eobp) (signal 'end-of-buffer nil))
345 ((looking-at (rx (and (* space) ";"))) (forward-line))
346 ((looking-at (rx (+ (or space "\n")))) (goto-char (match-end 0)))
347
348 ;; FIXME: can the rest be done more generically?
349 ((and (looking-at (rx (or (syntax symbol) (syntax word))))
350 (not (looking-at "\\_<"))
351 (not (funcall looking-at-from-back ",@" 2)))
352 (forward-symbol 1))
353 ((or (and (looking-at "'") (funcall looking-at-from-back "#" 1))
354 (and (looking-at "@") (funcall looking-at-from-back "," 1)))
355 (forward-char))
356 (t (setq stop-here t)))))
357 (condition-case nil
358 (progn
359 (setq res (save-excursion (read (current-buffer))))
360 (setq not-done nil))
361 (error (forward-char))))
362 res))
363
364 (defvar el-search--pcase-macros '()
365 "List of additional \"el-search\" pcase macros.")
366
367 (defun el-search--make-docstring ()
368 ;; code mainly from `pcase--make-docstring'
369 (let* ((main (documentation (symbol-function 'el-search-pattern) 'raw))
370 (ud (help-split-fundoc main 'pcase)))
371 (with-temp-buffer
372 (insert (or (cdr ud) main))
373 (mapc
374 (pcase-lambda (`(,symbol . ,fun))
375 (when-let ((doc (documentation fun)))
376 (insert "\n\n-- ")
377 (setq doc (help-fns--signature symbol doc fun fun nil))
378 (insert "\n" (or doc "Not documented."))))
379 (reverse el-search--pcase-macros))
380 (let ((combined-doc (buffer-string)))
381 (if ud (help-add-fundoc-usage combined-doc (car ud)) combined-doc)))))
382
383 (put 'el-search-pattern 'function-documentation '(el-search--make-docstring))
384
385 (defmacro el-search-defpattern (name args &rest body)
386 "Like `pcase-defmacro', but limited to el-search patterns.
387 The semantics is exactly that of `pcase-defmacro', but the scope
388 of the definitions is limited to \"el-search\"."
389 (declare (indent 2) (debug defun))
390 `(setf (alist-get ',name el-search--pcase-macros)
391 (lambda ,args ,@body)))
392
393
394 (defmacro el-search--with-additional-pcase-macros (&rest body)
395 `(cl-letf ,(mapcar (pcase-lambda (`(,symbol . ,fun))
396 `((get ',symbol 'pcase-macroexpander) #',fun))
397 el-search--pcase-macros)
398 ,@body))
399
400 (defun el-search--matcher (pattern &rest body)
401 (eval ;use `eval' to allow for user defined pattern types at run time
402 `(el-search--with-additional-pcase-macros
403 (let ((byte-compile-debug t) ;make undefined pattern types raise an error
404 (warning-suppress-log-types '((bytecomp)))
405 (pcase--dontwarn-upats (cons '_ pcase--dontwarn-upats)))
406 (byte-compile (lambda (expression)
407 (pcase expression
408 (,pattern ,@(or body (list t)))
409 (_ nil))))))))
410
411 (defun el-search--match-p (matcher expression)
412 (funcall matcher expression))
413
414 (defun el-search--wrap-pattern (pattern)
415 `(and ,el-search-this-expression-identifier ,pattern))
416
417 (defun el-search--skip-expression (expression &optional read)
418 ;; Move forward at least one character. Don't move into a string or
419 ;; comment. Don't move further than the beginning of the next sexp.
420 ;; Try to move as far as possible. Point must be at the beginning
421 ;; of an expression.
422 ;; If there are positions where `read' would succeed, but that do
423 ;; not represent a valid sexp start, move past them (e.g. when
424 ;; before "#'" move past both characters).
425 ;;
426 ;; EXPRESSION must be the (read) expression at point, but when READ
427 ;; is non-nil, ignore the first argument and read the expression at
428 ;; point instead.
429 (when read (setq expression (save-excursion (read (current-buffer)))))
430 (cond
431 ((or (null expression)
432 (equal [] expression)
433 (not (or (listp expression) (vectorp expression))))
434 (goto-char (el-search--end-of-sexp)))
435 ((looking-at (rx (or ",@" "," "#'" "'")))
436 (goto-char (match-end 0)))
437 (t (forward-char))))
438
439 (defun el-search--search-pattern (pattern &optional noerror)
440 "Search elisp buffer with `pcase' PATTERN.
441 Set point to the beginning of the occurrence found and return
442 point. Optional second argument, if non-nil, means if fail just
443 return nil (no error)."
444
445 (let ((matcher (el-search--matcher pattern)) (match-beg nil) (opoint (point)) current-expr)
446
447 ;; when inside a string or comment, move past it
448 (let ((syntax-here (syntax-ppss)))
449 (when (nth 3 syntax-here) ;inside a string
450 (goto-char (nth 8 syntax-here))
451 (forward-sexp))
452 (when (nth 4 syntax-here) ;inside a comment
453 (forward-line 1)
454 (while (and (not (eobp)) (looking-at (rx (and (* space) ";"))))
455 (forward-line 1))))
456
457 (if (catch 'no-match
458 (while (not match-beg)
459 (condition-case nil
460 (setq current-expr (el-search--ensure-sexp-start))
461 (end-of-buffer
462 (goto-char opoint)
463 (throw 'no-match t)))
464 (if (el-search--match-p matcher current-expr)
465 (setq match-beg (point)
466 opoint (point))
467 (el-search--skip-expression current-expr))))
468 (if noerror nil (signal 'end-of-buffer nil)))
469 match-beg))
470
471 (defun el-search--do-subsexps (pos do-fun &optional ret-fun bound)
472 ;; In current buffer, for any expression start between POS and BOUND
473 ;; or (point-max), in order, call two argument function DO-FUN with
474 ;; the current sexp string and the ending position of the current
475 ;; sexp. When done, with RET-FUN given, call it with no args and
476 ;; return the result; else, return nil.
477 (save-excursion
478 (goto-char pos)
479 (condition-case nil
480 (while (< (point) (or bound (point-max)))
481 (let* ((this-sexp-end (save-excursion (thing-at-point--end-of-sexp) (point)))
482 (this-sexp-string (buffer-substring-no-properties (point) this-sexp-end)))
483 (funcall do-fun this-sexp-string this-sexp-end)
484 (el-search--skip-expression (read this-sexp-string))
485 (el-search--ensure-sexp-start)))
486 (end-of-buffer))
487 (when ret-fun (funcall ret-fun))))
488
489 (defun el-search--create-read-map (&optional pos)
490 (let ((mapping '()))
491 (el-search--do-subsexps
492 (or pos (point))
493 (lambda (sexp _) (push (cons (read sexp) sexp) mapping))
494 (lambda () (nreverse mapping))
495 (save-excursion (thing-at-point--end-of-sexp) (point)))))
496
497 (defun el-search--repair-replacement-layout (printed mapping)
498 (with-temp-buffer
499 (insert printed)
500 (el-search--do-subsexps
501 (point-min)
502 (lambda (sexp sexp-end)
503 (when-let ((old (cdr (assoc (read sexp) mapping))))
504 (delete-region (point) sexp-end)
505 (when (string-match-p "\n" old)
506 (unless (looking-back "^[[:space:]]*" (line-beginning-position))
507 (insert "\n"))
508 (unless (looking-at "[[:space:]\)]*$")
509 (insert "\n")
510 (backward-char)))
511 (save-excursion (insert old))))
512 (lambda () (buffer-substring (point-min) (point-max))))))
513
514 (defun el-search--check-pattern-args (type args predicate &optional message)
515 "Check whether all ARGS fulfill PREDICATE.
516 Raise an error if not. TYPE and optional argument MESSAGE are
517 used to construct the error message."
518 (mapc (lambda (arg)
519 (unless (funcall predicate arg)
520 (error (concat "Pattern `%S': "
521 (or message (format "argument doesn't fulfill %S" predicate))
522 ": %S")
523 type arg)))
524 args))
525
526
527 ;;;; Additional pattern type definitions
528
529 (defun el-search--split (matcher1 matcher2 list)
530 "Helper for the append pattern type.
531
532 When a splitting of LIST into two lists L1, L2 exist so that Li
533 is matched by MATCHERi, return (L1 L2) for such Li, else return
534 nil."
535 (let ((try-match (lambda (list1 list2)
536 (when (and (el-search--match-p matcher1 list1)
537 (el-search--match-p matcher2 list2))
538 (list list1 list2))))
539 (list1 list) (list2 '()) (match nil))
540 ;; don't use recursion, this could hit `max-lisp-eval-depth'
541 (while (and (not (setq match (funcall try-match list1 list2)))
542 (consp list1))
543 (let ((last-list1 (last list1)))
544 (if-let ((cdr-last-list1 (cdr last-list1)))
545 ;; list1 is a dotted list. Then list2 must be empty.
546 (progn (setcdr last-list1 nil)
547 (setq list2 cdr-last-list1))
548 (setq list1 (butlast list1 1)
549 list2 (cons (car last-list1) list2)))))
550 match))
551
552 (el-search-defpattern append (&rest patterns)
553 "Matches any list factorable into lists matched by PATTERNS in order.
554
555 PATTERNS is a list of patterns P1..Pn. Match any list L for that
556 lists L1..Ln exist that are matched by P1..Pn in order and L is
557 equal to the concatenation of L1..Ln. Ln is allowed to be no
558 list.
559
560 When different ways of matching are possible, it is unspecified
561 which one is chosen.
562
563 Example: the pattern
564
565 (append '(1 2 3) x (app car-safe 7))
566
567 matches the list (1 2 3 4 5 6 7 8 9) and binds `x' to (4 5 6)."
568 (if (null patterns)
569 '(pred null)
570 (pcase-let ((`(,pattern . ,more-patterns) patterns))
571 (cond
572 ((null more-patterns) pattern)
573 ((null (cdr more-patterns))
574 `(and (pred listp)
575 (app ,(apply-partially #'el-search--split
576 (el-search--matcher pattern)
577 (el-search--matcher (car more-patterns)))
578 (,'\` ((,'\, ,pattern)
579 (,'\, ,(car more-patterns)))))))
580 (t `(append ,pattern (append ,@more-patterns)))))))
581
582 (el-search-defpattern string (&rest regexps)
583 "Matches any string that is matched by all REGEXPS."
584 (el-search--check-pattern-args 'string regexps #'stringp)
585 (let ((string (make-symbol "string"))
586 (regexp (make-symbol "regexp")))
587 `(and (pred stringp)
588 (pred (lambda (,string)
589 (cl-every
590 (lambda (,regexp) (string-match-p ,regexp ,string))
591 (list ,@regexps)))))))
592
593 (el-search-defpattern symbol (&rest regexps)
594 "Matches any symbol whose name is matched by all REGEXPS."
595 (el-search--check-pattern-args 'symbol regexps #'stringp)
596 `(and (pred symbolp)
597 (app symbol-name (string ,@regexps))))
598
599 (defun el-search--match-symbol-file (regexp symbol)
600 (when-let ((symbol-file (and (symbolp symbol)
601 (symbol-file symbol))))
602 (string-match-p
603 (if (symbolp regexp) (concat "\\`" (symbol-name regexp) "\\'") regexp)
604 (file-name-sans-extension (file-name-nondirectory symbol-file)))))
605
606 (el-search-defpattern source (regexp)
607 "Matches any symbol whose `symbol-file' is matched by REGEXP.
608
609 This pattern matches when the object is a symbol for that
610 `symbol-file' returns a (non-nil) FILE-NAME that fulfills
611 (string-match-p REGEXP (file-name-sans-extension
612 (file-name-nondirectory FILENAME)))
613
614 REGEXP can also be a symbol, in which case
615
616 (concat \"^\" (symbol-name regexp) \"$\")
617
618 is used as regular expression."
619 (el-search--check-pattern-args 'source (list regexp) #'stringp)
620 `(pred (el-search--match-symbol-file ,regexp)))
621
622 (defun el-search--match-key-sequence (keys expr)
623 (when-let ((expr-keys (pcase expr
624 ((or (pred stringp) (pred vectorp)) expr)
625 (`(kbd ,(and (pred stringp) string)) (ignore-errors (kbd string))))))
626 (apply #'equal
627 (mapcar (lambda (keys) (ignore-errors (key-description keys)))
628 (list keys expr-keys)))))
629
630 (el-search-defpattern keys (key-sequence)
631 "Matches descriptions of the KEY-SEQUENCE.
632 KEY-SEQUENCE is a string or vector representing a key sequence,
633 or an expression of the form (kbd STRING).
634
635 Match any description of the same key sequence in any of these
636 formats.
637
638 Example: the pattern
639
640 (keys (kbd \"C-s\"))
641
642 matches any of these expressions:
643
644 \"\\C-s\"
645 \"\C-s\"
646 (kbd \"C-s\")
647 [(control ?s)]"
648 (when (eq (car-safe key-sequence) 'kbd)
649 (setq key-sequence (kbd (cadr key-sequence))))
650 (el-search--check-pattern-args 'keys (list key-sequence) (lambda (x) (or (stringp x) (vectorp x)))
651 "argument not a string or vector")
652 `(pred (el-search--match-key-sequence ,key-sequence)))
653
654
655 ;;;; Highlighting
656
657 (defvar-local el-search-hl-overlay nil)
658
659 (defvar el-search-keep-hl nil)
660
661 (defun el-search-hl-sexp (&optional bounds)
662 (let ((bounds (or bounds
663 (list (point) (el-search--end-of-sexp)))))
664 (if (overlayp el-search-hl-overlay)
665 (apply #'move-overlay el-search-hl-overlay bounds)
666 (overlay-put (setq el-search-hl-overlay (apply #'make-overlay bounds))
667 'face 'el-search-match)))
668 (add-hook 'post-command-hook #'el-search-hl-post-command-fun t t))
669
670 (defun el-search-hl-remove ()
671 (when (overlayp el-search-hl-overlay)
672 (delete-overlay el-search-hl-overlay)))
673
674 (defun el-search-hl-post-command-fun ()
675 (unless (or el-search-keep-hl
676 (eq this-command 'el-search-query-replace)
677 (eq this-command 'el-search-pattern))
678 (el-search-hl-remove)
679 (remove-hook 'post-command-hook 'el-search-hl-post-command-fun t)))
680
681
682 ;;;; Core functions
683
684 (defvar el-search-history '()
685 "List of input strings.")
686
687 (defvar el-search-success nil)
688 (defvar el-search-current-pattern nil)
689
690 ;;;###autoload
691 (defun el-search-pattern (pattern)
692 "Start new or resume last elisp search.
693
694 Search current buffer for expressions that are matched by `pcase'
695 PATTERN. Use `read' to transform buffer contents into
696 expressions.
697
698
699 Additional `pcase' pattern types to be used with this command can
700 be defined with `el-search-defpattern'.
701
702 The following additional pattern types are currently defined:\n"
703 (interactive (list (if (and (eq this-command last-command)
704 el-search-success)
705 el-search-current-pattern
706 (let ((pattern
707 (el-search--read-pattern "Find pcase pattern: "
708 (car el-search-history)
709 t)))
710 ;; A very common mistake: input "foo" instead of "'foo"
711 (when (and (symbolp pattern)
712 (not (eq pattern '_))
713 (or (not (boundp pattern))
714 (not (eq (symbol-value pattern) pattern))))
715 (error "Please don't forget the quote when searching for a symbol"))
716 (el-search--wrap-pattern pattern)))))
717 (setq this-command 'el-search-pattern) ;in case we come from isearch
718 (setq el-search-current-pattern pattern)
719 (let ((opoint (point)))
720 (when (and (eq this-command last-command) el-search-success)
721 (el-search--skip-expression nil t))
722 (setq el-search-success nil)
723 (message "%s" (substitute-command-keys "Type \\[el-search-pattern] to repeat"))
724 (when (condition-case nil
725 (el-search--search-pattern pattern)
726 (end-of-buffer (message "No match")
727 (goto-char opoint)
728 (el-search-hl-remove)
729 (ding)
730 nil))
731 (setq el-search-success t)
732 (el-search-hl-sexp))))
733
734 (defvar el-search-search-and-replace-help-string
735 "\
736 y Replace this match and move to the next.
737 SPC or n Skip this match and move to the next.
738 r Replace this match but don't move.
739 ! Replace all remaining matches automatically.
740 q Quit. To resume, use e.g. `repeat-complex-command'.
741 ? Show this help.
742 s Toggle splicing mode. When splicing mode is
743 on (default off), the replacement expression must
744 evaluate to a list, and the result is spliced into the
745 buffer, instead of just inserted.
746
747 Hit any key to proceed."
748 "Help string for ? in `el-search-query-replace'.")
749
750 (defun el-search-search-and-replace-pattern (pattern replacement &optional mapping splice)
751 (let ((replace-all nil) (nbr-replaced 0) (nbr-skipped 0) (done nil)
752 (el-search-keep-hl t) (opoint (point))
753 (get-replacement (el-search--matcher pattern replacement)))
754 (unwind-protect
755 (while (and (not done) (el-search--search-pattern pattern t))
756 (setq opoint (point))
757 (unless replace-all (el-search-hl-sexp))
758 (let* ((read-mapping (el-search--create-read-map))
759 (region (list (point) (el-search--end-of-sexp)))
760 (substring (apply #'buffer-substring-no-properties region))
761 (expr (read substring))
762 (replaced-this nil)
763 (new-expr (funcall get-replacement expr))
764 (get-replacement-string
765 (lambda () (if (and splice (not (listp new-expr)))
766 (error "Expression to splice in is an atom")
767 (el-search--repair-replacement-layout
768 (if splice
769 (mapconcat #'el-search--print new-expr " ")
770 (el-search--print new-expr))
771 (append mapping read-mapping)))))
772 (to-insert (funcall get-replacement-string))
773 (do-replace (lambda ()
774 (atomic-change-group
775 (apply #'delete-region region)
776 (let ((inhibit-message t)
777 (opoint (point)))
778 (insert to-insert)
779 (indent-region opoint (point))
780 (el-search-hl-sexp (list opoint (point)))
781 (goto-char opoint)))
782 (cl-incf nbr-replaced)
783 (setq replaced-this t))))
784 (if replace-all
785 (funcall do-replace)
786 (while (not (pcase (if replaced-this
787 (read-char-choice "[SPC ! q] (? for help)"
788 '(?\ ?! ?q ?n ??))
789 (read-char-choice
790 (concat "Replace this occurrence"
791 (if (or (string-match-p "\n" to-insert)
792 (< 40 (length to-insert)))
793 "" (format " with `%s'" to-insert))
794 "? "
795 (if splice "{splice} " "")
796 "[y SPC r ! s q] (? for help)" )
797 '(?y ?n ?r ?\ ?! ?q ?s ??)))
798 (?r (funcall do-replace)
799 nil)
800 (?y (funcall do-replace)
801 t)
802 ((or ?\ ?n)
803 (unless replaced-this (cl-incf nbr-skipped))
804 t)
805 (?! (unless replaced-this
806 (funcall do-replace))
807 (setq replace-all t)
808 t)
809 (?s (cl-callf not splice)
810 (setq to-insert (funcall get-replacement-string))
811 nil)
812 (?q (setq done t)
813 t)
814 (?? (ignore (read-char el-search-search-and-replace-help-string))
815 nil)))))
816 (unless (or done (eobp)) (el-search--skip-expression nil t)))))
817 (el-search-hl-remove)
818 (goto-char opoint)
819 (message "Replaced %d matches%s"
820 nbr-replaced
821 (if (zerop nbr-skipped) ""
822 (format " (%d skipped)" nbr-skipped)))))
823
824 (defun el-search-query-replace-read-args ()
825 (barf-if-buffer-read-only)
826 (let* ((from (el-search--read-pattern "Replace from: "))
827 (to (let ((el-search--initial-mb-contents nil))
828 (el-search--read-pattern "Replace with result of evaluation of: " from))))
829 (list (el-search--wrap-pattern (read from)) (read to)
830 (with-temp-buffer
831 (insert to)
832 (el-search--create-read-map 1)))))
833
834 ;;;###autoload
835 (defun el-search-query-replace (from to &optional mapping)
836 "Replace some occurrences of FROM pattern with evaluated TO."
837 (interactive (el-search-query-replace-read-args))
838 (setq this-command 'el-search-query-replace) ;in case we come from isearch
839 (setq el-search-current-pattern from)
840 (barf-if-buffer-read-only)
841 (el-search-search-and-replace-pattern from to mapping))
842
843 (defun el-search--take-over-from-isearch ()
844 (let ((other-end isearch-other-end)
845 (input isearch-string))
846 (isearch-exit)
847 (when (and other-end (< other-end (point)))
848 (goto-char other-end))
849 input))
850
851 ;;;###autoload
852 (defun el-search-search-from-isearch ()
853 ;; FIXME: an interesting alternative would be to really integrate it
854 ;; with Isearch, using `isearch-search-fun-function'.
855 ;; Alas, this is not trivial if we want to transfer our optimizations.
856 (interactive)
857 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch))))
858 ;; use `call-interactively' so we get recorded in `extended-command-history'
859 (call-interactively #'el-search-pattern)))
860
861 ;;;###autoload
862 (defun el-search-replace-from-isearch ()
863 (interactive)
864 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch))))
865 (call-interactively #'el-search-query-replace)))
866
867
868
869 (provide 'el-search)
870 ;;; el-search.el ends here