]> code.delx.au - gnu-emacs-elpa/blob - packages/sotlisp/sotlisp.el
Merge commit '5825163e2a8520bbb2751f9692f51a1b73cb81ad' from context-coloring
[gnu-emacs-elpa] / packages / sotlisp / sotlisp.el
1 ;;; sotlisp.el --- Write lisp at the speed of thought. -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 2014, 2015 Free Software Foundation, Inc.
4
5 ;; Author: Artur Malabarba <bruce.connor.am@>
6 ;; URL: https://github.com/Malabarba/speed-of-thought-lisp
7 ;; Keywords: convenience, lisp
8 ;; Package-Requires: ((emacs "24.1"))
9 ;; Version: 1.1
10
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.
15
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.
20
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/>.
23
24 ;;; Commentary:
25 ;;
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.
29 ;;
30 ;; The mode is quite simple, and is composed of two parts:
31 ;;
32 ;;; Abbrevs
33 ;;
34 ;; A large number of abbrevs which expand function
35 ;; initials to their name. A few examples:
36 ;;
37 ;; - wcb -> with-current-buffer
38 ;; - i -> insert
39 ;; - r -> require '
40 ;; - a -> and
41 ;;
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).
48 ;;
49 ;;; Commands
50 ;;
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.
55 ;;
56 ;; - M-RET :: Break line, and insert "()" with point in the middle.
57 ;; - C-RET :: Do `forward-up-list', then do M-RET.
58 ;;
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.
62 ;;
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.
66 ;;
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.
71 ;;
72 ;;; Small Example
73 ;;
74 ;; With the above (assuming you use something like paredit or
75 ;; electric-pair-mode), if you write:
76 ;;
77 ;; ( w t b M-RET i SPC text
78 ;;
79 ;; You get
80 ;;
81 ;; (with-temp-buffer (insert text))
82
83 \f
84 ;;; Code:
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 ("blp" . "buffer-live-p ")
192 ("bn" . "buffer-name")
193 ("bod" . "beginning-of-defun")
194 ("bol" . "forward-line 0$")
195 ("bp" . "boundp '")
196 ("bs" . "buffer-string$")
197 ("bsn" . "buffer-substring-no-properties")
198 ("bss" . "buffer-substring ")
199 ("bw" . "forward-word -1")
200 ("c" . "concat ")
201 ("ca" . "char-after$")
202 ("cb" . "current-buffer$")
203 ("cc" . "condition-case er\n$\n(error nil)")
204 ("ci" . "call-interactively ")
205 ("cip" . "called-interactively-p 'any")
206 ("csv" . "customize-save-variable '")
207 ("d" . "delete-char 1")
208 ("dc" . "delete-char 1")
209 ("dcu" . "defcustom $ t\n \"\"\n :type 'boolean")
210 ("df" . "defun $ ()\n \"\"\n ")
211 ("dfa" . "defface $ \n '((t))\n \"\"\n ")
212 ("dfc" . "defcustom $ t\n \"\"\n :type 'boolean")
213 ("dff" . "defface $ \n '((t))\n \"\"\n ")
214 ("dfv" . "defvar $ t\n \"\"")
215 ("dk" . "define-key ")
216 ("dl" . "dolist (it $)")
217 ("dmp" . "derived-mode-p '")
218 ("dr" . "delete-region ")
219 ("dv" . "defvar $ t\n \"\"")
220 ("e" . "error \"$\"")
221 ("efn" . "expand-file-name ")
222 ("eol" . "end-of-line")
223 ("f" . "format \"$\"")
224 ("fb" . "fboundp '")
225 ("fbp" . "fboundp '")
226 ("fc" . "forward-char 1")
227 ("ff" . "find-file ")
228 ("fl" . "forward-line 1")
229 ("fp" . "functionp ")
230 ("frp" . "file-readable-p ")
231 ("fs" . "forward-sexp 1")
232 ("fw" . "forward-word 1")
233 ("g" . "goto-char ")
234 ("gc" . "goto-char ")
235 ("gsk" . "global-set-key ")
236 ("i" . "insert ")
237 ("ie" . "ignore-errors ")
238 ("ii" . "interactive")
239 ("ir" . "indent-region ")
240 ("jcl" . "justify-current-line ")
241 ("jl" . "delete-indentation")
242 ("jos" . "just-one-space")
243 ("jr" . "json-read$")
244 ("jtr" . "jump-to-register ")
245 ("k" . "kbd \"$\"")
246 ("kb" . "kill-buffer")
247 ("kn" . "kill-new ")
248 ("kp" . "keywordp ")
249 ("l" . "lambda ($)")
250 ("la" . "looking-at \"$\"")
251 ("lap" . "looking-at-p \"$\"")
252 ("lb" . "looking-back \"$\"")
253 ("lbp" . "line-beginning-position")
254 ("lep" . "line-end-position")
255 ("let" . "let (($))")
256 ("lp" . "listp ")
257 ("m" . "message \"$%s\"")
258 ("mb" . "match-beginning 0")
259 ("me" . "match-end 0")
260 ("ms" . "match-string 0")
261 ("msn" . "match-string-no-properties 0")
262 ("msnp" . "match-string-no-properties 0")
263 ("msp" . "match-string-no-properties 0")
264 ("n" . "not ")
265 ("nai" . "newline-and-indent$")
266 ("nl" . "forward-line 1")
267 ("np" . "numberp ")
268 ("ntr" . "narrow-to-region ")
269 ("ow" . "other-window 1")
270 ("p" . "point$")
271 ("pm" . "point-marker$")
272 ("pa" . "point-max$")
273 ("pg" . "plist-get ")
274 ("pi" . "point-min$")
275 ("r" . "require '")
276 ("ra" . "use-region-p$")
277 ("rap" . "use-region-p$")
278 ("rb" . "region-beginning")
279 ("re" . "region-end")
280 ("rh" . "remove-hook '")
281 ("rm" . "replace-match \"$\"")
282 ("ro" . "regexp-opt ")
283 ("rq" . "regexp-quote ")
284 ("rris" . "replace-regexp-in-string ")
285 ("rrs" . "replace-regexp-in-string ")
286 ("rs" . "while (search-forward $ nil t)\n(replace-match \"\") nil t)")
287 ("rsb" . "re-search-backward $ nil 'noerror")
288 ("rsf" . "re-search-forward $ nil 'noerror")
289 ("s" . "setq ")
290 ("sb" . "search-backward $ nil 'noerror")
291 ("sbr" . "search-backward-regexp $ nil 'noerror")
292 ("scb" . "skip-chars-backward \"$\\r\\n[:blank:]\"")
293 ("scf" . "skip-chars-forward \"$\\r\\n[:blank:]\"")
294 ("se" . "save-excursion")
295 ("sf" . "search-forward $ nil 'noerror")
296 ("sfr" . "search-forward-regexp $ nil 'noerror")
297 ("sic" . "self-insert-command")
298 ("sl" . "string<")
299 ("sm" . "string-match \"$\"")
300 ("smd" . "save-match-data")
301 ("sn" . "symbol-name ")
302 ("sp" . "stringp ")
303 ("sq" . "string= ")
304 ("sr" . "save-restriction")
305 ("ss" . "substring ")
306 ("ssn" . "substring-no-properties ")
307 ("ssnp" . "substring-no-properties ")
308 ("stb" . "switch-to-buffer ")
309 ("sw" . "selected-window$")
310 ("syp" . "symbolp ")
311 ("tap" . "thing-at-point 'symbol")
312 ("u" . "unless ")
313 ("ul" . "up-list")
314 ("up" . "unwind-protect\n(progn $)")
315 ("urp" . "use-region-p$")
316 ("w" . "when ")
317 ("wcb" . "with-current-buffer ")
318 ("wf" . "write-file ")
319 ("wh" . "while ")
320 ("wl" . "window-list nil 'nominibuffer")
321 ("we" . "window-end")
322 ("ws" . "window-start")
323 ("wtb" . "with-temp-buffer")
324 ("wtf" . "with-temp-file ")
325 )
326 "Alist of (ABBREV . EXPANSION) used by `sotlisp'.")
327
328 (defun sotlisp-define-function-abbrev (name expansion)
329 "Define a function abbrev expanding NAME to EXPANSION.
330 This abbrev will only be expanded in places where a function name is
331 sensible. Roughly, this is right after a `(' or a `#''.
332
333 If EXPANSION is any string, it doesn't have to be the just the
334 name of a function. In particular:
335 - if it contains a `$', this char will not be inserted and
336 point will be moved to its position after expansion.
337 - if it contains a space, only a substring of it up to the
338 first space is inserted when expanding after a `#'' (this is done
339 by defining two different abbrevs).
340
341 For instance, if one defines
342 (sotlisp-define-function-abbrev \"d\" \"delete-char 1\")
343
344 then triggering `expand-abbrev' after \"d\" expands in the
345 following way:
346 (d => (delete-char 1
347 #'d => #'delete-char"
348 (define-abbrev emacs-lisp-mode-abbrev-table
349 name t #'sotlisp--expand-function
350 ;; Don't override user abbrevs
351 :system t
352 ;; Only expand in function places.
353 :enable-function #'sotlisp--function-p)
354 (puthash name expansion sotlisp--function-table))
355
356 (defun sotlisp-erase-all-abbrevs ()
357 "Undefine all abbrevs defined by `sotlisp'."
358 (interactive)
359 (maphash (lambda (x _) (define-abbrev emacs-lisp-mode-abbrev-table x nil))
360 sotlisp--function-table))
361
362 (defun sotlisp-define-all-abbrevs ()
363 "Define all abbrevs in `sotlisp--default-function-abbrevs'."
364 (interactive)
365 (mapc (lambda (x) (sotlisp-define-function-abbrev (car x) (cdr x)))
366 sotlisp--default-function-abbrevs))
367
368 \f
369 ;;; The global minor-mode
370 (defvar speed-of-thought-turn-on-hook '()
371 "Hook run once when `speed-of-thought-mode' is enabled.
372 Note that `speed-of-thought-mode' is global, so this is not run
373 on every buffer.
374
375 See `sotlisp-turn-on-everywhere' for an example of what a
376 function in this hook should do.")
377
378 (defvar speed-of-thought-turn-off-hook '()
379 "Hook run once when `speed-of-thought-mode' is disabled.
380 Note that `speed-of-thought-mode' is global, so this is not run
381 on every buffer.
382
383 See `sotlisp-turn-on-everywhere' for an example of what a
384 function in this hook should do.")
385
386 ;;;###autoload
387 (define-minor-mode speed-of-thought-mode
388 nil nil nil nil
389 :global t
390 (run-hooks (if speed-of-thought-mode
391 'speed-of-thought-turn-on-hook
392 'speed-of-thought-turn-off-hook)))
393
394 ;;;###autoload
395 (defun speed-of-thought-hook-in (on off)
396 "Add functions ON and OFF to `speed-of-thought-mode' hooks.
397 If `speed-of-thought-mode' is already on, call ON."
398 (add-hook 'speed-of-thought-turn-on-hook on)
399 (add-hook 'speed-of-thought-turn-off-hook off)
400 (when speed-of-thought-mode (funcall on)))
401
402 \f
403 ;;; The local minor-mode
404 (define-minor-mode sotlisp-mode
405 nil nil " SoT"
406 '(([M-return] . sotlisp-newline-and-parentheses)
407 ([C-return] . sotlisp-downlist-newline-and-parentheses)
408 ("\C-cf" . sotlisp-find-or-define-function)
409 ("\C-cv" . sotlisp-find-or-define-variable)))
410
411 (defun sotlisp-turn-on-everywhere ()
412 "Call-once function to turn on sotlisp everywhere.
413 Calls `sotlisp-mode' on all `emacs-lisp-mode' buffers, and sets
414 up a hook and abbrevs."
415 (add-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
416 (sotlisp-define-all-abbrevs)
417 (mapc (lambda (b)
418 (with-current-buffer b
419 (when (derived-mode-p 'emacs-lisp-mode)
420 (sotlisp-mode 1))))
421 (buffer-list)))
422
423 (defun sotlisp-turn-off-everywhere ()
424 "Call-once function to turn off sotlisp everywhere.
425 Removes `sotlisp-mode' from all `emacs-lisp-mode' buffers, and
426 removes hooks and abbrevs."
427 (remove-hook 'emacs-lisp-mode-hook #'sotlisp-mode)
428 (sotlisp-erase-all-abbrevs)
429 (mapc (lambda (b)
430 (with-current-buffer b
431 (when (derived-mode-p 'emacs-lisp-mode)
432 (sotlisp-mode -1))))
433 (buffer-list)))
434
435 (speed-of-thought-hook-in #'sotlisp-turn-on-everywhere #'sotlisp-turn-off-everywhere)
436
437 \f
438 ;;; Commands
439 (defun sotlisp-newline-and-parentheses ()
440 "`newline-and-indent' then insert a pair of parentheses."
441 (interactive)
442 (point)
443 (ignore-errors (expand-abbrev))
444 (newline-and-indent)
445 (insert "()")
446 (forward-char -1))
447
448 (defun sotlisp-downlist-newline-and-parentheses ()
449 "`up-list', `newline-and-indent', then insert a parentheses pair."
450 (interactive)
451 (ignore-errors (expand-abbrev))
452 (up-list)
453 (newline-and-indent)
454 (insert "()")
455 (forward-char -1))
456
457 (defun sotlisp--find-in-buffer (r s)
458 "Find the string (concat R (regexp-quote S)) somewhere in this buffer."
459 (let ((l (save-excursion
460 (goto-char (point-min))
461 (save-match-data
462 (when (search-forward-regexp (concat r (regexp-quote s) "\\_>")
463 nil :noerror)
464 (match-beginning 0))))))
465 (when l
466 (push-mark)
467 (goto-char l)
468 l)))
469
470 (defun sotlisp--beginning-of-defun ()
471 "`push-mark' and move above this defun."
472 (push-mark)
473 (beginning-of-defun)
474 (when (looking-back "^;;;###autoload\\s-*\n")
475 (forward-line -1)))
476
477 (defun sotlisp--function-at-point ()
478 "Return name of `function-called-at-point'."
479 (if (save-excursion
480 (ignore-errors (forward-sexp -1)
481 (looking-at-p "#'")))
482 (thing-at-point 'symbol)
483 (let ((fcap (function-called-at-point)))
484 (if fcap (symbol-name fcap)
485 (thing-at-point 'symbol)))))
486
487 (defun sotlisp-find-or-define-function (&optional prefix)
488 "If symbol under point is a defined function, go to it, otherwise define it.
489 Essentially `find-function' on steroids.
490
491 If you write in your code the name of a function you haven't
492 defined yet, just place point on its name and hit \\[sotlisp-find-or-define-function]
493 and a defun will be inserted with point inside it. After that,
494 you can just hit `pop-mark' to go back to where you were.
495 With a PREFIX argument, creates a `defmacro' instead.
496
497 If the function under point is already defined this just calls
498 `find-function', with one exception:
499 if there's a defun (or equivalent) for this function in the
500 current buffer, we go to that even if it's not where the
501 global definition comes from (this is useful if you're
502 writing an Emacs package that also happens to be installed
503 through package.el).
504
505 With a prefix argument, defines a `defmacro' instead of a `defun'."
506 (interactive "P")
507 (let ((name (sotlisp--function-at-point)))
508 (unless (and name (sotlisp--find-in-buffer "(def\\(un\\|macro\\|alias\\) " name))
509 (let ((name-s (intern-soft name)))
510 (if (fboundp name-s)
511 (find-function name-s)
512 (sotlisp--beginning-of-defun)
513 (insert "(def" (if prefix "macro" "un")
514 " " name " (")
515 (save-excursion (insert ")\n \"\"\n )\n\n")))))))
516
517 (defun sotlisp-find-or-define-variable (&optional prefix)
518 "If symbol under point is a defined variable, go to it, otherwise define it.
519 Essentially `find-variable' on steroids.
520
521 If you write in your code the name of a variable you haven't
522 defined yet, place point on its name and hit \\[sotlisp-find-or-define-variable]
523 and a `defcustom' will be created with point inside. After that,
524 you can just `pop-mark' to go back to where you were. With a
525 PREFIX argument, creates a `defvar' instead.
526
527 If the variable under point is already defined this just calls
528 `find-variable', with one exception:
529 if there's a defvar (or equivalent) for this variable in the
530 current buffer, we go to that even if it's not where the
531 global definition comes from (this is useful if you're
532 writing an Emacs package that also happens to be installed
533 through package.el).
534
535 With a prefix argument, defines a `defvar' instead of a `defcustom'."
536 (interactive "P")
537 (let ((name (symbol-name (variable-at-point t))))
538 (unless (sotlisp--find-in-buffer "(def\\(custom\\|const\\|var\\) " name)
539 (unless (and (symbolp (variable-at-point))
540 (ignore-errors (find-variable (variable-at-point)) t))
541 (let ((name (thing-at-point 'symbol)))
542 (sotlisp--beginning-of-defun)
543 (insert "(def" (if prefix "var" "custom")
544 " " name " t")
545 (save-excursion
546 (insert "\n \"\""
547 (if prefix "" "\n :type 'boolean")
548 ")\n\n")))))))
549
550 (provide 'sotlisp)
551 ;;; sotlisp.el ends here