]> code.delx.au - gnu-emacs-elpa/blob - sotlisp.el
New abbrevs
[gnu-emacs-elpa] / sotlisp.el
1 ;;; sotlisp.el --- Write lisp at the speed of thought. -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
4
5 ;; Author: Artur Malabarba <bruce.connor.am@gmail.com>
6 ;; Keywords: convenience, lisp
7 ;; Package-Requires: ((emacs "24.1"))
8
9 ;; This program is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; This program is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23 ;;
24 ;; This defines a new global minor-mode `speed-of-thought-mode', which
25 ;; activates locally on any supported buffer. Currently, only
26 ;; `emacs-lisp-mode' buffers are supported.
27 ;;
28 ;; The mode is quite simple, and is composed of two parts:
29 ;;
30 ;;; Abbrevs
31 ;;
32 ;; A large number of abbrevs which expand function
33 ;; initials to their name. A few examples:
34 ;;
35 ;; - wcb -> with-current-buffer
36 ;; - i -> insert
37 ;; - r -> require '
38 ;; - a -> and
39 ;;
40 ;; However, these are defined in a way such that they ONLY expand in a
41 ;; place where you would use a function, so hitting SPC after "(r"
42 ;; expands to "(require '", but hitting SPC after "(delete-region r"
43 ;; will NOT expand the `r', because that's obviously not a function.
44 ;; Furtheromre, "#'r" will expand to "#'require" (note how it ommits
45 ;; that extra quote, since it would be useless here).
46 ;;
47 ;;; Commands
48 ;;
49 ;; It also defines 4 commands, which really fit into this "follow the
50 ;; thought-flow" way of writing. The bindings are as follows, I
51 ;; understand these don't fully adhere to conventions, and I'd
52 ;; appreciate suggestions on better bindings.
53 ;;
54 ;; - M-RET :: Break line, and insert "()" with point in the middle.
55 ;; - C-RET :: Do `forward-up-list', then do M-RET.
56 ;;
57 ;; Hitting RET followed by a `(' was one of the most common key sequences
58 ;; for me while writing elisp, so giving it a quick-to-hit key was a
59 ;; significant improvement.
60 ;;
61 ;; - C-c f :: Find function under point. If it is not defined, create a
62 ;; definition for it below the current function and leave point inside.
63 ;; - C-c v :: Same, but for variable.
64 ;;
65 ;; With these commands, you just write your code as you think of it. Once
66 ;; you hit a "stop-point" of sorts in your tought flow, you hit `C-c f/v`
67 ;; on any undefined functions/variables, write their definitions, and hit
68 ;; `C-u C-SPC` to go back to the main function.
69 ;;
70 ;;; Small Example
71 ;;
72 ;; With the above (assuming you use something like paredit or
73 ;; electric-pair-mode), if you write:
74 ;;
75 ;; ( w t b M-RET i SPC text
76 ;;
77 ;; You get
78 ;;
79 ;; (with-temp-buffer (insert text))
80
81 \f
82 ;;; Code:
83
84 ;;; Predicates
85 (defun sotlisp--auto-paired-p ()
86 "Non-nil if this buffer auto-inserts parentheses."
87 (or (bound-and-true-p electric-pair-mode)
88 (bound-and-true-p paredit-mode)
89 (bound-and-true-p smartparens-mode)))
90
91 (defun sotlisp--function-form-p ()
92 "Non-nil if point is at the start of a sexp.
93 Specially, avoids matching inside argument lists."
94 (and (eq (char-before) ?\()
95 (not (looking-back "(\\(defun\\s-+.*\\|lambda\\s-+\\)("))
96 (not (string-match (rx (syntax symbol)) (string last-command-event)))))
97
98 (defun sotlisp--function-quote-p ()
99 "Non-nil if point is at a sharp-quote."
100 (looking-back "#'"))
101
102 (defun sotlisp--function-p ()
103 "Non-nil if point is at reasonable place for a function name.
104 Returns non-nil if, after moving backwards by a sexp, either
105 `sotlisp--function-form-p' or `sotlisp--function-quote-p' return
106 non-nil."
107 (save-excursion
108 (ignore-errors
109 (skip-chars-backward (rx alnum))
110 (or (sotlisp--function-form-p)
111 (sotlisp--function-quote-p)))))
112
113 (defun sotlisp--whitespace-p ()
114 "Non-nil if current `self-insert'ed char is whitespace."
115 (ignore-errors
116 (string-match (rx space) (string last-command-event))))
117
118 \f
119 ;;; Expansion logic
120 (defvar sotlisp--needs-moving nil
121 "Will `sotlisp--move-to-$' move point after insertion?")
122
123 (defun sotlisp--move-to-$ ()
124 "Move backwards until `$' and delete it.
125 Point is left where the `$' char was. Does nothing if variable
126 `sotlisp-mode' is nil."
127 (when (bound-and-true-p speed-of-thought-mode)
128 (when sotlisp--needs-moving
129 (setq sotlisp--needs-moving nil)
130 (skip-chars-backward "^\\$")
131 (delete-char -1))))
132
133 (add-hook 'post-command-hook #'sotlisp--move-to-$ 'append)
134
135 (defun sotlisp--maybe-skip-closing-paren ()
136 "Move past `)' if variable `electric-pair-mode' is enabled."
137 (when (and (char-after ?\))
138 (sotlisp--auto-paired-p))
139 (forward-char 1)))
140
141 (defvar sotlisp--function-table (make-hash-table :test #'equal)
142 "Table where function abbrev expansions are stored.")
143
144 (defun sotlisp--expand-function ()
145 "Expand the function abbrev before point.
146 See `sotlisp-define-function-abbrev'."
147 (let ((r (point)))
148 (skip-chars-backward (rx alnum))
149 (let* ((name (buffer-substring (point) r))
150 (expansion (gethash name sotlisp--function-table)))
151 (delete-region (point) r)
152 (if (sotlisp--function-quote-p)
153 ;; After #' use the simple expansion.
154 (insert (sotlisp--simplify-function-expansion expansion))
155 ;; Inside a form, use the full expansion.
156 (insert expansion)
157 (when (string-match "\\$" expansion)
158 (setq sotlisp--needs-moving t))))
159 ;; Inform `expand-abbrev' that `self-insert-command' should not
160 ;; trigger, by returning non-nil on SPC.
161 (when (sotlisp--whitespace-p)
162 ;; And maybe move out of closing paren if expansion ends with $.
163 (when (eq (char-before) ?$)
164 (delete-char -1)
165 (setq sotlisp--needs-moving nil)
166 (sotlisp--maybe-skip-closing-paren))
167 t)))
168
169 (put 'sotlisp--expand-function 'no-self-insert t)
170
171 (defun sotlisp--simplify-function-expansion (expansion)
172 "Take a substring of EXPANSION up to first space.
173 The space char is not included. Any \"$\" are also removed."
174 (replace-regexp-in-string
175 "\\$" ""
176 (substring expansion 0 (string-match " " expansion))))
177
178 \f
179 ;;; Abbrev definitions
180 (defconst sotlisp--default-function-abbrevs
181 '(
182 ("a" . "and ")
183 ("ah" . "add-hook '")
184 ("atl" . "add-to-list '")
185 ("bb" . "bury-buffer")
186 ("bc" . "forward-char -1")
187 ("bfn" . "buffer-file-name")
188 ("bl" . "buffer-list$")
189 ("blp" . "buffer-live-p ")
190 ("bn" . "buffer-name")
191 ("bod" . "beginning-of-defun")
192 ("bol" . "forward-line 0$")
193 ("bp" . "boundp '")
194 ("bs" . "buffer-string$")
195 ("bsn" . "buffer-substring-no-properties")
196 ("bss" . "buffer-substring ")
197 ("bw" . "forward-word -1")
198 ("c" . "concat ")
199 ("ca" . "char-after$")
200 ("cb" . "current-buffer$")
201 ("cc" . "condition-case er\n$\n(error nil)")
202 ("ci" . "call-interactively ")
203 ("cip" . "called-interactively-p 'any")
204 ("csv" . "customize-save-variable '")
205 ("d" . "delete-char 1")
206 ("dc" . "delete-char 1")
207 ("dcu" . "defcustom $ t\n \"\"\n :type 'boolean")
208 ("df" . "defun $ ()\n \"\"\n ")
209 ("dfa" . "defface $ \n '((t))\n \"\"\n ")
210 ("dfc" . "defcustom $ t\n \"\"\n :type 'boolean")
211 ("dff" . "defface $ \n '((t))\n \"\"\n ")
212 ("dfv" . "defvar $ t\n \"\"")
213 ("dk" . "define-key ")
214 ("dl" . "dolist (it $)")
215 ("dmp" . "derived-mode-p '")
216 ("dr" . "delete-region ")
217 ("dv" . "defvar $ t\n \"\"")
218 ("e" . "error \"$\"")
219 ("efn" . "expand-file-name ")
220 ("eol" . "end-of-line")
221 ("f" . "format \"$\"")
222 ("fb" . "fboundp '")
223 ("fbp" . "fboundp '")
224 ("fc" . "forward-char 1")
225 ("ff" . "find-file ")
226 ("fl" . "forward-line 1")
227 ("fp" . "functionp ")
228 ("frp" . "file-readable-p ")
229 ("fs" . "forward-sexp 1")
230 ("fw" . "forward-word 1")
231 ("g" . "goto-char ")
232 ("gc" . "goto-char ")
233 ("gsk" . "global-set-key ")
234 ("i" . "insert ")
235 ("ie" . "ignore-errors ")
236 ("ii" . "interactive")
237 ("ir" . "indent-region ")
238 ("jcl" . "justify-current-line ")
239 ("jl" . "delete-indentation")
240 ("jos" . "just-one-space")
241 ("jr" . "json-read$")
242 ("jtr" . "jump-to-register ")
243 ("k" . "kbd \"$\"")
244 ("kb" . "kill-buffer")
245 ("kn" . "kill-new ")
246 ("l" . "lambda ($)")
247 ("la" . "looking-at \"$\"")
248 ("lap" . "looking-at-p \"$\"")
249 ("lb" . "looking-back \"$\"")
250 ("lbp" . "line-beginning-position")
251 ("lep" . "line-end-position")
252 ("let" . "let (($))")
253 ("lp" . "listp ")
254 ("m" . "message \"$%s\"")
255 ("mb" . "match-beginning 0")
256 ("me" . "match-end 0")
257 ("ms" . "match-string 0")
258 ("msn" . "match-string-no-properties 0")
259 ("msnp" . "match-string-no-properties 0")
260 ("msp" . "match-string-no-properties 0")
261 ("n" . "not ")
262 ("nai" . "newline-and-indent$")
263 ("nl" . "forward-line 1")
264 ("np" . "numberp ")
265 ("ntr" . "narrow-to-region ")
266 ("ow" . "other-window 1")
267 ("p" . "point$")
268 ("pm" . "point-marker$")
269 ("pa" . "point-max$")
270 ("pg" . "plist-get ")
271 ("pi" . "point-min$")
272 ("r" . "require '")
273 ("ra" . "use-region-p$")
274 ("rap" . "use-region-p$")
275 ("rb" . "region-beginning")
276 ("re" . "region-end")
277 ("rh" . "remove-hook '")
278 ("rm" . "replace-match \"$\"")
279 ("ro" . "regexp-opt ")
280 ("rq" . "regexp-quote ")
281 ("rris" . "replace-regexp-in-string ")
282 ("rrs" . "replace-regexp-in-string ")
283 ("rs" . "while (search-forward $ nil t)\n(replace-match \"\") nil t)")
284 ("rsb" . "re-search-backward $ nil 'noerror")
285 ("rsf" . "re-search-forward $ nil 'noerror")
286 ("s" . "setq ")
287 ("sb" . "search-backward $ nil 'noerror")
288 ("sbr" . "search-backward-regexp $ nil 'noerror")
289 ("scb" . "skip-chars-backward \"$\r\n[:blank:]\"")
290 ("scf" . "skip-chars-forward \"$\r\n[:blank:]\"")
291 ("se" . "save-excursion")
292 ("sf" . "search-forward $ nil 'noerror")
293 ("sfr" . "search-forward-regexp $ nil 'noerror")
294 ("sic" . "self-insert-command")
295 ("sl" . "string<")
296 ("sm" . "string-match \"$\"")
297 ("smd" . "save-match-data")
298 ("sn" . "symbol-name ")
299 ("sp" . "stringp ")
300 ("sq" . "string= ")
301 ("sr" . "save-restriction")
302 ("ss" . "substring ")
303 ("ssn" . "substring-no-properties ")
304 ("ssnp" . "substring-no-properties ")
305 ("stb" . "switch-to-buffer ")
306 ("sw" . "selected-window$")
307 ("syp" . "symbolp ")
308 ("tap" . "thing-at-point 'symbol")
309 ("u" . "unless ")
310 ("ul" . "up-list")
311 ("up" . "unwind-protect\n(progn $)")
312 ("urp" . "use-region-p$")
313 ("w" . "when ")
314 ("wcb" . "with-current-buffer ")
315 ("wf" . "write-file ")
316 ("wh" . "while ")
317 ("wl" . "window-list nil 'nominibuffer")
318 ("wtb" . "with-temp-buffer")
319 ("wtf" . "with-temp-file ")
320 )
321 "Alist of (ABBREV . EXPANSION) used by `sotlisp'.")
322
323 (defun sotlisp-define-function-abbrev (name expansion)
324 "Define a function abbrev expanding NAME to EXPANSION.
325 This abbrev will only be expanded in places where a function name is
326 sensible. Roughly, this is right after a `(' or a `#''.
327
328 If EXPANSION is any string, it doesn't have to be the just the
329 name of a function. In particular:
330 - if it contains a `$', this char will not be inserted and
331 point will be moved to its position after expansion.
332 - if it contains a space, only a substring of it up to the
333 first space is inserted when expanding after a `#'' (this is done
334 by defining two different abbrevs).
335
336 For instance, if one defines
337 (sotlisp-define-function-abbrev \"d\" \"delete-char 1\")
338
339 then triggering `expand-abbrev' after \"d\" expands in the
340 following way:
341 (d => (delete-char 1
342 #'d => #'delete-char"
343 (define-abbrev emacs-lisp-mode-abbrev-table
344 name t #'sotlisp--expand-function
345 ;; Don't override user abbrevs
346 :system t
347 ;; Only expand in function places.
348 :enable-function #'sotlisp--function-p)
349 (puthash name expansion sotlisp--function-table))
350
351 (defun sotlisp-erase-all-abbrevs ()
352 "Undefine all abbrevs defined by `sotlisp'."
353 (interactive)
354 (maphash (lambda (x _) (define-abbrev emacs-lisp-mode-abbrev-table x nil))
355 sotlisp--function-table))
356
357 (defun sotlisp-define-all-abbrevs ()
358 "Define all abbrevs in `sotlisp--default-function-abbrevs'."
359 (interactive)
360 (mapc (lambda (x) (sotlisp-define-function-abbrev (car x) (cdr x)))
361 sotlisp--default-function-abbrevs))
362
363 \f
364 ;;; The global minor-mode
365 (defvar speed-of-thought-turn-on-hook '(sotlisp-turn-on-everywhere)
366 "Hook run once when `speed-of-thought-mode' is enabled.
367 Note that `speed-of-thought-mode' is global, so this is not run
368 on every buffer.
369
370 See `sotlisp-turn-on-everywhere' for an example of what a
371 function in this hook should do.")
372
373 (defvar speed-of-thought-turn-off-hook '(sotlisp-turn-off-everywhere)
374 "Hook run once when `speed-of-thought-mode' is disabled.
375 Note that `speed-of-thought-mode' is global, so this is not run
376 on every buffer.
377
378 See `sotlisp-turn-on-everywhere' for an example of what a
379 function in this hook should do.")
380
381 ;;;###autoload
382 (define-minor-mode speed-of-thought-mode nil nil nil nil
383 :global t
384 (run-hooks (if speed-of-thought-mode
385 'speed-of-thought-turn-on-hook
386 'speed-of-thought-turn-off-hook)))
387
388 \f
389 ;;; The local minor-mode
390 (defun sotlisp-turn-on-everywhere ()
391 "Call-once function to turn on sotlisp everywhere.
392 Calls `sotlisp-mode' on all `emacs-lisp-mode' buffers, and sets
393 up a hook and abbrevs."
394 (add-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
395 (sotlisp-define-all-abbrevs)
396 (mapc (lambda (b)
397 (with-current-buffer b
398 (when (derived-mode-p 'emacs-lisp-mode)
399 (sotlisp-mode 1))))
400 (buffer-list)))
401
402 (defun sotlisp-turn-off-everywhere ()
403 "Call-once function to turn off sotlisp everywhere.
404 Removes `sotlisp-mode' from all `emacs-lisp-mode' buffers, and
405 removes hooks and abbrevs."
406 (remove-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
407 (sotlisp-erase-all-abbrevs)
408 (mapc (lambda (b)
409 (with-current-buffer b
410 (when (derived-mode-p 'emacs-lisp-mode)
411 (sotlisp-mode -1))))
412 (buffer-list)))
413
414 (define-minor-mode sotlisp-mode nil nil " SoT"
415 '(([M-return] . sotlisp-newline-and-parentheses)
416 ([C-return] . sotlisp-downlist-newline-and-parentheses)
417 ("\C-cf" . sotlisp-find-or-define-function)
418 ("\C-cv" . sotlisp-find-or-define-variable)))
419
420 \f
421 ;;; Commands
422 (defun sotlisp-newline-and-parentheses ()
423 "`newline-and-indent' then insert a pair of parentheses."
424 (interactive)
425 (point)
426 (ignore-errors (expand-abbrev))
427 (newline-and-indent)
428 (insert "()")
429 (forward-char -1))
430
431 (defun sotlisp-downlist-newline-and-parentheses ()
432 "`up-list', `newline-and-indent', then insert a parentheses pair."
433 (interactive)
434 (ignore-errors (expand-abbrev))
435 (up-list)
436 (newline-and-indent)
437 (insert "()")
438 (forward-char -1))
439
440 (defun sotlisp--find-in-buffer (r s)
441 "Find the string (concat R (regexp-quote S)) somewhere in this buffer."
442 (let ((l (save-excursion
443 (goto-char (point-min))
444 (save-match-data
445 (when (search-forward-regexp (concat r (regexp-quote s) "\\_>")
446 nil :noerror)
447 (match-beginning 0))))))
448 (when l
449 (push-mark)
450 (goto-char l)
451 l)))
452
453 (defun sotlisp--beginning-of-defun ()
454 "`push-mark' and move above this defun."
455 (push-mark)
456 (beginning-of-defun)
457 (when (looking-back "^;;;###autoload\\s-*\n")
458 (forward-line -1)))
459
460 (defun sotlisp--function-at-point ()
461 "Return name of `function-called-at-point'."
462 (if (save-excursion
463 (ignore-errors (forward-sexp -1)
464 (looking-at-p "#'")))
465 (thing-at-point 'symbol)
466 (let ((fcap (function-called-at-point)))
467 (if fcap
468 (symbol-name fcap)
469 (thing-at-point 'symbol)))))
470
471 (defun sotlisp-find-or-define-function (&optional prefix)
472 "If symbol under point is a defined function, go to it, otherwise define it.
473 Essentially `find-function' on steroids.
474
475 If you write in your code the name of a function you haven't
476 defined yet, just place point on its name and hit \\[sotlisp-find-or-define-function]
477 and a defun will be inserted with point inside it. After that,
478 you can just hit `pop-mark' to go back to where you were.
479 With a PREFIX argument, creates a `defmacro' instead.
480
481 If the function under point is already defined this just calls
482 `find-function', with one exception:
483 if there's a defun (or equivalent) for this function in the
484 current buffer, we go to that even if it's not where the
485 global definition comes from (this is useful if you're
486 writing an Emacs package that also happens to be installed
487 through package.el).
488
489 With a prefix argument, defines a `defmacro' instead of a `defun'."
490 (interactive "P")
491 (let ((name (sotlisp--function-at-point)))
492 (unless (and name (sotlisp--find-in-buffer "(def\\(un\\|macro\\|alias\\) " name))
493 (let ((name-s (intern-soft name)))
494 (if (fboundp name-s)
495 (find-function name-s)
496 (sotlisp--beginning-of-defun)
497 (insert "(def" (if prefix "macro" "un")
498 " " name " (")
499 (save-excursion (insert ")\n \"\"\n )\n\n")))))))
500
501 (defun sotlisp-find-or-define-variable (&optional prefix)
502 "If symbol under point is a defined variable, go to it, otherwise define it.
503 Essentially `find-variable' on steroids.
504
505 If you write in your code the name of a variable you haven't
506 defined yet, place point on its name and hit \\[sotlisp-find-or-define-variable]
507 and a `defcustom' will be created with point inside. After that,
508 you can just `pop-mark' to go back to where you were. With a
509 PREFIX argument, creates a `defvar' instead.
510
511 If the variable under point is already defined this just calls
512 `find-variable', with one exception:
513 if there's a defvar (or equivalent) for this variable in the
514 current buffer, we go to that even if it's not where the
515 global definition comes from (this is useful if you're
516 writing an Emacs package that also happens to be installed
517 through package.el).
518
519 With a prefix argument, defines a `defvar' instead of a `defcustom'."
520 (interactive "P")
521 (let ((name (symbol-name (variable-at-point t))))
522 (unless (sotlisp--find-in-buffer "(def\\(custom\\|const\\|var\\) " name)
523 (unless (and (symbolp (variable-at-point))
524 (ignore-errors (find-variable (variable-at-point)) t))
525 (let ((name (thing-at-point 'symbol)))
526 (sotlisp--beginning-of-defun)
527 (insert "(def" (if prefix "var" "custom")
528 " " name " t")
529 (save-excursion
530 (insert "\n \"\""
531 (if prefix "" "\n :type 'boolean")
532 ")\n\n")))))))
533
534 (provide 'sotlisp)
535 ;;; sotlisp.el ends here
536