org-element: Elements can accept multiple secondary strings
[org-mode.git] / lisp / org-macro.el
blobe5fa1fc464e3d62cfb4c824c42a5e988c9593f3c
1 ;;; org-macro.el --- Macro Replacement Code for Org Mode
3 ;; Copyright (C) 2013-2015 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/>.
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)}}}, {{{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.
45 ;;; Code:
46 (require 'org-macs)
48 (declare-function org-element-at-point "org-element" ())
49 (declare-function org-element-context "org-element" (&optional element))
50 (declare-function org-element-property "org-element" (property element))
51 (declare-function org-element-type "org-element" (element))
52 (declare-function org-remove-double-quotes "org" (s))
53 (declare-function org-mode "org" ())
54 (declare-function org-file-contents "org" (file &optional noerror))
55 (declare-function org-with-wide-buffer "org-macs" (&rest body))
57 ;;; Variables
59 (defvar org-macro-templates nil
60 "Alist containing all macro templates in current buffer.
61 Associations are in the shape of (NAME . TEMPLATE) where NAME
62 stands for macro's name and template for its replacement value,
63 both as strings. This is an internal variable. Do not set it
64 directly, use instead:
66 #+MACRO: name template")
67 (make-variable-buffer-local 'org-macro-templates)
70 ;;; Functions
72 (defun org-macro--collect-macros ()
73 "Collect macro definitions in current buffer and setup files.
74 Return an alist containing all macro templates found."
75 (let* (collect-macros ; For byte-compiler.
76 (collect-macros
77 (lambda (files templates)
78 ;; Return an alist of macro templates. FILES is a list of
79 ;; setup files names read so far, used to avoid circular
80 ;; dependencies. TEMPLATES is the alist collected so far.
81 (let ((case-fold-search t))
82 (org-with-wide-buffer
83 (goto-char (point-min))
84 (while (re-search-forward
85 "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t)
86 (let ((element (org-element-at-point)))
87 (when (eq (org-element-type element) 'keyword)
88 (let ((val (org-element-property :value element)))
89 (if (equal (org-element-property :key element) "MACRO")
90 ;; Install macro in TEMPLATES.
91 (when (string-match
92 "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val)
93 (let* ((name (match-string 1 val))
94 (template (or (match-string 2 val) ""))
95 (old-cell (assoc name templates)))
96 (if old-cell (setcdr old-cell template)
97 (push (cons name template) templates))))
98 ;; Enter setup file.
99 (let ((file (expand-file-name
100 (org-remove-double-quotes val))))
101 (unless (member file files)
102 (with-temp-buffer
103 (org-mode)
104 (insert (org-file-contents file 'noerror))
105 (setq templates
106 (funcall collect-macros (cons file files)
107 templates)))))))))))
108 templates))))
109 (funcall collect-macros nil nil)))
111 (defun org-macro-initialize-templates ()
112 "Collect macro templates defined in current buffer.
113 Templates are stored in buffer-local variable
114 `org-macro-templates'. In addition to buffer-defined macros, the
115 function installs the following ones: \"property\",
116 \"time\". and, if the buffer is associated to a file,
117 \"input-file\" and \"modification-time\"."
118 (let* ((templates (org-macro--collect-macros))
119 (update-templates
120 (lambda (cell)
121 (let ((old-template (assoc (car cell) templates)))
122 (if old-template (setcdr old-template (cdr cell))
123 (push cell templates))))))
124 ;; Install hard-coded macros.
125 (mapc (lambda (cell) (funcall update-templates cell))
126 (list (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
127 (cons "time" "(eval (format-time-string \"$1\"))")))
128 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
129 (when (and visited-file (file-exists-p visited-file))
130 (mapc (lambda (cell) (funcall update-templates cell))
131 (list (cons "input-file" (file-name-nondirectory visited-file))
132 (cons "modification-time"
133 (format "(eval (format-time-string \"$1\" '%s))"
134 (prin1-to-string
135 (nth 5 (file-attributes visited-file)))))))))
136 (setq org-macro-templates templates)))
138 (defun org-macro-expand (macro templates)
139 "Return expanded MACRO, as a string.
140 MACRO is an object, obtained, for example, with
141 `org-element-context'. TEMPLATES is an alist of templates used
142 for expansion. See `org-macro-templates' for a buffer-local
143 default value. Return nil if no template was found."
144 (let ((template
145 ;; Macro names are case-insensitive.
146 (cdr (assoc-string (org-element-property :key macro) templates t))))
147 (when template
148 (let ((value (replace-regexp-in-string
149 "\\$[0-9]+"
150 (lambda (arg)
151 (or (nth (1- (string-to-number (substring arg 1)))
152 (org-element-property :args macro))
153 ;; No argument: remove place-holder.
154 ""))
155 template nil 'literal)))
156 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
157 (when (string-match "\\`(eval\\>" value)
158 (setq value (eval (read value))))
159 ;; Return string.
160 (format "%s" (or value ""))))))
162 (defun org-macro-replace-all (templates &optional finalize)
163 "Replace all macros in current buffer by their expansion.
165 TEMPLATES is an alist of templates used for expansion. See
166 `org-macro-templates' for a buffer-local default value.
168 If optional arg FINALIZE is non-nil, raise an error if a macro is
169 found in the buffer with no definition in TEMPLATES."
170 (save-excursion
171 (goto-char (point-min))
172 (let (record)
173 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
174 (let ((object (org-element-context)))
175 (when (eq (org-element-type object) 'macro)
176 (let* ((value (org-macro-expand object templates))
177 (begin (org-element-property :begin object))
178 (signature (list begin
179 object
180 (org-element-property :args object))))
181 ;; Avoid circular dependencies by checking if the same
182 ;; macro with the same arguments is expanded at the same
183 ;; position twice.
184 (if (member signature record)
185 (error "Circular macro expansion: %s"
186 (org-element-property :key object))
187 (cond (value
188 (push signature record)
189 (delete-region
190 begin
191 ;; Preserve white spaces after the macro.
192 (progn (goto-char (org-element-property :end object))
193 (skip-chars-backward " \t")
194 (point)))
195 ;; Leave point before replacement in case of recursive
196 ;; expansions.
197 (save-excursion (insert value)))
198 (finalize
199 (error "Undefined Org macro: %s; aborting"
200 (org-element-property :key object))))))))))))
202 (defun org-macro-escape-arguments (&rest args)
203 "Build macro's arguments string from ARGS.
204 ARGS are strings. Return value is a string with arguments
205 properly escaped and separated with commas. This is the opposite
206 of `org-macro-extract-arguments'."
207 (let ((s ""))
208 (dolist (arg (reverse args) (substring s 1))
209 (setq s
210 (concat
212 (replace-regexp-in-string
213 "\\(\\\\*\\),"
214 (lambda (m)
215 (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
216 ","))
217 ;; If a non-terminal argument ends on backslashes, make
218 ;; sure to also escape them as they will be followed by
219 ;; a comma.
220 (concat arg (and (not (equal s ""))
221 (string-match "\\\\+\\'" arg)
222 (match-string 0 arg)))
223 nil t)
224 s)))))
226 (defun org-macro-extract-arguments (s)
227 "Extract macro arguments from string S.
228 S is a string containing comma separated values properly escaped.
229 Return a list of arguments, as strings. This is the opposite of
230 `org-macro-escape-arguments'."
231 ;; Do not use `org-split-string' since empty strings are
232 ;; meaningful here.
233 (split-string
234 (replace-regexp-in-string
235 "\\(\\\\*\\),"
236 (lambda (str)
237 (let ((len (length (match-string 1 str))))
238 (concat (make-string (/ len 2) ?\\)
239 (if (zerop (mod len 2)) "\000" ","))))
240 s nil t)
241 "\000"))
244 (provide 'org-macro)
245 ;;; org-macro.el ends here