1 ;;; org-macro.el --- Macro Replacement Code for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs 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.
15 ;; GNU Emacs 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.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
25 ;; Macros are expanded with `org-macro-replace-all', which relies
26 ;; internally on `org-macro-expand'.
28 ;; Default templates for expansion are stored in the buffer-local
29 ;; variable `org-macro-templates'. This variable is updated by
30 ;; `org-macro-initialize-templates', which recursively calls
31 ;; `org-macro--collect-macros' in order to read setup files.
33 ;; Argument in macros are separated with commas. Proper escaping rules
34 ;; are implemented in `org-macro-escape-arguments' and arguments can
35 ;; be extracted from a string with `org-macro-extract-arguments'.
37 ;; Along with macros defined through #+MACRO: keyword, default
38 ;; templates include the following hard-coded macros:
39 ;; {{{time(format-string)}}},
40 ;; {{{property(node-property)}}},
42 ;; {{{modification-time(format-string)}}},
43 ;; {{{n(counter,action}}}.
45 ;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}},
46 ;; {{{email}}} and {{{title}}} macros.
53 (declare-function org-element-at-point
"org-element" ())
54 (declare-function org-element-context
"org-element" (&optional element
))
55 (declare-function org-element-macro-parser
"org-element" ())
56 (declare-function org-element-property
"org-element" (property element
))
57 (declare-function org-element-type
"org-element" (element))
58 (declare-function org-file-contents
"org" (file &optional noerror nocache
))
59 (declare-function org-file-url-p
"org" (file))
60 (declare-function org-in-commented-heading-p
"org" (&optional no-inheritance
))
61 (declare-function org-mode
"org" ())
62 (declare-function org-trim
"org" (s &optional keep-lead
))
63 (declare-function vc-backend
"vc-hooks" (f))
64 (declare-function vc-call
"vc-hooks" (fun file
&rest args
) t
)
65 (declare-function vc-exec-after
"vc-dispatcher" (code))
69 (defvar-local org-macro-templates nil
70 "Alist containing all macro templates in current buffer.
71 Associations are in the shape of (NAME . TEMPLATE) where NAME
72 stands for macro's name and template for its replacement value,
73 both as strings. This is an internal variable. Do not set it
74 directly, use instead:
76 #+MACRO: name template")
80 (defun org-macro--collect-macros ()
81 "Collect macro definitions in current buffer and setup files.
82 Return an alist containing all macro templates found."
83 (letrec ((collect-macros
84 (lambda (files templates
)
85 ;; Return an alist of macro templates. FILES is a list
86 ;; of setup files names read so far, used to avoid
87 ;; circular dependencies. TEMPLATES is the alist
89 (let ((case-fold-search t
))
91 (goto-char (point-min))
92 (while (re-search-forward
93 "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t
)
94 (let ((element (org-element-at-point)))
95 (when (eq (org-element-type element
) 'keyword
)
96 (let ((val (org-element-property :value element
)))
97 (if (equal (org-element-property :key element
) "MACRO")
98 ;; Install macro in TEMPLATES.
100 "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val
)
101 (let* ((name (match-string 1 val
))
102 (template (or (match-string 2 val
) ""))
103 (old-cell (assoc name templates
)))
104 (if old-cell
(setcdr old-cell template
)
105 (push (cons name template
) templates
))))
107 (let* ((uri (org-unbracket-string "\"" "\"" (org-trim val
)))
108 (uri-is-url (org-file-url-p uri
))
111 (expand-file-name uri
))))
112 ;; Avoid circular dependencies.
113 (unless (member uri files
)
116 (setq default-directory
117 (file-name-directory uri
)))
119 (insert (org-file-contents uri
'noerror
))
121 (funcall collect-macros
(cons uri files
)
124 (funcall collect-macros nil nil
)))
126 (defun org-macro-initialize-templates ()
127 "Collect macro templates defined in current buffer.
128 Templates are stored in buffer-local variable
129 `org-macro-templates'. In addition to buffer-defined macros, the
130 function installs the following ones: \"property\",
131 \"time\". and, if the buffer is associated to a file,
132 \"input-file\" and \"modification-time\"."
133 (let* ((templates (org-macro--collect-macros))
136 (let ((old-template (assoc (car cell
) templates
)))
137 (if old-template
(setcdr old-template
(cdr cell
))
138 (push cell templates
))))))
139 ;; Install "author, "date, "email", "keyword", "title" and
141 (mapc update-templates
143 (cons "author" (org-macro--find-keyword-value "AUTHOR"))
145 (let* ((value (org-macro--find-keyword-value "DATE"))
146 (date (org-element-parse-secondary-string
147 value
(org-element-restriction 'keyword
))))
148 (if (and (consp date
)
150 (eq (org-element-type (car date
)) 'timestamp
))
151 (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
152 (format "(org-timestamp-format '%S \"$1\")"
153 (org-element-copy (car date
)))
156 (cons "email" (org-macro--find-keyword-value "EMAIL"))
157 (cons "keyword" "(eval (org-macro--find-keyword-value \"$1\"))")
158 (cons "results" "$1")
159 (cons "title" (org-macro--find-keyword-value "TITLE"))))
160 ;; Install "property", "time" macros.
161 (mapc update-templates
162 (list (cons "property"
163 "(eval (save-excursion
165 (when (org-string-nw-p l)
167 (let ((org-link-search-must-match-exact-headline t))
168 (org-link-search l nil t))
170 (error \"Macro property failed: cannot find location %s\"
172 (org-entry-get nil \"$1\" 'selective)))")
173 (cons "time" "(eval (format-time-string \"$1\"))")))
174 ;; Install "input-file", "modification-time" macros.
175 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
176 (when (and visited-file
(file-exists-p visited-file
))
177 (mapc update-templates
178 (list (cons "input-file" (file-name-nondirectory visited-file
))
179 (cons "modification-time"
181 \(format-time-string \"$1\"
182 (or (and (org-string-nw-p \"$2\")
183 (org-macro--vc-modified-time %s))
185 (prin1-to-string visited-file
)
187 (nth 5 (file-attributes visited-file
)))))))))
188 ;; Initialize and install "n" macro.
189 (org-macro--counter-initialize)
190 (funcall update-templates
191 (cons "n" "(eval (org-macro--counter-increment \"$1\" \"$2\"))"))
192 (setq org-macro-templates templates
)))
194 (defun org-macro-expand (macro templates
)
195 "Return expanded MACRO, as a string.
196 MACRO is an object, obtained, for example, with
197 `org-element-context'. TEMPLATES is an alist of templates used
198 for expansion. See `org-macro-templates' for a buffer-local
199 default value. Return nil if no template was found."
201 ;; Macro names are case-insensitive.
202 (cdr (assoc-string (org-element-property :key macro
) templates t
))))
204 (let ((value (replace-regexp-in-string
207 (or (nth (1- (string-to-number (substring arg
1)))
208 (org-element-property :args macro
))
209 ;; No argument: remove place-holder.
211 template nil
'literal
)))
212 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
213 (when (string-match "\\`(eval\\>" value
)
214 (setq value
(eval (read value
))))
216 (format "%s" (or value
""))))))
218 (defun org-macro-replace-all (templates &optional keywords
)
219 "Replace all macros in current buffer by their expansion.
221 TEMPLATES is an alist of templates used for expansion. See
222 `org-macro-templates' for a buffer-local default value.
224 Optional argument KEYWORDS, when non-nil is a list of keywords,
225 as strings, where macro expansion is allowed.
227 Return an error if a macro in the buffer cannot be associated to
228 a definition in TEMPLATES."
229 (org-with-wide-buffer
230 (goto-char (point-min))
231 (let ((properties-regexp (format "\\`EXPORT_%s\\+?\\'"
232 (regexp-opt keywords
)))
234 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t
)
235 (unless (save-match-data (org-in-commented-heading-p))
236 (let* ((datum (save-match-data (org-element-context)))
237 (type (org-element-type datum
))
240 ((eq type
'macro
) datum
)
241 ;; In parsed keywords and associated node
242 ;; properties, force macro recognition.
243 ((or (and (eq type
'keyword
)
244 (member (org-element-property :key datum
) keywords
))
245 (and (eq type
'node-property
)
246 (string-match-p properties-regexp
247 (org-element-property :key datum
))))
249 (goto-char (match-beginning 0))
250 (org-element-macro-parser))))))
252 (let* ((value (org-macro-expand macro templates
))
253 (begin (org-element-property :begin macro
))
254 (signature (list begin
256 (org-element-property :args macro
))))
257 ;; Avoid circular dependencies by checking if the same
258 ;; macro with the same arguments is expanded at the
259 ;; same position twice.
260 (cond ((member signature record
)
261 (error "Circular macro expansion: %s"
262 (org-element-property :key macro
)))
264 (push signature record
)
267 ;; Preserve white spaces after the macro.
268 (progn (goto-char (org-element-property :end macro
))
269 (skip-chars-backward " \t")
271 ;; Leave point before replacement in case of
272 ;; recursive expansions.
273 (save-excursion (insert value
)))
275 (error "Undefined Org macro: %s; aborting"
276 (org-element-property :key macro
))))))))))))
278 (defun org-macro-escape-arguments (&rest args
)
279 "Build macro's arguments string from ARGS.
280 ARGS are strings. Return value is a string with arguments
281 properly escaped and separated with commas. This is the opposite
282 of `org-macro-extract-arguments'."
284 (dolist (arg (reverse args
) (substring s
1))
288 (replace-regexp-in-string
291 (concat (make-string (1+ (* 2 (length (match-string 1 m
)))) ?
\\)
293 ;; If a non-terminal argument ends on backslashes, make
294 ;; sure to also escape them as they will be followed by
296 (concat arg
(and (not (equal s
""))
297 (string-match "\\\\+\\'" arg
)
298 (match-string 0 arg
)))
302 (defun org-macro-extract-arguments (s)
303 "Extract macro arguments from string S.
304 S is a string containing comma separated values properly escaped.
305 Return a list of arguments, as strings. This is the opposite of
306 `org-macro-escape-arguments'."
307 ;; Do not use `org-split-string' since empty strings are
310 (replace-regexp-in-string
313 (let ((len (length (match-string 1 str
))))
314 (concat (make-string (/ len
2) ?
\\)
315 (if (zerop (mod len
2)) "\000" ","))))
320 ;;; Helper functions and variables for internal macros
322 (defun org-macro--find-keyword-value (name)
323 "Find value for keyword NAME in current buffer.
324 KEYWORD is a string. Return value associated to the keywords
325 named after NAME, as a string, or nil."
327 (let ((regexp (format "^[ \t]*#\\+%s:" (regexp-quote name
)))
330 (while (re-search-forward regexp nil t
)
331 (let ((element (org-element-at-point)))
332 (when (eq 'keyword
(org-element-type element
))
333 (setq result
(concat result
335 (org-element-property :value element
))))))
336 (and result
(org-trim result
)))))
338 (defun org-macro--vc-modified-time (file)
339 (save-window-excursion
340 (when (vc-backend file
)
341 (let ((buf (get-buffer-create " *org-vc*"))
346 (vc-call print-log file buf nil nil
1)
347 (with-current-buffer buf
350 (goto-char (point-min))
351 (when (re-search-forward "Date:?[ \t]*" nil t
)
352 (let ((time (parse-time-string
354 (point) (line-end-position)))))
355 (when (cl-some #'identity time
)
356 (setq date
(apply #'encode-time time
))))))))
357 (let ((proc (get-buffer-process buf
)))
358 (while (and proc
(accept-process-output proc
.5 nil t
)))))
362 (defvar org-macro--counter-table nil
363 "Hash table containing counter value per name.")
365 (defun org-macro--counter-initialize ()
366 "Initialize `org-macro--counter-table'."
367 (setq org-macro--counter-table
(make-hash-table :test
#'equal
)))
369 (defun org-macro--counter-increment (name &optional action
)
370 "Increment counter NAME.
371 NAME is a string identifying the counter.
373 When non-nil, optional argument ACTION is a string.
375 If the string is \"-\", keep the NAME counter at its current
376 value, i.e. do not increment.
378 If the string represents an integer, set the counter to this number.
380 Any other non-empty string resets the counter to 1."
381 (let ((name-trimmed (org-trim name
))
382 (action-trimmed (when (org-string-nw-p action
)
384 (puthash name-trimmed
385 (cond ((not (org-string-nw-p action-trimmed
))
386 (1+ (gethash name-trimmed org-macro--counter-table
0)))
387 ((string= "-" action-trimmed
)
388 (gethash name-trimmed org-macro--counter-table
1))
389 ((string-match-p "\\`[0-9]+\\'" action-trimmed
)
390 (string-to-number action-trimmed
))
392 org-macro--counter-table
)))
396 ;;; org-macro.el ends here