ob.el 80 KB

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