ob.el 76 KB

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