org-tempo: Enable Tempo in all Org buffers after load
[org-mode.git] / lisp / org-macro.el
blob6c4fc5b0a012814c34228c8e2ab43555ad1756ab
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/>.
23 ;;; Commentary:
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)}}},
41 ;; {{{input-file}}},
42 ;; {{{modification-time(format-string)}}},
43 ;; {{{n(counter,action}}}.
45 ;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}},
46 ;; {{{email}}} and {{{title}}} macros.
48 ;;; Code:
49 (require 'cl-lib)
50 (require 'org-macs)
51 (require 'org-compat)
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))
70 ;;; Variables
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")
81 ;;; Functions
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
91 ;; collected so far.
92 (let ((case-fold-search t))
93 (org-with-wide-buffer
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.
102 (when (string-match
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))))
109 ;; Enter setup file.
110 (let* ((uri (org-unbracket-string "\"" "\"" (org-trim val)))
111 (uri-is-url (org-file-url-p uri))
112 (uri (if uri-is-url
114 (expand-file-name uri))))
115 ;; Avoid circular dependencies.
116 (unless (member uri files)
117 (with-temp-buffer
118 (unless uri-is-url
119 (setq default-directory
120 (file-name-directory uri)))
121 (org-mode)
122 (insert (org-file-contents uri 'noerror))
123 (setq templates
124 (funcall collect-macros (cons uri files)
125 templates)))))))))))
126 templates))))
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 (let* ((templates (org-macro--collect-macros))
137 (update-templates
138 (lambda (cell)
139 (let ((old-template (assoc (car cell) templates)))
140 (if old-template (setcdr old-template (cdr cell))
141 (push cell templates))))))
142 ;; Install "author, "date, "email", "keyword", "title" and
143 ;; "results" macros.
144 (mapc update-templates
145 (list
146 (cons "author" (org-macro--find-keyword-value "AUTHOR"))
147 (cons "date"
148 (let* ((value (org-macro--find-keyword-value "DATE"))
149 (date (org-element-parse-secondary-string
150 value (org-element-restriction 'keyword))))
151 (if (and (consp date)
152 (not (cdr date))
153 (eq (org-element-type (car date)) 'timestamp))
154 (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
155 (format "(org-timestamp-format '%S \"$1\")"
156 (org-element-copy (car date)))
157 value)
158 value)))
159 (cons "email" (org-macro--find-keyword-value "EMAIL"))
160 (cons "keyword" "(eval (org-macro--find-keyword-value \"$1\"))")
161 (cons "results" "$1")
162 (cons "title" (org-macro--find-keyword-value "TITLE"))))
163 ;; Install "property", "time" macros.
164 (mapc update-templates
165 (list (cons "property"
166 "(eval (save-excursion
167 (let ((l \"$2\"))
168 (when (org-string-nw-p l)
169 (condition-case _
170 (let ((org-link-search-must-match-exact-headline t))
171 (org-link-search l nil t))
172 (error
173 (error \"Macro property failed: cannot find location %s\"
174 l)))))
175 (org-entry-get nil \"$1\" 'selective)))")
176 (cons "time" "(eval (format-time-string \"$1\"))")))
177 ;; Install "input-file", "modification-time" macros.
178 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
179 (when (and visited-file (file-exists-p visited-file))
180 (mapc update-templates
181 (list (cons "input-file" (file-name-nondirectory visited-file))
182 (cons "modification-time"
183 (format "(eval
184 \(format-time-string \"$1\"
185 (or (and (org-string-nw-p \"$2\")
186 (org-macro--vc-modified-time %s))
187 '%s)))"
188 (prin1-to-string visited-file)
189 (prin1-to-string
190 (nth 5 (file-attributes visited-file)))))))))
191 ;; Initialize and install "n" macro.
192 (org-macro--counter-initialize)
193 (funcall update-templates
194 (cons "n" "(eval (org-macro--counter-increment \"$1\" \"$2\"))"))
195 (setq org-macro-templates templates)))
197 (defun org-macro-expand (macro templates)
198 "Return expanded MACRO, as a string.
199 MACRO is an object, obtained, for example, with
200 `org-element-context'. TEMPLATES is an alist of templates used
201 for expansion. See `org-macro-templates' for a buffer-local
202 default value. Return nil if no template was found."
203 (let ((template
204 ;; Macro names are case-insensitive.
205 (cdr (assoc-string (org-element-property :key macro) templates t))))
206 (when template
207 (let ((value (replace-regexp-in-string
208 "\\$[0-9]+"
209 (lambda (arg)
210 (or (nth (1- (string-to-number (substring arg 1)))
211 (org-element-property :args macro))
212 ;; No argument: remove place-holder.
213 ""))
214 template nil 'literal)))
215 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
216 (when (string-match "\\`(eval\\>" value)
217 (setq value (eval (read value))))
218 ;; Return string.
219 (format "%s" (or value ""))))))
221 (defun org-macro-replace-all (templates &optional keywords)
222 "Replace all macros in current buffer by their expansion.
224 TEMPLATES is an alist of templates used for expansion. See
225 `org-macro-templates' for a buffer-local default value.
227 Optional argument KEYWORDS, when non-nil is a list of keywords,
228 as strings, where macro expansion is allowed.
230 Return an error if a macro in the buffer cannot be associated to
231 a definition in TEMPLATES."
232 (org-with-wide-buffer
233 (goto-char (point-min))
234 (let ((properties-regexp (format "\\`EXPORT_%s\\+?\\'"
235 (regexp-opt keywords)))
236 record)
237 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
238 (unless (save-match-data (org-in-commented-heading-p))
239 (let* ((datum (save-match-data (org-element-context)))
240 (type (org-element-type datum))
241 (macro
242 (cond
243 ((eq type 'macro) datum)
244 ;; In parsed keywords and associated node
245 ;; properties, force macro recognition.
246 ((or (and (eq type 'keyword)
247 (member (org-element-property :key datum) keywords))
248 (and (eq type 'node-property)
249 (string-match-p properties-regexp
250 (org-element-property :key datum))))
251 (save-excursion
252 (goto-char (match-beginning 0))
253 (org-element-macro-parser))))))
254 (when macro
255 (let* ((value (org-macro-expand macro templates))
256 (begin (org-element-property :begin macro))
257 (signature (list begin
258 macro
259 (org-element-property :args macro))))
260 ;; Avoid circular dependencies by checking if the same
261 ;; macro with the same arguments is expanded at the
262 ;; same position twice.
263 (cond ((member signature record)
264 (error "Circular macro expansion: %s"
265 (org-element-property :key macro)))
266 (value
267 (push signature record)
268 (delete-region
269 begin
270 ;; Preserve white spaces after the macro.
271 (progn (goto-char (org-element-property :end macro))
272 (skip-chars-backward " \t")
273 (point)))
274 ;; Leave point before replacement in case of
275 ;; recursive expansions.
276 (save-excursion (insert value)))
278 (error "Undefined Org macro: %s; aborting"
279 (org-element-property :key macro))))))))))))
281 (defun org-macro-escape-arguments (&rest args)
282 "Build macro's arguments string from ARGS.
283 ARGS are strings. Return value is a string with arguments
284 properly escaped and separated with commas. This is the opposite
285 of `org-macro-extract-arguments'."
286 (let ((s ""))
287 (dolist (arg (reverse args) (substring s 1))
288 (setq s
289 (concat
291 (replace-regexp-in-string
292 "\\(\\\\*\\),"
293 (lambda (m)
294 (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
295 ","))
296 ;; If a non-terminal argument ends on backslashes, make
297 ;; sure to also escape them as they will be followed by
298 ;; a comma.
299 (concat arg (and (not (equal s ""))
300 (string-match "\\\\+\\'" arg)
301 (match-string 0 arg)))
302 nil t)
303 s)))))
305 (defun org-macro-extract-arguments (s)
306 "Extract macro arguments from string S.
307 S is a string containing comma separated values properly escaped.
308 Return a list of arguments, as strings. This is the opposite of
309 `org-macro-escape-arguments'."
310 ;; Do not use `org-split-string' since empty strings are
311 ;; meaningful here.
312 (split-string
313 (replace-regexp-in-string
314 "\\(\\\\*\\),"
315 (lambda (str)
316 (let ((len (length (match-string 1 str))))
317 (concat (make-string (/ len 2) ?\\)
318 (if (zerop (mod len 2)) "\000" ","))))
319 s nil t)
320 "\000"))
323 ;;; Helper functions and variables for internal macros
325 (defun org-macro--find-keyword-value (name)
326 "Find value for keyword NAME in current buffer.
327 KEYWORD is a string. Return value associated to the keywords
328 named after NAME, as a string, or nil."
329 (org-with-point-at 1
330 (let ((regexp (format "^[ \t]*#\\+%s:" (regexp-quote name)))
331 (case-fold-search t)
332 (result nil))
333 (while (re-search-forward regexp nil t)
334 (let ((element (org-element-at-point)))
335 (when (eq 'keyword (org-element-type element))
336 (setq result (concat result
338 (org-element-property :value element))))))
339 (and result (org-trim result)))))
341 (defun org-macro--vc-modified-time (file)
342 (save-window-excursion
343 (when (vc-backend file)
344 (let ((buf (get-buffer-create " *org-vc*"))
345 (case-fold-search t)
346 date)
347 (unwind-protect
348 (progn
349 (vc-call print-log file buf nil nil 1)
350 (with-current-buffer buf
351 (vc-exec-after
352 (lambda ()
353 (goto-char (point-min))
354 (when (re-search-forward "Date:?[ \t]*" nil t)
355 (let ((time (parse-time-string
356 (buffer-substring
357 (point) (line-end-position)))))
358 (when (cl-some #'identity time)
359 (setq date (apply #'encode-time time))))))))
360 (let ((proc (get-buffer-process buf)))
361 (while (and proc (accept-process-output proc .5 nil t)))))
362 (kill-buffer buf))
363 date))))
365 (defvar org-macro--counter-table nil
366 "Hash table containing counter value per name.")
368 (defun org-macro--counter-initialize ()
369 "Initialize `org-macro--counter-table'."
370 (setq org-macro--counter-table (make-hash-table :test #'equal)))
372 (defun org-macro--counter-increment (name &optional action)
373 "Increment counter NAME.
374 NAME is a string identifying the counter.
376 When non-nil, optional argument ACTION is a string.
378 If the string is \"-\", keep the NAME counter at its current
379 value, i.e. do not increment.
381 If the string represents an integer, set the counter to this number.
383 Any other non-empty string resets the counter to 1."
384 (let ((name-trimmed (org-trim name))
385 (action-trimmed (when (org-string-nw-p action)
386 (org-trim action))))
387 (puthash name-trimmed
388 (cond ((not (org-string-nw-p action-trimmed))
389 (1+ (gethash name-trimmed org-macro--counter-table 0)))
390 ((string= "-" action-trimmed)
391 (gethash name-trimmed org-macro--counter-table 1))
392 ((string-match-p "\\`[0-9]+\\'" action-trimmed)
393 (string-to-number action-trimmed))
394 (t 1))
395 org-macro--counter-table)))
398 (provide 'org-macro)
399 ;;; org-macro.el ends here