1 ;;; sotlisp.el --- Write lisp at the speed of thought. -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2014, 2015 Free Software Foundation, Inc.
5 ;; Author: Artur Malabarba <emacs@endlessparentheses.com>
6 ;; URL: https://github.com/Malabarba/speed-of-thought-lisp
7 ;; Keywords: convenience, lisp
8 ;; Package-Requires: ((emacs "24.1"))
11 ;; This program is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; This program is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
26 ;; This defines a new global minor-mode `speed-of-thought-mode', which
27 ;; activates locally on any supported buffer. Currently, only
28 ;; `emacs-lisp-mode' buffers are supported.
30 ;; The mode is quite simple, and is composed of two parts:
34 ;; A large number of abbrevs which expand function
35 ;; initials to their name. A few examples:
37 ;; - wcb -> with-current-buffer
42 ;; However, these are defined in a way such that they ONLY expand in a
43 ;; place where you would use a function, so hitting SPC after "(r"
44 ;; expands to "(require '", but hitting SPC after "(delete-region r"
45 ;; will NOT expand the `r', because that's obviously not a function.
46 ;; Furtheromre, "#'r" will expand to "#'require" (note how it ommits
47 ;; that extra quote, since it would be useless here).
51 ;; It also defines 4 commands, which really fit into this "follow the
52 ;; thought-flow" way of writing. The bindings are as follows, I
53 ;; understand these don't fully adhere to conventions, and I'd
54 ;; appreciate suggestions on better bindings.
56 ;; - M-RET :: Break line, and insert "()" with point in the middle.
57 ;; - C-RET :: Do `forward-up-list', then do M-RET.
59 ;; Hitting RET followed by a `(' was one of the most common key sequences
60 ;; for me while writing elisp, so giving it a quick-to-hit key was a
61 ;; significant improvement.
63 ;; - C-c f :: Find function under point. If it is not defined, create a
64 ;; definition for it below the current function and leave point inside.
65 ;; - C-c v :: Same, but for variable.
67 ;; With these commands, you just write your code as you think of it. Once
68 ;; you hit a "stop-point" of sorts in your tought flow, you hit `C-c f/v`
69 ;; on any undefined functions/variables, write their definitions, and hit
70 ;; `C-u C-SPC` to go back to the main function.
74 ;; With the above (assuming you use something like paredit or
75 ;; electric-pair-mode), if you write:
77 ;; ( w t b M-RET i SPC text
81 ;; (with-temp-buffer (insert text))
86 (defun sotlisp--auto-paired-p ()
87 "Non-nil if this buffer auto-inserts parentheses."
88 (or (bound-and-true-p electric-pair-mode)
89 (bound-and-true-p paredit-mode)
90 (bound-and-true-p smartparens-mode)))
92 (defun sotlisp--looking-back (regexp)
95 (buffer-substring (line-beginning-position) (point))))
97 (defun sotlisp--function-form-p ()
98 "Non-nil if point is at the start of a sexp.
99 Specially, avoids matching inside argument lists."
100 (and (eq (char-before) ?\()
101 (not (sotlisp--looking-back "(\\(defun\\s-+.*\\|\\(lambda\\|dolist\\|dotimes\\)\\s-+\\)("))
109 (looking-at-p (rx (* (or (syntax word) (syntax symbol) "-"))
112 (not (string-match (rx (syntax symbol)) (string last-command-event)))))
114 (defun sotlisp--function-quote-p ()
115 "Non-nil if point is at a sharp-quote."
119 (looking-at-p "#'"))))
121 (defun sotlisp--code-p ()
125 (let ((pps (parse-partial-sexp (point) r)))
129 (defun sotlisp--function-p ()
130 "Non-nil if point is at reasonable place for a function name.
131 Returns non-nil if, after moving backwards by a sexp, either
132 `sotlisp--function-form-p' or `sotlisp--function-quote-p' return
136 (skip-chars-backward (rx alnum))
137 (and (sotlisp--code-p)
138 (or (sotlisp--function-form-p)
139 (sotlisp--function-quote-p))))))
141 (defun sotlisp--whitespace-p ()
142 "Non-nil if current `self-insert'ed char is whitespace."
143 (sotlisp--whitespace-char-p last-command-event))
144 (make-obsolete 'sotlisp--whitespace-p 'sotlisp--whitespace-char-p "1.2")
146 (defun sotlisp--whitespace-char-p (char)
147 "Non-nil if CHAR is has whitespace syntax."
149 (string-match (rx space) (string char))))
153 (defvar sotlisp--needs-moving nil
154 "Will `sotlisp--move-to-$' move point after insertion?")
156 (defun sotlisp--move-to-$ ()
157 "Move backwards until `$' and delete it.
158 Point is left where the `$' char was. Does nothing if variable
159 `sotlisp-mode' is nil."
160 (when (bound-and-true-p speed-of-thought-mode)
161 (when sotlisp--needs-moving
162 (setq sotlisp--needs-moving nil)
163 (skip-chars-backward "^\\$")
166 (add-hook 'post-command-hook #'sotlisp--move-to-$ 'append)
168 (defun sotlisp--maybe-skip-closing-paren ()
169 "Move past `)' if variable `electric-pair-mode' is enabled."
170 (when (and (char-after ?\))
171 (sotlisp--auto-paired-p))
174 (defun sotlisp--post-expansion-cleanup ()
175 "Do some processing conditioned on the expansion done.
176 If the command that triggered the expansion was a whitespace
177 char, perform the steps below and return t.
179 If the expansion ended in a $, delete it and call
180 `sotlisp--maybe-skip-closing-paren'.
181 If it ended in a space and there's a space ahead, delete the
183 ;; Inform `expand-abbrev' that `self-insert-command' should not
184 ;; trigger, by returning non-nil on SPC.
185 (when (sotlisp--whitespace-char-p last-command-event)
186 ;; And maybe move out of closing paren if expansion ends with $.
187 (if (eq (char-before) ?$)
188 (progn (delete-char -1)
189 (setq sotlisp--needs-moving nil)
190 (sotlisp--maybe-skip-closing-paren))
191 (when (and (sotlisp--whitespace-char-p (char-after))
192 (sotlisp--whitespace-char-p (char-before)))
196 (defvar sotlisp--function-table (make-hash-table :test #'equal)
197 "Table where function abbrev expansions are stored.")
199 (defun sotlisp--expand-function ()
200 "Expand the function abbrev before point.
201 See `sotlisp-define-function-abbrev'."
203 (skip-chars-backward (rx alnum))
204 (let* ((name (buffer-substring (point) r))
205 (expansion (gethash name sotlisp--function-table)))
207 (progn (goto-char r) nil)
208 (delete-region (point) r)
209 (if (sotlisp--function-quote-p)
210 ;; After #' use the simple expansion.
211 (insert (sotlisp--simplify-function-expansion expansion))
212 ;; Inside a form, use the full expansion.
214 (when (string-match "\\$" expansion)
215 (setq sotlisp--needs-moving t)))
217 (sotlisp--post-expansion-cleanup)))))
219 (put 'sotlisp--expand-function 'no-self-insert t)
221 (defun sotlisp--simplify-function-expansion (expansion)
222 "Take a substring of EXPANSION up to first space.
223 The space char is not included. Any \"$\" are also removed."
224 (replace-regexp-in-string
226 (substring expansion 0 (string-match " " expansion))))
229 ;;; Abbrev definitions
230 (defconst sotlisp--default-function-abbrevs
233 ("ah" . "add-hook '")
234 ("atl" . "add-to-list '")
235 ("bb" . "bury-buffer")
236 ("bc" . "forward-char -1")
237 ("bfn" . "buffer-file-name")
238 ("bl" . "buffer-list$")
239 ("blp" . "buffer-live-p ")
240 ("bn" . "buffer-name")
241 ("bod" . "beginning-of-defun")
242 ("bol" . "forward-line 0$")
244 ("bs" . "buffer-string$")
245 ("bsn" . "buffer-substring-no-properties")
246 ("bss" . "buffer-substring ")
247 ("bw" . "forward-word -1")
249 ("ca" . "char-after$")
250 ("cb" . "current-buffer$")
251 ("cc" . "condition-case er\n$\n(error nil)")
252 ("ci" . "call-interactively ")
253 ("cip" . "called-interactively-p 'any")
254 ("csv" . "customize-save-variable '")
255 ("d" . "delete-char 1")
256 ("dc" . "delete-char 1")
257 ("dcu" . "defcustom $ t\n \"\"\n :type 'boolean")
258 ("df" . "defun $ ()\n \"\"\n ")
259 ("dfa" . "defface $ \n '((t))\n \"\"\n ")
260 ("dfc" . "defcustom $ t\n \"\"\n :type 'boolean")
261 ("dff" . "defface $ \n '((t))\n \"\"\n ")
262 ("dfv" . "defvar $ t\n \"\"")
263 ("dk" . "define-key ")
264 ("dl" . "dolist (it $)")
265 ("dt" . "dotimes (it $)")
266 ("dmp" . "derived-mode-p '")
267 ("dm" . "defmacro $ ()\n \"\"\n ")
268 ("dr" . "delete-region ")
269 ("dv" . "defvar $ t\n \"\"")
270 ("e" . "error \"$\"")
271 ("efn" . "expand-file-name ")
272 ("eol" . "end-of-line")
273 ("f" . "format \"$\"")
275 ("fbp" . "fboundp '")
276 ("fc" . "forward-char 1")
277 ("ff" . "find-file ")
278 ("fl" . "forward-line 1")
279 ("fp" . "functionp ")
280 ("frp" . "file-readable-p ")
281 ("fs" . "forward-sexp 1")
283 ("fw" . "forward-word 1")
285 ("gc" . "goto-char ")
286 ("gsk" . "global-set-key ")
288 ("ie" . "ignore-errors ")
289 ("ii" . "interactive")
290 ("il" . "if-let (($))")
291 ("ir" . "indent-region ")
292 ("jcl" . "justify-current-line ")
293 ("jl" . "delete-indentation")
294 ("jos" . "just-one-space")
295 ("jr" . "json-read$")
296 ("jtr" . "jump-to-register ")
298 ("kb" . "kill-buffer")
302 ("la" . "looking-at \"$\"")
303 ("lap" . "looking-at-p \"$\"")
304 ("lb" . "looking-back \"$\"")
305 ("lbp" . "line-beginning-position")
306 ("lep" . "line-end-position")
307 ("let" . "let (($))")
309 ("m" . "message \"$%s\"")
310 ("mb" . "match-beginning 0")
312 ("mct" . "mapconcat ")
313 ("me" . "match-end 0")
314 ("ms" . "match-string 0")
315 ("msn" . "match-string-no-properties 0")
316 ("msnp" . "match-string-no-properties 0")
317 ("msp" . "match-string-no-properties 0")
318 ("mt" . "mapconcat ")
320 ("nai" . "newline-and-indent$")
321 ("nl" . "forward-line 1")
323 ("ntr" . "narrow-to-region ")
324 ("ow" . "other-window 1")
326 ("pm" . "point-marker$")
327 ("pa" . "point-max$")
328 ("pg" . "plist-get ")
329 ("pi" . "point-min$")
330 ("pz" . "propertize ")
332 ("ra" . "use-region-p$")
333 ("rap" . "use-region-p$")
334 ("rb" . "region-beginning")
335 ("re" . "region-end")
336 ("rh" . "remove-hook '")
337 ("rm" . "replace-match \"$\"")
338 ("ro" . "regexp-opt ")
339 ("rq" . "regexp-quote ")
340 ("rris" . "replace-regexp-in-string ")
341 ("rrs" . "replace-regexp-in-string ")
342 ("rs" . "while (search-forward $ nil t)\n(replace-match \"\") nil t)")
343 ("rsb" . "re-search-backward \"$\" nil 'noerror")
344 ("rsf" . "re-search-forward \"$\" nil 'noerror")
346 ("sb" . "search-backward $ nil 'noerror")
347 ("sbr" . "search-backward-regexp $ nil 'noerror")
348 ("scb" . "skip-chars-backward \"$\\r\\n[:blank:]\"")
349 ("scf" . "skip-chars-forward \"$\\r\\n[:blank:]\"")
350 ("se" . "save-excursion")
351 ("sf" . "search-forward $ nil 'noerror")
352 ("sfr" . "search-forward-regexp $ nil 'noerror")
353 ("sic" . "self-insert-command")
354 ("sl" . "setq-local ")
355 ("sm" . "string-match \"$\"")
356 ("smd" . "save-match-data")
357 ("sn" . "symbol-name ")
360 ("sr" . "save-restriction")
361 ("ss" . "substring ")
362 ("ssn" . "substring-no-properties ")
363 ("ssnp" . "substring-no-properties ")
364 ("stb" . "switch-to-buffer ")
365 ("sw" . "selected-window$")
367 ("tap" . "thing-at-point 'symbol")
370 ("up" . "unwind-protect\n(progn $)")
371 ("urp" . "use-region-p$")
373 ("wcb" . "with-current-buffer ")
374 ("wf" . "write-file ")
376 ("wl" . "when-let (($))")
377 ("we" . "window-end")
378 ("ws" . "window-start")
379 ("wsw" . "with-selected-window ")
380 ("wtb" . "with-temp-buffer")
381 ("wtf" . "with-temp-file ")
383 "Alist of (ABBREV . EXPANSION) used by `sotlisp'.")
385 (defun sotlisp-define-function-abbrev (name expansion)
386 "Define a function abbrev expanding NAME to EXPANSION.
387 This abbrev will only be expanded in places where a function name is
388 sensible. Roughly, this is right after a `(' or a `#''.
390 If EXPANSION is any string, it doesn't have to be the just the
391 name of a function. In particular:
392 - if it contains a `$', this char will not be inserted and
393 point will be moved to its position after expansion.
394 - if it contains a space, only a substring of it up to the
395 first space is inserted when expanding after a `#'' (this is done
396 by defining two different abbrevs).
398 For instance, if one defines
399 (sotlisp-define-function-abbrev \"d\" \"delete-char 1\")
401 then triggering `expand-abbrev' after \"d\" expands in the
404 #'d => #'delete-char"
405 (define-abbrev emacs-lisp-mode-abbrev-table
406 name t #'sotlisp--expand-function
407 ;; Don't override user abbrevs
409 ;; Only expand in function places.
410 :enable-function #'sotlisp--function-p)
411 (puthash name expansion sotlisp--function-table))
413 (defun sotlisp-erase-all-abbrevs ()
414 "Undefine all abbrevs defined by `sotlisp'."
416 (maphash (lambda (x _) (define-abbrev emacs-lisp-mode-abbrev-table x nil))
417 sotlisp--function-table))
419 (defun sotlisp-define-all-abbrevs ()
420 "Define all abbrevs in `sotlisp--default-function-abbrevs'."
422 (mapc (lambda (x) (sotlisp-define-function-abbrev (car x) (cdr x)))
423 sotlisp--default-function-abbrevs))
426 ;;; The global minor-mode
427 (defvar speed-of-thought-turn-on-hook '()
428 "Hook run once when `speed-of-thought-mode' is enabled.
429 Note that `speed-of-thought-mode' is global, so this is not run
432 See `sotlisp-turn-on-everywhere' for an example of what a
433 function in this hook should do.")
435 (defvar speed-of-thought-turn-off-hook '()
436 "Hook run once when `speed-of-thought-mode' is disabled.
437 Note that `speed-of-thought-mode' is global, so this is not run
440 See `sotlisp-turn-on-everywhere' for an example of what a
441 function in this hook should do.")
444 (define-minor-mode speed-of-thought-mode
447 (run-hooks (if speed-of-thought-mode
448 'speed-of-thought-turn-on-hook
449 'speed-of-thought-turn-off-hook)))
452 (defun speed-of-thought-hook-in (on off)
453 "Add functions ON and OFF to `speed-of-thought-mode' hooks.
454 If `speed-of-thought-mode' is already on, call ON."
455 (add-hook 'speed-of-thought-turn-on-hook on)
456 (add-hook 'speed-of-thought-turn-off-hook off)
457 (when speed-of-thought-mode (funcall on)))
460 ;;; The local minor-mode
461 (define-minor-mode sotlisp-mode
463 `(([M-return] . sotlisp-newline-and-parentheses)
464 ([C-return] . sotlisp-downlist-newline-and-parentheses)
465 (,(kbd "C-M-;") . ,(if (fboundp 'comment-or-uncomment-sexp)
466 #'comment-or-uncomment-sexp
467 #'sotlisp-comment-or-uncomment-sexp))
468 ("\C-cf" . sotlisp-find-or-define-function)
469 ("\C-cv" . sotlisp-find-or-define-variable)))
471 (defun sotlisp-turn-on-everywhere ()
472 "Call-once function to turn on sotlisp everywhere.
473 Calls `sotlisp-mode' on all `emacs-lisp-mode' buffers, and sets
474 up a hook and abbrevs."
475 (add-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
476 (sotlisp-define-all-abbrevs)
478 (with-current-buffer b
479 (when (derived-mode-p 'emacs-lisp-mode)
483 (defun sotlisp-turn-off-everywhere ()
484 "Call-once function to turn off sotlisp everywhere.
485 Removes `sotlisp-mode' from all `emacs-lisp-mode' buffers, and
486 removes hooks and abbrevs."
487 (remove-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
488 (sotlisp-erase-all-abbrevs)
490 (with-current-buffer b
491 (when (derived-mode-p 'emacs-lisp-mode)
495 (speed-of-thought-hook-in #'sotlisp-turn-on-everywhere #'sotlisp-turn-off-everywhere)
499 (defun sotlisp-newline-and-parentheses ()
500 "`newline-and-indent' then insert a pair of parentheses."
503 (ignore-errors (expand-abbrev))
508 (defun sotlisp-downlist-newline-and-parentheses ()
509 "`up-list', `newline-and-indent', then insert a parentheses pair."
511 (ignore-errors (expand-abbrev))
517 (defun sotlisp--find-in-buffer (r s)
518 "Find the string (concat R (regexp-quote S)) somewhere in this buffer."
519 (let ((l (save-excursion
520 (goto-char (point-min))
522 (when (search-forward-regexp (concat r (regexp-quote s) "\\_>")
524 (match-beginning 0))))))
530 (defun sotlisp--beginning-of-defun ()
531 "`push-mark' and move above this defun."
535 (unless (looking-at "^;;;###autoload\\s-*\n")
538 (defun sotlisp--function-at-point ()
539 "Return name of `function-called-at-point'."
541 (ignore-errors (forward-sexp -1)
542 (looking-at-p "#'")))
543 (thing-at-point 'symbol)
544 (let ((fcap (function-called-at-point)))
547 (thing-at-point 'symbol)))))
549 (defun sotlisp-find-or-define-function (&optional prefix)
550 "If symbol under point is a defined function, go to it, otherwise define it.
551 Essentially `find-function' on steroids.
553 If you write in your code the name of a function you haven't
554 defined yet, just place point on its name and hit \\[sotlisp-find-or-define-function]
555 and a defun will be inserted with point inside it. After that,
556 you can just hit `pop-mark' to go back to where you were.
557 With a PREFIX argument, creates a `defmacro' instead.
559 If the function under point is already defined this just calls
560 `find-function', with one exception:
561 if there's a defun (or equivalent) for this function in the
562 current buffer, we go to that even if it's not where the
563 global definition comes from (this is useful if you're
564 writing an Emacs package that also happens to be installed
567 With a prefix argument, defines a `defmacro' instead of a `defun'."
569 (let ((name (sotlisp--function-at-point)))
570 (unless (and name (sotlisp--find-in-buffer "(def\\(un\\|macro\\|alias\\) " name))
571 (let ((name-s (intern-soft name)))
573 (find-function name-s)
574 (sotlisp--beginning-of-defun)
575 (insert "(def" (if prefix "macro" "un")
577 (save-excursion (insert ")\n \"\"\n )\n\n")))))))
579 (defun sotlisp-find-or-define-variable (&optional prefix)
580 "If symbol under point is a defined variable, go to it, otherwise define it.
581 Essentially `find-variable' on steroids.
583 If you write in your code the name of a variable you haven't
584 defined yet, place point on its name and hit \\[sotlisp-find-or-define-variable]
585 and a `defcustom' will be created with point inside. After that,
586 you can just `pop-mark' to go back to where you were. With a
587 PREFIX argument, creates a `defvar' instead.
589 If the variable under point is already defined this just calls
590 `find-variable', with one exception:
591 if there's a defvar (or equivalent) for this variable in the
592 current buffer, we go to that even if it's not where the
593 global definition comes from (this is useful if you're
594 writing an Emacs package that also happens to be installed
597 With a prefix argument, defines a `defvar' instead of a `defcustom'."
599 (let ((name (symbol-name (variable-at-point t))))
600 (unless (sotlisp--find-in-buffer "(def\\(custom\\|const\\|var\\) " name)
601 (unless (and (symbolp (variable-at-point))
602 (ignore-errors (find-variable (variable-at-point)) t))
603 (let ((name (thing-at-point 'symbol)))
604 (sotlisp--beginning-of-defun)
605 (insert "(def" (if prefix "var" "custom")
609 (if prefix "" "\n :type 'boolean")
614 (defun sotlisp-uncomment-sexp (&optional n)
615 "Uncomment a sexp around point."
617 (let* ((initial-point (point-marker))
618 (inhibit-field-text-motion t)
621 (when (elt (syntax-ppss) 4)
622 (re-search-backward comment-start-skip
623 (line-beginning-position)
625 (setq p (point-marker))
626 (comment-forward (point-max))
630 (while (and (not (bobp))
631 (= end (save-excursion
632 (comment-forward (point-max))
635 (goto-char (line-end-position))
636 (re-search-backward comment-start-skip
637 (line-beginning-position)
640 (while (looking-at comment-start-skip)
642 (unless (looking-at "[\n\r[:blank]]")
646 (uncomment-region beg end)
648 ;; Indentify the "top-level" sexp inside the comment.
650 (while (>= (point) beg)
651 (backward-prefix-chars)
652 (skip-chars-backward "\r\n[:blank:]")
653 (setq p (point-marker))
655 ;; Re-comment everything before it.
657 (comment-region beg p))
658 ;; And everything after it.
660 (forward-sexp (or n 1))
661 (skip-chars-forward "\r\n[:blank:]")
664 (comment-region (point) end))
665 ;; If this is a closing delimiter, pull it up.
667 (skip-chars-forward "\r\n[:blank:]")
668 (when (eq 5 (car (syntax-after (point))))
669 (delete-indentation))))
670 ;; Without a prefix, it's more useful to leave point where
673 (goto-char initial-point))))
675 (defun sotlisp--comment-sexp-raw ()
676 "Comment the sexp at point or ahead of point."
677 (pcase (or (bounds-of-thing-at-point 'sexp)
679 (skip-chars-forward "\r\n[:blank:]")
680 (bounds-of-thing-at-point 'sexp)))
683 (skip-chars-forward "\r\n[:blank:]")
685 (comment-region l r))
686 (skip-chars-forward "\r\n[:blank:]"))))
688 (defun sotlisp-comment-or-uncomment-sexp (&optional n)
689 "Comment the sexp at point and move past it.
690 If already inside (or before) a comment, uncomment instead.
691 With a prefix argument N, (un)comment that many sexps."
693 (if (or (elt (syntax-ppss) 4)
695 (skip-chars-forward "\r\n[:blank:]")
700 (sotlisp-uncomment-sexp n)
701 (dotimes (_ (or n 1))
702 (sotlisp--comment-sexp-raw))))
705 ;;; sotlisp.el ends here