]> code.delx.au - gnu-emacs-elpa/blob - packages/el-search/el-search.el
fix whitespace
[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.0.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 the command `el-search-pattern'. It
37 ;; prompts for a `pcase' pattern and searches the current buffer for
38 ;; expressions that are matched by it when read. Point is put at the
39 ;; beginning of the expression found (unlike isearch).
40 ;;
41 ;; It doesn't matter how the code is actually formatted. Comments are
42 ;; ignored by the search, and strings are treated as objects, their
43 ;; contents are not being searched.
44 ;;
45 ;; Example 1: if you enter
46 ;;
47 ;; 97
48 ;;
49 ;; at the prompt, this will find any occurrence of the number 97 in
50 ;; the code, but not 977 or (+ 90 7) or "My string containing 97".
51 ;; But it will find anything `eq' to 97 after reading, e.g. #x61 or
52 ;; ?a.
53 ;;
54 ;;
55 ;; Example 2: If you enter the pattern
56 ;;
57 ;; `(defvar ,_)
58 ;;
59 ;; you search for all defvar forms that don't specify an init value.
60 ;;
61 ;; The following will search for defvar forms with a docstring whose
62 ;; first line is longer than 70 characters:
63 ;;
64 ;; `(defvar ,_ ,_
65 ;; ,(and s (guard (< 70 (length (car (split-string s "\n")))))))
66 ;;
67 ;;
68 ;; Convenience
69 ;; ===========
70 ;;
71 ;; For expression input, the minibuffer prompts here uses
72 ;; `emacs-lisp-mode'.
73 ;;
74 ;; When reading a search pattern in the minibuffer, the input is
75 ;; automatically wrapped into `(and exp ,(read input)). So, if you
76 ;; want to search a buffer for symbols that are defined in "cl-lib",
77 ;; you can use this pattern
78 ;;
79 ;; (guard (and (symbolp exp)
80 ;; (when-let ((file (symbol-file exp)))
81 ;; (string-match-p "cl-lib\\.elc?$" file))))
82 ;;
83 ;; without binding the variable `exp'.
84 ;;
85 ;;
86 ;; Replacing
87 ;; =========
88 ;;
89 ;; You can replace expressions with command `el-search-query-replace'.
90 ;; You are queried for a (pcase) pattern and a replacement expression.
91 ;; For each match of the pattern, the replacement expression is
92 ;; evaluated with the bindings created by the pcase matching in
93 ;; effect, and printed to produce the replacement string.
94 ;;
95 ;; Example: In some buffer you want to swap the two expressions at the
96 ;; places of the first two arguments in all calls of function `foo',
97 ;; so that e.g.
98 ;;
99 ;; (foo 'a (* 2 (+ 3 4)) t)
100 ;;
101 ;; becomes
102 ;;
103 ;; (foo (* 2 (+ 3 4)) 'a t).
104 ;;
105 ;; This will do it:
106 ;;
107 ;; M-x el-search-query-replace RET
108 ;; `(foo ,a ,b . ,rest) RET
109 ;; `(foo ,b ,a . ,rest) RET
110 ;;
111 ;; Type y to replace a match and go to the next one, r to replace
112 ;; without moving, SPC to go to the next match and ! to replace all
113 ;; remaining matches automatically. q quits. n is like SPC, so that
114 ;; y and n work like in isearch (meaning "yes" and "no") if you are
115 ;; used to that.
116 ;;
117 ;;
118 ;; Suggested key bindings
119 ;; ======================
120 ;;
121 ;; (define-key emacs-lisp-mode-map [(control ?S)] #'el-search-pattern)
122 ;; (define-key emacs-lisp-mode-map [(control ?%)] #'el-search-query-replace)
123 ;;
124 ;; (define-key isearch-mode-map [(control ?S)] #'el-search-search-from-isearch)
125 ;; (define-key isearch-mode-map [(control ?%)] #'el-search-replace-from-isearch)
126 ;;
127 ;; The bindings in `isearch-mode-map' let you conveniently switch to
128 ;; elisp searching from isearch.
129 ;;
130 ;;
131 ;; Bugs, Known Limitations
132 ;; =======================
133 ;;
134 ;; - Replacing: in some cases the reader syntax of forms
135 ;; is changing due to reading+printing. "Some" because we can treat
136 ;; that problem in most cases.
137 ;;
138 ;; - Similarly: Comments are normally preserved (where it makes
139 ;; sense). But when replacing like `(foo ,a ,b) -> `(foo ,b ,a)
140 ;;
141 ;; in a content like
142 ;;
143 ;; (foo
144 ;; a
145 ;; ;;a comment
146 ;; b)
147 ;;
148 ;; the comment will be lost.
149 ;;
150 ;;
151 ;; Acknowledgments
152 ;; ===============
153 ;;
154 ;; Thanks to Stefan Monnier for corrections and advice.
155 ;;
156 ;;
157 ;; TODO:
158 ;;
159 ;; - display something useful in the echo area. or leave it for being
160 ;; able to `message' in the pattern?
161 ;;
162 ;; - implement backward searching
163 ;;
164 ;; - improve docstrings
165 ;;
166 ;; - add more examples
167 ;;
168 ;; - handle more reader syntaxes, e.g. #n, #n#
169 ;;
170 ;; - Implement sessions; add multi-file support based on iterators. A
171 ;; file list is read in (or the user can specify an iterator as a
172 ;; variable). The state in the current buffer is just (buffer
173 ;; . marker). Or should this be abstracted into an own lib? Could be
174 ;; named "files-session" or so.
175
176
177
178 ;;; Code:
179
180 ;;;; Requirements
181
182 (eval-when-compile
183 (require 'subr-x))
184
185 (require 'cl-lib)
186 (require 'elisp-mode)
187 (require 'thingatpt)
188
189
190 ;;;; Configuration stuff
191
192 (defgroup el-search nil
193 "Expression based search and replace for `emacs-lisp-mode'."
194 :group 'lisp)
195
196 (defcustom el-search-this-expression-identifier 'exp
197 "Name of the identifier referring to the current expression.
198 The default value is `exp'. You can use this name in the search
199 prompt to refer to the value of the currently tested expression."
200 :type 'symbol)
201
202 (defface el-search-match '((((background dark)) (:background "#0000A0"))
203 (t (:background "DarkSlateGray1")))
204 "Face for highlighting the current match.")
205
206
207 ;;;; Helpers
208
209 (defun el-search--print (expr)
210 (let ((print-quoted t)
211 (print-length nil)
212 (print-level nil))
213 (prin1-to-string expr)))
214
215 (defvar el-search-read-expression-map
216 (let ((map (make-sparse-keymap)))
217 (set-keymap-parent map read-expression-map)
218 (define-key map [(control ?g)] #'abort-recursive-edit)
219 (define-key map [up] nil)
220 (define-key map [down] nil)
221 (define-key map [(control meta backspace)] #'backward-kill-sexp)
222 (define-key map [(control ?S)] #'exit-minibuffer)
223 map)
224 "Map for reading input with `el-search-read-expression'.")
225
226 ;; $$$$$FIXME: this should be in Emacs! There is only a helper `read--expression'.
227 (defun el-search-read-expression (prompt &optional initial-contents hist default read)
228 "Read expression for `my-eval-expression'."
229 (minibuffer-with-setup-hook
230 (lambda ()
231 (emacs-lisp-mode)
232 (use-local-map el-search-read-expression-map)
233 (setq font-lock-mode t)
234 (funcall font-lock-function 1)
235 (backward-sexp)
236 (indent-sexp)
237 (goto-char (point-max)))
238 (read-from-minibuffer prompt initial-contents el-search-read-expression-map read
239 (or hist 'read-expression-history) default)))
240
241 (defun el-search--read-pattern (prompt &optional default read)
242 (el-search-read-expression
243 prompt el-search--initial-mb-contents 'el-search-history
244 (or default (when-let ((this-sexp (sexp-at-point)))
245 (concat "'" (el-search--print this-sexp))))
246 read))
247
248 (defun el-search--end-of-sexp ()
249 ;;Point must be at sexp beginning
250 (or (scan-sexps (point) 1) (point-max)))
251
252 (defun el-search--ensure-sexp-start ()
253 "Move point to the beginning of the next sexp if necessary.
254 Don't move if already at beginning of a sexp.
255 Point must not be inside a string or comment."
256 (let ((not-done t) res)
257 (while not-done
258 (let ((stop-here nil)
259 (looking-at-from-back (lambda (regexp n)
260 (save-excursion
261 (backward-char n)
262 (looking-at regexp)))))
263 (while (not stop-here)
264 (cond
265 ((eobp) (signal 'end-of-buffer nil))
266 ((looking-at (rx (and (* space) ";"))) (forward-line))
267 ((looking-at (rx (+ (or space "\n")))) (goto-char (match-end 0)))
268
269 ;; FIXME: can the rest be done more generically?
270 ((and (looking-at (rx (or (syntax symbol) (syntax word))))
271 (not (looking-at "\\_<"))
272 (not (funcall looking-at-from-back ",@" 2)))
273 (forward-symbol 1))
274 ((or (and (looking-at "'") (funcall looking-at-from-back "#" 1))
275 (and (looking-at "@") (funcall looking-at-from-back "," 1)))
276 (forward-char))
277 (t (setq stop-here t)))))
278 (condition-case nil
279 (progn
280 (setq res (save-excursion (read (current-buffer))))
281 (setq not-done nil))
282 (error (forward-char))))
283 res))
284
285 (defun el-search--matcher (pattern &rest body)
286 (let ((warning-suppress-log-types '((bytecomp))))
287 (byte-compile
288 `(lambda (expression)
289 (pcase expression
290 (,pattern ,@(or body (list t)))
291 (_ nil))))))
292
293 (defun el-search--match-p (matcher expression)
294 (funcall matcher expression))
295
296 (defun el-search--wrap-pattern (pattern)
297 `(and ,el-search-this-expression-identifier ,pattern))
298
299 (defun el-search--skip-expression (expression &optional read)
300 ;; Move forward at least one character. Don't move into a string or
301 ;; comment. Don't move further than the beginning of the next sexp.
302 ;; Try to move as far as possible. Point must be at the beginning
303 ;; of an expression.
304 ;; If there are positions where `read' would succeed, but that do
305 ;; not represent a valid sexp start, move past them (e.g. when
306 ;; before "#'" move past both characters).
307 ;;
308 ;; EXPRESSION must be the (read) expression at point, but when READ
309 ;; is non-nil, ignore the first argument and read the expression at
310 ;; point instead.
311 (when read (setq expression (save-excursion (read (current-buffer)))))
312 (cond
313 ((or (null expression)
314 (equal [] expression)
315 (not (or (listp expression) (vectorp expression))))
316 (goto-char (el-search--end-of-sexp)))
317 ((looking-at (rx (or ",@" "," "#'" "'")))
318 (goto-char (match-end 0)))
319 (t (forward-char))))
320
321 (defun el-search--search-pattern (pattern &optional noerror)
322 "Search elisp buffer with `pcase' PATTERN.
323 Set point to the beginning of the occurrence found and return
324 point. Optional second argument, if non-nil, means if fail just
325 return nil (no error)."
326
327 (let ((matcher (el-search--matcher pattern)) (match-beg nil) (opoint (point)) current-expr)
328
329 ;; when inside a string or comment, move past it
330 (let ((syntax-here (syntax-ppss)))
331 (when (nth 3 syntax-here) ;inside a string
332 (goto-char (nth 8 syntax-here))
333 (forward-sexp))
334 (when (nth 4 syntax-here) ;inside a comment
335 (forward-line 1)
336 (while (and (not (eobp)) (looking-at (rx (and (* space) ";"))))
337 (forward-line 1))))
338
339 (if (catch 'no-match
340 (while (not match-beg)
341 (condition-case nil
342 (setq current-expr (el-search--ensure-sexp-start))
343 (end-of-buffer
344 (goto-char opoint)
345 (throw 'no-match t)))
346 (if (el-search--match-p matcher current-expr)
347 (setq match-beg (point)
348 opoint (point))
349 (el-search--skip-expression current-expr))))
350 (if noerror nil (signal 'end-of-buffer nil)))
351 match-beg))
352
353 (defun el-search--do-subsexps (pos do-fun &optional ret-fun bound)
354 ;; In current buffer, for any expression start between POS and BOUND
355 ;; or (point-max), in oder, call two argument function DO-FUN with
356 ;; the current sexp string and the ending position of the current
357 ;; sexp. When done, with RET-FUN given, call it with no args and
358 ;; return the result; else, return nil.
359 (save-excursion
360 (goto-char pos)
361 (condition-case nil
362 (while (< (point) (or bound (point-max)))
363 (let* ((this-sexp-end (save-excursion (thing-at-point--end-of-sexp) (point)))
364 (this-sexp-string (buffer-substring-no-properties (point) this-sexp-end)))
365 (funcall do-fun this-sexp-string this-sexp-end)
366 (el-search--skip-expression (read this-sexp-string))
367 (el-search--ensure-sexp-start)))
368 (end-of-buffer))
369 (when ret-fun (funcall ret-fun))))
370
371 (defun el-search--create-read-map (&optional pos)
372 (let ((mapping '()))
373 (el-search--do-subsexps
374 (or pos (point))
375 (lambda (sexp _) (push (cons (read sexp) sexp) mapping))
376 (lambda () (nreverse mapping))
377 (save-excursion (thing-at-point--end-of-sexp) (point)))))
378
379 (defun el-search--repair-replacement-layout (printed mapping)
380 (with-temp-buffer
381 (insert printed)
382 (el-search--do-subsexps
383 (point-min)
384 (lambda (sexp sexp-end)
385 (when-let ((old (cdr (assoc (read sexp) mapping))))
386 (delete-region (point) sexp-end)
387 (when (string-match-p "\n" old)
388 (unless (looking-back "^[[:space:]]*" (line-beginning-position))
389 (insert "\n"))
390 (unless (looking-at "[[:space:]\)]*$")
391 (insert "\n")
392 (backward-char)))
393 (save-excursion (insert old))))
394 (lambda () (buffer-substring (point-min) (point-max))))))
395
396
397 ;;;; Highlighting
398
399 (defvar-local el-search-hl-overlay nil)
400
401 (defvar el-search-keep-hl nil)
402
403 (defun el-search-hl-sexp-at-point ()
404 (let ((bounds (list (point) (el-search--end-of-sexp))))
405 (if (overlayp el-search-hl-overlay)
406 (apply #'move-overlay el-search-hl-overlay bounds)
407 (overlay-put (setq el-search-hl-overlay (apply #'make-overlay bounds))
408 'face 'el-search-match)))
409 (add-hook 'post-command-hook (el-search-hl-post-command-fun (current-buffer)) t t))
410
411 (defun el-search-hl-remove ()
412 (when (overlayp el-search-hl-overlay)
413 (delete-overlay el-search-hl-overlay)))
414
415 (defun el-search-hl-post-command-fun (buf)
416 (letrec ((fun (lambda ()
417 (when (buffer-live-p buf)
418 (unless (or el-search-keep-hl
419 (eq this-command 'el-search-query-replace)
420 (eq this-command 'el-search-pattern))
421 (with-current-buffer buf
422 (el-search-hl-remove)
423 (remove-hook 'post-command-hook fun t)))))))
424 fun))
425
426
427 ;;;; Core functions
428
429 (defvar el-search-history '()
430 "List of input strings.")
431
432 (defvar el-search-success nil)
433 (defvar el-search-current-pattern nil)
434
435 ;;;###autoload
436 (defun el-search-pattern (pattern)
437 "Do incremental elisp search or resume last search."
438 (interactive (list (if (eq this-command last-command)
439 el-search-current-pattern
440 (let ((pattern
441 (el-search--read-pattern "Find pcase pattern: "
442 (car el-search-history)
443 t)))
444 ;; A very common mistake: input "foo" instead of "'foo"
445 (when (and (symbolp pattern)
446 (not (eq pattern '_))
447 (or (not (boundp pattern))
448 (not (eq (symbol-value pattern) pattern))))
449 (error "Please don't forget the quote when searching for a symbol"))
450 (el-search--wrap-pattern pattern)))))
451 (setq this-command 'el-search-pattern) ;in case we come from isearch
452 (setq el-search-current-pattern pattern)
453 (let ((opoint (point)))
454 (when (eq this-command last-command)
455 (if el-search-success
456 (el-search--skip-expression nil t)
457 ;; wrap search
458 (goto-char (point-min))))
459 (setq el-search-success nil)
460 (when (condition-case nil
461 (el-search--search-pattern pattern)
462 (end-of-buffer (message "No match")
463 (goto-char opoint)
464 (el-search-hl-remove)
465 (ding)
466 nil))
467 (setq el-search-success t)
468 (el-search-hl-sexp-at-point))))
469
470 (defun el-search-search-and-replace-pattern (pattern replacement &optional mapping)
471 (let ((replace-all nil) (nbr-replaced 0) (nbr-skipped 0) (done nil)
472 (el-search-keep-hl t) (opoint (point))
473 (get-replacement (el-search--matcher pattern replacement)))
474 (unwind-protect
475 (while (and (not done) (el-search--search-pattern pattern t))
476 (setq opoint (point))
477 (unless replace-all (el-search-hl-sexp-at-point))
478 (let* ((read-mapping (el-search--create-read-map))
479 (region (list (point) (el-search--end-of-sexp)))
480 (substring (apply #'buffer-substring-no-properties region))
481 (expr (read substring))
482 (replaced-this nil)
483 (new-expr (funcall get-replacement expr))
484 (to-insert (el-search--repair-replacement-layout
485 (el-search--print new-expr) (append mapping read-mapping)))
486 (do-replace (lambda ()
487 (atomic-change-group
488 (apply #'delete-region region)
489 (let ((inhibit-message t)
490 (opoint (point)))
491 (insert to-insert)
492 (indent-region opoint (point))
493 (goto-char opoint)
494 (el-search-hl-sexp-at-point)))
495 (cl-incf nbr-replaced)
496 (setq replaced-this t))))
497 (if replace-all
498 (funcall do-replace)
499 (while (not (pcase (if replaced-this
500 (read-char-choice "[SPC ! q]" '(?\ ?! ?q ?n))
501 (read-char-choice
502 (concat "Replace this occurence"
503 (if (or (string-match-p "\n" to-insert)
504 (< 40 (length to-insert)))
505 "" (format " with `%s'" to-insert))
506 "? [y SPC r ! q]" )
507 '(?y ?n ?r ?\ ?! ?q)))
508 (?r (funcall do-replace)
509 nil)
510 (?y (funcall do-replace)
511 t)
512 ((or ?\ ?n)
513 (unless replaced-this (cl-incf nbr-skipped))
514 t)
515 (?! (unless replaced-this
516 (funcall do-replace))
517 (setq replace-all t)
518 t)
519 (?q (setq done t)
520 t)))))
521 (unless (or done (eobp)) (el-search--skip-expression nil t)))))
522 (el-search-hl-remove)
523 (goto-char opoint)
524 (message "Replaced %d matches%s"
525 nbr-replaced
526 (if (zerop nbr-skipped) ""
527 (format " (%d skipped)" nbr-skipped)))))
528
529 ;; We need a variable for the initial contents because we want to `call-interactively'
530 ;; `el-search-query-replace-read-args'
531 (defvar el-search--initial-mb-contents nil)
532
533 (defun el-search-query-replace-read-args ()
534 (barf-if-buffer-read-only)
535 (let* ((from (el-search--read-pattern "Replace from: "))
536 (to (let ((el-search--initial-mb-contents nil))
537 (el-search--read-pattern "Replace with result of evaluation of: " from))))
538 (list (el-search--wrap-pattern (read from)) (read to)
539 (with-temp-buffer
540 (insert to)
541 (el-search--create-read-map 1)))))
542
543 ;;;###autoload
544 (defun el-search-query-replace (from to &optional mapping)
545 "Replace some occurrences of FROM pattern with evaluated TO."
546 (interactive (el-search-query-replace-read-args))
547 (setq this-command 'el-search-query-replace) ;in case we come from isearch
548 (setq el-search-current-pattern from)
549 (barf-if-buffer-read-only)
550 (el-search-search-and-replace-pattern from to mapping))
551
552 (defun el-search--take-over-from-isearch ()
553 (let ((other-end isearch-other-end)
554 (input isearch-string))
555 (isearch-exit)
556 (when (and other-end (< other-end (point)))
557 (goto-char other-end))
558 input))
559
560 ;;;###autoload
561 (defun el-search-search-from-isearch ()
562 ;; FIXME: an interesting alternative would be to really integrate it
563 ;; with Isearch, using `isearch-search-fun-function'.
564 ;; Alas, this is not trivial if we want to transfer our optimizations.
565 (interactive)
566 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch))))
567 ;; use `call-interactively' so we get recorded in `extended-command-history'
568 (call-interactively #'el-search-pattern)))
569
570 ;;;###autoload
571 (defun el-search-replace-from-isearch ()
572 (interactive)
573 (let ((el-search--initial-mb-contents (concat "'" (el-search--take-over-from-isearch))))
574 (call-interactively #'el-search-query-replace)))
575
576
577
578 (provide 'el-search)
579 ;;; el-search.el ends here