ob.el 76 KB

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