]> code.delx.au - gnu-emacs-elpa/blob - sotlisp.el
Better 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 ("kp" . "keywordp ")
247 ("l" . "lambda ($)")
248 ("la" . "looking-at \"$\"")
249 ("lap" . "looking-at-p \"$\"")
250 ("lb" . "looking-back \"$\"")
251 ("lbp" . "line-beginning-position")
252 ("lep" . "line-end-position")
253 ("let" . "let (($))")
254 ("lp" . "listp ")
255 ("m" . "message \"$%s\"")
256 ("mb" . "match-beginning 0")
257 ("me" . "match-end 0")
258 ("ms" . "match-string 0")
259 ("msn" . "match-string-no-properties 0")
260 ("msnp" . "match-string-no-properties 0")
261 ("msp" . "match-string-no-properties 0")
262 ("n" . "not ")
263 ("nai" . "newline-and-indent$")
264 ("nl" . "forward-line 1")
265 ("np" . "numberp ")
266 ("ntr" . "narrow-to-region ")
267 ("ow" . "other-window 1")
268 ("p" . "point$")
269 ("pm" . "point-marker$")
270 ("pa" . "point-max$")
271 ("pg" . "plist-get ")
272 ("pi" . "point-min$")
273 ("r" . "require '")
274 ("ra" . "use-region-p$")
275 ("rap" . "use-region-p$")
276 ("rb" . "region-beginning")
277 ("re" . "region-end")
278 ("rh" . "remove-hook '")
279 ("rm" . "replace-match \"$\"")
280 ("ro" . "regexp-opt ")
281 ("rq" . "regexp-quote ")
282 ("rris" . "replace-regexp-in-string ")
283 ("rrs" . "replace-regexp-in-string ")
284 ("rs" . "while (search-forward $ nil t)\n(replace-match \"\") nil t)")
285 ("rsb" . "re-search-backward $ nil 'noerror")
286 ("rsf" . "re-search-forward $ nil 'noerror")
287 ("s" . "setq ")
288 ("sb" . "search-backward $ nil 'noerror")
289 ("sbr" . "search-backward-regexp $ nil 'noerror")
290 ("scb" . "skip-chars-backward \"$\\r\\n[:blank:]\"")
291 ("scf" . "skip-chars-forward \"$\\r\\n[:blank:]\"")
292 ("se" . "save-excursion")
293 ("sf" . "search-forward $ nil 'noerror")
294 ("sfr" . "search-forward-regexp $ nil 'noerror")
295 ("sic" . "self-insert-command")
296 ("sl" . "string<")
297 ("sm" . "string-match \"$\"")
298 ("smd" . "save-match-data")
299 ("sn" . "symbol-name ")
300 ("sp" . "stringp ")
301 ("sq" . "string= ")
302 ("sr" . "save-restriction")
303 ("ss" . "substring ")
304 ("ssn" . "substring-no-properties ")
305 ("ssnp" . "substring-no-properties ")
306 ("stb" . "switch-to-buffer ")
307 ("sw" . "selected-window$")
308 ("syp" . "symbolp ")
309 ("tap" . "thing-at-point 'symbol")
310 ("u" . "unless ")
311 ("ul" . "up-list")
312 ("up" . "unwind-protect\n(progn $)")
313 ("urp" . "use-region-p$")
314 ("w" . "when ")
315 ("wcb" . "with-current-buffer ")
316 ("wf" . "write-file ")
317 ("wh" . "while ")
318 ("wl" . "window-list nil 'nominibuffer")
319 ("wtb" . "with-temp-buffer")
320 ("wtf" . "with-temp-file ")
321 )
322 "Alist of (ABBREV . EXPANSION) used by `sotlisp'.")
323
324 (defun sotlisp-define-function-abbrev (name expansion)
325 "Define a function abbrev expanding NAME to EXPANSION.
326 This abbrev will only be expanded in places where a function name is
327 sensible. Roughly, this is right after a `(' or a `#''.
328
329 If EXPANSION is any string, it doesn't have to be the just the
330 name of a function. In particular:
331 - if it contains a `$', this char will not be inserted and
332 point will be moved to its position after expansion.
333 - if it contains a space, only a substring of it up to the
334 first space is inserted when expanding after a `#'' (this is done
335 by defining two different abbrevs).
336
337 For instance, if one defines
338 (sotlisp-define-function-abbrev \"d\" \"delete-char 1\")
339
340 then triggering `expand-abbrev' after \"d\" expands in the
341 following way:
342 (d => (delete-char 1
343 #'d => #'delete-char"
344 (define-abbrev emacs-lisp-mode-abbrev-table
345 name t #'sotlisp--expand-function
346 ;; Don't override user abbrevs
347 :system t
348 ;; Only expand in function places.
349 :enable-function #'sotlisp--function-p)
350 (puthash name expansion sotlisp--function-table))
351
352 (defun sotlisp-erase-all-abbrevs ()
353 "Undefine all abbrevs defined by `sotlisp'."
354 (interactive)
355 (maphash (lambda (x _) (define-abbrev emacs-lisp-mode-abbrev-table x nil))
356 sotlisp--function-table))
357
358 (defun sotlisp-define-all-abbrevs ()
359 "Define all abbrevs in `sotlisp--default-function-abbrevs'."
360 (interactive)
361 (mapc (lambda (x) (sotlisp-define-function-abbrev (car x) (cdr x)))
362 sotlisp--default-function-abbrevs))
363
364 \f
365 ;;; The global minor-mode
366 (defvar speed-of-thought-turn-on-hook '(sotlisp-turn-on-everywhere)
367 "Hook run once when `speed-of-thought-mode' is enabled.
368 Note that `speed-of-thought-mode' is global, so this is not run
369 on every buffer.
370
371 See `sotlisp-turn-on-everywhere' for an example of what a
372 function in this hook should do.")
373
374 (defvar speed-of-thought-turn-off-hook '(sotlisp-turn-off-everywhere)
375 "Hook run once when `speed-of-thought-mode' is disabled.
376 Note that `speed-of-thought-mode' is global, so this is not run
377 on every buffer.
378
379 See `sotlisp-turn-on-everywhere' for an example of what a
380 function in this hook should do.")
381
382 ;;;###autoload
383 (define-minor-mode speed-of-thought-mode nil nil nil nil
384 :global t
385 (run-hooks (if speed-of-thought-mode
386 'speed-of-thought-turn-on-hook
387 'speed-of-thought-turn-off-hook)))
388
389 \f
390 ;;; The local minor-mode
391 (defun sotlisp-turn-on-everywhere ()
392 "Call-once function to turn on sotlisp everywhere.
393 Calls `sotlisp-mode' on all `emacs-lisp-mode' buffers, and sets
394 up a hook and abbrevs."
395 (add-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
396 (sotlisp-define-all-abbrevs)
397 (mapc (lambda (b)
398 (with-current-buffer b
399 (when (derived-mode-p 'emacs-lisp-mode)
400 (sotlisp-mode 1))))
401 (buffer-list)))
402
403 (defun sotlisp-turn-off-everywhere ()
404 "Call-once function to turn off sotlisp everywhere.
405 Removes `sotlisp-mode' from all `emacs-lisp-mode' buffers, and
406 removes hooks and abbrevs."
407 (remove-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
408 (sotlisp-erase-all-abbrevs)
409 (mapc (lambda (b)
410 (with-current-buffer b
411 (when (derived-mode-p 'emacs-lisp-mode)
412 (sotlisp-mode -1))))
413 (buffer-list)))
414
415 (define-minor-mode sotlisp-mode nil nil " SoT"
416 '(([M-return] . sotlisp-newline-and-parentheses)
417 ([C-return] . sotlisp-downlist-newline-and-parentheses)
418 ("\C-cf" . sotlisp-find-or-define-function)
419 ("\C-cv" . sotlisp-find-or-define-variable)))
420
421 \f
422 ;;; Commands
423 (defun sotlisp-newline-and-parentheses ()
424 "`newline-and-indent' then insert a pair of parentheses."
425 (interactive)
426 (point)
427 (ignore-errors (expand-abbrev))
428 (newline-and-indent)
429 (insert "()")
430 (forward-char -1))
431
432 (defun sotlisp-downlist-newline-and-parentheses ()
433 "`up-list', `newline-and-indent', then insert a parentheses pair."
434 (interactive)
435 (ignore-errors (expand-abbrev))
436 (up-list)
437 (newline-and-indent)
438 (insert "()")
439 (forward-char -1))
440
441 (defun sotlisp--find-in-buffer (r s)
442 "Find the string (concat R (regexp-quote S)) somewhere in this buffer."
443 (let ((l (save-excursion
444 (goto-char (point-min))
445 (save-match-data
446 (when (search-forward-regexp (concat r (regexp-quote s) "\\_>")
447 nil :noerror)
448 (match-beginning 0))))))
449 (when l
450 (push-mark)
451 (goto-char l)
452 l)))
453
454 (defun sotlisp--beginning-of-defun ()
455 "`push-mark' and move above this defun."
456 (push-mark)
457 (beginning-of-defun)
458 (when (looking-back "^;;;###autoload\\s-*\n")
459 (forward-line -1)))
460
461 (defun sotlisp--function-at-point ()
462 "Return name of `function-called-at-point'."
463 (if (save-excursion
464 (ignore-errors (forward-sexp -1)
465 (looking-at-p "#'")))
466 (thing-at-point 'symbol)
467 (let ((fcap (function-called-at-point)))
468 (if fcap
469 (symbol-name fcap)
470 (thing-at-point 'symbol)))))
471
472 (defun sotlisp-find-or-define-function (&optional prefix)
473 "If symbol under point is a defined function, go to it, otherwise define it.
474 Essentially `find-function' on steroids.
475
476 If you write in your code the name of a function you haven't
477 defined yet, just place point on its name and hit \\[sotlisp-find-or-define-function]
478 and a defun will be inserted with point inside it. After that,
479 you can just hit `pop-mark' to go back to where you were.
480 With a PREFIX argument, creates a `defmacro' instead.
481
482 If the function under point is already defined this just calls
483 `find-function', with one exception:
484 if there's a defun (or equivalent) for this function in the
485 current buffer, we go to that even if it's not where the
486 global definition comes from (this is useful if you're
487 writing an Emacs package that also happens to be installed
488 through package.el).
489
490 With a prefix argument, defines a `defmacro' instead of a `defun'."
491 (interactive "P")
492 (let ((name (sotlisp--function-at-point)))
493 (unless (and name (sotlisp--find-in-buffer "(def\\(un\\|macro\\|alias\\) " name))
494 (let ((name-s (intern-soft name)))
495 (if (fboundp name-s)
496 (find-function name-s)
497 (sotlisp--beginning-of-defun)
498 (insert "(def" (if prefix "macro" "un")
499 " " name " (")
500 (save-excursion (insert ")\n \"\"\n )\n\n")))))))
501
502 (defun sotlisp-find-or-define-variable (&optional prefix)
503 "If symbol under point is a defined variable, go to it, otherwise define it.
504 Essentially `find-variable' on steroids.
505
506 If you write in your code the name of a variable you haven't
507 defined yet, place point on its name and hit \\[sotlisp-find-or-define-variable]
508 and a `defcustom' will be created with point inside. After that,
509 you can just `pop-mark' to go back to where you were. With a
510 PREFIX argument, creates a `defvar' instead.
511
512 If the variable under point is already defined this just calls
513 `find-variable', with one exception:
514 if there's a defvar (or equivalent) for this variable in the
515 current buffer, we go to that even if it's not where the
516 global definition comes from (this is useful if you're
517 writing an Emacs package that also happens to be installed
518 through package.el).
519
520 With a prefix argument, defines a `defvar' instead of a `defcustom'."
521 (interactive "P")
522 (let ((name (symbol-name (variable-at-point t))))
523 (unless (sotlisp--find-in-buffer "(def\\(custom\\|const\\|var\\) " name)
524 (unless (and (symbolp (variable-at-point))
525 (ignore-errors (find-variable (variable-at-point)) t))
526 (let ((name (thing-at-point 'symbol)))
527 (sotlisp--beginning-of-defun)
528 (insert "(def" (if prefix "var" "custom")
529 " " name " t")
530 (save-excursion
531 (insert "\n \"\""
532 (if prefix "" "\n :type 'boolean")
533 ")\n\n")))))))
534
535 (provide 'sotlisp)
536 ;;; sotlisp.el ends here
537