1 ;;; org-macro.el --- Macro Replacement Code for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2013-2018 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-copy
"org-element" (datum))
56 (declare-function org-element-macro-parser
"org-element" ())
57 (declare-function org-element-parse-secondary-string
"org-element" (string restriction
&optional parent
))
58 (declare-function org-element-property
"org-element" (property element
))
59 (declare-function org-element-restriction
"org-element" (element))
60 (declare-function org-element-type
"org-element" (element))
61 (declare-function org-file-contents
"org" (file &optional noerror nocache
))
62 (declare-function org-file-url-p
"org" (file))
63 (declare-function org-in-commented-heading-p
"org" (&optional no-inheritance
))
64 (declare-function org-mode
"org" ())
65 (declare-function org-trim
"org" (s &optional keep-lead
))
66 (declare-function vc-backend
"vc-hooks" (f))
67 (declare-function vc-call
"vc-hooks" (fun file
&rest args
) t
)
68 (declare-function vc-exec-after
"vc-dispatcher" (code))
72 (defvar-local org-macro-templates nil
73 "Alist containing all macro templates in current buffer.
74 Associations are in the shape of (NAME . TEMPLATE) where NAME
75 stands for macro's name and template for its replacement value,
76 both as strings. This is an internal variable. Do not set it
77 directly, use instead:
79 #+MACRO: name template")
83 (defun org-macro--collect-macros ()
84 "Collect macro definitions in current buffer and setup files.
85 Return an alist containing all macro templates found."
86 (letrec ((collect-macros
87 (lambda (files templates
)
88 ;; Return an alist of macro templates. FILES is a list
89 ;; of setup files names read so far, used to avoid
90 ;; circular dependencies. TEMPLATES is the alist
92 (let ((case-fold-search t
))
94 (goto-char (point-min))
95 (while (re-search-forward
96 "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t
)
97 (let ((element (org-element-at-point)))
98 (when (eq (org-element-type element
) 'keyword
)
99 (let ((val (org-element-property :value element
)))
100 (if (equal (org-element-property :key element
) "MACRO")
101 ;; Install macro in TEMPLATES.
103 "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val
)
104 (let* ((name (match-string 1 val
))
105 (template (or (match-string 2 val
) ""))
106 (old-cell (assoc name templates
)))
107 (if old-cell
(setcdr old-cell template
)
108 (push (cons name template
) templates
))))
110 (let* ((uri (org-unbracket-string "\"" "\"" (org-trim val
)))
111 (uri-is-url (org-file-url-p uri
))
114 (expand-file-name uri
))))
115 ;; Avoid circular dependencies.
116 (unless (member uri files
)
119 (setq default-directory
120 (file-name-directory uri
)))
122 (insert (org-file-contents uri
'noerror
))
124 (funcall collect-macros
(cons uri files
)
127 (funcall collect-macros nil nil
)))
129 (defun org-macro-initialize-templates ()
130 "Collect macro templates defined in current buffer.
131 Templates are stored in buffer-local variable
132 `org-macro-templates'. In addition to buffer-defined macros, the
133 function installs the following ones: \"property\",
134 \"time\". and, if the buffer is associated to a file,
135 \"input-file\" and \"modification-time\"."
136 (org-macro--counter-initialize) ;for "n" macro
137 (setq org-macro-templates
139 ;; Install user-defined macros.
140 (org-macro--collect-macros)
141 ;; Install file-specific macros.
142 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
144 (file-exists-p visited-file
)
146 `("input-file" .
,(file-name-nondirectory visited-file
))
147 `("modification-time" .
149 \(format-time-string $1
150 (or (and (org-string-nw-p $2)
151 (org-macro--vc-modified-time %s))
153 (prin1-to-string visited-file
)
155 (nth 5 (file-attributes visited-file
))))))))
156 ;; Install built-in macros.
158 '("n" .
"(eval (org-macro--counter-increment $1 $2))")
159 `("author" .
,(org-macro--find-keyword-value "AUTHOR"))
160 `("email" .
,(org-macro--find-keyword-value "EMAIL"))
161 '("keyword" .
"(eval (org-macro--find-keyword-value $1))")
163 '("time" .
"(eval (format-time-string $1))")
164 `("title" .
,(org-macro--find-keyword-value "TITLE"))
165 '("property" .
"(eval
168 (when (org-string-nw-p l)
170 (let ((org-link-search-must-match-exact-headline t))
171 (org-link-search l nil t))
173 (error \"Macro property failed: cannot find location %s\" l)))))
174 (org-entry-get nil $1 'selective)))")
176 ,(let* ((value (org-macro--find-keyword-value "DATE"))
177 (date (org-element-parse-secondary-string
178 value
(org-element-restriction 'keyword
))))
179 (if (and (consp date
)
181 (eq 'timestamp
(org-element-type (car date
))))
182 (format "(eval (if (org-string-nw-p $1) %s %S))"
183 (format "(org-timestamp-format '%S $1)"
184 (org-element-copy (car date
)))
188 (defun org-macro-expand (macro templates
)
189 "Return expanded MACRO, as a string.
190 MACRO is an object, obtained, for example, with
191 `org-element-context'. TEMPLATES is an alist of templates used
192 for expansion. See `org-macro-templates' for a buffer-local
193 default value. Return nil if no template was found."
195 ;; Macro names are case-insensitive.
196 (cdr (assoc-string (org-element-property :key macro
) templates t
))))
198 (let* ((eval?
(string-match-p "\\`(eval\\>" template
))
200 (replace-regexp-in-string
203 (let ((arg (or (nth (1- (string-to-number (substring m
1)))
204 (org-element-property :args macro
))
205 ;; No argument: remove place-holder.
207 ;; `eval' implies arguments are strings.
208 (if eval?
(format "%S" arg
) arg
)))
209 template nil
'literal
)))
211 (setq value
(eval (condition-case nil
(read value
)
213 ;; Force return value to be a string.
214 (format "%s" (or value
""))))))
216 (defun org-macro-replace-all (templates &optional keywords
)
217 "Replace all macros in current buffer by their expansion.
219 TEMPLATES is an alist of templates used for expansion. See
220 `org-macro-templates' for a buffer-local default value.
222 Optional argument KEYWORDS, when non-nil is a list of keywords,
223 as strings, where macro expansion is allowed.
225 Return an error if a macro in the buffer cannot be associated to
226 a definition in TEMPLATES."
227 (org-with-wide-buffer
228 (goto-char (point-min))
229 (let ((properties-regexp (format "\\`EXPORT_%s\\+?\\'"
230 (regexp-opt keywords
)))
232 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t
)
233 (unless (save-match-data (org-in-commented-heading-p))
234 (let* ((datum (save-match-data (org-element-context)))
235 (type (org-element-type datum
))
238 ((eq type
'macro
) datum
)
239 ;; In parsed keywords and associated node
240 ;; properties, force macro recognition.
241 ((or (and (eq type
'keyword
)
242 (member (org-element-property :key datum
) keywords
))
243 (and (eq type
'node-property
)
244 (string-match-p properties-regexp
245 (org-element-property :key datum
))))
247 (goto-char (match-beginning 0))
248 (org-element-macro-parser))))))
250 (let* ((value (org-macro-expand macro templates
))
251 (begin (org-element-property :begin macro
))
252 (signature (list begin
254 (org-element-property :args macro
))))
255 ;; Avoid circular dependencies by checking if the same
256 ;; macro with the same arguments is expanded at the
257 ;; same position twice.
258 (cond ((member signature record
)
259 (error "Circular macro expansion: %s"
260 (org-element-property :key macro
)))
262 (push signature record
)
265 ;; Preserve white spaces after the macro.
266 (progn (goto-char (org-element-property :end macro
))
267 (skip-chars-backward " \t")
269 ;; Leave point before replacement in case of
270 ;; recursive expansions.
271 (save-excursion (insert value
)))
273 (error "Undefined Org macro: %s; aborting"
274 (org-element-property :key macro
))))))))))))
276 (defun org-macro-escape-arguments (&rest args
)
277 "Build macro's arguments string from ARGS.
278 ARGS are strings. Return value is a string with arguments
279 properly escaped and separated with commas. This is the opposite
280 of `org-macro-extract-arguments'."
282 (dolist (arg (reverse args
) (substring s
1))
286 (replace-regexp-in-string
289 (concat (make-string (1+ (* 2 (length (match-string 1 m
)))) ?
\\)
291 ;; If a non-terminal argument ends on backslashes, make
292 ;; sure to also escape them as they will be followed by
294 (concat arg
(and (not (equal s
""))
295 (string-match "\\\\+\\'" arg
)
296 (match-string 0 arg
)))
300 (defun org-macro-extract-arguments (s)
301 "Extract macro arguments from string S.
302 S is a string containing comma separated values properly escaped.
303 Return a list of arguments, as strings. This is the opposite of
304 `org-macro-escape-arguments'."
305 ;; Do not use `org-split-string' since empty strings are
308 (replace-regexp-in-string
311 (let ((len (length (match-string 1 str
))))
312 (concat (make-string (/ len
2) ?
\\)
313 (if (zerop (mod len
2)) "\000" ","))))
318 ;;; Helper functions and variables for internal macros
320 (defun org-macro--find-keyword-value (name)
321 "Find value for keyword NAME in current buffer.
322 KEYWORD is a string. Return value associated to the keywords
323 named after NAME, as a string, or nil."
325 (let ((regexp (format "^[ \t]*#\\+%s:" (regexp-quote name
)))
328 (while (re-search-forward regexp nil t
)
329 (let ((element (org-element-at-point)))
330 (when (eq 'keyword
(org-element-type element
))
331 (setq result
(concat result
333 (org-element-property :value element
))))))
334 (and result
(org-trim result
)))))
336 (defun org-macro--vc-modified-time (file)
337 (save-window-excursion
338 (when (vc-backend file
)
339 (let ((buf (get-buffer-create " *org-vc*"))
344 (vc-call print-log file buf nil nil
1)
345 (with-current-buffer buf
348 (goto-char (point-min))
349 (when (re-search-forward "Date:?[ \t]*" nil t
)
350 (let ((time (parse-time-string
352 (point) (line-end-position)))))
353 (when (cl-some #'identity time
)
354 (setq date
(apply #'encode-time time
))))))))
355 (let ((proc (get-buffer-process buf
)))
356 (while (and proc
(accept-process-output proc
.5 nil t
)))))
360 (defvar org-macro--counter-table nil
361 "Hash table containing counter value per name.")
363 (defun org-macro--counter-initialize ()
364 "Initialize `org-macro--counter-table'."
365 (setq org-macro--counter-table
(make-hash-table :test
#'equal
)))
367 (defun org-macro--counter-increment (name &optional action
)
368 "Increment counter NAME.
369 NAME is a string identifying the counter.
371 When non-nil, optional argument ACTION is a string.
373 If the string is \"-\", keep the NAME counter at its current
374 value, i.e. do not increment.
376 If the string represents an integer, set the counter to this number.
378 Any other non-empty string resets the counter to 1."
379 (let ((name-trimmed (org-trim name
))
380 (action-trimmed (when (org-string-nw-p action
)
382 (puthash name-trimmed
383 (cond ((not (org-string-nw-p action-trimmed
))
384 (1+ (gethash name-trimmed org-macro--counter-table
0)))
385 ((string= "-" action-trimmed
)
386 (gethash name-trimmed org-macro--counter-table
1))
387 ((string-match-p "\\`[0-9]+\\'" action-trimmed
)
388 (string-to-number action-trimmed
))
390 org-macro--counter-table
)))
394 ;;; org-macro.el ends here