ob.el 74 KB

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