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--function-form-p ()
94 "Non-nil if point is at the start of a sexp.
95 Specially, avoids matching inside argument lists."
96 (and (eq (char-before) ?\()
97 (not (looking-back "(\\(defun\\s-+.*\\|lambda\\s-+\\)("))
98 (not (string-match (rx (syntax symbol)) (string last-command-event)))))
100 (defun sotlisp--function-quote-p ()
101 "Non-nil if point is at a sharp-quote."
104 (defun sotlisp--function-p ()
105 "Non-nil if point is at reasonable place for a function name.
106 Returns non-nil if, after moving backwards by a sexp, either
107 `sotlisp--function-form-p' or `sotlisp--function-quote-p' return
111 (skip-chars-backward (rx alnum))
112 (or (sotlisp--function-form-p)
113 (sotlisp--function-quote-p)))))
115 (defun sotlisp--whitespace-p ()
116 "Non-nil if current `self-insert'ed char is whitespace."
118 (string-match (rx space) (string last-command-event))))
122 (defvar sotlisp--needs-moving nil
123 "Will `sotlisp--move-to-$' move point after insertion?")
125 (defun sotlisp--move-to-$ ()
126 "Move backwards until `$' and delete it.
127 Point is left where the `$' char was. Does nothing if variable
128 `sotlisp-mode' is nil."
129 (when (bound-and-true-p speed-of-thought-mode)
130 (when sotlisp--needs-moving
131 (setq sotlisp--needs-moving nil)
132 (skip-chars-backward "^\\$")
135 (add-hook 'post-command-hook #'sotlisp--move-to-$ 'append)
137 (defun sotlisp--maybe-skip-closing-paren ()
138 "Move past `)' if variable `electric-pair-mode' is enabled."
139 (when (and (char-after ?\))
140 (sotlisp--auto-paired-p))
143 (defun sotlisp--post-expansion-cleanup ()
144 "Do some processing conditioned on the expansion done.
145 If the command that triggered the expansion was a whitespace
146 char, perform the steps below and return t.
148 If the expansion ended in a $, delete it and call
149 `sotlisp--maybe-skip-closing-paren'.
150 If it ended in a space and there's a space ahead, delete the
152 ;; Inform `expand-abbrev' that `self-insert-command' should not
153 ;; trigger, by returning non-nil on SPC.
154 (when (sotlisp--whitespace-p)
155 ;; And maybe move out of closing paren if expansion ends with $.
156 (if (eq (char-before) ?$)
157 (progn (delete-char -1)
158 (setq sotlisp--needs-moving nil)
159 (sotlisp--maybe-skip-closing-paren))
160 (when (and (string-match (rx space) (string (char-after)))
161 (string-match (rx space) (string (char-before))))
165 (defvar sotlisp--function-table (make-hash-table :test #'equal)
166 "Table where function abbrev expansions are stored.")
168 (defun sotlisp--expand-function ()
169 "Expand the function abbrev before point.
170 See `sotlisp-define-function-abbrev'."
172 (skip-chars-backward (rx alnum))
173 (let* ((name (buffer-substring (point) r))
174 (expansion (gethash name sotlisp--function-table)))
176 (progn (goto-char r) nil)
177 (delete-region (point) r)
178 (if (sotlisp--function-quote-p)
179 ;; After #' use the simple expansion.
180 (insert (sotlisp--simplify-function-expansion expansion))
181 ;; Inside a form, use the full expansion.
183 (when (string-match "\\$" expansion)
184 (setq sotlisp--needs-moving t)))
186 (sotlisp--post-expansion-cleanup)))))
188 (put 'sotlisp--expand-function 'no-self-insert t)
190 (defun sotlisp--simplify-function-expansion (expansion)
191 "Take a substring of EXPANSION up to first space.
192 The space char is not included. Any \"$\" are also removed."
193 (replace-regexp-in-string
195 (substring expansion 0 (string-match " " expansion))))
198 ;;; Abbrev definitions
199 (defconst sotlisp--default-function-abbrevs
202 ("ah" . "add-hook '")
203 ("atl" . "add-to-list '")
204 ("bb" . "bury-buffer")
205 ("bc" . "forward-char -1")
206 ("bfn" . "buffer-file-name")
207 ("bl" . "buffer-list$")
208 ("blp" . "buffer-live-p ")
209 ("bn" . "buffer-name")
210 ("bod" . "beginning-of-defun")
211 ("bol" . "forward-line 0$")
213 ("bs" . "buffer-string$")
214 ("bsn" . "buffer-substring-no-properties")
215 ("bss" . "buffer-substring ")
216 ("bw" . "forward-word -1")
218 ("ca" . "char-after$")
219 ("cb" . "current-buffer$")
220 ("cc" . "condition-case er\n$\n(error nil)")
221 ("ci" . "call-interactively ")
222 ("cip" . "called-interactively-p 'any")
223 ("csv" . "customize-save-variable '")
224 ("d" . "delete-char 1")
225 ("dc" . "delete-char 1")
226 ("dcu" . "defcustom $ t\n \"\"\n :type 'boolean")
227 ("df" . "defun $ ()\n \"\"\n ")
228 ("dfa" . "defface $ \n '((t))\n \"\"\n ")
229 ("dfc" . "defcustom $ t\n \"\"\n :type 'boolean")
230 ("dff" . "defface $ \n '((t))\n \"\"\n ")
231 ("dfv" . "defvar $ t\n \"\"")
232 ("dk" . "define-key ")
233 ("dl" . "dolist (it $)")
234 ("dmp" . "derived-mode-p '")
235 ("dr" . "delete-region ")
236 ("dv" . "defvar $ t\n \"\"")
237 ("e" . "error \"$\"")
238 ("efn" . "expand-file-name ")
239 ("eol" . "end-of-line")
240 ("f" . "format \"$\"")
242 ("fbp" . "fboundp '")
243 ("fc" . "forward-char 1")
244 ("ff" . "find-file ")
245 ("fl" . "forward-line 1")
246 ("fp" . "functionp ")
247 ("frp" . "file-readable-p ")
248 ("fs" . "forward-sexp 1")
249 ("fw" . "forward-word 1")
251 ("gc" . "goto-char ")
252 ("gsk" . "global-set-key ")
254 ("ie" . "ignore-errors ")
255 ("ii" . "interactive")
256 ("ir" . "indent-region ")
257 ("jcl" . "justify-current-line ")
258 ("jl" . "delete-indentation")
259 ("jos" . "just-one-space")
260 ("jr" . "json-read$")
261 ("jtr" . "jump-to-register ")
263 ("kb" . "kill-buffer")
267 ("la" . "looking-at \"$\"")
268 ("lap" . "looking-at-p \"$\"")
269 ("lb" . "looking-back \"$\"")
270 ("lbp" . "line-beginning-position")
271 ("lep" . "line-end-position")
272 ("let" . "let (($))")
274 ("m" . "message \"$%s\"")
275 ("mb" . "match-beginning 0")
276 ("me" . "match-end 0")
277 ("ms" . "match-string 0")
278 ("msn" . "match-string-no-properties 0")
279 ("msnp" . "match-string-no-properties 0")
280 ("msp" . "match-string-no-properties 0")
282 ("nai" . "newline-and-indent$")
283 ("nl" . "forward-line 1")
285 ("ntr" . "narrow-to-region ")
286 ("ow" . "other-window 1")
288 ("pm" . "point-marker$")
289 ("pa" . "point-max$")
290 ("pg" . "plist-get ")
291 ("pi" . "point-min$")
293 ("ra" . "use-region-p$")
294 ("rap" . "use-region-p$")
295 ("rb" . "region-beginning")
296 ("re" . "region-end")
297 ("rh" . "remove-hook '")
298 ("rm" . "replace-match \"$\"")
299 ("ro" . "regexp-opt ")
300 ("rq" . "regexp-quote ")
301 ("rris" . "replace-regexp-in-string ")
302 ("rrs" . "replace-regexp-in-string ")
303 ("rs" . "while (search-forward $ nil t)\n(replace-match \"\") nil t)")
304 ("rsb" . "re-search-backward $ nil 'noerror")
305 ("rsf" . "re-search-forward $ nil 'noerror")
307 ("sb" . "search-backward $ nil 'noerror")
308 ("sbr" . "search-backward-regexp $ nil 'noerror")
309 ("scb" . "skip-chars-backward \"$\\r\\n[:blank:]\"")
310 ("scf" . "skip-chars-forward \"$\\r\\n[:blank:]\"")
311 ("se" . "save-excursion")
312 ("sf" . "search-forward $ nil 'noerror")
313 ("sfr" . "search-forward-regexp $ nil 'noerror")
314 ("sic" . "self-insert-command")
316 ("sm" . "string-match \"$\"")
317 ("smd" . "save-match-data")
318 ("sn" . "symbol-name ")
321 ("sr" . "save-restriction")
322 ("ss" . "substring ")
323 ("ssn" . "substring-no-properties ")
324 ("ssnp" . "substring-no-properties ")
325 ("stb" . "switch-to-buffer ")
326 ("sw" . "selected-window$")
328 ("tap" . "thing-at-point 'symbol")
331 ("up" . "unwind-protect\n(progn $)")
332 ("urp" . "use-region-p$")
334 ("wcb" . "with-current-buffer ")
335 ("wf" . "write-file ")
337 ("wl" . "window-list nil 'nominibuffer")
338 ("we" . "window-end")
339 ("ws" . "window-start")
340 ("wtb" . "with-temp-buffer")
341 ("wtf" . "with-temp-file ")
343 "Alist of (ABBREV . EXPANSION) used by `sotlisp'.")
345 (defun sotlisp-define-function-abbrev (name expansion)
346 "Define a function abbrev expanding NAME to EXPANSION.
347 This abbrev will only be expanded in places where a function name is
348 sensible. Roughly, this is right after a `(' or a `#''.
350 If EXPANSION is any string, it doesn't have to be the just the
351 name of a function. In particular:
352 - if it contains a `$', this char will not be inserted and
353 point will be moved to its position after expansion.
354 - if it contains a space, only a substring of it up to the
355 first space is inserted when expanding after a `#'' (this is done
356 by defining two different abbrevs).
358 For instance, if one defines
359 (sotlisp-define-function-abbrev \"d\" \"delete-char 1\")
361 then triggering `expand-abbrev' after \"d\" expands in the
364 #'d => #'delete-char"
365 (define-abbrev emacs-lisp-mode-abbrev-table
366 name t #'sotlisp--expand-function
367 ;; Don't override user abbrevs
369 ;; Only expand in function places.
370 :enable-function #'sotlisp--function-p)
371 (puthash name expansion sotlisp--function-table))
373 (defun sotlisp-erase-all-abbrevs ()
374 "Undefine all abbrevs defined by `sotlisp'."
376 (maphash (lambda (x _) (define-abbrev emacs-lisp-mode-abbrev-table x nil))
377 sotlisp--function-table))
379 (defun sotlisp-define-all-abbrevs ()
380 "Define all abbrevs in `sotlisp--default-function-abbrevs'."
382 (mapc (lambda (x) (sotlisp-define-function-abbrev (car x) (cdr x)))
383 sotlisp--default-function-abbrevs))
386 ;;; The global minor-mode
387 (defvar speed-of-thought-turn-on-hook '()
388 "Hook run once when `speed-of-thought-mode' is enabled.
389 Note that `speed-of-thought-mode' is global, so this is not run
392 See `sotlisp-turn-on-everywhere' for an example of what a
393 function in this hook should do.")
395 (defvar speed-of-thought-turn-off-hook '()
396 "Hook run once when `speed-of-thought-mode' is disabled.
397 Note that `speed-of-thought-mode' is global, so this is not run
400 See `sotlisp-turn-on-everywhere' for an example of what a
401 function in this hook should do.")
404 (define-minor-mode speed-of-thought-mode
407 (run-hooks (if speed-of-thought-mode
408 'speed-of-thought-turn-on-hook
409 'speed-of-thought-turn-off-hook)))
412 (defun speed-of-thought-hook-in (on off)
413 "Add functions ON and OFF to `speed-of-thought-mode' hooks.
414 If `speed-of-thought-mode' is already on, call ON."
415 (add-hook 'speed-of-thought-turn-on-hook on)
416 (add-hook 'speed-of-thought-turn-off-hook off)
417 (when speed-of-thought-mode (funcall on)))
420 ;;; The local minor-mode
421 (define-minor-mode sotlisp-mode
423 '(([M-return] . sotlisp-newline-and-parentheses)
424 ([C-return] . sotlisp-downlist-newline-and-parentheses)
425 ("\C-cf" . sotlisp-find-or-define-function)
426 ("\C-cv" . sotlisp-find-or-define-variable)))
428 (defun sotlisp-turn-on-everywhere ()
429 "Call-once function to turn on sotlisp everywhere.
430 Calls `sotlisp-mode' on all `emacs-lisp-mode' buffers, and sets
431 up a hook and abbrevs."
432 (add-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
433 (sotlisp-define-all-abbrevs)
435 (with-current-buffer b
436 (when (derived-mode-p 'emacs-lisp-mode)
440 (defun sotlisp-turn-off-everywhere ()
441 "Call-once function to turn off sotlisp everywhere.
442 Removes `sotlisp-mode' from all `emacs-lisp-mode' buffers, and
443 removes hooks and abbrevs."
444 (remove-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
445 (sotlisp-erase-all-abbrevs)
447 (with-current-buffer b
448 (when (derived-mode-p 'emacs-lisp-mode)
452 (speed-of-thought-hook-in #'sotlisp-turn-on-everywhere #'sotlisp-turn-off-everywhere)
456 (defun sotlisp-newline-and-parentheses ()
457 "`newline-and-indent' then insert a pair of parentheses."
460 (ignore-errors (expand-abbrev))
465 (defun sotlisp-downlist-newline-and-parentheses ()
466 "`up-list', `newline-and-indent', then insert a parentheses pair."
468 (ignore-errors (expand-abbrev))
474 (defun sotlisp--find-in-buffer (r s)
475 "Find the string (concat R (regexp-quote S)) somewhere in this buffer."
476 (let ((l (save-excursion
477 (goto-char (point-min))
479 (when (search-forward-regexp (concat r (regexp-quote s) "\\_>")
481 (match-beginning 0))))))
487 (defun sotlisp--beginning-of-defun ()
488 "`push-mark' and move above this defun."
491 (when (looking-back "^;;;###autoload\\s-*\n")
494 (defun sotlisp--function-at-point ()
495 "Return name of `function-called-at-point'."
497 (ignore-errors (forward-sexp -1)
498 (looking-at-p "#'")))
499 (thing-at-point 'symbol)
500 (let ((fcap (function-called-at-point)))
503 (thing-at-point 'symbol)))))
505 (defun sotlisp-find-or-define-function (&optional prefix)
506 "If symbol under point is a defined function, go to it, otherwise define it.
507 Essentially `find-function' on steroids.
509 If you write in your code the name of a function you haven't
510 defined yet, just place point on its name and hit \\[sotlisp-find-or-define-function]
511 and a defun will be inserted with point inside it. After that,
512 you can just hit `pop-mark' to go back to where you were.
513 With a PREFIX argument, creates a `defmacro' instead.
515 If the function under point is already defined this just calls
516 `find-function', with one exception:
517 if there's a defun (or equivalent) for this function in the
518 current buffer, we go to that even if it's not where the
519 global definition comes from (this is useful if you're
520 writing an Emacs package that also happens to be installed
523 With a prefix argument, defines a `defmacro' instead of a `defun'."
525 (let ((name (sotlisp--function-at-point)))
526 (unless (and name (sotlisp--find-in-buffer "(def\\(un\\|macro\\|alias\\) " name))
527 (let ((name-s (intern-soft name)))
529 (find-function name-s)
530 (sotlisp--beginning-of-defun)
531 (insert "(def" (if prefix "macro" "un")
533 (save-excursion (insert ")\n \"\"\n )\n\n")))))))
535 (defun sotlisp-find-or-define-variable (&optional prefix)
536 "If symbol under point is a defined variable, go to it, otherwise define it.
537 Essentially `find-variable' on steroids.
539 If you write in your code the name of a variable you haven't
540 defined yet, place point on its name and hit \\[sotlisp-find-or-define-variable]
541 and a `defcustom' will be created with point inside. After that,
542 you can just `pop-mark' to go back to where you were. With a
543 PREFIX argument, creates a `defvar' instead.
545 If the variable under point is already defined this just calls
546 `find-variable', with one exception:
547 if there's a defvar (or equivalent) for this variable in the
548 current buffer, we go to that even if it's not where the
549 global definition comes from (this is useful if you're
550 writing an Emacs package that also happens to be installed
553 With a prefix argument, defines a `defvar' instead of a `defcustom'."
555 (let ((name (symbol-name (variable-at-point t))))
556 (unless (sotlisp--find-in-buffer "(def\\(custom\\|const\\|var\\) " name)
557 (unless (and (symbolp (variable-at-point))
558 (ignore-errors (find-variable (variable-at-point)) t))
559 (let ((name (thing-at-point 'symbol)))
560 (sotlisp--beginning-of-defun)
561 (insert "(def" (if prefix "var" "custom")
565 (if prefix "" "\n :type 'boolean")
569 ;;; sotlisp.el ends here