ob.el 80 KB

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