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)}}}, {{{property(node-property)}}},
40 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
42 ;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}},
43 ;; {{{email}}} and {{{title}}} macros.
50 (declare-function org-element-at-point
"org-element" ())
51 (declare-function org-element-context
"org-element" (&optional element
))
52 (declare-function org-element-macro-parser
"org-element" ())
53 (declare-function org-element-property
"org-element" (property element
))
54 (declare-function org-element-type
"org-element" (element))
55 (declare-function org-file-contents
"org" (file &optional noerror
))
56 (declare-function org-in-commented-heading-p
"org" (&optional no-inheritance
))
57 (declare-function org-mode
"org" ())
58 (declare-function vc-backend
"vc-hooks" (f))
59 (declare-function vc-call
"vc-hooks" (fun file
&rest args
) t
)
60 (declare-function vc-exec-after
"vc-dispatcher" (code))
64 (defvar-local org-macro-templates nil
65 "Alist containing all macro templates in current buffer.
66 Associations are in the shape of (NAME . TEMPLATE) where NAME
67 stands for macro's name and template for its replacement value,
68 both as strings. This is an internal variable. Do not set it
69 directly, use instead:
71 #+MACRO: name template")
75 (defun org-macro--collect-macros ()
76 "Collect macro definitions in current buffer and setup files.
77 Return an alist containing all macro templates found."
78 (letrec ((collect-macros
79 (lambda (files templates
)
80 ;; Return an alist of macro templates. FILES is a list
81 ;; of setup files names read so far, used to avoid
82 ;; circular dependencies. TEMPLATES is the alist
84 (let ((case-fold-search t
))
86 (goto-char (point-min))
87 (while (re-search-forward
88 "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t
)
89 (let ((element (org-element-at-point)))
90 (when (eq (org-element-type element
) 'keyword
)
91 (let ((val (org-element-property :value element
)))
92 (if (equal (org-element-property :key element
) "MACRO")
93 ;; Install macro in TEMPLATES.
95 "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val
)
96 (let* ((name (match-string 1 val
))
97 (template (or (match-string 2 val
) ""))
98 (old-cell (assoc name templates
)))
99 (if old-cell
(setcdr old-cell template
)
100 (push (cons name template
) templates
))))
102 (let ((file (expand-file-name
103 (org-unbracket-string "\"" "\"" val
))))
104 (unless (member file files
)
106 (setq default-directory
107 (file-name-directory file
))
109 (insert (org-file-contents file
'noerror
))
111 (funcall collect-macros
(cons file files
)
114 (funcall collect-macros nil nil
)))
116 (defun org-macro-initialize-templates ()
117 "Collect macro templates defined in current buffer.
118 Templates are stored in buffer-local variable
119 `org-macro-templates'. In addition to buffer-defined macros, the
120 function installs the following ones: \"property\",
121 \"time\". and, if the buffer is associated to a file,
122 \"input-file\" and \"modification-time\"."
123 (let* ((templates (org-macro--collect-macros))
126 (let ((old-template (assoc (car cell
) templates
)))
127 (if old-template
(setcdr old-template
(cdr cell
))
128 (push cell templates
))))))
129 ;; Install hard-coded macros.
130 (mapc update-templates
131 (list (cons "property"
132 "(eval (save-excursion
134 (when (org-string-nw-p l)
136 (let ((org-link-search-must-match-exact-headline t))
137 (org-link-search l nil t))
139 (error \"Macro property failed: cannot find location %s\"
141 (org-entry-get nil \"$1\" 'selective)))")
142 (cons "time" "(eval (format-time-string \"$1\"))")))
143 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
144 (when (and visited-file
(file-exists-p visited-file
))
145 (mapc update-templates
146 (list (cons "input-file" (file-name-nondirectory visited-file
))
147 (cons "modification-time"
148 (format "(eval (format-time-string \"$1\" (or (and (org-string-nw-p \"$2\") (org-macro--vc-modified-time %s)) '%s)))"
149 (prin1-to-string visited-file
)
151 (nth 5 (file-attributes visited-file
)))))))))
152 (setq org-macro-templates templates
)))
154 (defun org-macro-expand (macro templates
)
155 "Return expanded MACRO, as a string.
156 MACRO is an object, obtained, for example, with
157 `org-element-context'. TEMPLATES is an alist of templates used
158 for expansion. See `org-macro-templates' for a buffer-local
159 default value. Return nil if no template was found."
161 ;; Macro names are case-insensitive.
162 (cdr (assoc-string (org-element-property :key macro
) templates t
))))
164 (let ((value (replace-regexp-in-string
167 (or (nth (1- (string-to-number (substring arg
1)))
168 (org-element-property :args macro
))
169 ;; No argument: remove place-holder.
171 template nil
'literal
)))
172 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
173 (when (string-match "\\`(eval\\>" value
)
174 (setq value
(eval (read value
))))
176 (format "%s" (or value
""))))))
178 (defun org-macro-replace-all (templates &optional finalize keywords
)
179 "Replace all macros in current buffer by their expansion.
181 TEMPLATES is an alist of templates used for expansion. See
182 `org-macro-templates' for a buffer-local default value.
184 If optional arg FINALIZE is non-nil, raise an error if a macro is
185 found in the buffer with no definition in TEMPLATES.
187 Optional argument KEYWORDS, when non-nil is a list of keywords,
188 as strings, where macro expansion is allowed."
190 (goto-char (point-min))
191 (let ((properties-regexp
192 (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords
)))
194 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t
)
195 (unless (save-match-data (org-in-commented-heading-p))
196 (let* ((datum (save-match-data (org-element-context)))
197 (type (org-element-type datum
))
200 ((eq type
'macro
) datum
)
201 ;; In parsed keywords and associated node
202 ;; properties, force macro recognition.
203 ((or (and (eq type
'keyword
)
204 (member (org-element-property :key datum
)
206 (and (eq type
'node-property
)
207 (string-match-p properties-regexp
208 (org-element-property :key
211 (goto-char (match-beginning 0))
212 (org-element-macro-parser))))))
214 (let* ((value (org-macro-expand macro templates
))
215 (begin (org-element-property :begin macro
))
216 (signature (list begin
218 (org-element-property :args macro
))))
219 ;; Avoid circular dependencies by checking if the same
220 ;; macro with the same arguments is expanded at the
221 ;; same position twice.
222 (cond ((member signature record
)
223 (error "Circular macro expansion: %s"
224 (org-element-property :key macro
)))
226 (push signature record
)
229 ;; Preserve white spaces after the macro.
230 (progn (goto-char (org-element-property :end macro
))
231 (skip-chars-backward " \t")
233 ;; Leave point before replacement in case of
234 ;; recursive expansions.
235 (save-excursion (insert value
)))
237 (error "Undefined Org macro: %s; aborting"
238 (org-element-property :key macro
))))))))))))
240 (defun org-macro-escape-arguments (&rest args
)
241 "Build macro's arguments string from ARGS.
242 ARGS are strings. Return value is a string with arguments
243 properly escaped and separated with commas. This is the opposite
244 of `org-macro-extract-arguments'."
246 (dolist (arg (reverse args
) (substring s
1))
250 (replace-regexp-in-string
253 (concat (make-string (1+ (* 2 (length (match-string 1 m
)))) ?
\\)
255 ;; If a non-terminal argument ends on backslashes, make
256 ;; sure to also escape them as they will be followed by
258 (concat arg
(and (not (equal s
""))
259 (string-match "\\\\+\\'" arg
)
260 (match-string 0 arg
)))
264 (defun org-macro-extract-arguments (s)
265 "Extract macro arguments from string S.
266 S is a string containing comma separated values properly escaped.
267 Return a list of arguments, as strings. This is the opposite of
268 `org-macro-escape-arguments'."
269 ;; Do not use `org-split-string' since empty strings are
272 (replace-regexp-in-string
275 (let ((len (length (match-string 1 str
))))
276 (concat (make-string (/ len
2) ?
\\)
277 (if (zerop (mod len
2)) "\000" ","))))
281 (defun org-macro--vc-modified-time (file)
282 (save-window-excursion
283 (when (vc-backend file
)
284 (let ((buf (get-buffer-create " *org-vc*"))
289 (vc-call print-log file buf nil nil
1)
290 (with-current-buffer buf
293 (goto-char (point-min))
294 (when (re-search-forward "Date:?[ \t]*" nil t
)
295 (let ((time (parse-time-string
297 (point) (line-end-position)))))
298 (when (cl-some #'identity time
)
299 (setq date
(apply #'encode-time time
))))))))
300 (let ((proc (get-buffer-process buf
)))
301 (while (and proc
(accept-process-output proc
.5 nil t
)))))
307 ;;; org-macro.el ends here