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 <http://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,reset}}}.
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
))
59 (declare-function org-mode
"org" ())
60 (declare-function vc-backend
"vc-hooks" (f))
61 (declare-function vc-call
"vc-hooks" (fun file
&rest args
) t
)
62 (declare-function vc-exec-after
"vc-dispatcher" (code))
66 (defvar-local org-macro-templates nil
67 "Alist containing all macro templates in current buffer.
68 Associations are in the shape of (NAME . TEMPLATE) where NAME
69 stands for macro's name and template for its replacement value,
70 both as strings. This is an internal variable. Do not set it
71 directly, use instead:
73 #+MACRO: name template")
77 (defun org-macro--collect-macros ()
78 "Collect macro definitions in current buffer and setup files.
79 Return an alist containing all macro templates found."
80 (letrec ((collect-macros
81 (lambda (files templates
)
82 ;; Return an alist of macro templates. FILES is a list
83 ;; of setup files names read so far, used to avoid
84 ;; circular dependencies. TEMPLATES is the alist
86 (let ((case-fold-search t
))
88 (goto-char (point-min))
89 (while (re-search-forward
90 "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t
)
91 (let ((element (org-element-at-point)))
92 (when (eq (org-element-type element
) 'keyword
)
93 (let ((val (org-element-property :value element
)))
94 (if (equal (org-element-property :key element
) "MACRO")
95 ;; Install macro in TEMPLATES.
97 "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val
)
98 (let* ((name (match-string 1 val
))
99 (template (or (match-string 2 val
) ""))
100 (old-cell (assoc name templates
)))
101 (if old-cell
(setcdr old-cell template
)
102 (push (cons name template
) templates
))))
104 (let ((file (expand-file-name
105 (org-unbracket-string "\"" "\"" val
))))
106 (unless (member file files
)
108 (setq default-directory
109 (file-name-directory file
))
111 (insert (org-file-contents file
'noerror
))
113 (funcall collect-macros
(cons file files
)
116 (funcall collect-macros nil nil
)))
118 (defun org-macro-initialize-templates ()
119 "Collect macro templates defined in current buffer.
120 Templates are stored in buffer-local variable
121 `org-macro-templates'. In addition to buffer-defined macros, the
122 function installs the following ones: \"property\",
123 \"time\". and, if the buffer is associated to a file,
124 \"input-file\" and \"modification-time\"."
125 (let* ((templates (org-macro--collect-macros))
128 (let ((old-template (assoc (car cell
) templates
)))
129 (if old-template
(setcdr old-template
(cdr cell
))
130 (push cell templates
))))))
131 ;; Install "property", "time" macros.
132 (mapc update-templates
133 (list (cons "property"
134 "(eval (save-excursion
136 (when (org-string-nw-p l)
138 (let ((org-link-search-must-match-exact-headline t))
139 (org-link-search l nil t))
141 (error \"Macro property failed: cannot find location %s\"
143 (org-entry-get nil \"$1\" 'selective)))")
144 (cons "time" "(eval (format-time-string \"$1\"))")))
145 ;; Install "input-file", "modification-time" macros.
146 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
147 (when (and visited-file
(file-exists-p visited-file
))
148 (mapc update-templates
149 (list (cons "input-file" (file-name-nondirectory visited-file
))
150 (cons "modification-time"
151 (format "(eval (format-time-string \"$1\" (or (and (org-string-nw-p \"$2\") (org-macro--vc-modified-time %s)) '%s)))"
152 (prin1-to-string visited-file
)
154 (nth 5 (file-attributes visited-file
)))))))))
155 ;; Initialize and install "n" macro.
156 (org-macro--counter-initialize)
157 (funcall update-templates
158 (cons "n" "(eval (org-macro--counter-increment \"$1\" \"$2\"))"))
159 (setq org-macro-templates templates
)))
161 (defun org-macro-expand (macro templates
)
162 "Return expanded MACRO, as a string.
163 MACRO is an object, obtained, for example, with
164 `org-element-context'. TEMPLATES is an alist of templates used
165 for expansion. See `org-macro-templates' for a buffer-local
166 default value. Return nil if no template was found."
168 ;; Macro names are case-insensitive.
169 (cdr (assoc-string (org-element-property :key macro
) templates t
))))
171 (let ((value (replace-regexp-in-string
174 (or (nth (1- (string-to-number (substring arg
1)))
175 (org-element-property :args macro
))
176 ;; No argument: remove place-holder.
178 template nil
'literal
)))
179 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
180 (when (string-match "\\`(eval\\>" value
)
181 (setq value
(eval (read value
))))
183 (format "%s" (or value
""))))))
185 (defun org-macro-replace-all (templates &optional finalize keywords
)
186 "Replace all macros in current buffer by their expansion.
188 TEMPLATES is an alist of templates used for expansion. See
189 `org-macro-templates' for a buffer-local default value.
191 If optional arg FINALIZE is non-nil, raise an error if a macro is
192 found in the buffer with no definition in TEMPLATES.
194 Optional argument KEYWORDS, when non-nil is a list of keywords,
195 as strings, where macro expansion is allowed."
197 (goto-char (point-min))
198 (let ((properties-regexp
199 (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords
)))
201 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t
)
202 (let* ((datum (save-match-data (org-element-context)))
203 (type (org-element-type datum
))
206 ((eq type
'macro
) datum
)
207 ;; In parsed keywords and associated node properties,
208 ;; force macro recognition.
209 ((or (and (eq type
'keyword
)
210 (member (org-element-property :key datum
) keywords
))
211 (and (eq type
'node-property
)
212 (string-match-p properties-regexp
213 (org-element-property :key datum
))))
215 (goto-char (match-beginning 0))
216 (org-element-macro-parser))))))
218 (let* ((value (org-macro-expand macro templates
))
219 (begin (org-element-property :begin macro
))
220 (signature (list begin
222 (org-element-property :args macro
))))
223 ;; Avoid circular dependencies by checking if the same
224 ;; macro with the same arguments is expanded at the same
226 (cond ((member signature record
)
227 (error "Circular macro expansion: %s"
228 (org-element-property :key macro
)))
230 (push signature record
)
233 ;; Preserve white spaces after the macro.
234 (progn (goto-char (org-element-property :end macro
))
235 (skip-chars-backward " \t")
237 ;; Leave point before replacement in case of
238 ;; recursive expansions.
239 (save-excursion (insert value
)))
241 (error "Undefined Org macro: %s; aborting"
242 (org-element-property :key macro
)))))))))))
244 (defun org-macro-escape-arguments (&rest args
)
245 "Build macro's arguments string from ARGS.
246 ARGS are strings. Return value is a string with arguments
247 properly escaped and separated with commas. This is the opposite
248 of `org-macro-extract-arguments'."
250 (dolist (arg (reverse args
) (substring s
1))
254 (replace-regexp-in-string
257 (concat (make-string (1+ (* 2 (length (match-string 1 m
)))) ?
\\)
259 ;; If a non-terminal argument ends on backslashes, make
260 ;; sure to also escape them as they will be followed by
262 (concat arg
(and (not (equal s
""))
263 (string-match "\\\\+\\'" arg
)
264 (match-string 0 arg
)))
268 (defun org-macro-extract-arguments (s)
269 "Extract macro arguments from string S.
270 S is a string containing comma separated values properly escaped.
271 Return a list of arguments, as strings. This is the opposite of
272 `org-macro-escape-arguments'."
273 ;; Do not use `org-split-string' since empty strings are
276 (replace-regexp-in-string
279 (let ((len (length (match-string 1 str
))))
280 (concat (make-string (/ len
2) ?
\\)
281 (if (zerop (mod len
2)) "\000" ","))))
286 ;;; Helper functions and variables for internal macros
288 (defun org-macro--vc-modified-time (file)
289 (save-window-excursion
290 (when (vc-backend file
)
291 (let ((buf (get-buffer-create " *org-vc*"))
296 (vc-call print-log file buf nil nil
1)
297 (with-current-buffer buf
300 (goto-char (point-min))
301 (when (re-search-forward "Date:?[ \t]*" nil t
)
302 (let ((time (parse-time-string
304 (point) (line-end-position)))))
305 (when (cl-some #'identity time
)
306 (setq date
(apply #'encode-time time
))))))))
307 (let ((proc (get-buffer-process buf
)))
308 (while (and proc
(accept-process-output proc
.5 nil t
)))))
312 (defvar org-macro--counter-table nil
313 "Hash table containing counter value per name.")
315 (defun org-macro--counter-initialize ()
316 "Initialize `org-macro--counter-table'."
317 (setq org-macro--counter-table
(make-hash-table :test
#'equal
)))
319 (defun org-macro--counter-increment (name &optional reset
)
320 "Increment counter NAME.
321 NAME is a string identifying the counter. If optional argument
322 RESET is a non-empty string, reset the counter instead."
323 (if (org-string-nw-p reset
)
324 (let ((new-value (if (string-match-p "\\`[ \t]*[0-9]+[ \t]*\\'" reset
)
325 (string-to-number reset
)
327 (puthash name new-value org-macro--counter-table
))
328 (let ((value (gethash name org-macro--counter-table
)))
330 (if (null value
) 1 (1+ value
))
331 org-macro--counter-table
))))
335 ;;; org-macro.el ends here