Fix Rmail editing with reapplying encoding to message body
[emacs.git] / lisp / org / org-macro.el
blob3b8f8140c9c83d0e5e2ad87981f425733c459ad3
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/>.
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 'cl-lib)
47 (require 'org-macs)
48 (require 'org-compat)
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))
62 ;;; Variables
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")
73 ;;; Functions
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
83 ;; collected so far.
84 (let ((case-fold-search t))
85 (org-with-wide-buffer
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.
94 (when (string-match
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))))
101 ;; Enter setup file.
102 (let ((file (expand-file-name
103 (org-unbracket-string "\"" "\"" val))))
104 (unless (member file files)
105 (with-temp-buffer
106 (setq default-directory
107 (file-name-directory file))
108 (org-mode)
109 (insert (org-file-contents file 'noerror))
110 (setq templates
111 (funcall collect-macros (cons file files)
112 templates)))))))))))
113 templates))))
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))
124 (update-templates
125 (lambda (cell)
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
133 (let ((l \"$2\"))
134 (when (org-string-nw-p l)
135 (condition-case _
136 (let ((org-link-search-must-match-exact-headline t))
137 (org-link-search l nil t))
138 (error
139 (error \"Macro property failed: cannot find location %s\"
140 l)))))
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)
150 (prin1-to-string
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."
160 (let ((template
161 ;; Macro names are case-insensitive.
162 (cdr (assoc-string (org-element-property :key macro) templates t))))
163 (when template
164 (let ((value (replace-regexp-in-string
165 "\\$[0-9]+"
166 (lambda (arg)
167 (or (nth (1- (string-to-number (substring arg 1)))
168 (org-element-property :args macro))
169 ;; No argument: remove place-holder.
170 ""))
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))))
175 ;; Return string.
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."
189 (org-with-wide-buffer
190 (goto-char (point-min))
191 (let ((properties-regexp (format "\\`EXPORT_%s\\+?\\'"
192 (regexp-opt keywords)))
193 record)
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))
198 (macro
199 (cond
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) keywords))
205 (and (eq type 'node-property)
206 (string-match-p properties-regexp
207 (org-element-property :key datum))))
208 (save-excursion
209 (goto-char (match-beginning 0))
210 (org-element-macro-parser))))))
211 (when macro
212 (let* ((value (org-macro-expand macro templates))
213 (begin (org-element-property :begin macro))
214 (signature (list begin
215 macro
216 (org-element-property :args macro))))
217 ;; Avoid circular dependencies by checking if the same
218 ;; macro with the same arguments is expanded at the
219 ;; same position twice.
220 (cond ((member signature record)
221 (error "Circular macro expansion: %s"
222 (org-element-property :key macro)))
223 (value
224 (push signature record)
225 (delete-region
226 begin
227 ;; Preserve white spaces after the macro.
228 (progn (goto-char (org-element-property :end macro))
229 (skip-chars-backward " \t")
230 (point)))
231 ;; Leave point before replacement in case of
232 ;; recursive expansions.
233 (save-excursion (insert value)))
234 (finalize
235 (error "Undefined Org macro: %s; aborting"
236 (org-element-property :key macro))))))))))))
238 (defun org-macro-escape-arguments (&rest args)
239 "Build macro's arguments string from ARGS.
240 ARGS are strings. Return value is a string with arguments
241 properly escaped and separated with commas. This is the opposite
242 of `org-macro-extract-arguments'."
243 (let ((s ""))
244 (dolist (arg (reverse args) (substring s 1))
245 (setq s
246 (concat
248 (replace-regexp-in-string
249 "\\(\\\\*\\),"
250 (lambda (m)
251 (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
252 ","))
253 ;; If a non-terminal argument ends on backslashes, make
254 ;; sure to also escape them as they will be followed by
255 ;; a comma.
256 (concat arg (and (not (equal s ""))
257 (string-match "\\\\+\\'" arg)
258 (match-string 0 arg)))
259 nil t)
260 s)))))
262 (defun org-macro-extract-arguments (s)
263 "Extract macro arguments from string S.
264 S is a string containing comma separated values properly escaped.
265 Return a list of arguments, as strings. This is the opposite of
266 `org-macro-escape-arguments'."
267 ;; Do not use `org-split-string' since empty strings are
268 ;; meaningful here.
269 (split-string
270 (replace-regexp-in-string
271 "\\(\\\\*\\),"
272 (lambda (str)
273 (let ((len (length (match-string 1 str))))
274 (concat (make-string (/ len 2) ?\\)
275 (if (zerop (mod len 2)) "\000" ","))))
276 s nil t)
277 "\000"))
279 (defun org-macro--vc-modified-time (file)
280 (save-window-excursion
281 (when (vc-backend file)
282 (let ((buf (get-buffer-create " *org-vc*"))
283 (case-fold-search t)
284 date)
285 (unwind-protect
286 (progn
287 (vc-call print-log file buf nil nil 1)
288 (with-current-buffer buf
289 (vc-exec-after
290 (lambda ()
291 (goto-char (point-min))
292 (when (re-search-forward "Date:?[ \t]*" nil t)
293 (let ((time (parse-time-string
294 (buffer-substring
295 (point) (line-end-position)))))
296 (when (cl-some #'identity time)
297 (setq date (apply #'encode-time time))))))))
298 (let ((proc (get-buffer-process buf)))
299 (while (and proc (accept-process-output proc .5 nil t)))))
300 (kill-buffer buf))
301 date))))
304 (provide 'org-macro)
305 ;;; org-macro.el ends here