org-exp-blocks.el 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. ;;; org-exp-blocks.el --- pre-process blocks when exporting org files
  2. ;; Copyright (C) 2009
  3. ;; Free Software Foundation, Inc.
  4. ;; Author: Eric Schulte
  5. ;; This file is part of GNU Emacs.
  6. ;;
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;;
  19. ;; This is a utility for pre-processing blocks in org files before
  20. ;; export using the `org-export-preprocess-hook'. It can be used for
  21. ;; exporting new types of blocks from org-mode files and also for
  22. ;; changing the default export behavior of existing org-mode blocks.
  23. ;; The `org-export-blocks' and `org-export-interblocks' variables can
  24. ;; be used to control how blocks and the spaces between blocks
  25. ;; respectively are processed upon export.
  26. ;;
  27. ;; The type of a block is defined as the string following =#+begin_=,
  28. ;; so for example the following block would be of type ditaa. Note
  29. ;; that both upper or lower case are allowed in =#+BEGIN_= and
  30. ;; =#+END_=.
  31. ;;
  32. ;; #+begin_ditaa blue.png -r -S
  33. ;; +---------+
  34. ;; | cBLU |
  35. ;; | |
  36. ;; | +----+
  37. ;; | |cPNK|
  38. ;; | | |
  39. ;; +----+----+
  40. ;; #+end_ditaa
  41. ;;
  42. ;;; Currently Implemented Block Types
  43. ;;
  44. ;; ditaa :: Convert ascii pictures to actual images using ditaa
  45. ;; http://ditaa.sourceforge.net/. To use this set
  46. ;; `org-ditaa-jar-path' to the path to ditaa.jar on your
  47. ;; system (should be set automatically in most cases) .
  48. ;;
  49. ;; dot :: Convert graphs defined using the dot graphing language to
  50. ;; images using the dot utility. For information on dot see
  51. ;; http://www.graphviz.org/
  52. ;;
  53. ;; comment :: Wrap comments with titles and author information, in
  54. ;; their own divs with author-specific ids allowing for css
  55. ;; coloring of comments based on the author.
  56. ;;
  57. ;; R :: Implements Sweave type exporting, evaluates blocks of R code,
  58. ;; and also replaces \R{} chunks in the file with their result
  59. ;; when passed to R. This require the `R' command which is
  60. ;; provided by ESS (Emacs Speaks Statistics).
  61. ;;
  62. ;;; Adding new blocks
  63. ;;
  64. ;; When adding a new block type first define a formatting function
  65. ;; along the same lines as `org-export-blocks-format-dot' and then use
  66. ;; `org-export-blocks-add-block' to add your block type to
  67. ;; `org-export-blocks'.
  68. (eval-when-compile
  69. (require 'cl))
  70. (require 'org)
  71. (defvar comint-last-input-end)
  72. (defvar comint-prompt-regexp)
  73. (defvar comint-last-input-end)
  74. (defvar htmlp)
  75. (defvar latexp)
  76. (defvar docbookp)
  77. (defvar asciip)
  78. (declare-function comint-send-input "comint" (&optional no-newline artificial))
  79. (declare-function R "ext:ess" nil)
  80. (defun org-export-blocks-set (var value)
  81. "Set the value of `org-export-blocks' and install fontification."
  82. (set var value)
  83. (mapc (lambda (spec)
  84. (if (nth 2 spec)
  85. (setq org-protecting-blocks
  86. (delete (symbol-name (car spec))
  87. org-protecting-blocks))
  88. (add-to-list 'org-protecting-blocks
  89. (symbol-name (car spec)))))
  90. value))
  91. (defcustom org-export-blocks
  92. '((comment org-export-blocks-format-comment t)
  93. (ditaa org-export-blocks-format-ditaa nil)
  94. (dot org-export-blocks-format-dot nil)
  95. (r org-export-blocks-format-R nil)
  96. (R org-export-blocks-format-R nil))
  97. "Use this a-list to associate block types with block exporting
  98. functions. The type of a block is determined by the text
  99. immediately following the '#+BEGIN_' portion of the block header.
  100. Each block export function should accept three argumets..."
  101. :group 'org-export-general
  102. :type '(repeat
  103. (list
  104. (symbol :tag "Block name")
  105. (function :tag "Block formatter")
  106. (boolean :tag "Fontify content as Org syntax")))
  107. :set 'org-export-blocks-set)
  108. (defun org-export-blocks-add-block (block-spec)
  109. "Add a new block type to `org-export-blocks'. BLOCK-SPEC
  110. should be a three element list the first element of which should
  111. indicate the name of the block, the second element should be the
  112. formatting function called by `org-export-blocks-preprocess' and
  113. the third element a flag indicating whether these types of blocks
  114. should be fontified in org-mode buffers (see
  115. `org-protecting-blocks'). For example the BLOCK-SPEC for ditaa
  116. blocks is as follows...
  117. (ditaa org-export-blocks-format-ditaa nil)"
  118. (unless (member block-spec org-export-blocks)
  119. (setq org-export-blocks (cons block-spec org-export-blocks))
  120. (org-export-blocks-set 'org-export-blocks org-export-blocks)))
  121. (defcustom org-export-interblocks
  122. '((r org-export-interblocks-format-R)
  123. (R org-export-interblocks-format-R))
  124. "Use this a-list to associate block types with block exporting
  125. functions. The type of a block is determined by the text
  126. immediately following the '#+BEGIN_' portion of the block header.
  127. Each block export function should accept three argumets..."
  128. :group 'org-export-general
  129. :type 'alist)
  130. (defcustom org-export-blocks-witheld
  131. '(hidden)
  132. "List of block types (see `org-export-blocks') which should not
  133. be exported."
  134. :group 'org-export-general
  135. :type 'list)
  136. (defvar org-export-blocks-postblock-hooks nil "")
  137. (defun org-export-blocks-html-quote (body &optional open close)
  138. "Protext BODY from org html export. The optional OPEN and
  139. CLOSE tags will be inserted around BODY."
  140. (concat
  141. "\n#+BEGIN_HTML\n"
  142. (or open "")
  143. body (if (string-match "\n$" body) "" "\n")
  144. (or close "")
  145. "#+END_HTML\n"))
  146. (defun org-export-blocks-latex-quote (body &optional open close)
  147. "Protext BODY from org latex export. The optional OPEN and
  148. CLOSE tags will be inserted around BODY."
  149. (concat
  150. "\n#+BEGIN_LaTeX\n"
  151. (or open "")
  152. body (if (string-match "\n$" body) "" "\n")
  153. (or close "")
  154. "#+END_LaTeX\n"))
  155. (defun org-export-blocks-preprocess ()
  156. "Export all blocks acording to the `org-export-blocks' block
  157. exportation alist. Does not export block types specified in
  158. specified in BLOCKS which default to the value of
  159. `org-export-blocks-witheld'."
  160. (interactive)
  161. (save-window-excursion
  162. (let ((count 0)
  163. (blocks org-export-blocks-witheld)
  164. (case-fold-search t)
  165. (types '())
  166. indentation type func start end)
  167. (flet ((interblock (start end type)
  168. (save-match-data
  169. (when (setf func (cadr (assoc type org-export-interblocks)))
  170. (funcall func start end)))))
  171. (goto-char (point-min))
  172. (setf start (point))
  173. (while (re-search-forward
  174. "^\\([ \t]*\\)#\\+begin_\\(\\S-+\\)[ \t]*\\(.*\\)?[\r\n]\\([^\000]*?\\)[\r\n][ \t]*#\\+end_\\S-+.*" nil t)
  175. (save-match-data (setq indentation (length (match-string 1))))
  176. (save-match-data (setf type (intern (match-string 2))))
  177. (unless (memq type types) (setf types (cons type types)))
  178. (setf end (save-match-data (match-beginning 0)))
  179. (interblock start end type)
  180. (if (setf func (cadr (assoc type org-export-blocks)))
  181. (progn
  182. (replace-match (save-match-data
  183. (if (memq type blocks)
  184. ""
  185. (apply func (save-match-data (org-remove-indentation (match-string 4)))
  186. (split-string (match-string 3) " ")))) t t)
  187. ;; indent block
  188. (indent-code-rigidly (match-beginning 0) (match-end 0) indentation)))
  189. (setf start (save-match-data (match-end 0))))
  190. (mapcar (lambda (type)
  191. (interblock start (point-max) type))
  192. types)))))
  193. (add-hook 'org-export-preprocess-hook 'org-export-blocks-preprocess)
  194. ;;================================================================================
  195. ;; type specific functions
  196. ;;--------------------------------------------------------------------------------
  197. ;; ditaa: create images from ASCII art using the ditaa utility
  198. (defvar org-ditaa-jar-path (expand-file-name
  199. "ditaa.jar"
  200. (file-name-as-directory
  201. (expand-file-name
  202. "scripts"
  203. (file-name-as-directory
  204. (expand-file-name
  205. "../contrib"
  206. (file-name-directory (or load-file-name buffer-file-name)))))))
  207. "Path to the ditaa jar executable")
  208. (defun org-export-blocks-format-ditaa (body &rest headers)
  209. "Pass block BODY to the ditaa utility creating an image.
  210. Specify the path at which the image should be saved as the first
  211. element of headers, any additional elements of headers will be
  212. passed to the ditaa utility as command line arguments."
  213. (message "ditaa-formatting...")
  214. (let ((out-file (if headers (car headers)))
  215. (args (if (cdr headers) (mapconcat 'identity (cdr headers) " ")))
  216. (data-file (make-temp-file "org-ditaa")))
  217. (unless (file-exists-p org-ditaa-jar-path)
  218. (error (format "Could not find ditaa.jar at %s" org-ditaa-jar-path)))
  219. (setq body (if (string-match "^\\([^:\\|:[^ ]\\)" body)
  220. body
  221. (mapconcat (lambda (x) (substring x (if (> (length x) 1) 2 1)))
  222. (org-split-string body "\n")
  223. "\n")))
  224. (cond
  225. ((or htmlp latexp docbookp)
  226. (with-temp-file data-file (insert body))
  227. (message (concat "java -jar " org-ditaa-jar-path " " args " " data-file " " out-file))
  228. (shell-command (concat "java -jar " org-ditaa-jar-path " " args " " data-file " " out-file))
  229. (format "\n[[file:%s]]\n" out-file))
  230. (t (concat
  231. "\n#+BEGIN_EXAMPLE\n"
  232. body (if (string-match "\n$" body) "" "\n")
  233. "#+END_EXAMPLE\n")))))
  234. ;;--------------------------------------------------------------------------------
  235. ;; dot: create graphs using the dot graphing language
  236. ;; (require the dot executable to be in your path)
  237. (defun org-export-blocks-format-dot (body &rest headers)
  238. "Pass block BODY to the dot graphing utility creating an image.
  239. Specify the path at which the image should be saved as the first
  240. element of headers, any additional elements of headers will be
  241. passed to the dot utility as command line arguments. Don't
  242. forget to specify the output type for the dot command, so if you
  243. are exporting to a file with a name like 'image.png' you should
  244. include a '-Tpng' argument, and your block should look like the
  245. following.
  246. #+begin_dot models.png -Tpng
  247. digraph data_relationships {
  248. \"data_requirement\" [shape=Mrecord, label=\"{DataRequirement|description\lformat\l}\"]
  249. \"data_product\" [shape=Mrecord, label=\"{DataProduct|name\lversion\lpoc\lformat\l}\"]
  250. \"data_requirement\" -> \"data_product\"
  251. }
  252. #+end_dot"
  253. (message "dot-formatting...")
  254. (let ((out-file (if headers (car headers)))
  255. (args (if (cdr headers) (mapconcat 'identity (cdr headers) " ")))
  256. (data-file (make-temp-file "org-ditaa")))
  257. (cond
  258. ((or htmlp latexp docbookp)
  259. (with-temp-file data-file (insert body))
  260. (message (concat "dot " data-file " " args " -o " out-file))
  261. (shell-command (concat "dot " data-file " " args " -o " out-file))
  262. (format "\n[[file:%s]]\n" out-file))
  263. (t (concat
  264. "\n#+BEGIN_EXAMPLE\n"
  265. body (if (string-match "\n$" body) "" "\n")
  266. "#+END_EXAMPLE\n")))))
  267. ;;--------------------------------------------------------------------------------
  268. ;; comment: export comments in author-specific css-stylable divs
  269. (defun org-export-blocks-format-comment (body &rest headers)
  270. "Format comment BODY by OWNER and return it formatted for export.
  271. Currently, this only does something for HTML export, for all
  272. other backends, it converts the comment into an EXAMPLE segment."
  273. (let ((owner (if headers (car headers)))
  274. (title (if (cdr headers) (mapconcat 'identity (cdr headers) " "))))
  275. (cond
  276. (htmlp ;; We are exporting to HTML
  277. (concat "#+BEGIN_HTML\n"
  278. "<div class=\"org-comment\""
  279. (if owner (format " id=\"org-comment-%s\" " owner))
  280. ">\n"
  281. (if owner (concat "<b>" owner "</b> ") "")
  282. (if (and title (> (length title) 0)) (concat " -- " title "</br>\n") "</br>\n")
  283. "<p>\n"
  284. "#+END_HTML\n"
  285. body
  286. "#+BEGIN_HTML\n"
  287. "</p>\n"
  288. "</div>\n"
  289. "#+END_HTML\n"))
  290. (t ;; This is not HTML, so just make it an example.
  291. (concat "#+BEGIN_EXAMPLE\n"
  292. (if title (concat "Title:" title "\n") "")
  293. (if owner (concat "By:" owner "\n") "")
  294. body
  295. (if (string-match "\n\\'" body) "" "\n")
  296. "#+END_EXAMPLE\n")))))
  297. ;;--------------------------------------------------------------------------------
  298. ;; R: Sweave-type functionality
  299. (defvar interblock-R-buffer nil
  300. "Holds the buffer for the current R process")
  301. (defvar count) ; dynamicaly scoped from `org-export-blocks-preprocess'?
  302. (defun org-export-blocks-format-R (body &rest headers)
  303. "Process R blocks and replace \R{} forms outside the blocks
  304. with their values as determined by R."
  305. (interactive)
  306. (message "R processing...")
  307. (let ((image-path (or (and (car headers)
  308. (string-match "\\(.?\\)\.\\(EPS\\|eps\\)" (car headers))
  309. (match-string 1 (car headers)))
  310. (and (> (length (car headers)) 0)
  311. (car headers))
  312. ;; create the default filename
  313. (format "Rplot-%03d" count)))
  314. (plot (string-match "plot" body))
  315. R-proc)
  316. (setf count (+ count 1))
  317. (interblock-initiate-R-buffer)
  318. (setf R-proc (get-buffer-process interblock-R-buffer))
  319. ;; send strings to the ESS process using `comint-send-string'
  320. (setf body (mapconcat (lambda (line)
  321. (interblock-R-input-command line) (concat "> " line))
  322. (butlast (split-string body "[\r\n]"))
  323. "\n"))
  324. ;; if there is a plot command, then create the images
  325. (when plot
  326. (interblock-R-input-command (format "dev.copy2eps(file=\"%s.eps\")" image-path)))
  327. (concat (cond
  328. (htmlp (org-export-blocks-html-quote body
  329. (format "<div id=\"R-%d\">\n<pre>\n" count)
  330. "</pre>\n</div>\n"))
  331. (latexp (org-export-blocks-latex-quote body
  332. "\\begin{Schunk}\n\\begin{Sinput}\n"
  333. "\\end{Sinput}\n\\end{Schunk}\n"))
  334. (t (insert ;; default export
  335. "#+begin_R " (mapconcat 'identity headers " ") "\n"
  336. body (if (string-match "\n$" body) "" "\n")
  337. "#+end_R\n")))
  338. (if plot
  339. (format "[[file:%s.eps]]\n" image-path)
  340. ""))))
  341. (defun org-export-interblocks-format-R (start end)
  342. "This is run over parts of the org-file which are between R
  343. blocks. Its main use is to expand the \R{stuff} chunks for
  344. export."
  345. (save-excursion
  346. (goto-char start)
  347. (interblock-initiate-R-buffer)
  348. (let (code replacement)
  349. (while (and (< (point) end) (re-search-forward "\\\\R{\\(.*\\)}" end t))
  350. (save-match-data (setf code (match-string 1)))
  351. (setf replacement (interblock-R-command-to-string code))
  352. (setf replacement (cond
  353. (htmlp replacement)
  354. (latexp replacement)
  355. (t replacement)))
  356. (setf end (+ end (- (length replacement) (length code))))
  357. (replace-match replacement t t)))))
  358. (defun interblock-initiate-R-buffer ()
  359. "If there is not a current R process then create one."
  360. (unless (and (buffer-live-p interblock-R-buffer) (get-buffer interblock-R-buffer))
  361. (save-excursion
  362. (R)
  363. (setf interblock-R-buffer (current-buffer))
  364. (interblock-R-wait-for-output)
  365. (interblock-R-input-command ""))))
  366. (defun interblock-R-command-to-string (command)
  367. "Send a command to R, and return the results as a string."
  368. (interblock-R-input-command command)
  369. (interblock-R-last-output))
  370. (defun interblock-R-input-command (command)
  371. "Pass COMMAND to the R process running in `interblock-R-buffer'."
  372. (save-excursion
  373. (save-match-data
  374. (set-buffer interblock-R-buffer)
  375. (goto-char (process-mark (get-buffer-process (current-buffer))))
  376. (insert command)
  377. (comint-send-input)
  378. (interblock-R-wait-for-output))))
  379. (defun interblock-R-wait-for-output ()
  380. "Wait until output arrives"
  381. (save-excursion
  382. (save-match-data
  383. (set-buffer interblock-R-buffer)
  384. (while (progn
  385. (goto-char comint-last-input-end)
  386. (not (re-search-forward comint-prompt-regexp nil t)))
  387. (accept-process-output (get-buffer-process (current-buffer)))))))
  388. (defun interblock-R-last-output ()
  389. "Return the last R output as a string"
  390. (save-excursion
  391. (save-match-data
  392. (set-buffer interblock-R-buffer)
  393. (goto-char (process-mark (get-buffer-process (current-buffer))))
  394. (forward-line 0)
  395. (let ((raw (buffer-substring comint-last-input-end (- (point) 1))))
  396. (if (string-match "\n" raw)
  397. raw
  398. (and (string-match "\\[[[:digit:]+]\\] *\\(.*\\)$" raw)
  399. (message raw)
  400. (message (match-string 1 raw))
  401. (match-string 1 raw)))))))
  402. (provide 'org-exp-blocks)
  403. ;; arch-tag: 1c365fe9-8808-4f72-bb15-0b00f36d8024
  404. ;;; org-exp-blocks.el ends here