]> code.delx.au - gnu-emacs-elpa/blob - packages/el-search/el-search.el
el-search: some comment changes
[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"))
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 expr ,(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 expr)
80 ;; (when-let ((file (symbol-file expr)))
81 ;; (string-match-p "cl-lib\\.elc?$" file))))
82 ;;
83 ;; without binding the variable `expr'.
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 ;; - improve docstrings
160 ;;
161 ;; - add more examples
162 ;;
163 ;; - Implement sessions; add multi-file support based on iterators. A
164 ;; file list is read in (or the user can specify an iterator as a
165 ;; variable). The state in the current buffer is just (buffer
166 ;; . marker). Or should this be abstracted into an own lib? Could be
167 ;; named "files-session" or so.
168
169
170
171 ;;; Code:
172
173 ;;;; Requirements
174
175 (eval-when-compile
176 (require 'subr-x))
177
178 (require 'cl-lib)
179 (require 'elisp-mode)
180 (require 'thingatpt)
181
182
183 ;;;; Configuration stuff
184
185 (defgroup el-search nil
186 "Expression based search and replace for `emacs-lisp-mode'."
187 :group 'lisp)
188
189 (defcustom el-search-this-expression-identifier 'expr
190 "Name of the identifier referring to the whole expression.
191 The default value is `expr'. You can use this variable in the
192 search prompt to refer to value of the currently searched
193 expression."
194 :type 'symbol)
195
196 (defface el-search-match '((((background dark)) (:background "#0000A0"))
197 (t (:background "DarkSlateGray1")))
198 "Face for highlighting the current match.")
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 ;;;###autoload
405 (defun el-search-pattern (pattern)
406 "Do incremental elisp search forward."
407 (interactive (list (if (and (eq this-command last-command)
408 el-search-success)
409 el-search-current-pattern
410 (let ((pattern
411 (el-search--read-pattern "Find pcase pattern: "
412 (car el-search-history)
413 nil t)))
414 ;; A very common mistake: input "foo" instead of "'foo"
415 (when (and (symbolp pattern)
416 (not (eq pattern '_))
417 (or (not (boundp pattern))
418 (not (eq (symbol-value pattern) pattern))))
419 (error "Please don't forget the quote when searching for a symbol"))
420 (el-search--maybe-wrap-pattern pattern)))))
421 (setq el-search-current-pattern pattern)
422 (setq el-search-success nil)
423 (let ((opoint (point)))
424 (when (eq this-command last-command)
425 (forward-char))
426 (when (condition-case nil
427 (el-search--search-pattern pattern)
428 (end-of-buffer (message "No match")
429 (goto-char opoint)
430 (el-search-hl-remove)
431 (ding)
432 nil))
433 (setq el-search-success t)
434 (el-search-hl-sexp)
435 (message "%s" (substitute-command-keys "Type \\[el-search-pattern] to repeat")))))
436
437 (defun el-search-search-and-replace-pattern (pattern replacement &optional mapping)
438 (let ((replace-all nil) (nbr-replaced 0) (nbr-skipped 0) (done nil)
439 (el-search-keep-hl t) (opoint (point)))
440 (unwind-protect
441 (while (and (not done) (el-search--search-pattern pattern t))
442 (setq opoint (point))
443 (unless replace-all (el-search-hl-sexp))
444 (let* ((read-mapping (el-search--create-read-map))
445 (region (list (point) (scan-sexps (point) 1)))
446 (substring (apply #'buffer-substring-no-properties region))
447 (expr (read substring))
448 (replaced-this nil)
449 (new-expr (funcall `(lambda () (pcase ',expr (,pattern ,replacement)))))
450 (to-insert (el-search--repair-replacement-layout
451 (el-search--print new-expr) (append mapping read-mapping)))
452 (do-replace (lambda ()
453 (atomic-change-group
454 (apply #'delete-region region)
455 (let ((inhibit-message t)
456 (opoint (point)))
457 (insert to-insert)
458 (indent-region opoint (point))
459 (goto-char opoint)
460 (el-search-hl-sexp)))
461 (cl-incf nbr-replaced)
462 (setq replaced-this t))))
463 (if replace-all
464 (funcall do-replace)
465 (while (not (pcase (if replaced-this
466 (read-char-choice "[SPC ! q]" '(?\ ?! ?q ?n))
467 (read-char-choice
468 (concat "Replace this occurence"
469 (if (or (string-match-p "\n" to-insert)
470 (< 40 (length to-insert)))
471 "" (format " with `%s'" to-insert))
472 "? [y SPC r ! q]" )
473 '(?y ?n ?r ?\ ?! ?q)))
474 (?r (funcall do-replace)
475 nil)
476 (?y (funcall do-replace)
477 t)
478 ((or ?\ ?n)
479 (unless replaced-this (cl-incf nbr-skipped))
480 t)
481 (?! (unless replaced-this
482 (funcall do-replace))
483 (setq replace-all t)
484 t)
485 (?q (setq done t)
486 t)))))
487 (unless (or done (eobp)) (forward-char 1)))))
488 (el-search-hl-remove)
489 (goto-char opoint)
490 (message "Replaced %d matches%s"
491 nbr-replaced
492 (if (zerop nbr-skipped) ""
493 (format " (%d skipped)" nbr-skipped)))))
494
495 (defun el-search-query-replace-read-args (&optional initial-contents)
496 (barf-if-buffer-read-only)
497 (let* ((from (el-search--read-pattern "Replace from: " nil initial-contents))
498 (to (el-search--read-pattern "Replace with result of evaluation of: " from)))
499 (list (el-search--maybe-wrap-pattern (read from)) (read to)
500 (with-temp-buffer
501 (insert to)
502 (el-search--create-read-map 1)))))
503
504 ;;;###autoload
505 (defun el-search-query-replace (from to &optional mapping)
506 "Replace some occurrences of FROM pattern with evaluated TO."
507 (interactive (el-search-query-replace-read-args))
508 (setq el-search-current-pattern from)
509 (barf-if-buffer-read-only)
510 (el-search-search-and-replace-pattern from to mapping))
511
512 (defun el-search--take-over-from-isearch ()
513 (let ((other-end isearch-other-end)
514 (input isearch-string))
515 (isearch-exit)
516 (when (and other-end (< other-end (point)))
517 (goto-char other-end))
518 input))
519
520 ;;;###autoload
521 (defun el-search-search-from-isearch ()
522 ;; FIXME: an interesting alternative would be to really integrate it with
523 ;; Isearch, using `isearch-search-fun'.
524 (interactive)
525 (el-search-pattern
526 (el-search--read-pattern
527 "Find pcase pattern: " nil (concat "'" (el-search--take-over-from-isearch)) t))
528 (setq this-command 'el-search-pattern))
529
530 ;;;###autoload
531 (defun el-search-replace-from-isearch ()
532 (interactive)
533 (let ((this-command 'el-search-query-replace))
534 (apply #'el-search-query-replace
535 (el-search-query-replace-read-args (concat "'" (el-search--take-over-from-isearch))))))
536
537
538
539 (provide 'el-search)
540 ;;; el-search.el ends here