1 ;;; sotlisp.el --- Write lisp at the speed of thought. -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
5 ;; Author: Artur Malabarba <bruce.connor.am@gmail.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))
87 (defun sotlisp--auto-paired-p ()
88 "Non-nil if this buffer auto-inserts parentheses."
89 (or (bound-and-true-p electric-pair-mode)
90 (bound-and-true-p paredit-mode)
91 (bound-and-true-p smartparens-mode)))
93 (defun sotlisp--looking-back (regexp)
96 (buffer-substring (line-beginning-position) (point))))
98 (defun sotlisp--function-form-p ()
99 "Non-nil if point is at the start of a sexp.
100 Specially, avoids matching inside argument lists."
101 (and (eq (char-before) ?\()
102 (not (sotlisp--looking-back "(\\(defun\\s-+.*\\|lambda\\s-+\\)("))
103 (not (string-match (rx (syntax symbol)) (string last-command-event)))))
105 (defun sotlisp--function-quote-p ()
106 "Non-nil if point is at a sharp-quote."
110 (looking-at-p "#'"))))
112 (defun sotlisp--code-p ()
116 (let ((pps (parse-partial-sexp (point) r)))
120 (defun sotlisp--function-p ()
121 "Non-nil if point is at reasonable place for a function name.
122 Returns non-nil if, after moving backwards by a sexp, either
123 `sotlisp--function-form-p' or `sotlisp--function-quote-p' return
127 (skip-chars-backward (rx alnum))
128 (and (sotlisp--code-p)
129 (or (sotlisp--function-form-p)
130 (sotlisp--function-quote-p))))))
132 (defun sotlisp--whitespace-p ()
133 "Non-nil if current `self-insert'ed char is whitespace."
134 (sotlisp--whitespace-char-p last-command-event))
135 (make-obsolete 'sotlisp--whitespace-p 'sotlisp--whitespace-char-p "1.2")
137 (defun sotlisp--whitespace-char-p (char)
138 "Non-nil if CHAR is has whitespace syntax."
140 (string-match (rx space) (string char))))
144 (defvar sotlisp--needs-moving nil
145 "Will `sotlisp--move-to-$' move point after insertion?")
147 (defun sotlisp--move-to-$ ()
148 "Move backwards until `$' and delete it.
149 Point is left where the `$' char was. Does nothing if variable
150 `sotlisp-mode' is nil."
151 (when (bound-and-true-p speed-of-thought-mode)
152 (when sotlisp--needs-moving
153 (setq sotlisp--needs-moving nil)
154 (skip-chars-backward "^\\$")
157 (add-hook 'post-command-hook #'sotlisp--move-to-$ 'append)
159 (defun sotlisp--maybe-skip-closing-paren ()
160 "Move past `)' if variable `electric-pair-mode' is enabled."
161 (when (and (char-after ?\))
162 (sotlisp--auto-paired-p))
165 (defun sotlisp--post-expansion-cleanup ()
166 "Do some processing conditioned on the expansion done.
167 If the command that triggered the expansion was a whitespace
168 char, perform the steps below and return t.
170 If the expansion ended in a $, delete it and call
171 `sotlisp--maybe-skip-closing-paren'.
172 If it ended in a space and there's a space ahead, delete the
174 ;; Inform `expand-abbrev' that `self-insert-command' should not
175 ;; trigger, by returning non-nil on SPC.
176 (when (sotlisp--whitespace-char-p last-command-event)
177 ;; And maybe move out of closing paren if expansion ends with $.
178 (if (eq (char-before) ?$)
179 (progn (delete-char -1)
180 (setq sotlisp--needs-moving nil)
181 (sotlisp--maybe-skip-closing-paren))
182 (when (and (sotlisp--whitespace-char-p (char-after))
183 (sotlisp--whitespace-char-p (char-before)))
187 (defvar sotlisp--function-table (make-hash-table :test #'equal)
188 "Table where function abbrev expansions are stored.")
190 (defun sotlisp--expand-function ()
191 "Expand the function abbrev before point.
192 See `sotlisp-define-function-abbrev'."
194 (skip-chars-backward (rx alnum))
195 (let* ((name (buffer-substring (point) r))
196 (expansion (gethash name sotlisp--function-table)))
198 (progn (goto-char r) nil)
199 (delete-region (point) r)
200 (if (sotlisp--function-quote-p)
201 ;; After #' use the simple expansion.
202 (insert (sotlisp--simplify-function-expansion expansion))
203 ;; Inside a form, use the full expansion.
205 (when (string-match "\\$" expansion)
206 (setq sotlisp--needs-moving t)))
208 (sotlisp--post-expansion-cleanup)))))
210 (put 'sotlisp--expand-function 'no-self-insert t)
212 (defun sotlisp--simplify-function-expansion (expansion)
213 "Take a substring of EXPANSION up to first space.
214 The space char is not included. Any \"$\" are also removed."
215 (replace-regexp-in-string
217 (substring expansion 0 (string-match " " expansion))))
220 ;;; Abbrev definitions
221 (defconst sotlisp--default-function-abbrevs
224 ("ah" . "add-hook '")
225 ("atl" . "add-to-list '")
226 ("bb" . "bury-buffer")
227 ("bc" . "forward-char -1")
228 ("bfn" . "buffer-file-name")
229 ("bl" . "buffer-list$")
230 ("blp" . "buffer-live-p ")
231 ("bn" . "buffer-name")
232 ("bod" . "beginning-of-defun")
233 ("bol" . "forward-line 0$")
235 ("bs" . "buffer-string$")
236 ("bsn" . "buffer-substring-no-properties")
237 ("bss" . "buffer-substring ")
238 ("bw" . "forward-word -1")
240 ("ca" . "char-after$")
241 ("cb" . "current-buffer$")
242 ("cc" . "condition-case er\n$\n(error nil)")
243 ("ci" . "call-interactively ")
244 ("cip" . "called-interactively-p 'any")
245 ("csv" . "customize-save-variable '")
246 ("d" . "delete-char 1")
247 ("dc" . "delete-char 1")
248 ("dcu" . "defcustom $ t\n \"\"\n :type 'boolean")
249 ("df" . "defun $ ()\n \"\"\n ")
250 ("dfa" . "defface $ \n '((t))\n \"\"\n ")
251 ("dfc" . "defcustom $ t\n \"\"\n :type 'boolean")
252 ("dff" . "defface $ \n '((t))\n \"\"\n ")
253 ("dfv" . "defvar $ t\n \"\"")
254 ("dk" . "define-key ")
255 ("dl" . "dolist (it $)")
256 ("dmp" . "derived-mode-p '")
257 ("dr" . "delete-region ")
258 ("dv" . "defvar $ t\n \"\"")
259 ("e" . "error \"$\"")
260 ("efn" . "expand-file-name ")
261 ("eol" . "end-of-line")
262 ("f" . "format \"$\"")
264 ("fbp" . "fboundp '")
265 ("fc" . "forward-char 1")
266 ("ff" . "find-file ")
267 ("fl" . "forward-line 1")
268 ("fp" . "functionp ")
269 ("frp" . "file-readable-p ")
270 ("fs" . "forward-sexp 1")
271 ("fw" . "forward-word 1")
273 ("gc" . "goto-char ")
274 ("gsk" . "global-set-key ")
276 ("ie" . "ignore-errors ")
277 ("ii" . "interactive")
278 ("ir" . "indent-region ")
279 ("jcl" . "justify-current-line ")
280 ("jl" . "delete-indentation")
281 ("jos" . "just-one-space")
282 ("jr" . "json-read$")
283 ("jtr" . "jump-to-register ")
285 ("kb" . "kill-buffer")
289 ("la" . "looking-at \"$\"")
290 ("lap" . "looking-at-p \"$\"")
291 ("lb" . "looking-back \"$\"")
292 ("lbp" . "line-beginning-position")
293 ("lep" . "line-end-position")
294 ("let" . "let (($))")
296 ("m" . "message \"$%s\"")
297 ("mb" . "match-beginning 0")
298 ("me" . "match-end 0")
299 ("ms" . "match-string 0")
300 ("msn" . "match-string-no-properties 0")
301 ("msnp" . "match-string-no-properties 0")
302 ("msp" . "match-string-no-properties 0")
304 ("nai" . "newline-and-indent$")
305 ("nl" . "forward-line 1")
307 ("ntr" . "narrow-to-region ")
308 ("ow" . "other-window 1")
310 ("pm" . "point-marker$")
311 ("pa" . "point-max$")
312 ("pg" . "plist-get ")
313 ("pi" . "point-min$")
315 ("ra" . "use-region-p$")
316 ("rap" . "use-region-p$")
317 ("rb" . "region-beginning")
318 ("re" . "region-end")
319 ("rh" . "remove-hook '")
320 ("rm" . "replace-match \"$\"")
321 ("ro" . "regexp-opt ")
322 ("rq" . "regexp-quote ")
323 ("rris" . "replace-regexp-in-string ")
324 ("rrs" . "replace-regexp-in-string ")
325 ("rs" . "while (search-forward $ nil t)\n(replace-match \"\") nil t)")
326 ("rsb" . "re-search-backward $ nil 'noerror")
327 ("rsf" . "re-search-forward $ nil 'noerror")
329 ("sb" . "search-backward $ nil 'noerror")
330 ("sbr" . "search-backward-regexp $ nil 'noerror")
331 ("scb" . "skip-chars-backward \"$\\r\\n[:blank:]\"")
332 ("scf" . "skip-chars-forward \"$\\r\\n[:blank:]\"")
333 ("se" . "save-excursion")
334 ("sf" . "search-forward $ nil 'noerror")
335 ("sfr" . "search-forward-regexp $ nil 'noerror")
336 ("sic" . "self-insert-command")
338 ("sm" . "string-match \"$\"")
339 ("smd" . "save-match-data")
340 ("sn" . "symbol-name ")
343 ("sr" . "save-restriction")
344 ("ss" . "substring ")
345 ("ssn" . "substring-no-properties ")
346 ("ssnp" . "substring-no-properties ")
347 ("stb" . "switch-to-buffer ")
348 ("sw" . "selected-window$")
350 ("tap" . "thing-at-point 'symbol")
353 ("up" . "unwind-protect\n(progn $)")
354 ("urp" . "use-region-p$")
356 ("wcb" . "with-current-buffer ")
357 ("wf" . "write-file ")
359 ("wl" . "window-list nil 'nominibuffer")
360 ("we" . "window-end")
361 ("ws" . "window-start")
362 ("wtb" . "with-temp-buffer")
363 ("wtf" . "with-temp-file ")
365 "Alist of (ABBREV . EXPANSION) used by `sotlisp'.")
367 (defun sotlisp-define-function-abbrev (name expansion)
368 "Define a function abbrev expanding NAME to EXPANSION.
369 This abbrev will only be expanded in places where a function name is
370 sensible. Roughly, this is right after a `(' or a `#''.
372 If EXPANSION is any string, it doesn't have to be the just the
373 name of a function. In particular:
374 - if it contains a `$', this char will not be inserted and
375 point will be moved to its position after expansion.
376 - if it contains a space, only a substring of it up to the
377 first space is inserted when expanding after a `#'' (this is done
378 by defining two different abbrevs).
380 For instance, if one defines
381 (sotlisp-define-function-abbrev \"d\" \"delete-char 1\")
383 then triggering `expand-abbrev' after \"d\" expands in the
386 #'d => #'delete-char"
387 (define-abbrev emacs-lisp-mode-abbrev-table
388 name t #'sotlisp--expand-function
389 ;; Don't override user abbrevs
391 ;; Only expand in function places.
392 :enable-function #'sotlisp--function-p)
393 (puthash name expansion sotlisp--function-table))
395 (defun sotlisp-erase-all-abbrevs ()
396 "Undefine all abbrevs defined by `sotlisp'."
398 (maphash (lambda (x _) (define-abbrev emacs-lisp-mode-abbrev-table x nil))
399 sotlisp--function-table))
401 (defun sotlisp-define-all-abbrevs ()
402 "Define all abbrevs in `sotlisp--default-function-abbrevs'."
404 (mapc (lambda (x) (sotlisp-define-function-abbrev (car x) (cdr x)))
405 sotlisp--default-function-abbrevs))
408 ;;; The global minor-mode
409 (defvar speed-of-thought-turn-on-hook '()
410 "Hook run once when `speed-of-thought-mode' is enabled.
411 Note that `speed-of-thought-mode' is global, so this is not run
414 See `sotlisp-turn-on-everywhere' for an example of what a
415 function in this hook should do.")
417 (defvar speed-of-thought-turn-off-hook '()
418 "Hook run once when `speed-of-thought-mode' is disabled.
419 Note that `speed-of-thought-mode' is global, so this is not run
422 See `sotlisp-turn-on-everywhere' for an example of what a
423 function in this hook should do.")
426 (define-minor-mode speed-of-thought-mode
429 (run-hooks (if speed-of-thought-mode
430 'speed-of-thought-turn-on-hook
431 'speed-of-thought-turn-off-hook)))
434 (defun speed-of-thought-hook-in (on off)
435 "Add functions ON and OFF to `speed-of-thought-mode' hooks.
436 If `speed-of-thought-mode' is already on, call ON."
437 (add-hook 'speed-of-thought-turn-on-hook on)
438 (add-hook 'speed-of-thought-turn-off-hook off)
439 (when speed-of-thought-mode (funcall on)))
442 ;;; The local minor-mode
443 (define-minor-mode sotlisp-mode
445 '(([M-return] . sotlisp-newline-and-parentheses)
446 ([C-return] . sotlisp-downlist-newline-and-parentheses)
447 ("\C-cf" . sotlisp-find-or-define-function)
448 ("\C-cv" . sotlisp-find-or-define-variable)))
450 (defun sotlisp-turn-on-everywhere ()
451 "Call-once function to turn on sotlisp everywhere.
452 Calls `sotlisp-mode' on all `emacs-lisp-mode' buffers, and sets
453 up a hook and abbrevs."
454 (add-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
455 (sotlisp-define-all-abbrevs)
457 (with-current-buffer b
458 (when (derived-mode-p 'emacs-lisp-mode)
462 (defun sotlisp-turn-off-everywhere ()
463 "Call-once function to turn off sotlisp everywhere.
464 Removes `sotlisp-mode' from all `emacs-lisp-mode' buffers, and
465 removes hooks and abbrevs."
466 (remove-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
467 (sotlisp-erase-all-abbrevs)
469 (with-current-buffer b
470 (when (derived-mode-p 'emacs-lisp-mode)
474 (speed-of-thought-hook-in #'sotlisp-turn-on-everywhere #'sotlisp-turn-off-everywhere)
478 (defun sotlisp-newline-and-parentheses ()
479 "`newline-and-indent' then insert a pair of parentheses."
482 (ignore-errors (expand-abbrev))
487 (defun sotlisp-downlist-newline-and-parentheses ()
488 "`up-list', `newline-and-indent', then insert a parentheses pair."
490 (ignore-errors (expand-abbrev))
496 (defun sotlisp--find-in-buffer (r s)
497 "Find the string (concat R (regexp-quote S)) somewhere in this buffer."
498 (let ((l (save-excursion
499 (goto-char (point-min))
501 (when (search-forward-regexp (concat r (regexp-quote s) "\\_>")
503 (match-beginning 0))))))
509 (defun sotlisp--beginning-of-defun ()
510 "`push-mark' and move above this defun."
513 (when (looking-back "^;;;###autoload\\s-*\n")
516 (defun sotlisp--function-at-point ()
517 "Return name of `function-called-at-point'."
519 (ignore-errors (forward-sexp -1)
520 (looking-at-p "#'")))
521 (thing-at-point 'symbol)
522 (let ((fcap (function-called-at-point)))
525 (thing-at-point 'symbol)))))
527 (defun sotlisp-find-or-define-function (&optional prefix)
528 "If symbol under point is a defined function, go to it, otherwise define it.
529 Essentially `find-function' on steroids.
531 If you write in your code the name of a function you haven't
532 defined yet, just place point on its name and hit \\[sotlisp-find-or-define-function]
533 and a defun will be inserted with point inside it. After that,
534 you can just hit `pop-mark' to go back to where you were.
535 With a PREFIX argument, creates a `defmacro' instead.
537 If the function under point is already defined this just calls
538 `find-function', with one exception:
539 if there's a defun (or equivalent) for this function in the
540 current buffer, we go to that even if it's not where the
541 global definition comes from (this is useful if you're
542 writing an Emacs package that also happens to be installed
545 With a prefix argument, defines a `defmacro' instead of a `defun'."
547 (let ((name (sotlisp--function-at-point)))
548 (unless (and name (sotlisp--find-in-buffer "(def\\(un\\|macro\\|alias\\) " name))
549 (let ((name-s (intern-soft name)))
551 (find-function name-s)
552 (sotlisp--beginning-of-defun)
553 (insert "(def" (if prefix "macro" "un")
555 (save-excursion (insert ")\n \"\"\n )\n\n")))))))
557 (defun sotlisp-find-or-define-variable (&optional prefix)
558 "If symbol under point is a defined variable, go to it, otherwise define it.
559 Essentially `find-variable' on steroids.
561 If you write in your code the name of a variable you haven't
562 defined yet, place point on its name and hit \\[sotlisp-find-or-define-variable]
563 and a `defcustom' will be created with point inside. After that,
564 you can just `pop-mark' to go back to where you were. With a
565 PREFIX argument, creates a `defvar' instead.
567 If the variable under point is already defined this just calls
568 `find-variable', with one exception:
569 if there's a defvar (or equivalent) for this variable in the
570 current buffer, we go to that even if it's not where the
571 global definition comes from (this is useful if you're
572 writing an Emacs package that also happens to be installed
575 With a prefix argument, defines a `defvar' instead of a `defcustom'."
577 (let ((name (symbol-name (variable-at-point t))))
578 (unless (sotlisp--find-in-buffer "(def\\(custom\\|const\\|var\\) " name)
579 (unless (and (symbolp (variable-at-point))
580 (ignore-errors (find-variable (variable-at-point)) t))
581 (let ((name (thing-at-point 'symbol)))
582 (sotlisp--beginning-of-defun)
583 (insert "(def" (if prefix "var" "custom")
587 (if prefix "" "\n :type 'boolean")
591 ;;; sotlisp.el ends here