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