ob.el 73 KB

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