]> 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 (eval-when-compile
84 (require 'subr-x))
85
86 ;;; Predicates
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)))
92
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)))))
99
100 (defun sotlisp--function-quote-p ()
101 "Non-nil if point is at a sharp-quote."
102 (looking-back "#'"))
103
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
108 non-nil."
109 (save-excursion
110 (ignore-errors
111 (skip-chars-backward (rx alnum))
112 (or (sotlisp--function-form-p)
113 (sotlisp--function-quote-p)))))
114
115 (defun sotlisp--whitespace-p ()
116 "Non-nil if current `self-insert'ed char is whitespace."
117 (ignore-errors
118 (string-match (rx space) (string last-command-event))))
119
120 \f
121 ;;; Expansion logic
122 (defvar sotlisp--needs-moving nil
123 "Will `sotlisp--move-to-$' move point after insertion?")
124
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 "^\\$")
133 (delete-char -1))))
134
135 (add-hook 'post-command-hook #'sotlisp--move-to-$ 'append)
136
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))
141 (forward-char 1)))
142
143 (defvar sotlisp--function-table (make-hash-table :test #'equal)
144 "Table where function abbrev expansions are stored.")
145
146 (defun sotlisp--expand-function ()
147 "Expand the function abbrev before point.
148 See `sotlisp-define-function-abbrev'."
149 (let ((r (point)))
150 (skip-chars-backward (rx alnum))
151 (let* ((name (buffer-substring (point) r))
152 (expansion (gethash name sotlisp--function-table)))
153 (delete-region (point) r)
154 (if (sotlisp--function-quote-p)
155 ;; After #' use the simple expansion.
156 (insert (sotlisp--simplify-function-expansion expansion))
157 ;; Inside a form, use the full expansion.
158 (insert expansion)
159 (when (string-match "\\$" expansion)
160 (setq sotlisp--needs-moving t))))
161 ;; Inform `expand-abbrev' that `self-insert-command' should not
162 ;; trigger, by returning non-nil on SPC.
163 (when (sotlisp--whitespace-p)
164 ;; And maybe move out of closing paren if expansion ends with $.
165 (when (eq (char-before) ?$)
166 (delete-char -1)
167 (setq sotlisp--needs-moving nil)
168 (sotlisp--maybe-skip-closing-paren))
169 t)))
170
171 (put 'sotlisp--expand-function 'no-self-insert t)
172
173 (defun sotlisp--simplify-function-expansion (expansion)
174 "Take a substring of EXPANSION up to first space.
175 The space char is not included. Any \"$\" are also removed."
176 (replace-regexp-in-string
177 "\\$" ""
178 (substring expansion 0 (string-match " " expansion))))
179
180 \f
181 ;;; Abbrev definitions
182 (defconst sotlisp--default-function-abbrevs
183 '(
184 ("a" . "and ")
185 ("ah" . "add-hook '")
186 ("atl" . "add-to-list '")
187 ("bb" . "bury-buffer")
188 ("bc" . "forward-char -1")
189 ("bfn" . "buffer-file-name")
190 ("bl" . "buffer-list$")
191 ("bn" . "buffer-name")
192 ("bod" . "beginning-of-defun")
193 ("bol" . "forward-line 0$")
194 ("bp" . "boundp '")
195 ("bs" . "buffer-string$")
196 ("bsn" . "buffer-substring-no-properties")
197 ("bss" . "buffer-substring ")
198 ("bw" . "forward-word -1")
199 ("c" . "concat ")
200 ("ca" . "char-after$")
201 ("cb" . "current-buffer$")
202 ("cc" . "condition-case er\n$\n(error nil)")
203 ("ci" . "call-interactively ")
204 ("cip" . "called-interactively-p 'any")
205 ("csv" . "customize-save-variable '")
206 ("d" . "delete-char 1")
207 ("dc" . "delete-char 1")
208 ("dcu" . "defcustom $ t\n \"\"\n :type 'boolean")
209 ("df" . "defun $ ()\n \"\"\n ")
210 ("dfa" . "defface $ \n '((t))\n \"\"\n ")
211 ("dfc" . "defcustom $ t\n \"\"\n :type 'boolean")
212 ("dff" . "defface $ \n '((t))\n \"\"\n ")
213 ("dfv" . "defvar $ t\n \"\"")
214 ("dk" . "define-key ")
215 ("dl" . "dolist (it $)")
216 ("dmp" . "derived-mode-p '")
217 ("dr" . "delete-region ")
218 ("dv" . "defvar $ t\n \"\"")
219 ("e" . "error \"$\"")
220 ("efn" . "expand-file-name ")
221 ("eol" . "end-of-line")
222 ("f" . "format \"$\"")
223 ("fb" . "fboundp '")
224 ("fbp" . "fboundp '")
225 ("fc" . "forward-char 1")
226 ("ff" . "find-file ")
227 ("fl" . "forward-line 1")
228 ("fp" . "functionp ")
229 ("frp" . "file-readable-p ")
230 ("fs" . "forward-sexp 1")
231 ("fw" . "forward-word 1")
232 ("g" . "goto-char ")
233 ("gc" . "goto-char ")
234 ("gsk" . "global-set-key ")
235 ("i" . "insert ")
236 ("ie" . "ignore-errors ")
237 ("ii" . "interactive")
238 ("ir" . "indent-region ")
239 ("jcl" . "justify-current-line ")
240 ("jl" . "delete-indentation")
241 ("jos" . "just-one-space")
242 ("jr" . "json-read$")
243 ("jtr" . "jump-to-register ")
244 ("k" . "kbd \"$\"")
245 ("kb" . "kill-buffer")
246 ("kn" . "kill-new ")
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 ("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 (if-let ((fcap (function-called-at-point)))
467 (symbol-name fcap)
468 (thing-at-point 'symbol))))
469
470 (defun sotlisp-find-or-define-function (&optional prefix)
471 "If symbol under point is a defined function, go to it, otherwise define it.
472 Essentially `find-function' on steroids.
473
474 If you write in your code the name of a function you haven't
475 defined yet, just place point on its name and hit \\[sotlisp-find-or-define-function]
476 and a defun will be inserted with point inside it. After that,
477 you can just hit `pop-mark' to go back to where you were.
478 With a PREFIX argument, creates a `defmacro' instead.
479
480 If the function under point is already defined this just calls
481 `find-function', with one exception:
482 if there's a defun (or equivalent) for this function in the
483 current buffer, we go to that even if it's not where the
484 global definition comes from (this is useful if you're
485 writing an Emacs package that also happens to be installed
486 through package.el).
487
488 With a prefix argument, defines a `defmacro' instead of a `defun'."
489 (interactive "P")
490 (let ((name (sotlisp--function-at-point)))
491 (unless (and name (sotlisp--find-in-buffer "(def\\(un\\|macro\\|alias\\) " name))
492 (let ((name-s (intern-soft name)))
493 (if (fboundp name-s)
494 (find-function name-s)
495 (sotlisp--beginning-of-defun)
496 (insert "(def" (if prefix "macro" "un")
497 " " name " (")
498 (save-excursion (insert ")\n \"\"\n )\n\n")))))))
499
500 (defun sotlisp-find-or-define-variable (&optional prefix)
501 "If symbol under point is a defined variable, go to it, otherwise define it.
502 Essentially `find-variable' on steroids.
503
504 If you write in your code the name of a variable you haven't
505 defined yet, place point on its name and hit \\[sotlisp-find-or-define-variable]
506 and a `defcustom' will be created with point inside. After that,
507 you can just `pop-mark' to go back to where you were. With a
508 PREFIX argument, creates a `defvar' instead.
509
510 If the variable under point is already defined this just calls
511 `find-variable', with one exception:
512 if there's a defvar (or equivalent) for this variable in the
513 current buffer, we go to that even if it's not where the
514 global definition comes from (this is useful if you're
515 writing an Emacs package that also happens to be installed
516 through package.el).
517
518 With a prefix argument, defines a `defvar' instead of a `defcustom'."
519 (interactive "P")
520 (let ((name (symbol-name (variable-at-point t))))
521 (unless (sotlisp--find-in-buffer "(def\\(custom\\|const\\|var\\) " name)
522 (unless (and (symbolp (variable-at-point))
523 (ignore-errors (find-variable (variable-at-point)) t))
524 (let ((name (thing-at-point 'symbol)))
525 (sotlisp--beginning-of-defun)
526 (insert "(def" (if prefix "var" "custom")
527 " " name " t")
528 (save-excursion
529 (insert "\n \"\""
530 (if prefix "" "\n :type 'boolean")
531 ")\n\n")))))))
532
533 (provide 'sotlisp)
534 ;;; sotlisp.el ends here
535