ob.el 73 KB

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