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