org-macro.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. ;;; org-macro.el --- Macro Replacement Code for Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; Macros are expanded with `org-macro-replace-all', which relies
  18. ;; internally on `org-macro-expand'.
  19. ;; Default templates for expansion are stored in the buffer-local
  20. ;; variable `org-macro-templates'. This variable is updated by
  21. ;; `org-macro-initialize-templates', which recursively calls
  22. ;; `org-macro--collect-macros' in order to read setup files.
  23. ;; Argument in macros are separated with commas. Proper escaping rules
  24. ;; are implemented in `org-macro-escape-arguments' and arguments can
  25. ;; be extracted from a string with `org-macro-extract-arguments'.
  26. ;; Along with macros defined through #+MACRO: keyword, default
  27. ;; templates include the following hard-coded macros:
  28. ;; {{{time(format-string)}}},
  29. ;; {{{property(node-property)}}},
  30. ;; {{{input-file}}},
  31. ;; {{{modification-time(format-string)}}},
  32. ;; {{{n(counter,reset}}}.
  33. ;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}},
  34. ;; {{{email}}} and {{{title}}} macros.
  35. ;;; Code:
  36. (require 'cl-lib)
  37. (require 'org-macs)
  38. (require 'org-compat)
  39. (declare-function org-element-at-point "org-element" ())
  40. (declare-function org-element-context "org-element" (&optional element))
  41. (declare-function org-element-map "org-element"
  42. (data types fun &optional info first-match no-recursion
  43. with-affiliated))
  44. (declare-function org-element-parse-buffer "org-element"
  45. (&optional granularity visible-only))
  46. (declare-function org-element-property "org-element" (property element))
  47. (declare-function org-element-type "org-element" (element))
  48. (declare-function org-file-contents "org" (file &optional noerror))
  49. (declare-function org-mode "org" ())
  50. (declare-function vc-backend "vc-hooks" (f))
  51. (declare-function vc-call "vc-hooks" (fun file &rest args) t)
  52. (declare-function vc-exec-after "vc-dispatcher" (code))
  53. ;;; Variables
  54. (defvar-local org-macro-templates nil
  55. "Alist containing all macro templates in current buffer.
  56. Associations are in the shape of (NAME . TEMPLATE) where NAME
  57. stands for macro's name and template for its replacement value,
  58. both as strings. This is an internal variable. Do not set it
  59. directly, use instead:
  60. #+MACRO: name template")
  61. ;;; Functions
  62. (defun org-macro--collect-macros ()
  63. "Collect macro definitions in current buffer and setup files.
  64. Return an alist containing all macro templates found."
  65. (letrec ((collect-macros
  66. (lambda (files templates)
  67. ;; Return an alist of macro templates. FILES is a list
  68. ;; of setup files names read so far, used to avoid
  69. ;; circular dependencies. TEMPLATES is the alist
  70. ;; collected so far.
  71. (let ((case-fold-search t))
  72. (org-with-wide-buffer
  73. (goto-char (point-min))
  74. (while (re-search-forward
  75. "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t)
  76. (let ((element (org-element-at-point)))
  77. (when (eq (org-element-type element) 'keyword)
  78. (let ((val (org-element-property :value element)))
  79. (if (equal (org-element-property :key element) "MACRO")
  80. ;; Install macro in TEMPLATES.
  81. (when (string-match
  82. "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val)
  83. (let* ((name (match-string 1 val))
  84. (template (or (match-string 2 val) ""))
  85. (old-cell (assoc name templates)))
  86. (if old-cell (setcdr old-cell template)
  87. (push (cons name template) templates))))
  88. ;; Enter setup file.
  89. (let ((file (expand-file-name
  90. (org-unbracket-string "\"" "\"" val))))
  91. (unless (member file files)
  92. (with-temp-buffer
  93. (setq default-directory
  94. (file-name-directory file))
  95. (org-mode)
  96. (insert (org-file-contents file 'noerror))
  97. (setq templates
  98. (funcall collect-macros (cons file files)
  99. templates)))))))))))
  100. templates))))
  101. (funcall collect-macros nil nil)))
  102. (defun org-macro-initialize-templates ()
  103. "Collect macro templates defined in current buffer.
  104. Templates are stored in buffer-local variable
  105. `org-macro-templates'. In addition to buffer-defined macros, the
  106. function installs the following ones: \"property\",
  107. \"time\". and, if the buffer is associated to a file,
  108. \"input-file\" and \"modification-time\"."
  109. (let* ((templates (org-macro--collect-macros))
  110. (update-templates
  111. (lambda (cell)
  112. (let ((old-template (assoc (car cell) templates)))
  113. (if old-template (setcdr old-template (cdr cell))
  114. (push cell templates))))))
  115. ;; Install "property", "time" macros.
  116. (mapc update-templates
  117. (list (cons "property"
  118. "(eval (save-excursion
  119. (let ((l \"$2\"))
  120. (when (org-string-nw-p l)
  121. (condition-case _
  122. (let ((org-link-search-must-match-exact-headline t))
  123. (org-link-search l nil t))
  124. (error
  125. (error \"Macro property failed: cannot find location %s\"
  126. l)))))
  127. (org-entry-get nil \"$1\" 'selective)))")
  128. (cons "time" "(eval (format-time-string \"$1\"))")))
  129. ;; Install "input-file", "modification-time" macros.
  130. (let ((visited-file (buffer-file-name (buffer-base-buffer))))
  131. (when (and visited-file (file-exists-p visited-file))
  132. (mapc update-templates
  133. (list (cons "input-file" (file-name-nondirectory visited-file))
  134. (cons "modification-time"
  135. (format "(eval (format-time-string \"$1\" (or (and (org-string-nw-p \"$2\") (org-macro--vc-modified-time %s)) '%s)))"
  136. (prin1-to-string visited-file)
  137. (prin1-to-string
  138. (nth 5 (file-attributes visited-file)))))))))
  139. ;; Initialize and install "n" macro.
  140. (org-macro--counter-initialize)
  141. (funcall update-templates
  142. (cons "n" "(eval (org-macro--counter-increment \"$1\" \"$2\"))"))
  143. (setq org-macro-templates templates)))
  144. (defun org-macro-expand (macro templates)
  145. "Return expanded MACRO, as a string.
  146. MACRO is an object, obtained, for example, with
  147. `org-element-context'. TEMPLATES is an alist of templates used
  148. for expansion. See `org-macro-templates' for a buffer-local
  149. default value. Return nil if no template was found."
  150. (let ((template
  151. ;; Macro names are case-insensitive.
  152. (cdr (assoc-string (org-element-property :key macro) templates t))))
  153. (when template
  154. (let ((value (replace-regexp-in-string
  155. "\\$[0-9]+"
  156. (lambda (arg)
  157. (or (nth (1- (string-to-number (substring arg 1)))
  158. (org-element-property :args macro))
  159. ;; No argument: remove place-holder.
  160. ""))
  161. template nil 'literal)))
  162. ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
  163. (when (string-match "\\`(eval\\>" value)
  164. (setq value (eval (read value))))
  165. ;; Return string.
  166. (format "%s" (or value ""))))))
  167. (defun org-macro-replace-all (templates &optional finalize keywords)
  168. "Replace all macros in current buffer by their expansion.
  169. TEMPLATES is an alist of templates used for expansion. See
  170. `org-macro-templates' for a buffer-local default value.
  171. If optional arg FINALIZE is non-nil, raise an error if a macro is
  172. found in the buffer with no definition in TEMPLATES.
  173. Optional argument KEYWORDS, when non-nil is a list of keywords,
  174. as strings, where macro expansion is allowed."
  175. (org-with-wide-buffer
  176. (goto-char (point-min))
  177. (let ((properties-regexp
  178. (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords)))
  179. record)
  180. (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
  181. (let* ((datum (save-match-data (org-element-context)))
  182. (type (org-element-type datum))
  183. (macro
  184. (cond
  185. ((eq type 'macro) datum)
  186. ;; In parsed keywords and associated node properties,
  187. ;; force macro recognition.
  188. ((or (and (eq type 'keyword)
  189. (member (org-element-property :key datum) keywords))
  190. (and (eq type 'node-property)
  191. (string-match-p
  192. properties-regexp
  193. (org-element-property :key datum))))
  194. (save-restriction
  195. (narrow-to-region (match-beginning 0) (line-end-position))
  196. (org-element-map (org-element-parse-buffer) 'macro
  197. #'identity nil t))))))
  198. (when macro
  199. (let* ((value (org-macro-expand macro templates))
  200. (begin (org-element-property :begin macro))
  201. (signature (list begin
  202. macro
  203. (org-element-property :args macro))))
  204. ;; Avoid circular dependencies by checking if the same
  205. ;; macro with the same arguments is expanded at the same
  206. ;; position twice.
  207. (cond ((member signature record)
  208. (error "Circular macro expansion: %s"
  209. (org-element-property :key macro)))
  210. (value
  211. (push signature record)
  212. (delete-region
  213. begin
  214. ;; Preserve white spaces after the macro.
  215. (progn (goto-char (org-element-property :end macro))
  216. (skip-chars-backward " \t")
  217. (point)))
  218. ;; Leave point before replacement in case of
  219. ;; recursive expansions.
  220. (save-excursion (insert value)))
  221. (finalize
  222. (error "Undefined Org macro: %s; aborting"
  223. (org-element-property :key macro)))))))))))
  224. (defun org-macro-escape-arguments (&rest args)
  225. "Build macro's arguments string from ARGS.
  226. ARGS are strings. Return value is a string with arguments
  227. properly escaped and separated with commas. This is the opposite
  228. of `org-macro-extract-arguments'."
  229. (let ((s ""))
  230. (dolist (arg (reverse args) (substring s 1))
  231. (setq s
  232. (concat
  233. ","
  234. (replace-regexp-in-string
  235. "\\(\\\\*\\),"
  236. (lambda (m)
  237. (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
  238. ","))
  239. ;; If a non-terminal argument ends on backslashes, make
  240. ;; sure to also escape them as they will be followed by
  241. ;; a comma.
  242. (concat arg (and (not (equal s ""))
  243. (string-match "\\\\+\\'" arg)
  244. (match-string 0 arg)))
  245. nil t)
  246. s)))))
  247. (defun org-macro-extract-arguments (s)
  248. "Extract macro arguments from string S.
  249. S is a string containing comma separated values properly escaped.
  250. Return a list of arguments, as strings. This is the opposite of
  251. `org-macro-escape-arguments'."
  252. ;; Do not use `org-split-string' since empty strings are
  253. ;; meaningful here.
  254. (split-string
  255. (replace-regexp-in-string
  256. "\\(\\\\*\\),"
  257. (lambda (str)
  258. (let ((len (length (match-string 1 str))))
  259. (concat (make-string (/ len 2) ?\\)
  260. (if (zerop (mod len 2)) "\000" ","))))
  261. s nil t)
  262. "\000"))
  263. ;;; Helper functions and variables for internal macros
  264. (defun org-macro--vc-modified-time (file)
  265. (save-window-excursion
  266. (when (vc-backend file)
  267. (let ((buf (get-buffer-create " *org-vc*"))
  268. (case-fold-search t)
  269. date)
  270. (unwind-protect
  271. (progn
  272. (vc-call print-log file buf nil nil 1)
  273. (with-current-buffer buf
  274. (vc-exec-after
  275. (lambda ()
  276. (goto-char (point-min))
  277. (when (re-search-forward "Date:?[ \t]*" nil t)
  278. (let ((time (parse-time-string
  279. (buffer-substring
  280. (point) (line-end-position)))))
  281. (when (cl-some #'identity time)
  282. (setq date (apply #'encode-time time))))))))
  283. (let ((proc (get-buffer-process buf)))
  284. (while (and proc (accept-process-output proc .5 nil t)))))
  285. (kill-buffer buf))
  286. date))))
  287. (defvar org-macro--counter-table nil
  288. "Hash table containing counter value per name.")
  289. (defun org-macro--counter-initialize ()
  290. "Initialize `org-macro--counter-table'."
  291. (setq org-macro--counter-table (make-hash-table :test #'equal)))
  292. (defun org-macro--counter-increment (name &optional reset)
  293. "Increment counter NAME.
  294. NAME is a string identifying the counter. If optional argument
  295. RESET is a non-empty string, reset the counter instead."
  296. (if (org-string-nw-p reset)
  297. (let ((new-value (if (string-match-p "\\`[ \t]*[0-9]+[ \t]*\\'" reset)
  298. (string-to-number reset)
  299. 1)))
  300. (puthash name new-value org-macro--counter-table))
  301. (let ((value (gethash name org-macro--counter-table)))
  302. (puthash name
  303. (if (null value) 1 (1+ value))
  304. org-macro--counter-table))))
  305. (provide 'org-macro)
  306. ;;; org-macro.el ends here