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