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