org-exp-blocks.el 16 KB

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