ob.el 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866
  1. ;;; ob.el --- working with code blocks in org-mode
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 7.01trans
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; See the online documentation for more information
  20. ;;
  21. ;; http://orgmode.org/worg/org-contrib/babel/
  22. ;;; Code:
  23. (eval-when-compile
  24. (require 'cl))
  25. (require 'org-macs)
  26. (defvar org-babel-call-process-region-original)
  27. (declare-function show-all "outline" ())
  28. (declare-function tramp-compat-make-temp-file "tramp-compat"
  29. (filename &optional dir-flag))
  30. (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
  31. (declare-function tramp-file-name-user "tramp" (vec))
  32. (declare-function tramp-file-name-host "tramp" (vec))
  33. (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
  34. (declare-function org-icompleting-read "org" (&rest args))
  35. (declare-function org-edit-src-code "org-src"
  36. (&optional context code edit-buffer-name quietp))
  37. (declare-function org-edit-src-exit "org-src" (&optional context))
  38. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  39. (declare-function org-save-outline-visibility "org" (use-markers &rest body))
  40. (declare-function org-outline-overlay-data "org" (&optional use-markers))
  41. (declare-function org-set-outline-overlay-data "org" (data))
  42. (declare-function org-narrow-to-subtree "org" ())
  43. (declare-function org-entry-get "org"
  44. (pom property &optional inherit literal-nil))
  45. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  46. (declare-function org-do-remove-indentation "org" (&optional n))
  47. (declare-function org-show-context "org" (&optional key))
  48. (declare-function org-at-table-p "org" (&optional table-type))
  49. (declare-function org-cycle "org" (&optional arg))
  50. (declare-function org-uniquify "org" (list))
  51. (declare-function org-current-level "org" ())
  52. (declare-function org-table-import "org-table" (file arg))
  53. (declare-function org-add-hook "org-compat"
  54. (hook function &optional append local))
  55. (declare-function org-table-align "org-table" ())
  56. (declare-function org-table-end "org-table" (&optional table-type))
  57. (declare-function orgtbl-to-generic "org-table" (table params))
  58. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  59. (declare-function org-babel-lob-get-info "ob-lob" nil)
  60. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  61. (declare-function org-babel-ref-parse "ob-ref" (assignment))
  62. (declare-function org-babel-lob-execute-maybe "ob-lob" ())
  63. (declare-function org-number-sequence "org-compat" (from &optional to inc))
  64. (defgroup org-babel nil
  65. "Code block evaluation and management in `org-mode' documents."
  66. :tag "Babel"
  67. :group 'org)
  68. (defcustom org-confirm-babel-evaluate t
  69. "Confirm before evaluation.
  70. Require confirmation before interactively evaluating code
  71. blocks in Org-mode buffers. The default value of this variable
  72. is t, meaning confirmation is required for any code block
  73. evaluation. This variable can be set to nil to inhibit any
  74. future confirmation requests. This variable can also be set to a
  75. function which takes two arguments the language of the code block
  76. and the body of the code block. Such a function should then
  77. return a non-nil value if the user should be prompted for
  78. execution or nil if no prompt is required.
  79. Warning: Disabling confirmation may result in accidental
  80. evaluation of potentially harmful code. It may be advisable
  81. remove code block execution from C-c C-c as further protection
  82. against accidental code block evaluation. The
  83. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  84. remove code block execution from the C-c C-c keybinding."
  85. :group 'org-babel
  86. :type '(choice boolean function))
  87. ;; don't allow this variable to be changed through file settings
  88. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  89. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  90. "Remove code block evaluation from the C-c C-c key binding."
  91. :group 'org-babel
  92. :type 'boolean)
  93. (defvar org-babel-src-name-regexp
  94. "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
  95. "Regular expression used to match a source name line.")
  96. (defvar org-babel-multi-line-header-regexp
  97. "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
  98. "Regular expression used to match multi-line header arguments.")
  99. (defvar org-babel-src-name-w-name-regexp
  100. (concat org-babel-src-name-regexp
  101. "\\("
  102. org-babel-multi-line-header-regexp
  103. "\\)*"
  104. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
  105. "Regular expression matching source name lines with a name.")
  106. (defvar org-babel-src-block-regexp
  107. (concat
  108. ;; (1) indentation (2) lang
  109. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  110. ;; (3) switches
  111. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  112. ;; (4) header arguments
  113. "\\([^\n]*\\)\n"
  114. ;; (5) body
  115. "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
  116. "Regexp used to identify code blocks.")
  117. (defvar org-babel-inline-src-block-regexp
  118. (concat
  119. ;; (1) replacement target (2) lang
  120. "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
  121. ;; (3,4) (unused, headers)
  122. "\\(\\|\\[\\(.*?\\)\\]\\)"
  123. ;; (5) body
  124. "{\\([^\f\n\r\v]+?\\)}\\)")
  125. "Regexp used to identify inline src-blocks.")
  126. (defun org-babel-get-header (params key &optional others)
  127. "Select only header argument of type KEY from a list.
  128. Optional argument OTHERS indicates that only the header that do
  129. not match KEY should be returned."
  130. (delq nil
  131. (mapcar
  132. (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
  133. params)))
  134. (defun org-babel-get-src-block-info (&optional light)
  135. "Get information on the current source block.
  136. Optional argument LIGHT does not resolve remote variable
  137. references; a process which could likely result in the execution
  138. of other code blocks.
  139. Returns a list
  140. (language body header-arguments-alist switches name indent)."
  141. (let ((case-fold-search t) head info name indent)
  142. ;; full code block
  143. (if (setq head (org-babel-where-is-src-block-head))
  144. (save-excursion
  145. (goto-char head)
  146. (setq info (org-babel-parse-src-block-match))
  147. (setq indent (car (last info)))
  148. (setq info (butlast info))
  149. (while (and (forward-line -1)
  150. (looking-at org-babel-multi-line-header-regexp))
  151. (setf (nth 2 info)
  152. (org-babel-merge-params
  153. (org-babel-parse-header-arguments (match-string 1))
  154. (nth 2 info))))
  155. (when (looking-at org-babel-src-name-w-name-regexp)
  156. (setq name (org-babel-clean-text-properties (match-string 4)))
  157. (when (match-string 5)
  158. (setf (nth 2 info) ;; merge functional-syntax vars and header-args
  159. (org-babel-merge-params
  160. (mapcar (lambda (ref) (cons :var ref))
  161. (org-babel-ref-split-args (match-string 5)))
  162. (nth 2 info))))))
  163. ;; inline source block
  164. (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t)
  165. (looking-at org-babel-inline-src-block-regexp))
  166. (setq info (org-babel-parse-inline-src-block-match))))
  167. ;; resolve variable references and add summary parameters
  168. (when (and info (not light))
  169. (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
  170. (when info (append info (list name indent)))))
  171. (defun org-babel-confirm-evaluate (info)
  172. "Confirm evaluation of the code block INFO.
  173. This behavior can be suppressed by setting the value of
  174. `org-confirm-babel-evaluate' to nil, in which case all future
  175. interactive code block evaluations will proceed without any
  176. confirmation from the user.
  177. Note disabling confirmation may result in accidental evaluation
  178. of potentially harmful code."
  179. (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
  180. (when (assoc :noeval (nth 2 info)) "no")))
  181. (query (or (equal eval "query")
  182. (if (functionp org-confirm-babel-evaluate)
  183. (funcall org-confirm-babel-evaluate
  184. (nth 0 info) (nth 1 info))
  185. org-confirm-babel-evaluate))))
  186. (if (or (equal eval "never") (equal eval "no")
  187. (and query
  188. (not (yes-or-no-p
  189. (format "Evaluate this%scode on your system? "
  190. (if info (format " %s " (nth 0 info)) " "))))))
  191. (prog1 nil (message "evaluation aborted"))
  192. t)))
  193. ;;;###autoload
  194. (defun org-babel-execute-safely-maybe ()
  195. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  196. (org-babel-execute-maybe)))
  197. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
  198. ;;;###autoload
  199. (defun org-babel-execute-maybe ()
  200. (interactive)
  201. (or (org-babel-execute-src-block-maybe)
  202. (org-babel-lob-execute-maybe)))
  203. (defun org-babel-execute-src-block-maybe ()
  204. "Conditionally execute a source block.
  205. Detect if this is context for a Babel src-block and if so
  206. then run `org-babel-execute-src-block'."
  207. (interactive)
  208. (let ((info (org-babel-get-src-block-info)))
  209. (if info
  210. (progn (org-babel-execute-src-block current-prefix-arg info) t) nil)))
  211. ;;;###autoload
  212. (defun org-babel-expand-src-block-maybe ()
  213. "Conditionally expand a source block.
  214. Detect if this is context for a org-babel src-block and if so
  215. then run `org-babel-expand-src-block'."
  216. (interactive)
  217. (let ((info (org-babel-get-src-block-info)))
  218. (if info
  219. (progn (org-babel-expand-src-block current-prefix-arg info) t)
  220. nil)))
  221. ;;;###autoload
  222. (defun org-babel-load-in-session-maybe ()
  223. "Conditionally load a source block in a session.
  224. Detect if this is context for a org-babel src-block and if so
  225. then run `org-babel-load-in-session'."
  226. (interactive)
  227. (let ((info (org-babel-get-src-block-info)))
  228. (if info
  229. (progn (org-babel-load-in-session current-prefix-arg info) t)
  230. nil)))
  231. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  232. ;;;###autoload
  233. (defun org-babel-pop-to-session-maybe ()
  234. "Conditionally pop to a session.
  235. Detect if this is context for a org-babel src-block and if so
  236. then run `org-babel-pop-to-session'."
  237. (interactive)
  238. (let ((info (org-babel-get-src-block-info)))
  239. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  240. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  241. (defconst org-babel-header-arg-names
  242. '(cache cmdline colnames dir exports file noweb results
  243. session tangle var eval noeval comments)
  244. "Common header arguments used by org-babel.
  245. Note that individual languages may define their own language
  246. specific header arguments as well.")
  247. (defvar org-babel-default-header-args
  248. '((:session . "none") (:results . "replace") (:exports . "code")
  249. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
  250. "Default arguments to use when evaluating a source block.")
  251. (defvar org-babel-default-inline-header-args
  252. '((:session . "none") (:results . "silent") (:exports . "results"))
  253. "Default arguments to use when evaluating an inline source block.")
  254. (defvar org-babel-current-buffer-properties nil
  255. "Local cache for buffer properties.")
  256. (make-variable-buffer-local 'org-babel-current-buffer-properties)
  257. (defvar org-babel-result-regexp
  258. "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
  259. "Regular expression used to match result lines.
  260. If the results are associated with a hash key then the hash will
  261. be saved in the second match data.")
  262. (defvar org-babel-result-w-name-regexp
  263. (concat org-babel-result-regexp
  264. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  265. (defvar org-babel-min-lines-for-block-output 10
  266. "The minimum number of lines for block output.
  267. If number of lines of output is equal to or exceeds this
  268. value, the output is placed in a #+begin_example...#+end_example
  269. block. Otherwise the output is marked as literal by inserting
  270. colons at the starts of the lines. This variable only takes
  271. effect if the :results output option is in effect.")
  272. (defvar org-babel-noweb-error-langs nil
  273. "Languages for which Babel will raise literate programming errors.
  274. List of languages for which errors should be raised when the
  275. source code block satisfying a noweb reference in this language
  276. can not be resolved.")
  277. (defvar org-babel-hash-show 4
  278. "Number of initial characters to show of a hidden results hash.")
  279. (defvar org-babel-after-execute-hook nil
  280. "Hook for functions to be called after `org-babel-execute-src-block'")
  281. (defun org-babel-named-src-block-regexp-for-name (name)
  282. "This generates a regexp used to match a src block named NAME."
  283. (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
  284. (substring org-babel-src-block-regexp 1)))
  285. ;;; functions
  286. (defvar call-process-region)
  287. ;;;###autoload
  288. (defun org-babel-execute-src-block (&optional arg info params)
  289. "Execute the current source code block.
  290. Insert the results of execution into the buffer. Source code
  291. execution and the collection and formatting of results can be
  292. controlled through a variety of header arguments.
  293. With prefix argument ARG, force re-execution even if a an
  294. existing result cached in the buffer would otherwise have been
  295. returned.
  296. Optionally supply a value for INFO in the form returned by
  297. `org-babel-get-src-block-info'.
  298. Optionally supply a value for PARAMS which will be merged with
  299. the header arguments specified at the front of the source code
  300. block."
  301. (interactive)
  302. (let ((info (or info (org-babel-get-src-block-info))))
  303. (when (org-babel-confirm-evaluate info)
  304. (let* ((lang (nth 0 info))
  305. (params (if params
  306. (org-babel-process-params
  307. (org-babel-merge-params (nth 2 info) params))
  308. (nth 2 info)))
  309. (cache? (and (cdr (assoc :cache params))
  310. (string= "yes" (cdr (assoc :cache params)))))
  311. (params (setf (nth 2 info)
  312. (if cache?
  313. (sort params
  314. (lambda (el1 el2)
  315. (string< (symbol-name (car el1))
  316. (symbol-name (car el2)))))
  317. params)))
  318. (new-hash (when cache? (org-babel-sha1-hash info)))
  319. (old-hash (when cache? (org-babel-result-hash info)))
  320. (body (setf (nth 1 info)
  321. (if (and (cdr (assoc :noweb params))
  322. (string= "yes" (cdr (assoc :noweb params))))
  323. (org-babel-expand-noweb-references info)
  324. (nth 1 info))))
  325. (cmd (intern (concat "org-babel-execute:" lang)))
  326. (dir (cdr (assoc :dir params)))
  327. (default-directory
  328. (or (and dir (file-name-as-directory dir)) default-directory))
  329. (org-babel-call-process-region-original
  330. (if (boundp 'org-babel-call-process-region-original)
  331. org-babel-call-process-region-original
  332. (symbol-function 'call-process-region)))
  333. (indent (car (last info)))
  334. result)
  335. (unwind-protect
  336. (flet ((call-process-region (&rest args)
  337. (apply 'org-babel-tramp-handle-call-process-region args)))
  338. (unless (fboundp cmd)
  339. (error "No org-babel-execute function for %s!" lang))
  340. (if (and (not arg) new-hash (equal new-hash old-hash))
  341. (save-excursion ;; return cached result
  342. (goto-char (org-babel-where-is-src-block-result nil info))
  343. (end-of-line 1) (forward-char 1)
  344. (setq result (org-babel-read-result))
  345. (message (replace-regexp-in-string
  346. "%" "%%" (format "%S" result))) result)
  347. (message "executing %s code block%s..."
  348. (capitalize lang)
  349. (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
  350. (setq result (funcall cmd body params))
  351. (if (eq result-type 'value)
  352. (setq result (if (and (or (member "vector" result-params)
  353. (member "table" result-params))
  354. (not (listp result)))
  355. (list (list result))
  356. result)))
  357. (org-babel-insert-result
  358. result result-params info new-hash indent lang)
  359. (run-hooks 'org-babel-after-execute-hook)
  360. result))
  361. (setq call-process-region 'org-babel-call-process-region-original))))))
  362. (defun org-babel-expand-body:generic (body params)
  363. "Expand BODY with PARAMS.
  364. Expand a block of code with org-babel according to it's header
  365. arguments. This generic implementation of body expansion is
  366. called for languages which have not defined their own specific
  367. org-babel-expand-body:lang function." body)
  368. ;;;###autoload
  369. (defun org-babel-expand-src-block (&optional arg info params)
  370. "Expand the current source code block.
  371. Expand according to the source code block's header
  372. arguments and pop open the results in a preview buffer."
  373. (interactive)
  374. (let* ((info (or info (org-babel-get-src-block-info)))
  375. (lang (nth 0 info))
  376. (params (setf (nth 2 info)
  377. (sort (org-babel-merge-params (nth 2 info) params)
  378. (lambda (el1 el2) (string< (symbol-name (car el1))
  379. (symbol-name (car el2)))))))
  380. (body (setf (nth 1 info)
  381. (if (and (cdr (assoc :noweb params))
  382. (string= "yes" (cdr (assoc :noweb params))))
  383. (org-babel-expand-noweb-references info) (nth 1 info))))
  384. (cmd (intern (concat "org-babel-expand-body:" lang)))
  385. (expanded (funcall (if (fboundp cmd) cmd 'org-babel-expand-body:generic)
  386. body params)))
  387. (org-edit-src-code
  388. nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
  389. ;;;###autoload
  390. (defun org-babel-load-in-session (&optional arg info)
  391. "Load the body of the current source-code block.
  392. Evaluate the header arguments for the source block before
  393. entering the session. After loading the body this pops open the
  394. session."
  395. (interactive)
  396. (let* ((info (or info (org-babel-get-src-block-info)))
  397. (lang (nth 0 info))
  398. (params (nth 2 info))
  399. (body (setf (nth 1 info)
  400. (if (and (cdr (assoc :noweb params))
  401. (string= "yes" (cdr (assoc :noweb params))))
  402. (org-babel-expand-noweb-references info)
  403. (nth 1 info))))
  404. (session (cdr (assoc :session params)))
  405. (dir (cdr (assoc :dir params)))
  406. (default-directory
  407. (or (and dir (file-name-as-directory dir)) default-directory))
  408. (cmd (intern (concat "org-babel-load-session:" lang))))
  409. (unless (fboundp cmd)
  410. (error "No org-babel-load-session function for %s!" lang))
  411. (pop-to-buffer (funcall cmd session body params))
  412. (end-of-line 1)))
  413. ;;;###autoload
  414. (defun org-babel-initiate-session (&optional arg info)
  415. "Initiate session for current code block.
  416. If called with a prefix argument then evaluate the header arguments
  417. for the code block before entering the session. Copy the body
  418. of the code block to the kill ring."
  419. (interactive "P")
  420. (let* ((info (or info (org-babel-get-src-block-info)))
  421. (lang (nth 0 info))
  422. (body (nth 1 info))
  423. (params (nth 2 info))
  424. (session (cdr (assoc :session params)))
  425. (dir (cdr (assoc :dir params)))
  426. (default-directory
  427. (or (and dir (file-name-as-directory dir)) default-directory))
  428. (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
  429. (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
  430. (if (and (stringp session) (string= session "none"))
  431. (error "This block is not using a session!"))
  432. (unless (fboundp init-cmd)
  433. (error "No org-babel-initiate-session function for %s!" lang))
  434. (with-temp-buffer (insert (org-babel-trim body))
  435. (copy-region-as-kill (point-min) (point-max)))
  436. (when arg
  437. (unless (fboundp prep-cmd)
  438. (error "No org-babel-prep-session function for %s!" lang))
  439. (funcall prep-cmd session params))
  440. (funcall init-cmd session params)))
  441. ;;;###autoload
  442. (defun org-babel-switch-to-session (&optional arg info)
  443. "Switch to the session of the current code block.
  444. Uses `org-babel-initiate-session' to start the session. If called
  445. with a prefix argument then this is passed on to
  446. `org-babel-initiate-session'."
  447. (interactive "P")
  448. (pop-to-buffer (org-babel-initiate-session arg info))
  449. (end-of-line 1))
  450. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  451. ;;;###autoload
  452. (defun org-babel-switch-to-session-with-code (&optional arg info)
  453. "Switch to code buffer and display session."
  454. (interactive "P")
  455. (flet ((swap-windows
  456. ()
  457. (let ((other-window-buffer (window-buffer (next-window))))
  458. (set-window-buffer (next-window) (current-buffer))
  459. (set-window-buffer (selected-window) other-window-buffer))
  460. (other-window 1)))
  461. (let ((info (org-babel-get-src-block-info))
  462. (org-src-window-setup 'reorganize-frame))
  463. (save-excursion
  464. (org-babel-switch-to-session arg info))
  465. (org-edit-src-code))
  466. (swap-windows)))
  467. (defmacro org-babel-do-in-edit-buffer (&rest body)
  468. "Evaluate BODY in edit buffer if there is a code block at point.
  469. Return t if a code block was found at point, nil otherwise."
  470. `(let ((org-src-window-setup 'switch-invisibly))
  471. (when (and (org-babel-where-is-src-block-head)
  472. (org-edit-src-code nil nil nil 'quietly))
  473. (unwind-protect (progn ,@body)
  474. (if (org-bound-and-true-p org-edit-src-from-org-mode)
  475. (org-edit-src-exit)))
  476. t)))
  477. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  478. "Read key sequence and execute the command in edit buffer.
  479. Enter a key sequence to be executed in the language major-mode
  480. edit buffer. For example, TAB will alter the contents of the
  481. Org-mode code block according to the effect of TAB in the
  482. language major-mode buffer. For languages that support
  483. interactive sessions, this can be used to send code from the Org
  484. buffer to the session for evaluation using the native major-mode
  485. evaluation mechanisms."
  486. (interactive "kEnter key-sequence to execute in edit buffer: ")
  487. (org-babel-do-in-edit-buffer
  488. (call-interactively
  489. (key-binding (or key (read-key-sequence nil))))))
  490. (defvar org-bracket-link-regexp)
  491. ;;;###autoload
  492. (defun org-babel-open-src-block-result (&optional re-run)
  493. "If `point' is on a src block then open the results of the
  494. source code block, otherwise return nil. With optional prefix
  495. argument RE-RUN the source-code block is evaluated even if
  496. results already exist."
  497. (interactive "P")
  498. (when (org-babel-get-src-block-info)
  499. (save-excursion
  500. ;; go to the results, if there aren't any then run the block
  501. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  502. (progn (org-babel-execute-src-block)
  503. (org-babel-where-is-src-block-result))))
  504. (end-of-line 1)
  505. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  506. ;; open the results
  507. (if (looking-at org-bracket-link-regexp)
  508. ;; file results
  509. (org-open-at-point)
  510. (let ((results (org-babel-read-result)))
  511. (flet ((echo-res (result)
  512. (if (stringp result) result (format "%S" result))))
  513. (pop-to-buffer (get-buffer-create "org-babel-results"))
  514. (delete-region (point-min) (point-max))
  515. (if (listp results)
  516. ;; table result
  517. (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
  518. ;; scalar result
  519. (insert (echo-res results))))))
  520. t)))
  521. ;;;###autoload
  522. (defun org-babel-execute-buffer (&optional arg)
  523. "Execute source code blocks in a buffer.
  524. Call `org-babel-execute-src-block' on every source block in
  525. the current buffer."
  526. (interactive "P")
  527. (org-save-outline-visibility t
  528. (org-babel-map-src-blocks nil
  529. (org-babel-execute-src-block arg))))
  530. ;;;###autoload
  531. (defun org-babel-execute-subtree (&optional arg)
  532. "Execute source code blocks in a subtree.
  533. Call `org-babel-execute-src-block' on every source block in
  534. the current subtree."
  535. (interactive "P")
  536. (save-restriction
  537. (save-excursion
  538. (org-narrow-to-subtree)
  539. (org-babel-execute-buffer arg)
  540. (widen))))
  541. ;;;###autoload
  542. (defun org-babel-sha1-hash (&optional info)
  543. "Generate an sha1 hash based on the value of info."
  544. (interactive)
  545. (let* ((info (or info (org-babel-get-src-block-info)))
  546. (hash (sha1
  547. (format "%s-%s"
  548. (mapconcat
  549. (lambda (arg)
  550. (if (stringp (cdr arg))
  551. (mapconcat
  552. #'identity
  553. (sort (split-string (cdr arg)) #'string<) " ")
  554. (cdr arg)))
  555. (nth 2 info) ":")
  556. (nth 1 info)))))
  557. (when (interactive-p) (message hash))
  558. hash))
  559. (defun org-babel-result-hash (&optional info)
  560. "Return the in-buffer hash associated with INFO."
  561. (org-babel-where-is-src-block-result nil info)
  562. (org-babel-clean-text-properties (match-string 3)))
  563. (defun org-babel-hide-hash ()
  564. "Hide the hash in the current results line.
  565. Only the initial `org-babel-hash-show' characters of the hash
  566. will remain visible."
  567. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  568. (save-excursion
  569. (when (and (re-search-forward org-babel-result-regexp nil t)
  570. (match-string 3))
  571. (let* ((start (match-beginning 3))
  572. (hide-start (+ org-babel-hash-show start))
  573. (end (match-end 3))
  574. (hash (match-string 3))
  575. ov1 ov2)
  576. (setq ov1 (make-overlay start hide-start))
  577. (setq ov2 (make-overlay hide-start end))
  578. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  579. (overlay-put ov1 'babel-hash hash)))))
  580. (defun org-babel-hide-all-hashes ()
  581. "Hide the hash in the current buffer.
  582. Only the initial `org-babel-hash-show' characters of each hash
  583. will remain visible. This function should be called as part of
  584. the `org-mode-hook'."
  585. (save-excursion
  586. (while (re-search-forward org-babel-result-regexp nil t)
  587. (goto-char (match-beginning 0))
  588. (org-babel-hide-hash)
  589. (goto-char (match-end 0)))))
  590. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  591. (defun org-babel-hash-at-point (&optional point)
  592. "Return the value of the hash at POINT.
  593. The hash is also added as the last element of the kill ring.
  594. This can be called with C-c C-c."
  595. (interactive)
  596. (let ((hash (car (delq nil (mapcar
  597. (lambda (ol) (overlay-get ol 'babel-hash))
  598. (overlays-at (or point (point))))))))
  599. (when hash (kill-new hash) (message hash))))
  600. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  601. (defun org-babel-result-hide-spec ()
  602. "Hide portions of results lines.
  603. Add `org-babel-hide-result' as an invisibility spec for hiding
  604. portions of results lines."
  605. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  606. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  607. (defvar org-babel-hide-result-overlays nil
  608. "Overlays hiding results.")
  609. (defun org-babel-result-hide-all ()
  610. "Fold all results in the current buffer."
  611. (interactive)
  612. (org-babel-show-result-all)
  613. (save-excursion
  614. (while (re-search-forward org-babel-result-regexp nil t)
  615. (save-excursion (goto-char (match-beginning 0))
  616. (org-babel-hide-result-toggle-maybe)))))
  617. (defun org-babel-show-result-all ()
  618. "Unfold all results in the current buffer."
  619. (mapc 'delete-overlay org-babel-hide-result-overlays)
  620. (setq org-babel-hide-result-overlays nil))
  621. ;;;###autoload
  622. (defun org-babel-hide-result-toggle-maybe ()
  623. "Toggle visibility of result at point."
  624. (interactive)
  625. (let ((case-fold-search t))
  626. (if (save-excursion
  627. (beginning-of-line 1)
  628. (looking-at org-babel-result-regexp))
  629. (progn (org-babel-hide-result-toggle)
  630. t) ;; to signal that we took action
  631. nil))) ;; to signal that we did not
  632. (defun org-babel-hide-result-toggle (&optional force)
  633. "Toggle the visibility of the current result."
  634. (interactive)
  635. (save-excursion
  636. (beginning-of-line)
  637. (if (re-search-forward org-babel-result-regexp nil t)
  638. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  639. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  640. ov)
  641. (if (memq t (mapcar (lambda (overlay)
  642. (eq (overlay-get overlay 'invisible)
  643. 'org-babel-hide-result))
  644. (overlays-at start)))
  645. (if (or (not force) (eq force 'off))
  646. (mapc (lambda (ov)
  647. (when (member ov org-babel-hide-result-overlays)
  648. (setq org-babel-hide-result-overlays
  649. (delq ov org-babel-hide-result-overlays)))
  650. (when (eq (overlay-get ov 'invisible)
  651. 'org-babel-hide-result)
  652. (delete-overlay ov)))
  653. (overlays-at start)))
  654. (setq ov (make-overlay start end))
  655. (overlay-put ov 'invisible 'org-babel-hide-result)
  656. ;; make the block accessible to isearch
  657. (overlay-put
  658. ov 'isearch-open-invisible
  659. (lambda (ov)
  660. (when (member ov org-babel-hide-result-overlays)
  661. (setq org-babel-hide-result-overlays
  662. (delq ov org-babel-hide-result-overlays)))
  663. (when (eq (overlay-get ov 'invisible)
  664. 'org-babel-hide-result)
  665. (delete-overlay ov))))
  666. (push ov org-babel-hide-result-overlays)))
  667. (error "Not looking at a result line"))))
  668. ;; org-tab-after-check-for-cycling-hook
  669. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  670. ;; Remove overlays when changing major mode
  671. (add-hook 'org-mode-hook
  672. (lambda () (org-add-hook 'change-major-mode-hook
  673. 'org-babel-show-result-all 'append 'local)))
  674. (defmacro org-babel-map-src-blocks (file &rest body)
  675. "Evaluate BODY forms on each source-block in FILE.
  676. If FILE is nil evaluate BODY forms on source blocks in current
  677. buffer. During evaluation of BODY the following local variables
  678. are set relative to the currently matched code block.
  679. full-block ------- string holding the entirety of the code block
  680. beg-block -------- point at the beginning of the code block
  681. end-block -------- point at the end of the matched code block
  682. lang ------------- string holding the language of the code block
  683. beg-lang --------- point at the beginning of the lang
  684. end-lang --------- point at the end of the lang
  685. switches --------- string holding the switches
  686. beg-switches ----- point at the beginning of the switches
  687. end-switches ----- point at the end of the switches
  688. header-args ------ string holding the header-args
  689. beg-header-args -- point at the beginning of the header-args
  690. end-header-args -- point at the end of the header-args
  691. body ------------- string holding the body of the code block
  692. beg-body --------- point at the beginning of the body
  693. end-body --------- point at the end of the body"
  694. (declare (indent 1))
  695. `(let ((visited-p (or (null ,file)
  696. (get-file-buffer (expand-file-name ,file))))
  697. (point (point)) to-be-removed)
  698. (save-window-excursion
  699. (when ,file (find-file ,file))
  700. (setq to-be-removed (current-buffer))
  701. (goto-char (point-min))
  702. (while (re-search-forward org-babel-src-block-regexp nil t)
  703. (goto-char (match-beginning 0))
  704. (let ((full-block (match-string 0))
  705. (beg-block (match-beginning 0))
  706. (end-block (match-end 0))
  707. (lang (match-string 2))
  708. (beg-lang (match-beginning 2))
  709. (end-lang (match-end 2))
  710. (switches (match-string 3))
  711. (beg-switches (match-beginning 3))
  712. (end-switches (match-end 3))
  713. (header-args (match-string 4))
  714. (beg-header-args (match-beginning 4))
  715. (end-header-args (match-end 4))
  716. (body (match-string 5))
  717. (beg-body (match-beginning 5))
  718. (end-body (match-end 5)))
  719. (save-match-data ,@body))
  720. (goto-char (match-end 0))))
  721. (unless visited-p
  722. (kill-buffer to-be-removed))
  723. (goto-char point)))
  724. (defvar org-file-properties)
  725. (defun org-babel-params-from-properties (&optional lang)
  726. "Retrieve parameters specified as properties.
  727. Return an association list of any source block params which
  728. may be specified in the properties of the current outline entry."
  729. (save-match-data
  730. (let (val sym)
  731. (delq nil
  732. (mapcar
  733. (lambda (header-arg)
  734. (and (setq val
  735. (or (condition-case nil
  736. (org-entry-get (point) header-arg t)
  737. (error nil))
  738. (cdr (assoc header-arg org-file-properties))))
  739. (cons (intern (concat ":" header-arg))
  740. (org-babel-read val))))
  741. (mapcar
  742. 'symbol-name
  743. (append
  744. org-babel-header-arg-names
  745. (progn
  746. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  747. (and (boundp sym) (eval sym))))))))))
  748. (defun org-babel-params-from-buffer ()
  749. "Retrieve per-buffer parameters.
  750. Return an association list of any source block params which
  751. may be specified at the top of the current buffer."
  752. (or org-babel-current-buffer-properties
  753. (setq org-babel-current-buffer-properties
  754. (save-match-data
  755. (save-excursion
  756. (save-restriction
  757. (widen)
  758. (goto-char (point-min))
  759. (when (re-search-forward
  760. (org-make-options-regexp (list "BABEL")) nil t)
  761. (org-babel-parse-header-arguments
  762. (org-match-string-no-properties 2)))))))))
  763. (defvar org-src-preserve-indentation)
  764. (defun org-babel-parse-src-block-match ()
  765. "Parse the results from a match of the `org-babel-src-block-regexp'."
  766. (let* ((block-indentation (length (match-string 1)))
  767. (lang (org-babel-clean-text-properties (match-string 2)))
  768. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  769. (switches (match-string 3))
  770. (body (org-babel-clean-text-properties (match-string 5)))
  771. (preserve-indentation (or org-src-preserve-indentation
  772. (string-match "-i\\>" switches))))
  773. (list lang
  774. ;; get block body less properties, protective commas, and indentation
  775. (with-temp-buffer
  776. (save-match-data
  777. (insert (org-babel-strip-protective-commas body))
  778. (unless preserve-indentation (org-do-remove-indentation))
  779. (buffer-string)))
  780. (org-babel-merge-params
  781. org-babel-default-header-args
  782. (org-babel-params-from-buffer)
  783. (org-babel-params-from-properties lang)
  784. (if (boundp lang-headers) (eval lang-headers) nil)
  785. (org-babel-parse-header-arguments
  786. (org-babel-clean-text-properties (or (match-string 4) ""))))
  787. switches
  788. block-indentation)))
  789. (defun org-babel-parse-inline-src-block-match ()
  790. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  791. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  792. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  793. (list lang
  794. (org-babel-strip-protective-commas
  795. (org-babel-clean-text-properties (match-string 5)))
  796. (org-babel-merge-params
  797. org-babel-default-inline-header-args
  798. (org-babel-params-from-buffer)
  799. (org-babel-params-from-properties lang)
  800. (if (boundp lang-headers) (eval lang-headers) nil)
  801. (org-babel-parse-header-arguments
  802. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  803. (defun org-babel-parse-header-arguments (arg-string)
  804. "Parse a string of header arguments returning an alist."
  805. (if (> (length arg-string) 0)
  806. (delq nil
  807. (mapcar
  808. (lambda (arg)
  809. (if (string-match
  810. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  811. arg)
  812. (cons (intern (concat ":" (match-string 1 arg)))
  813. (org-babel-read (org-babel-chomp (match-string 2 arg))))
  814. (cons (intern (concat ":" arg)) nil)))
  815. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  816. (defun org-babel-process-params (params)
  817. "Expand variables in PARAMS and add summary parameters."
  818. (let ((vars-and-names (org-babel-disassemble-tables
  819. (mapcar
  820. (lambda (el) (cons :var (if (consp (cdr el))
  821. (cdr el)
  822. (org-babel-ref-parse (cdr el)))))
  823. (org-babel-get-header params :var))
  824. (cdr (assoc :hlines params))
  825. (cdr (assoc :colnames params))
  826. (cdr (assoc :rownames params))))
  827. (result-params (split-string (or (cdr (assoc :results params)) ""))))
  828. (append
  829. (car vars-and-names)
  830. (list
  831. (cons :colname-names (cadr vars-and-names))
  832. (cons :rowname-names (caddr vars-and-names))
  833. (cons :result-params result-params)
  834. (cons :results-type (cond ((member "output" result-params) 'output)
  835. ((member "value" result-params) 'value)
  836. (t 'value))))
  837. (org-babel-get-header params :var 'other))))
  838. ;; row and column names
  839. (defun org-babel-del-hlines (table)
  840. "Remove all 'hlines from TABLE."
  841. (remove 'hline table))
  842. (defun org-babel-get-colnames (table)
  843. "Return the column names of TABLE.
  844. Return a cons cell, the `car' of which contains the TABLE less
  845. colnames, and the `cdr' of which contains a list of the column
  846. names."
  847. (if (equal 'hline (nth 1 table))
  848. (cons (cddr table) (car table))
  849. (cons (cdr table) (car table))))
  850. (defun org-babel-get-rownames (table)
  851. "Return the row names of TABLE.
  852. Return a cons cell, the `car' of which contains the TABLE less
  853. colnames, and the `cdr' of which contains a list of the column
  854. names. Note: this function removes any hlines in TABLE."
  855. (flet ((trans (table) (apply #'mapcar* #'list table)))
  856. (let* ((width (apply 'max
  857. (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  858. (table (trans (mapcar (lambda (row)
  859. (if (not (equal row 'hline))
  860. row
  861. (setq row '())
  862. (dotimes (n width)
  863. (setq row (cons 'hline row)))
  864. row))
  865. table))))
  866. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  867. (trans (cdr table)))
  868. (remove 'hline (car table))))))
  869. (defun org-babel-put-colnames (table colnames)
  870. "Add COLNAMES to TABLE if they exist."
  871. (if colnames (apply 'list colnames 'hline table) table))
  872. (defun org-babel-put-rownames (table rownames)
  873. "Add ROWNAMES to TABLE if they exist."
  874. (if rownames
  875. (mapcar (lambda (row)
  876. (if (listp row)
  877. (cons (or (pop rownames) "") row)
  878. row)) table)
  879. table))
  880. (defun org-babel-pick-name (names selector)
  881. "Select one out of an alist of row or column names.
  882. SELECTOR can be either a list of names in which case those names
  883. will be returned directly, or an index into the list NAMES in
  884. which case the indexed names will be return."
  885. (if (listp selector)
  886. selector
  887. (when names
  888. (if (and selector (symbolp selector) (not (equal t selector)))
  889. (cdr (assoc selector names))
  890. (if (integerp selector)
  891. (nth (- selector 1) names)
  892. (cdr (car (last names))))))))
  893. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  894. "Parse tables for further processing.
  895. Process the variables in VARS according to the HLINES,
  896. ROWNAMES and COLNAMES header arguments. Return a list consisting
  897. of the vars, cnames and rnames."
  898. (let (cnames rnames)
  899. (list
  900. (mapcar
  901. (lambda (var)
  902. (when (listp (cdr var))
  903. (when (and (not (equal colnames "no"))
  904. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  905. (not (member 'hline (cddr (cdr var)))))))
  906. (let ((both (org-babel-get-colnames (cdr var))))
  907. (setq cnames (cons (cons (car var) (cdr both))
  908. cnames))
  909. (setq var (cons (car var) (car both)))))
  910. (when (and rownames (not (equal rownames "no")))
  911. (let ((both (org-babel-get-rownames (cdr var))))
  912. (setq rnames (cons (cons (car var) (cdr both))
  913. rnames))
  914. (setq var (cons (car var) (car both)))))
  915. (when (and hlines (not (equal hlines "yes")))
  916. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  917. var)
  918. vars)
  919. cnames rnames)))
  920. (defun org-babel-reassemble-table (table colnames rownames)
  921. "Add column and row names to a table.
  922. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  923. to the table for reinsertion to org-mode."
  924. (if (listp table)
  925. ((lambda (table)
  926. (if (and colnames (listp (car table)) (= (length (car table))
  927. (length colnames)))
  928. (org-babel-put-colnames table colnames) table))
  929. (if (and rownames (= (length table) (length rownames)))
  930. (org-babel-put-rownames table rownames) table))
  931. table))
  932. (defun org-babel-where-is-src-block-head ()
  933. "Find where the current source block begins.
  934. Return the point at the beginning of the current source
  935. block. Specifically at the beginning of the #+BEGIN_SRC line.
  936. If the point is not on a source block then return nil."
  937. (let ((initial (point)) top bottom)
  938. (or
  939. (save-excursion ;; on a source name line
  940. (beginning-of-line 1)
  941. (and (looking-at org-babel-src-name-regexp) (forward-line 1)
  942. (looking-at org-babel-src-block-regexp)
  943. (point)))
  944. (save-excursion ;; on a #+begin_src line
  945. (beginning-of-line 1)
  946. (and (looking-at org-babel-src-block-regexp)
  947. (point)))
  948. (save-excursion ;; inside a src block
  949. (and
  950. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  951. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  952. (< top initial) (< initial bottom)
  953. (progn (goto-char top) (beginning-of-line 1)
  954. (looking-at org-babel-src-block-regexp))
  955. (point))))))
  956. ;;;###autoload
  957. (defun org-babel-goto-src-block-head ()
  958. "Go to the beginning of the current code block."
  959. (interactive)
  960. ((lambda (head)
  961. (if head (goto-char head) (error "not currently in a code block")))
  962. (org-babel-where-is-src-block-head)))
  963. ;;;###autoload
  964. (defun org-babel-goto-named-src-block (name)
  965. "Go to a named source-code block."
  966. (interactive
  967. (let ((completion-ignore-case t))
  968. (list (org-icompleting-read "source-block name: "
  969. (org-babel-src-block-names) nil t))))
  970. (let ((point (org-babel-find-named-block name)))
  971. (if point
  972. ;; taken from `org-open-at-point'
  973. (progn (goto-char point) (org-show-context))
  974. (message "source-code block '%s' not found in this buffer" name))))
  975. (defun org-babel-find-named-block (name)
  976. "Find a named source-code block.
  977. Return the location of the source block identified by source
  978. NAME, or nil if no such block exists. Set match data according to
  979. org-babel-named-src-block-regexp."
  980. (save-excursion
  981. (let ((case-fold-search t)
  982. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  983. (goto-char (point-min))
  984. (when (or (re-search-forward regexp nil t)
  985. (re-search-backward regexp nil t))
  986. (match-beginning 0)))))
  987. (defun org-babel-src-block-names (&optional file)
  988. "Returns the names of source blocks in FILE or the current buffer."
  989. (save-excursion
  990. (when file (find-file file)) (goto-char (point-min))
  991. (let (names)
  992. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  993. (setq names (cons (org-babel-clean-text-properties (match-string 3))
  994. names)))
  995. names)))
  996. ;;;###autoload
  997. (defun org-babel-goto-named-result (name)
  998. "Go to a named result."
  999. (interactive
  1000. (let ((completion-ignore-case t))
  1001. (list (org-icompleting-read "source-block name: "
  1002. (org-babel-result-names) nil t))))
  1003. (let ((point (org-babel-find-named-result name)))
  1004. (if point
  1005. ;; taken from `org-open-at-point'
  1006. (progn (goto-char point) (org-show-context))
  1007. (message "result '%s' not found in this buffer" name))))
  1008. (defun org-babel-find-named-result (name)
  1009. "Find a named result.
  1010. Return the location of the result named NAME in the current
  1011. buffer or nil if no such result exists."
  1012. (save-excursion
  1013. (goto-char (point-min))
  1014. (when (re-search-forward
  1015. (concat org-babel-result-regexp
  1016. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  1017. (beginning-of-line 0) (point))))
  1018. (defun org-babel-result-names (&optional file)
  1019. "Returns the names of results in FILE or the current buffer."
  1020. (save-excursion
  1021. (when file (find-file file)) (goto-char (point-min))
  1022. (let (names)
  1023. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1024. (setq names (cons (org-babel-clean-text-properties (match-string 4))
  1025. names)))
  1026. names)))
  1027. ;;;###autoload
  1028. (defun org-babel-next-src-block (&optional arg)
  1029. "Jump to the next source block.
  1030. With optional prefix argument ARG, jump forward ARG many source blocks."
  1031. (interactive "P")
  1032. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  1033. (condition-case nil
  1034. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  1035. (error (error "No further code blocks")))
  1036. (goto-char (match-beginning 0)) (org-show-context))
  1037. ;;;###autoload
  1038. (defun org-babel-previous-src-block (&optional arg)
  1039. "Jump to the previous source block.
  1040. With optional prefix argument ARG, jump backward ARG many source blocks."
  1041. (interactive "P")
  1042. (condition-case nil
  1043. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  1044. (error (error "No previous code blocks")))
  1045. (goto-char (match-beginning 0)) (org-show-context))
  1046. (defvar org-babel-load-languages)
  1047. ;;;###autoload
  1048. (defun org-babel-mark-block ()
  1049. "Mark current src block"
  1050. (interactive)
  1051. ((lambda (head)
  1052. (when head
  1053. (save-excursion
  1054. (goto-char head)
  1055. (looking-at org-babel-src-block-regexp))
  1056. (push-mark (match-end 5) nil t)
  1057. (goto-char (match-beginning 5))))
  1058. (org-babel-where-is-src-block-head)))
  1059. (defun org-babel-demarcate-block (&optional arg)
  1060. "Wrap or split the code in the region or on the point.
  1061. When called from inside of a code block the current block is
  1062. split. When called from outside of a code block a new code block
  1063. is created. In both cases if the region is demarcated and if the
  1064. region is not active then the point is demarcated."
  1065. (interactive "P")
  1066. (let ((info (org-babel-get-src-block-info))
  1067. (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
  1068. (if info
  1069. (mapc
  1070. (lambda (place)
  1071. (save-excursion
  1072. (goto-char place)
  1073. (let ((lang (nth 0 info))
  1074. (indent (make-string (nth 6 info) ? )))
  1075. (when (string-match "^[[:space:]]*$"
  1076. (buffer-substring (point-at-bol)
  1077. (point-at-eol)))
  1078. (delete-region (point-at-bol) (point-at-eol)))
  1079. (insert (concat (if (looking-at "^") "" "\n")
  1080. indent "#+end_src\n"
  1081. (if arg stars indent) "\n"
  1082. indent "#+begin_src " lang
  1083. (if (looking-at "[\n\r]") "" "\n")))))
  1084. (move-end-of-line 2))
  1085. (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
  1086. (let ((start (point))
  1087. (lang (org-icompleting-read "Lang: "
  1088. (mapcar (lambda (el) (symbol-name (car el)))
  1089. org-babel-load-languages)))
  1090. (body (delete-and-extract-region
  1091. (if (region-active-p) (mark) (point)) (point))))
  1092. (insert (concat (if (looking-at "^") "" "\n")
  1093. (if arg (concat stars "\n") "")
  1094. "#+begin_src " lang "\n"
  1095. body
  1096. (if (or (= (length body) 0)
  1097. (string-match "[\r\n]$" body)) "" "\n")
  1098. "#+end_src\n"))
  1099. (goto-char start) (move-end-of-line 1)))))
  1100. (defvar org-babel-lob-one-liner-regexp)
  1101. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1102. "Find where the current source block results begin.
  1103. Return the point at the beginning of the result of the current
  1104. source block. Specifically at the beginning of the results line.
  1105. If no result exists for this block then create a results line
  1106. following the source block."
  1107. (save-excursion
  1108. (let* ((on-lob-line (progn (beginning-of-line 1)
  1109. (looking-at org-babel-lob-one-liner-regexp)))
  1110. (name (if on-lob-line
  1111. (nth 0 (org-babel-lob-get-info))
  1112. (nth 4 (or info (org-babel-get-src-block-info)))))
  1113. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1114. found beg end)
  1115. (when head (goto-char head))
  1116. (setq
  1117. found ;; was there a result (before we potentially insert one)
  1118. (or
  1119. (and
  1120. ;; named results:
  1121. ;; - return t if it is found, else return nil
  1122. ;; - if it does not need to be rebuilt, then don't set end
  1123. ;; - if it does need to be rebuilt then do set end
  1124. name (setq beg (org-babel-find-named-result name))
  1125. (prog1 beg
  1126. (when (and hash (not (string= hash (match-string 3))))
  1127. (goto-char beg) (setq end beg) ;; beginning of result
  1128. (forward-line 1)
  1129. (delete-region end (org-babel-result-end)) nil)))
  1130. (and
  1131. ;; unnamed results:
  1132. ;; - return t if it is found, else return nil
  1133. ;; - if it is found, and the hash doesn't match, delete and set end
  1134. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1135. (progn (end-of-line 1)
  1136. (if (eobp) (insert "\n") (forward-char 1))
  1137. (setq end (point))
  1138. (or (and (not name)
  1139. (progn ;; unnamed results line already exists
  1140. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1141. (beginning-of-line 1)
  1142. (looking-at
  1143. (concat org-babel-result-regexp "\n")))
  1144. (prog1 (point)
  1145. ;; must remove and rebuild if hash!=old-hash
  1146. (if (and hash (not (string= hash (match-string 3))))
  1147. (prog1 nil
  1148. (forward-line 1)
  1149. (delete-region
  1150. end (org-babel-result-end)))
  1151. (setq end nil)))))))))
  1152. (if (and insert end)
  1153. (progn
  1154. (goto-char end)
  1155. (unless beg
  1156. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1157. (insert (concat
  1158. (if indent
  1159. (mapconcat
  1160. (lambda (el) " ")
  1161. (org-number-sequence 1 indent) "")
  1162. "")
  1163. "#+results"
  1164. (when hash (concat "["hash"]"))
  1165. ":"
  1166. (when name (concat " " name)) "\n"))
  1167. (unless beg (insert "\n") (backward-char))
  1168. (beginning-of-line 0)
  1169. (if hash (org-babel-hide-hash))
  1170. (point))
  1171. found))))
  1172. (defvar org-block-regexp)
  1173. (defun org-babel-read-result ()
  1174. "Read the result at `point' into emacs-lisp."
  1175. (let ((case-fold-search t) result-string)
  1176. (cond
  1177. ((org-at-table-p) (org-babel-read-table))
  1178. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1179. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1180. ((looking-at "^[ \t]*: ")
  1181. (setq result-string
  1182. (org-babel-trim
  1183. (mapconcat (lambda (line)
  1184. (if (and (> (length line) 1)
  1185. (string-match "^[ \t]*: \\(.+\\)" line))
  1186. (match-string 1 line)
  1187. line))
  1188. (split-string
  1189. (buffer-substring
  1190. (point) (org-babel-result-end)) "[\r\n]+")
  1191. "\n")))
  1192. (or (org-babel-number-p result-string) result-string))
  1193. ((looking-at org-babel-result-regexp)
  1194. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1195. (defun org-babel-read-table ()
  1196. "Read the table at `point' into emacs-lisp."
  1197. (mapcar (lambda (row)
  1198. (if (and (symbolp row) (equal row 'hline)) row
  1199. (mapcar #'org-babel-read row)))
  1200. (org-table-to-lisp)))
  1201. (defvar org-link-types-re)
  1202. (defun org-babel-read-link ()
  1203. "Read the link at `point' into emacs-lisp.
  1204. If the path of the link is a file path it is expanded using
  1205. `expand-file-name'."
  1206. (let* ((case-fold-search t)
  1207. (raw (and (looking-at org-bracket-link-regexp)
  1208. (org-babel-clean-text-properties (match-string 1))))
  1209. (type (and (string-match org-link-types-re raw)
  1210. (match-string 1 raw))))
  1211. (cond
  1212. ((not type) (expand-file-name raw))
  1213. ((string= type "file")
  1214. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1215. (expand-file-name (match-string 2 raw))))
  1216. (t raw))))
  1217. (defun org-babel-insert-result
  1218. (result &optional result-params info hash indent lang)
  1219. "Insert RESULT into the current buffer.
  1220. By default RESULT is inserted after the end of the
  1221. current source block. With optional argument RESULT-PARAMS
  1222. controls insertion of results in the org-mode file.
  1223. RESULT-PARAMS can take the following values...
  1224. replace - (default option) insert results after the source block
  1225. replacing any previously inserted results
  1226. silent -- no results are inserted
  1227. file ---- the results are interpreted as a file path, and are
  1228. inserted into the buffer using the Org-mode file syntax
  1229. raw ----- results are added directly to the org-mode file. This
  1230. is a good option if you code block will output org-mode
  1231. formatted text.
  1232. org ----- similar in effect to raw, only the results are wrapped
  1233. in an org code block. Similar to the raw option, on
  1234. export the results will be interpreted as org-formatted
  1235. text, however by wrapping the results in an org code
  1236. block they can be replaced upon re-execution of the
  1237. code block.
  1238. html ---- results are added inside of a #+BEGIN_HTML block. This
  1239. is a good option if you code block will output html
  1240. formatted text.
  1241. latex --- results are added inside of a #+BEGIN_LATEX block.
  1242. This is a good option if you code block will output
  1243. latex formatted text.
  1244. code ---- the results are extracted in the syntax of the source
  1245. code of the language being evaluated and are added
  1246. inside of a #+BEGIN_SRC block with the source-code
  1247. language set appropriately. Note this relies on the
  1248. optional LANG argument."
  1249. (if (stringp result)
  1250. (progn
  1251. (setq result (org-babel-clean-text-properties result))
  1252. (when (member "file" result-params)
  1253. (setq result (org-babel-result-to-file result))))
  1254. (unless (listp result) (setq result (format "%S" result))))
  1255. (if (and result-params (member "silent" result-params))
  1256. (progn
  1257. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1258. result)
  1259. (when (and (stringp result) ;; ensure results end in a newline
  1260. (> (length result) 0)
  1261. (not (or (string-equal (substring result -1) "\n")
  1262. (string-equal (substring result -1) "\r"))))
  1263. (setq result (concat result "\n")))
  1264. (save-excursion
  1265. (let ((existing-result (org-babel-where-is-src-block-result
  1266. t info hash indent))
  1267. (results-switches
  1268. (cdr (assoc :results_switches (nth 2 info))))
  1269. beg end)
  1270. (if (not existing-result)
  1271. (setq beg (point))
  1272. (goto-char existing-result)
  1273. (save-excursion
  1274. (re-search-forward "#" nil t)
  1275. (setq indent (- (current-column) 1)))
  1276. (forward-line 1)
  1277. (setq beg (point))
  1278. (cond
  1279. ((member "replace" result-params)
  1280. (delete-region (point) (org-babel-result-end)))
  1281. ((member "append" result-params)
  1282. (goto-char (org-babel-result-end)) (setq beg (point)))
  1283. ((member "prepend" result-params) ;; already there
  1284. )))
  1285. (setq results-switches
  1286. (if results-switches (concat " " results-switches) ""))
  1287. (cond
  1288. ;; do nothing for an empty result
  1289. ((= (length result) 0))
  1290. ;; assume the result is a table if it's not a string
  1291. ((not (stringp result))
  1292. (insert (concat (orgtbl-to-orgtbl
  1293. (if (or (eq 'hline (car result))
  1294. (and (listp (car result))
  1295. (listp (cdr (car result)))))
  1296. result (list result))
  1297. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1298. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1299. ((member "file" result-params)
  1300. (insert result))
  1301. ((member "html" result-params)
  1302. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
  1303. results-switches result)))
  1304. ((member "latex" result-params)
  1305. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
  1306. results-switches result)))
  1307. ((member "code" result-params)
  1308. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
  1309. (or lang "none") results-switches result)))
  1310. ((member "org" result-params)
  1311. (insert (format "#+BEGIN_SRC org\n%s#+END_SRC\n" result)))
  1312. ((member "raw" result-params)
  1313. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  1314. (t
  1315. (org-babel-examplize-region
  1316. (point) (progn (insert result) (point)) results-switches)))
  1317. ;; possibly indent the results to match the #+results line
  1318. (setq end (if (listp result) (org-table-end) (point)))
  1319. (when (and indent (> indent 0)
  1320. ;; in this case `table-align' does the work for us
  1321. (not (and (listp result)
  1322. (member "append" result-params))))
  1323. (indent-rigidly beg end indent))))
  1324. (if (= (length result) 0)
  1325. (if (member "value" result-params)
  1326. (message "No result returned by source block")
  1327. (message "Source block produced no output"))
  1328. (message "finished"))))
  1329. (defun org-babel-remove-result (&optional info)
  1330. "Remove the result of the current source block."
  1331. (interactive)
  1332. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1333. (when location
  1334. (save-excursion
  1335. (goto-char location) (setq start (point)) (forward-line 1)
  1336. (delete-region start (org-babel-result-end))))))
  1337. (defun org-babel-result-end ()
  1338. "Return the point at the end of the current set of results"
  1339. (save-excursion
  1340. (if (org-at-table-p)
  1341. (progn (goto-char (org-table-end)) (point))
  1342. (let ((case-fold-search t))
  1343. (cond
  1344. ((looking-at "[ \t]*#\\+begin_latex")
  1345. (re-search-forward "[ \t]*#\\+end_latex" nil t)
  1346. (forward-line 1))
  1347. ((looking-at "[ \t]*#\\+begin_html")
  1348. (re-search-forward "[ \t]*#\\+end_html" nil t)
  1349. (forward-line 1))
  1350. ((looking-at "[ \t]*#\\+begin_example")
  1351. (re-search-forward "[ \t]*#\\+end_example" nil t)
  1352. (forward-line 1))
  1353. ((looking-at "[ \t]*#\\+begin_src")
  1354. (re-search-forward "[ \t]*#\\+end_src" nil t)
  1355. (forward-line 1))
  1356. (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1357. (forward-line 1))))))
  1358. (point))))
  1359. (defun org-babel-result-to-file (result)
  1360. "Convert RESULT into an `org-mode' link.
  1361. If the `default-directory' is different from the containing
  1362. file's directory then expand relative links."
  1363. (format
  1364. "[[file:%s]]"
  1365. (if (and default-directory
  1366. buffer-file-name
  1367. (not (string= (expand-file-name default-directory)
  1368. (expand-file-name
  1369. (file-name-directory buffer-file-name)))))
  1370. (expand-file-name result default-directory)
  1371. result)))
  1372. (defun org-babel-examplize-region (beg end &optional results-switches)
  1373. "Comment out region using the ': ' org example quote."
  1374. (interactive "*r")
  1375. (let ((size (count-lines beg end)))
  1376. (save-excursion
  1377. (cond ((= size 0)
  1378. (error (concat "This should not be impossible:"
  1379. "a newline was appended to result if missing")))
  1380. ((< size org-babel-min-lines-for-block-output)
  1381. (goto-char beg)
  1382. (dotimes (n size)
  1383. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1384. (t
  1385. (goto-char beg)
  1386. (insert (if results-switches
  1387. (format "#+begin_example%s\n" results-switches)
  1388. "#+begin_example\n"))
  1389. (forward-char (- end beg))
  1390. (insert "#+end_example\n"))))))
  1391. (defun org-babel-merge-params (&rest plists)
  1392. "Combine all parameter association lists in PLISTS.
  1393. Later elements of PLISTS override the values of previous element.
  1394. This takes into account some special considerations for certain
  1395. parameters when merging lists."
  1396. (let ((results-exclusive-groups
  1397. '(("file" "vector" "table" "scalar" "raw" "org"
  1398. "html" "latex" "code" "pp")
  1399. ("replace" "silent" "append" "prepend")
  1400. ("output" "value")))
  1401. (exports-exclusive-groups
  1402. '(("code" "results" "both" "none")))
  1403. params results exports tangle noweb cache vars shebang comments)
  1404. (flet ((e-merge (exclusive-groups &rest result-params)
  1405. ;; maintain exclusivity of mutually exclusive parameters
  1406. (let (output)
  1407. (mapc (lambda (new-params)
  1408. (mapc (lambda (new-param)
  1409. (mapc (lambda (exclusive-group)
  1410. (when (member new-param exclusive-group)
  1411. (mapcar (lambda (excluded-param)
  1412. (setq output
  1413. (delete
  1414. excluded-param
  1415. output)))
  1416. exclusive-group)))
  1417. exclusive-groups)
  1418. (setq output (org-uniquify
  1419. (cons new-param output))))
  1420. new-params))
  1421. result-params)
  1422. output)))
  1423. (mapc
  1424. (lambda (plist)
  1425. (mapc
  1426. (lambda (pair)
  1427. (case (car pair)
  1428. (:var
  1429. (let ((name (if (listp (cdr pair))
  1430. (cadr pair)
  1431. (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1432. (cdr pair))
  1433. (intern (match-string 1 (cdr pair)))))))
  1434. (when name
  1435. (setq vars
  1436. (cons (cons name pair)
  1437. (if (member name (mapcar #'car vars))
  1438. (delq nil
  1439. (mapcar
  1440. (lambda (p) (unless (equal (car p) name) p))
  1441. vars))
  1442. vars))))))
  1443. (:results
  1444. (setq results (e-merge results-exclusive-groups
  1445. results (split-string (cdr pair)))))
  1446. (:file
  1447. (when (cdr pair)
  1448. (setq results (e-merge results-exclusive-groups
  1449. results '("file")))
  1450. (unless (or (member "both" exports)
  1451. (member "none" exports)
  1452. (member "code" exports))
  1453. (setq exports (e-merge exports-exclusive-groups
  1454. exports '("results"))))
  1455. (setq params (cons pair (assq-delete-all (car pair) params)))))
  1456. (:exports
  1457. (setq exports (e-merge exports-exclusive-groups
  1458. exports (split-string (cdr pair)))))
  1459. (:tangle ;; take the latest -- always overwrite
  1460. (setq tangle (or (list (cdr pair)) tangle)))
  1461. (:noweb
  1462. (setq noweb (e-merge '(("yes" "no")) noweb
  1463. (split-string (or (cdr pair) "")))))
  1464. (:cache
  1465. (setq cache (e-merge '(("yes" "no")) cache
  1466. (split-string (or (cdr pair) "")))))
  1467. (:shebang ;; take the latest -- always overwrite
  1468. (setq shebang (or (list (cdr pair)) shebang)))
  1469. (:comments
  1470. (setq comments (e-merge '(("yes" "no")) comments
  1471. (split-string (or (cdr pair) "")))))
  1472. (t ;; replace: this covers e.g. :session
  1473. (setq params (cons pair (assq-delete-all (car pair) params))))))
  1474. plist))
  1475. plists))
  1476. (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
  1477. (cons (cons :comments (mapconcat 'identity comments " "))
  1478. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1479. (cons (cons :cache (mapconcat 'identity cache " "))
  1480. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1481. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1482. (cons (cons :exports
  1483. (mapconcat 'identity exports " "))
  1484. (cons
  1485. (cons :results
  1486. (mapconcat 'identity results " "))
  1487. params)))))))))
  1488. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1489. "Expand Noweb references in the body of the current source code block.
  1490. For example the following reference would be replaced with the
  1491. body of the source-code block named 'example-block'.
  1492. <<example-block>>
  1493. Note that any text preceding the <<foo>> construct on a line will
  1494. be interposed between the lines of the replacement text. So for
  1495. example if <<foo>> is placed behind a comment, then the entire
  1496. replacement text will also be commented.
  1497. This function must be called from inside of the buffer containing
  1498. the source-code block which holds BODY.
  1499. In addition the following syntax can be used to insert the
  1500. results of evaluating the source-code block named 'example-block'.
  1501. <<example-block()>>
  1502. Any optional arguments can be passed to example-block by placing
  1503. the arguments inside the parenthesis following the convention
  1504. defined by `org-babel-lob'. For example
  1505. <<example-block(a=9)>>
  1506. would set the value of argument \"a\" equal to \"9\". Note that
  1507. these arguments are not evaluated in the current source-code
  1508. block but are passed literally to the \"example-block\"."
  1509. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1510. (info (or info (org-babel-get-src-block-info)))
  1511. (lang (nth 0 info))
  1512. (body (nth 1 info))
  1513. (new-body "") index source-name evaluate prefix)
  1514. (flet ((nb-add (text)
  1515. (setq new-body (concat new-body text))))
  1516. (with-temp-buffer
  1517. (insert body) (goto-char (point-min))
  1518. (setq index (point))
  1519. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1520. (save-match-data (setf source-name (match-string 1)))
  1521. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1522. (save-match-data
  1523. (setq prefix
  1524. (buffer-substring (match-beginning 0)
  1525. (save-excursion
  1526. (beginning-of-line 1) (point)))))
  1527. ;; add interval to new-body (removing noweb reference)
  1528. (goto-char (match-beginning 0))
  1529. (nb-add (buffer-substring index (point)))
  1530. (goto-char (match-end 0))
  1531. (setq index (point))
  1532. (nb-add (with-current-buffer parent-buffer
  1533. (mapconcat ;; interpose PREFIX between every line
  1534. #'identity
  1535. (split-string
  1536. (if evaluate
  1537. (let ((raw (org-babel-ref-resolve source-name)))
  1538. (if (stringp raw) raw (format "%S" raw)))
  1539. (save-restriction
  1540. (widen)
  1541. (let ((point (org-babel-find-named-block
  1542. source-name)))
  1543. (if point
  1544. (save-excursion
  1545. (goto-char point)
  1546. (org-babel-trim
  1547. (org-babel-expand-noweb-references
  1548. (org-babel-get-src-block-info))))
  1549. ;; optionally raise an error if named
  1550. ;; source-block doesn't exist
  1551. (if (member lang org-babel-noweb-error-langs)
  1552. (error "%s"
  1553. (concat
  1554. "<<" source-name ">> "
  1555. "could not be resolved (see "
  1556. "`org-babel-noweb-error-langs')"))
  1557. "")))))
  1558. "[\n\r]") (concat "\n" prefix)))))
  1559. (nb-add (buffer-substring index (point-max)))))
  1560. new-body))
  1561. (defun org-babel-clean-text-properties (text)
  1562. "Strip all properties from text return."
  1563. (when text
  1564. (set-text-properties 0 (length text) nil text) text))
  1565. (defun org-babel-strip-protective-commas (body)
  1566. "Strip protective commas from bodies of source blocks."
  1567. (replace-regexp-in-string "^,#" "#" body))
  1568. (defun org-babel-read (cell)
  1569. "Convert the string value of CELL to a number if appropriate.
  1570. Otherwise if cell looks like lisp (meaning it starts with a
  1571. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1572. unmodified as a string.
  1573. This is taken almost directly from `org-read-prop'."
  1574. (if (and (stringp cell) (not (equal cell "")))
  1575. (or (org-babel-number-p cell)
  1576. (if (or (equal "(" (substring cell 0 1))
  1577. (equal "'" (substring cell 0 1))
  1578. (equal "`" (substring cell 0 1)))
  1579. (eval (read cell))
  1580. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1581. cell))
  1582. (defun org-babel-number-p (string)
  1583. "If STRING represents a number return it's value."
  1584. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1585. (= (length (substring string (match-beginning 0)
  1586. (match-end 0)))
  1587. (length string)))
  1588. (string-to-number string)))
  1589. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1590. "Read the results located at FILE-NAME into an elisp table.
  1591. If the table is trivial, then return it as a scalar."
  1592. (let (result)
  1593. (save-window-excursion
  1594. (with-temp-buffer
  1595. (condition-case nil
  1596. (progn
  1597. (org-table-import file-name separator)
  1598. (delete-file file-name)
  1599. (setq result (mapcar (lambda (row)
  1600. (mapcar #'org-babel-string-read row))
  1601. (org-table-to-lisp))))
  1602. (error nil)))
  1603. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1604. (if (consp (car result))
  1605. (if (null (cdr (car result)))
  1606. (caar result)
  1607. result)
  1608. (car result))
  1609. result))))
  1610. (defun org-babel-string-read (cell)
  1611. "Strip nested \"s from around strings."
  1612. (org-babel-read (or (and (stringp cell)
  1613. (string-match "\\\"\\(.+\\)\\\"" cell)
  1614. (match-string 1 cell))
  1615. cell)))
  1616. (defun org-babel-reverse-string (string)
  1617. "Return the reverse of STRING."
  1618. (apply 'string (reverse (string-to-list string))))
  1619. (defun org-babel-chomp (string &optional regexp)
  1620. "Strip trailing spaces and carriage returns from STRING.
  1621. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1622. overwritten by specifying a regexp as a second argument."
  1623. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1624. (while (and (> (length string) 0)
  1625. (string-match regexp (substring string -1)))
  1626. (setq string (substring string 0 -1)))
  1627. string))
  1628. (defun org-babel-trim (string &optional regexp)
  1629. "Strip leading and trailing spaces and carriage returns from STRING.
  1630. Like `org-babel-chomp' only it runs on both the front and back
  1631. of the string."
  1632. (org-babel-chomp (org-babel-reverse-string
  1633. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1634. regexp))
  1635. (defvar org-babel-org-babel-call-process-region-original nil)
  1636. (defun org-babel-tramp-handle-call-process-region
  1637. (start end program &optional delete buffer display &rest args)
  1638. "Use tramp to handle call-process-region.
  1639. Fixes a bug in `tramp-handle-call-process-region'."
  1640. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1641. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1642. (write-region start end tmpfile)
  1643. (when delete (delete-region start end))
  1644. (unwind-protect
  1645. ;; (apply 'call-process program tmpfile buffer display args)
  1646. ;; bug in tramp
  1647. (apply 'process-file program tmpfile buffer display args)
  1648. (delete-file tmpfile)))
  1649. ;; org-babel-call-process-region-original is the original emacs
  1650. ;; definition. It is in scope from the let binding in
  1651. ;; org-babel-execute-src-block
  1652. (apply org-babel-call-process-region-original
  1653. start end program delete buffer display args)))
  1654. (defun org-babel-local-file-name (file)
  1655. "Return the local name component of FILE."
  1656. (if (file-remote-p file)
  1657. (let (localname)
  1658. (with-parsed-tramp-file-name file nil
  1659. localname))
  1660. file))
  1661. (defun org-babel-process-file-name (name &optional no-quote-p)
  1662. "Prepare NAME to be used in an external process.
  1663. If NAME specifies a remote location, the remote portion of the
  1664. name is removed, since in that case the process will be executing
  1665. remotely. The file name is then processed by
  1666. `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
  1667. the file name is additionally processed by
  1668. `shell-quote-argument'"
  1669. ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
  1670. (expand-file-name (org-babel-local-file-name name))))
  1671. (defvar org-babel-temporary-directory)
  1672. (unless (or noninteractive (boundp 'org-babel-temporary-directory))
  1673. (defvar org-babel-temporary-directory
  1674. (or (and (boundp 'org-babel-temporary-directory)
  1675. (file-exists-p org-babel-temporary-directory)
  1676. org-babel-temporary-directory)
  1677. (make-temp-file "babel-" t))
  1678. "Directory to hold temporary files created to execute code blocks.
  1679. Used by `org-babel-temp-file'. This directory will be removed on
  1680. Emacs shutdown."))
  1681. (defun org-babel-temp-file (prefix &optional suffix)
  1682. "Create a temporary file in the `org-babel-temporary-directory'.
  1683. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  1684. value of `temporary-file-directory' temporarily set to the value
  1685. of `org-babel-temporary-directory'."
  1686. (if (file-remote-p default-directory)
  1687. (make-temp-file
  1688. (concat (file-remote-p default-directory)
  1689. (expand-file-name
  1690. prefix temporary-file-directory)
  1691. nil suffix))
  1692. (let ((temporary-file-directory
  1693. (or (and (file-exists-p org-babel-temporary-directory)
  1694. org-babel-temporary-directory)
  1695. temporary-file-directory)))
  1696. (make-temp-file prefix nil suffix))))
  1697. (defun org-babel-remove-temporary-directory ()
  1698. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  1699. (when (and (boundp 'org-babel-temporary-directory)
  1700. (file-exists-p org-babel-temporary-directory))
  1701. ;; taken from `delete-directory' in files.el
  1702. (mapc (lambda (file)
  1703. ;; This test is equivalent to
  1704. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1705. ;; but more efficient
  1706. (if (eq t (car (file-attributes file)))
  1707. (delete-directory file)
  1708. (delete-file file)))
  1709. ;; We do not want to delete "." and "..".
  1710. (directory-files org-babel-temporary-directory 'full
  1711. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  1712. (delete-directory org-babel-temporary-directory)))
  1713. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  1714. (provide 'ob)
  1715. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1716. ;;; ob.el ends here