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