1 ;;; tiny.el --- Quickly generate linear ranges in Emacs
3 ;; Copyright (C) 2013-2015 Free Software Foundation, Inc.
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/tiny
8 ;; Keywords: convenience
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>
27 ;; To set it up, just bind e.g.:
29 ;; (global-set-key (kbd "C-;") 'tiny-expand)
32 ;; This extension's main command is `tiny-expand'.
33 ;; It's meant to quickly generate linear ranges, e.g. 5, 6, 7, 8.
34 ;; Some elisp proficiency is an advantage, since you can transform
35 ;; your numeric range with an elisp expression.
37 ;; There's also some emphasis on the brevity of the expression to be
38 ;; expanded: e.g. instead of typing (+ x 2), you can do +x2.
39 ;; You can still do the full thing, but +x2 would save you some
42 ;; You can test out the following snippets
43 ;; by positioning the point at the end of the expression
44 ;; and calling `tiny-expand' (default shortcut is C-;):
56 ;; m97,120stringxupcasex
57 ;; m97,120stringxupcasex)x
58 ;; m\n;; 10|%(+ x x) and %(* x x) and %s
61 ;; m5\n;; 20expx%014.2f
65 ;; m1\n14|*** TODO http://emacsrocks.com/e%02d.html
66 ;; m1\n10|convert img%s.jpg -monochrome -resize 50%% -rotate 180 img%s_mono.pdf
67 ;; (setq foo-list '(m1 11+x96|?%c))
68 ;; m1\n10listx+x96|convert img%s.jpg -monochrome -resize 50%% -rotate 180 img%c_mono.pdf
69 ;; m1\n10listxnthxfoo-list|convert img%s.jpg -monochrome -resize 50%% -rotate 180 img%c_mono.pdf
70 ;; m\n;; 16list*xxx)*xx%s:%s:%s
71 ;; m\n8|**** TODO Learning from Data Week %(+ x 2) \nSCHEDULED: <%(date "Oct 7" (* x 7))> DEADLINE: <%(date "Oct 14" (* x 7))>
73 ;; As you might have guessed, the syntax is as follows:
74 ;; m[<range start:=0>][<separator:= >]<range end>[Lisp expr]|[format expr]
76 ;; x is the default var in the elisp expression. It will take one by one
77 ;; the value of all numbers in the range.
79 ;; | means that elisp expr has ended and format expr has begun.
80 ;; It can be omitted if the format expr starts with %.
81 ;; The keys are the same as for format.
82 ;; In addition %(sexp) forms are allowed. The sexp can depend on x.
84 ;; Note that multiple % can be used in the format expression.
86 ;; * if the Lisp expression returns a list, the members of this list
87 ;; are used in the appropriate place.
88 ;; * otherwise, it's just the result of the expression repeated as
89 ;; many times as necessary.
99 "Last matched snippet start position.")
102 "Last matched snippet end position.")
105 (defun tiny-expand ()
106 "Expand current snippet.
107 It polls the expander functions one by one
108 if they can expand the thing at point.
109 First one to return a string succeeds.
110 These functions are expected to set `tiny-beg' and `tiny-end'
111 to the bounds of the snippet that they matched.
112 At the moment, only `tiny-mapconcat' is supported.
113 `tiny-mapconcat2' should be added to expand rectangles."
115 (let ((str (tiny-mapconcat)))
117 (delete-region tiny-beg tiny-end)
119 (tiny-replace-this-sexp))))
121 (defun tiny-setup-default ()
123 (global-set-key (kbd "C-;") 'tiny-expand))
126 (defun tiny-replace-this-sexp ()
127 "Eval and replace the current sexp.
128 On error go up list and try again."
130 (if (region-active-p)
131 (let ((s (buffer-substring-no-properties
134 (delete-region (region-beginning)
136 (insert (format "%s" (eval (read s)))))
140 (unless (looking-back ")")
141 (error "Bad location"))
142 (let ((sexp (preceding-sexp)))
143 (if (eq (car sexp) 'lambda)
144 (error "Lambda evaluates to itself")
145 (let ((value (eval sexp)))
147 (insert (format "%s" value))
148 (throw 'success t)))))
149 ;; if can't replace, go up list
153 (message "reached the highest point, couldn't eval.")
154 (throw 'success nil)))))))
156 (defun tiny-up-list ()
157 "An `up-list' that can exit from string.
158 Must throw an error when can't go up further."
160 ;; check if inside string
161 (let ((p (nth 8 (syntax-ppss))))
162 (when (eq (char-after p) ?\")
163 ;; go to beginning for string
167 (defun tiny-mapconcat ()
168 "Format output of `tiny-mapconcat-parse'.
169 Defaults are used in place of null values."
170 (let ((parsed (tiny-mapconcat-parse)))
172 (let* ((n1 (or (nth 0 parsed) "0"))
173 (s1 (or (nth 1 parsed) " "))
175 (expr (or (nth 3 parsed) "x"))
177 (n-have (if (and (listp lexpr) (eq (car lexpr) 'list))
180 (expr (if (zerop n-have) `(list ,lexpr) lexpr))
181 (n-have (if (zerop n-have) 1 n-have))
182 (tes (tiny-extract-sexps (or (nth 4 parsed) "%s")))
184 (n-need (cl-count nil (cdr tes)))
187 (concat "(mapconcat (lambda(x) (let ((lst %s)) (format %S "
188 (mapconcat (lambda (x)
190 (if (>= (1+ idx) n-have)
192 (format "(nth %d lst)" (incf idx)))))
195 ")))(number-sequence %s %s) \"%s\")")))
196 (unless (>= (read n1) (read n2))
200 (replace-regexp-in-string "\\\\n" "\n" fmt)
205 (defconst tiny-format-str
206 (let ((flags "[+ #-0]\\{0,1\\}")
208 (precision "\\(?:\\.[0-9]+\\)?")
209 (character "[sdoxXefgcS]?"))
210 (format "\\(%s%s%s%s\\)("
211 flags width precision character)))
213 (defun tiny-extract-sexps (str)
214 "Return (STR & FORMS).
215 Each element of FORMS corresponds to a `format'-style % form in STR.
217 * %% forms are skipped
218 * %(sexp) is replaced with %s in STR, and put in FORMS
219 * the rest of forms are untouched in STR, and put as nil in FORMS"
223 (while (setq beg (string-match "%" str start))
224 (setq start (1+ beg))
226 (cond ((= ?% (aref str (1+ beg)))
229 ((and (eq beg (string-match tiny-format-str str beg))
230 (setq fexp (match-string-no-properties 1 str)))
231 (incf beg (length fexp))
232 (destructuring-bind (sexp . end)
233 (read-from-string str beg)
235 (replace-regexp-in-string "(date" "(tiny-date"
236 (substring str beg end))
238 (setq str (concat (substring str 0 beg)
239 (if (string= fexp "%") "s" "")
240 (substring str end)))))
241 (t (push nil forms))))
242 (error (message "Malformed sexp: %s" (substring str beg))))
243 (cons str (nreverse forms))))
245 (defun tiny-mapconcat-parse ()
246 "Try to match a snippet of this form:
247 m[START][SEPARATOR]END[EXPR]|[FORMAT]
249 * START - integer (defaults to 0)
250 * SEPARATOR - string (defaults to \" \")
251 * END - integer (required)
252 * EXPR - Lisp expression: function body with argument x (defaults to x)
253 Parens are optional if it's unambiguous:
254 - `(* 2 (+ x 3))' <-> *2+x3
256 A closing paren may be added to resolve ambiguity:
257 - `(* 2 (+ x 3) x) <-> *2+x3)
258 * FORMAT - string, `format'-style (defaults to \"%s\")
259 | separator can be omitted if FORMAT starts with %.
261 Return nil if nothing was matched, otherwise
262 (START SEPARATOR END EXPR FORMAT)"
263 (let ((case-fold-search nil)
264 n1 s1 n2 expr fmt str
268 ;; either start with a number
269 ((looking-back "\\bm\\(-?[0-9]+\\)\\([^\n]*?\\)")
270 (setq n1 (match-string-no-properties 1)
271 str (match-string-no-properties 2)
272 tiny-beg (match-beginning 0)
273 tiny-end (match-end 0))
274 (when (zerop (length str))
278 ;; else capture the whole thing
279 ((looking-back "\\bm\\([^%|\n]*[0-9][^\n]*\\)")
280 (setq str (match-string-no-properties 1)
281 tiny-beg (match-beginning 0)
282 tiny-end (match-end 0))
283 (when (zerop (length str))
285 (t (throw 'done nil)))
286 ;; at this point, `str' should be either [sep]<num>[expr][fmt]
289 ;; First, try to match [expr][fmt]
290 (string-match "^\\(.*?\\)|?\\(%.*\\)?$" str)
291 (setq expr (match-string-no-properties 1 str))
292 (setq fmt (match-string-no-properties 2 str))
293 ;; If it's a valid expression, we're done
294 (when (setq expr (tiny-tokenize expr))
298 ;; at this point, `str' is [sep]<num>[expr][fmt]
299 (if (string-match "^\\([^\n0-9]*?\\)\\(-?[0-9]+\\)\\(.*\\)?$" str)
300 (setq s1 (match-string-no-properties 1 str)
301 n2 (match-string-no-properties 2 str)
302 str (match-string-no-properties 3 str))
303 ;; here there's only n2 that was matched as n1
307 (unless (zerop (length str))
308 (if (or (string-match "^\\([^\n%|]*?\\)|\\([^\n]*\\)?$" str)
309 (string-match "^\\([^\n%|]*?\\)\\(%[^\n]*\\)?$" str))
311 (setq expr (tiny-tokenize (match-string-no-properties 1 str)))
312 (setq fmt (match-string-no-properties 2 str)))
313 (error "Couldn't match %s" str)))
315 (when (equal expr "")
317 (list n1 s1 n2 expr fmt))))
319 ;; TODO: check for arity: this doesn't work: exptxy
320 (defun tiny-tokenize (str)
321 "Transform shorthand Lisp expression STR to proper Lisp."
331 (setq s (substring str i j))
339 (error "Unexpected \" \"")))
340 ;; special syntax to read chars
342 (setq s (format "%s" (read (substring str i (incf j)))))
346 ;; expect a close paren only if it's necessary
349 (error "Unexpected \")\""))
350 (when (string= (car out) " ")
355 ;; open paren is used sometimes
356 ;; when there are numbers in the expression
360 ((progn (setq sym (intern-soft s))
363 ((not (eq t (help-function-arglist sym)))
366 ;; (when (zerop n-paren) (push "(" out))
367 (unless (equal (car out) "(")
371 ((and sym (boundp sym) (not expect-fun))
376 (let* ((num (string-to-number (substring str i)))
377 (num-s (format "%s" num)))
380 (setq j (+ i (length num-s)))))
387 (when (string= (car out) " ")
390 (apply #'concat (nreverse out))
391 (make-string n-paren ?\)))))))
393 (defun tiny-date (s &optional shift)
394 "Return date representation of S.
395 `org-mode' format is used.
396 Optional SHIFT argument is the integer amount of days to shift."
397 (let* ((ct (decode-time (current-time)))
398 (time (apply 'encode-time
399 (org-read-date-analyze
403 (if (equal (cl-subseq ct 1 3)
404 (cl-subseq (decode-time time) 1 3))
406 "%Y-%m-%d %a %H:%M")))
408 (setq time (time-add time (days-to-time shift))))
409 (format-time-string formatter time)))
412 ;;; tiny.el ends here