ob.el 76 KB

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