ob-core.el 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677
  1. ;;; ob-core.el --- working with code blocks in org-mode
  2. ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
  3. ;; Authors: Eric Schulte
  4. ;; Dan Davison
  5. ;; Keywords: literate programming, reproducible research
  6. ;; Homepage: http://orgmode.org
  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. ;;; Code:
  19. (eval-when-compile
  20. (require 'cl))
  21. (require 'ob-eval)
  22. (require 'org-macs)
  23. (require 'org-compat)
  24. (defconst org-babel-exeext
  25. (if (memq system-type '(windows-nt cygwin))
  26. ".exe"
  27. nil))
  28. ;; dynamically scoped for tramp
  29. (defvar org-babel-call-process-region-original nil)
  30. (defvar org-src-lang-modes)
  31. (defvar org-babel-library-of-babel)
  32. (declare-function show-all "outline" ())
  33. (declare-function org-reduce "org" (CL-FUNC CL-SEQ &rest CL-KEYS))
  34. (declare-function org-mark-ring-push "org" (&optional pos buffer))
  35. (declare-function tramp-compat-make-temp-file "tramp-compat"
  36. (filename &optional dir-flag))
  37. (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
  38. (declare-function tramp-file-name-user "tramp" (vec))
  39. (declare-function tramp-file-name-host "tramp" (vec))
  40. (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
  41. (declare-function org-icompleting-read "org" (&rest args))
  42. (declare-function org-edit-src-code "org-src"
  43. (&optional context code edit-buffer-name quietp))
  44. (declare-function org-edit-src-exit "org-src" (&optional context))
  45. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  46. (declare-function org-save-outline-visibility "org-macs" (use-markers &rest body))
  47. (declare-function org-outline-overlay-data "org" (&optional use-markers))
  48. (declare-function org-set-outline-overlay-data "org" (data))
  49. (declare-function org-narrow-to-subtree "org" ())
  50. (declare-function org-split-string "org" (string &optional separators))
  51. (declare-function org-entry-get "org"
  52. (pom property &optional inherit literal-nil))
  53. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  54. (declare-function org-do-remove-indentation "org" (&optional n))
  55. (declare-function org-next-block "org" (arg &optional backward block-regexp))
  56. (declare-function org-previous-block "org" (arg &optional block-regexp))
  57. (declare-function org-show-context "org" (&optional key))
  58. (declare-function org-at-table-p "org" (&optional table-type))
  59. (declare-function org-cycle "org" (&optional arg))
  60. (declare-function org-uniquify "org" (list))
  61. (declare-function org-current-level "org" ())
  62. (declare-function org-table-import "org-table" (file arg))
  63. (declare-function org-add-hook "org-compat"
  64. (hook function &optional append local))
  65. (declare-function org-table-align "org-table" ())
  66. (declare-function org-table-end "org-table" (&optional table-type))
  67. (declare-function orgtbl-to-generic "org-table" (table params))
  68. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  69. (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
  70. (declare-function org-babel-lob-get-info "ob-lob" nil)
  71. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  72. (declare-function org-babel-ref-parse "ob-ref" (assignment))
  73. (declare-function org-babel-ref-resolve "ob-ref" (ref))
  74. (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
  75. (declare-function org-babel-ref-headline-body "ob-ref" ())
  76. (declare-function org-babel-lob-execute-maybe "ob-lob" ())
  77. (declare-function org-number-sequence "org-compat" (from &optional to inc))
  78. (declare-function org-at-item-p "org-list" ())
  79. (declare-function org-list-parse-list "org-list" (&optional delete))
  80. (declare-function org-list-to-generic "org-list" (LIST PARAMS))
  81. (declare-function org-list-struct "org-list" ())
  82. (declare-function org-list-prevs-alist "org-list" (struct))
  83. (declare-function org-list-get-list-end "org-list" (item struct prevs))
  84. (declare-function org-remove-if "org" (predicate seq))
  85. (declare-function org-completing-read "org" (&rest args))
  86. (declare-function org-escape-code-in-region "org-src" (beg end))
  87. (declare-function org-unescape-code-in-string "org-src" (s))
  88. (declare-function org-table-to-lisp "org-table" (&optional txt))
  89. (declare-function org-reverse-string "org" (string))
  90. (defgroup org-babel nil
  91. "Code block evaluation and management in `org-mode' documents."
  92. :tag "Babel"
  93. :group 'org)
  94. (defcustom org-confirm-babel-evaluate t
  95. "Confirm before evaluation.
  96. Require confirmation before interactively evaluating code
  97. blocks in Org-mode buffers. The default value of this variable
  98. is t, meaning confirmation is required for any code block
  99. evaluation. This variable can be set to nil to inhibit any
  100. future confirmation requests. This variable can also be set to a
  101. function which takes two arguments the language of the code block
  102. and the body of the code block. Such a function should then
  103. return a non-nil value if the user should be prompted for
  104. execution or nil if no prompt is required.
  105. Warning: Disabling confirmation may result in accidental
  106. evaluation of potentially harmful code. It may be advisable
  107. remove code block execution from C-c C-c as further protection
  108. against accidental code block evaluation. The
  109. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  110. remove code block execution from the C-c C-c keybinding."
  111. :group 'org-babel
  112. :version "24.1"
  113. :type '(choice boolean function))
  114. ;; don't allow this variable to be changed through file settings
  115. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  116. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  117. "Remove code block evaluation from the C-c C-c key binding."
  118. :group 'org-babel
  119. :version "24.1"
  120. :type 'boolean)
  121. (defcustom org-babel-results-keyword "RESULTS"
  122. "Keyword used to name results generated by code blocks.
  123. Should be either RESULTS or NAME however any capitalization may
  124. be used."
  125. :group 'org-babel
  126. :version "24.4"
  127. :package-version '(Org . "8.0")
  128. :type 'string)
  129. (defcustom org-babel-noweb-wrap-start "<<"
  130. "String used to begin a noweb reference in a code block.
  131. See also `org-babel-noweb-wrap-end'."
  132. :group 'org-babel
  133. :type 'string)
  134. (defcustom org-babel-noweb-wrap-end ">>"
  135. "String used to end a noweb reference in a code block.
  136. See also `org-babel-noweb-wrap-start'."
  137. :group 'org-babel
  138. :type 'string)
  139. (defun org-babel-noweb-wrap (&optional regexp)
  140. (concat org-babel-noweb-wrap-start
  141. (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
  142. org-babel-noweb-wrap-end))
  143. (defvar org-babel-src-name-regexp
  144. "^[ \t]*#\\+name:[ \t]*"
  145. "Regular expression used to match a source name line.")
  146. (defvar org-babel-multi-line-header-regexp
  147. "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
  148. "Regular expression used to match multi-line header arguments.")
  149. (defvar org-babel-src-name-w-name-regexp
  150. (concat org-babel-src-name-regexp
  151. "\\("
  152. org-babel-multi-line-header-regexp
  153. "\\)*"
  154. "\\([^ ()\f\t\n\r\v]+\\)")
  155. "Regular expression matching source name lines with a name.")
  156. (defvar org-babel-src-block-regexp
  157. (concat
  158. ;; (1) indentation (2) lang
  159. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  160. ;; (3) switches
  161. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  162. ;; (4) header arguments
  163. "\\([^\n]*\\)\n"
  164. ;; (5) body
  165. "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
  166. "Regexp used to identify code blocks.")
  167. (defvar org-babel-inline-src-block-regexp
  168. (concat
  169. ;; (1) replacement target (2) lang
  170. "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
  171. ;; (3,4) (unused, headers)
  172. "\\(\\|\\[\\(.*?\\)\\]\\)"
  173. ;; (5) body
  174. "{\\([^\f\n\r\v]+?\\)}\\)")
  175. "Regexp used to identify inline src-blocks.")
  176. (defun org-babel-get-header (params key &optional others)
  177. "Select only header argument of type KEY from a list.
  178. Optional argument OTHERS indicates that only the header that do
  179. not match KEY should be returned."
  180. (delq nil
  181. (mapcar
  182. (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
  183. params)))
  184. (defun org-babel-get-inline-src-block-matches()
  185. "Set match data if within body of an inline source block.
  186. Returns non-nil if match-data set"
  187. (let ((src-at-0-p (save-excursion
  188. (beginning-of-line 1)
  189. (string= "src" (thing-at-point 'word))))
  190. (first-line-p (= 1 (line-number-at-pos)))
  191. (orig (point)))
  192. (let ((search-for (cond ((and src-at-0-p first-line-p "src_"))
  193. (first-line-p "[[:punct:] \t]src_")
  194. (t "[[:punct:] \f\t\n\r\v]src_")))
  195. (lower-limit (if first-line-p
  196. nil
  197. (- (point-at-bol) 1))))
  198. (save-excursion
  199. (when (or (and src-at-0-p (bobp))
  200. (and (re-search-forward "}" (point-at-eol) t)
  201. (re-search-backward search-for lower-limit t)
  202. (> orig (point))))
  203. (when (looking-at org-babel-inline-src-block-regexp)
  204. t ))))))
  205. (defvar org-babel-inline-lob-one-liner-regexp)
  206. (defun org-babel-get-lob-one-liner-matches()
  207. "Set match data if on line of an lob one liner.
  208. Returns non-nil if match-data set"
  209. (save-excursion
  210. (unless (= (point) (point-at-bol)) ;; move before inline block
  211. (re-search-backward "[ \f\t\n\r\v]" nil t))
  212. (if (looking-at org-babel-inline-lob-one-liner-regexp)
  213. t
  214. nil)))
  215. (defun org-babel-get-src-block-info (&optional light)
  216. "Get information on the current source block.
  217. Optional argument LIGHT does not resolve remote variable
  218. references; a process which could likely result in the execution
  219. of other code blocks.
  220. Returns a list
  221. (language body header-arguments-alist switches name indent)."
  222. (let ((case-fold-search t) head info name indent)
  223. ;; full code block
  224. (if (setq head (org-babel-where-is-src-block-head))
  225. (save-excursion
  226. (goto-char head)
  227. (setq info (org-babel-parse-src-block-match))
  228. (setq indent (car (last info)))
  229. (setq info (butlast info))
  230. (while (and (forward-line -1)
  231. (looking-at org-babel-multi-line-header-regexp))
  232. (setf (nth 2 info)
  233. (org-babel-merge-params
  234. (nth 2 info)
  235. (org-babel-parse-header-arguments (match-string 1)))))
  236. (when (looking-at org-babel-src-name-w-name-regexp)
  237. (setq name (org-no-properties (match-string 3)))))
  238. ;; inline source block
  239. (when (org-babel-get-inline-src-block-matches)
  240. (setq info (org-babel-parse-inline-src-block-match))))
  241. ;; resolve variable references and add summary parameters
  242. (when (and info (not light))
  243. (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
  244. (when info (append info (list name indent)))))
  245. (defvar org-current-export-file) ; dynamically bound
  246. (defmacro org-babel-check-confirm-evaluate (info &rest body)
  247. "Evaluate BODY with special execution confirmation variables set.
  248. Specifically; NOEVAL will indicate if evaluation is allowed,
  249. QUERY will indicate if a user query is required, CODE-BLOCK will
  250. hold the language of the code block, and BLOCK-NAME will hold the
  251. name of the code block."
  252. (declare (indent defun))
  253. (org-with-gensyms
  254. (lang block-body headers name eval eval-no export eval-no-export)
  255. `(let* ((,lang (nth 0 ,info))
  256. (,block-body (nth 1 ,info))
  257. (,headers (nth 2 ,info))
  258. (,name (nth 4 ,info))
  259. (,eval (or (cdr (assoc :eval ,headers))
  260. (when (assoc :noeval ,headers) "no")))
  261. (,eval-no (or (equal ,eval "no")
  262. (equal ,eval "never")))
  263. (,export (org-bound-and-true-p org-current-export-file))
  264. (,eval-no-export (and ,export (or (equal ,eval "no-export")
  265. (equal ,eval "never-export"))))
  266. (noeval (or ,eval-no ,eval-no-export))
  267. (query (or (equal ,eval "query")
  268. (and ,export (equal ,eval "query-export"))
  269. (when (functionp org-confirm-babel-evaluate)
  270. (funcall org-confirm-babel-evaluate
  271. ,lang ,block-body))
  272. org-confirm-babel-evaluate))
  273. (code-block (if ,info (format " %s " ,lang) " "))
  274. (block-name (if ,name (format " (%s) " ,name) " ")))
  275. ,@body)))
  276. (defsubst org-babel-check-evaluate (info)
  277. "Check if code block INFO should be evaluated.
  278. Do not query the user."
  279. (org-babel-check-confirm-evaluate info
  280. (not (when noeval
  281. (message (format "Evaluation of this%scode-block%sis disabled."
  282. code-block block-name))))))
  283. ;; dynamically scoped for asynchroneous export
  284. (defvar org-babel-confirm-evaluate-answer-no)
  285. (defsubst org-babel-confirm-evaluate (info)
  286. "Confirm evaluation of the code block INFO.
  287. If the variable `org-babel-confirm-evaluate-answer-no´ is bound
  288. to a non-nil value, auto-answer with \"no\".
  289. This query can also be suppressed by setting the value of
  290. `org-confirm-babel-evaluate' to nil, in which case all future
  291. interactive code block evaluations will proceed without any
  292. confirmation from the user.
  293. Note disabling confirmation may result in accidental evaluation
  294. of potentially harmful code."
  295. (org-babel-check-confirm-evaluate info
  296. (not (when query
  297. (unless
  298. (and (not (org-bound-and-true-p
  299. org-babel-confirm-evaluate-answer-no))
  300. (yes-or-no-p
  301. (format "Evaluate this%scode block%son your system? "
  302. code-block block-name)))
  303. (message (format "Evaluation of this%scode-block%sis aborted."
  304. code-block block-name)))))))
  305. ;;;###autoload
  306. (defun org-babel-execute-safely-maybe ()
  307. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  308. (org-babel-execute-maybe)))
  309. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
  310. ;;;###autoload
  311. (defun org-babel-execute-maybe ()
  312. (interactive)
  313. (or (org-babel-execute-src-block-maybe)
  314. (org-babel-lob-execute-maybe)))
  315. (defun org-babel-execute-src-block-maybe ()
  316. "Conditionally execute a source block.
  317. Detect if this is context for a Babel src-block and if so
  318. then run `org-babel-execute-src-block'."
  319. (interactive)
  320. (let ((info (org-babel-get-src-block-info)))
  321. (if info
  322. (progn (org-babel-eval-wipe-error-buffer)
  323. (org-babel-execute-src-block current-prefix-arg info) t) nil)))
  324. ;;;###autoload
  325. (defun org-babel-view-src-block-info ()
  326. "Display information on the current source block.
  327. This includes header arguments, language and name, and is largely
  328. a window into the `org-babel-get-src-block-info' function."
  329. (interactive)
  330. (let ((info (org-babel-get-src-block-info 'light))
  331. (full (lambda (it) (> (length it) 0)))
  332. (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
  333. (when info
  334. (with-help-window (help-buffer)
  335. (let ((name (nth 4 info))
  336. (lang (nth 0 info))
  337. (switches (nth 3 info))
  338. (header-args (nth 2 info)))
  339. (when name (funcall printf "Name: %s\n" name))
  340. (when lang (funcall printf "Lang: %s\n" lang))
  341. (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
  342. (funcall printf "Header Arguments:\n")
  343. (dolist (pair (sort header-args
  344. (lambda (a b) (string< (symbol-name (car a))
  345. (symbol-name (car b))))))
  346. (when (funcall full (cdr pair))
  347. (funcall printf "\t%S%s\t%s\n"
  348. (car pair)
  349. (if (> (length (format "%S" (car pair))) 7) "" "\t")
  350. (cdr pair)))))))))
  351. ;;;###autoload
  352. (defun org-babel-expand-src-block-maybe ()
  353. "Conditionally expand a source block.
  354. Detect if this is context for a org-babel src-block and if so
  355. then run `org-babel-expand-src-block'."
  356. (interactive)
  357. (let ((info (org-babel-get-src-block-info)))
  358. (if info
  359. (progn (org-babel-expand-src-block current-prefix-arg info) t)
  360. nil)))
  361. ;;;###autoload
  362. (defun org-babel-load-in-session-maybe ()
  363. "Conditionally load a source block in a session.
  364. Detect if this is context for a org-babel src-block and if so
  365. then run `org-babel-load-in-session'."
  366. (interactive)
  367. (let ((info (org-babel-get-src-block-info)))
  368. (if info
  369. (progn (org-babel-load-in-session current-prefix-arg info) t)
  370. nil)))
  371. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  372. ;;;###autoload
  373. (defun org-babel-pop-to-session-maybe ()
  374. "Conditionally pop to a session.
  375. Detect if this is context for a org-babel src-block and if so
  376. then run `org-babel-pop-to-session'."
  377. (interactive)
  378. (let ((info (org-babel-get-src-block-info)))
  379. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  380. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  381. (defconst org-babel-common-header-args-w-values
  382. '((cache . ((no yes)))
  383. (cmdline . :any)
  384. (colnames . ((nil no yes)))
  385. (comments . ((no link yes org both noweb)))
  386. (dir . :any)
  387. (eval . ((never query)))
  388. (exports . ((code results both none)))
  389. (file . :any)
  390. (file-desc . :any)
  391. (hlines . ((no yes)))
  392. (mkdirp . ((yes no)))
  393. (no-expand)
  394. (noeval)
  395. (noweb . ((yes no tangle no-export strip-export)))
  396. (noweb-ref . :any)
  397. (noweb-sep . :any)
  398. (padline . ((yes no)))
  399. (results . ((file list vector table scalar verbatim)
  400. (raw html latex org code pp drawer)
  401. (replace silent none append prepend)
  402. (output value)))
  403. (rownames . ((no yes)))
  404. (sep . :any)
  405. (session . :any)
  406. (shebang . :any)
  407. (tangle . ((tangle yes no :any)))
  408. (var . :any)
  409. (wrap . :any)))
  410. (defconst org-babel-header-arg-names
  411. (mapcar #'car org-babel-common-header-args-w-values)
  412. "Common header arguments used by org-babel.
  413. Note that individual languages may define their own language
  414. specific header arguments as well.")
  415. (defvar org-babel-default-header-args
  416. '((:session . "none") (:results . "replace") (:exports . "code")
  417. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no")
  418. (:padnewline . "yes"))
  419. "Default arguments to use when evaluating a source block.")
  420. (defvar org-babel-default-inline-header-args
  421. '((:session . "none") (:results . "replace") (:exports . "results"))
  422. "Default arguments to use when evaluating an inline source block.")
  423. (defvar org-babel-data-names '("tblname" "results" "name"))
  424. (defvar org-babel-result-regexp
  425. (concat "^[ \t]*#\\+"
  426. (regexp-opt org-babel-data-names t)
  427. "\\(\\[\\("
  428. ;; FIXME The string below is `org-ts-regexp'
  429. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  430. " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
  431. "Regular expression used to match result lines.
  432. If the results are associated with a hash key then the hash will
  433. be saved in the second match data.")
  434. (defvar org-babel-result-w-name-regexp
  435. (concat org-babel-result-regexp
  436. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  437. (defvar org-babel-min-lines-for-block-output 10
  438. "The minimum number of lines for block output.
  439. If number of lines of output is equal to or exceeds this
  440. value, the output is placed in a #+begin_example...#+end_example
  441. block. Otherwise the output is marked as literal by inserting
  442. colons at the starts of the lines. This variable only takes
  443. effect if the :results output option is in effect.")
  444. (defvar org-babel-noweb-error-langs nil
  445. "Languages for which Babel will raise literate programming errors.
  446. List of languages for which errors should be raised when the
  447. source code block satisfying a noweb reference in this language
  448. can not be resolved.")
  449. (defvar org-babel-hash-show 4
  450. "Number of initial characters to show of a hidden results hash.")
  451. (defvar org-babel-hash-show-time nil
  452. "Non-nil means show the time the code block was evaluated in the result hash.")
  453. (defvar org-babel-after-execute-hook nil
  454. "Hook for functions to be called after `org-babel-execute-src-block'")
  455. (defun org-babel-named-src-block-regexp-for-name (name)
  456. "This generates a regexp used to match a src block named NAME."
  457. (concat org-babel-src-name-regexp (regexp-quote name)
  458. "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
  459. (substring org-babel-src-block-regexp 1)))
  460. (defun org-babel-named-data-regexp-for-name (name)
  461. "This generates a regexp used to match data named NAME."
  462. (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
  463. ;;; functions
  464. (defvar call-process-region)
  465. ;;;###autoload
  466. (defun org-babel-execute-src-block (&optional arg info params)
  467. "Execute the current source code block.
  468. Insert the results of execution into the buffer. Source code
  469. execution and the collection and formatting of results can be
  470. controlled through a variety of header arguments.
  471. With prefix argument ARG, force re-execution even if an existing
  472. result cached in the buffer would otherwise have been returned.
  473. Optionally supply a value for INFO in the form returned by
  474. `org-babel-get-src-block-info'.
  475. Optionally supply a value for PARAMS which will be merged with
  476. the header arguments specified at the front of the source code
  477. block."
  478. (interactive)
  479. (let* ((info (or info (org-babel-get-src-block-info)))
  480. (merged-params (org-babel-merge-params (nth 2 info) params)))
  481. (when (org-babel-check-evaluate
  482. (let ((i info)) (setf (nth 2 i) merged-params) i))
  483. (let* ((params (if params
  484. (org-babel-process-params merged-params)
  485. (nth 2 info)))
  486. (cachep (and (not arg) (cdr (assoc :cache params))
  487. (string= "yes" (cdr (assoc :cache params)))))
  488. (new-hash (when cachep (org-babel-sha1-hash info)))
  489. (old-hash (when cachep (org-babel-current-result-hash)))
  490. (cache-current-p (and (not arg) new-hash
  491. (equal new-hash old-hash))))
  492. (cond
  493. (cache-current-p
  494. (save-excursion ;; return cached result
  495. (goto-char (org-babel-where-is-src-block-result nil info))
  496. (end-of-line 1) (forward-char 1)
  497. (let ((result (org-babel-read-result)))
  498. (message (replace-regexp-in-string
  499. "%" "%%" (format "%S" result))) result)))
  500. ((org-babel-confirm-evaluate
  501. (let ((i info)) (setf (nth 2 i) merged-params) i))
  502. (let* ((lang (nth 0 info))
  503. (result-params (cdr (assoc :result-params params)))
  504. (body (setf (nth 1 info)
  505. (if (org-babel-noweb-p params :eval)
  506. (org-babel-expand-noweb-references info)
  507. (nth 1 info))))
  508. (dir (cdr (assoc :dir params)))
  509. (default-directory
  510. (or (and dir (file-name-as-directory (expand-file-name dir)))
  511. default-directory))
  512. (org-babel-call-process-region-original ;; for tramp handler
  513. (or (org-bound-and-true-p
  514. org-babel-call-process-region-original)
  515. (symbol-function 'call-process-region)))
  516. (indent (car (last info)))
  517. result cmd)
  518. (unwind-protect
  519. (let ((call-process-region
  520. (lambda (&rest args)
  521. (apply 'org-babel-tramp-handle-call-process-region
  522. args))))
  523. (let ((lang-check
  524. (lambda (f)
  525. (let ((f (intern (concat "org-babel-execute:" f))))
  526. (when (fboundp f) f)))))
  527. (setq cmd
  528. (or (funcall lang-check lang)
  529. (funcall lang-check
  530. (symbol-name
  531. (cdr (assoc lang org-src-lang-modes))))
  532. (error "No org-babel-execute function for %s!"
  533. lang))))
  534. (message "executing %s code block%s..."
  535. (capitalize lang)
  536. (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
  537. (if (member "none" result-params)
  538. (progn
  539. (funcall cmd body params)
  540. (message "result silenced"))
  541. (setq result
  542. ((lambda (result)
  543. (if (and (eq (cdr (assoc :result-type params))
  544. 'value)
  545. (or (member "vector" result-params)
  546. (member "table" result-params))
  547. (not (listp result)))
  548. (list (list result)) result))
  549. (funcall cmd body params)))
  550. ;; if non-empty result and :file then write to :file
  551. (when (cdr (assoc :file params))
  552. (when result
  553. (with-temp-file (cdr (assoc :file params))
  554. (insert
  555. (org-babel-format-result
  556. result (cdr (assoc :sep (nth 2 info)))))))
  557. (setq result (cdr (assoc :file params))))
  558. (org-babel-insert-result
  559. result result-params info new-hash indent lang)
  560. (run-hooks 'org-babel-after-execute-hook)
  561. result))
  562. (setq call-process-region
  563. 'org-babel-call-process-region-original)))))))))
  564. (defun org-babel-expand-body:generic (body params &optional var-lines)
  565. "Expand BODY with PARAMS.
  566. Expand a block of code with org-babel according to its header
  567. arguments. This generic implementation of body expansion is
  568. called for languages which have not defined their own specific
  569. org-babel-expand-body:lang function."
  570. (mapconcat #'identity (append var-lines (list body)) "\n"))
  571. ;;;###autoload
  572. (defun org-babel-expand-src-block (&optional arg info params)
  573. "Expand the current source code block.
  574. Expand according to the source code block's header
  575. arguments and pop open the results in a preview buffer."
  576. (interactive)
  577. (let* ((info (or info (org-babel-get-src-block-info)))
  578. (lang (nth 0 info))
  579. (params (setf (nth 2 info)
  580. (sort (org-babel-merge-params (nth 2 info) params)
  581. (lambda (el1 el2) (string< (symbol-name (car el1))
  582. (symbol-name (car el2)))))))
  583. (body (setf (nth 1 info)
  584. (if (org-babel-noweb-p params :eval)
  585. (org-babel-expand-noweb-references info) (nth 1 info))))
  586. (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
  587. (assignments-cmd (intern (concat "org-babel-variable-assignments:"
  588. lang)))
  589. (expanded
  590. (if (fboundp expand-cmd) (funcall expand-cmd body params)
  591. (org-babel-expand-body:generic
  592. body params (and (fboundp assignments-cmd)
  593. (funcall assignments-cmd params))))))
  594. (if (called-interactively-p 'any)
  595. (org-edit-src-code
  596. nil expanded
  597. (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
  598. expanded)))
  599. (defun org-babel-edit-distance (s1 s2)
  600. "Return the edit (levenshtein) distance between strings S1 S2."
  601. (let* ((l1 (length s1))
  602. (l2 (length s2))
  603. (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
  604. (number-sequence 1 (1+ l1)))))
  605. (in (lambda (i j) (aref (aref dist i) j))))
  606. (setf (aref (aref dist 0) 0) 0)
  607. (dolist (j (number-sequence 1 l2))
  608. (setf (aref (aref dist 0) j) j))
  609. (dolist (i (number-sequence 1 l1))
  610. (setf (aref (aref dist i) 0) i)
  611. (dolist (j (number-sequence 1 l2))
  612. (setf (aref (aref dist i) j)
  613. (min
  614. (1+ (funcall in (1- i) j))
  615. (1+ (funcall in i (1- j)))
  616. (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
  617. (funcall in (1- i) (1- j)))))))
  618. (funcall in l1 l2)))
  619. (defun org-babel-combine-header-arg-lists (original &rest others)
  620. "Combine a number of lists of header argument names and arguments."
  621. (let ((results (copy-sequence original)))
  622. (dolist (new-list others)
  623. (dolist (arg-pair new-list)
  624. (let ((header (car arg-pair))
  625. (args (cdr arg-pair)))
  626. (setq results
  627. (cons arg-pair (org-remove-if
  628. (lambda (pair) (equal header (car pair)))
  629. results))))))
  630. results))
  631. ;;;###autoload
  632. (defun org-babel-check-src-block ()
  633. "Check for misspelled header arguments in the current code block."
  634. (interactive)
  635. ;; TODO: report malformed code block
  636. ;; TODO: report incompatible combinations of header arguments
  637. ;; TODO: report uninitialized variables
  638. (let ((too-close 2) ;; <- control closeness to report potential match
  639. (names (mapcar #'symbol-name org-babel-header-arg-names)))
  640. (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
  641. (and (org-babel-where-is-src-block-head)
  642. (org-babel-parse-header-arguments
  643. (org-no-properties
  644. (match-string 4))))))
  645. (dolist (name names)
  646. (when (and (not (string= header name))
  647. (<= (org-babel-edit-distance header name) too-close)
  648. (not (member header names)))
  649. (error "Supplied header \"%S\" is suspiciously close to \"%S\""
  650. header name))))
  651. (message "No suspicious header arguments found.")))
  652. ;;;###autoload
  653. (defun org-babel-insert-header-arg ()
  654. "Insert a header argument selecting from lists of common args and values."
  655. (interactive)
  656. (let* ((lang (car (org-babel-get-src-block-info 'light)))
  657. (lang-headers (intern (concat "org-babel-header-args:" lang)))
  658. (headers (org-babel-combine-header-arg-lists
  659. org-babel-common-header-args-w-values
  660. (if (boundp lang-headers) (eval lang-headers) nil)))
  661. (arg (org-icompleting-read
  662. "Header Arg: "
  663. (mapcar
  664. (lambda (header-spec) (symbol-name (car header-spec)))
  665. headers))))
  666. (insert ":" arg)
  667. (let ((vals (cdr (assoc (intern arg) headers))))
  668. (when vals
  669. (insert
  670. " "
  671. (cond
  672. ((eq vals :any)
  673. (read-from-minibuffer "value: "))
  674. ((listp vals)
  675. (mapconcat
  676. (lambda (group)
  677. (let ((arg (org-icompleting-read
  678. "value: "
  679. (cons "default" (mapcar #'symbol-name group)))))
  680. (if (and arg (not (string= "default" arg)))
  681. (concat arg " ")
  682. "")))
  683. vals ""))))))))
  684. ;; Add support for completing-read insertion of header arguments after ":"
  685. (defun org-babel-header-arg-expand ()
  686. "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
  687. (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
  688. (org-babel-enter-header-arg-w-completion (match-string 2))))
  689. (defun org-babel-enter-header-arg-w-completion (&optional lang)
  690. "Insert header argument appropriate for LANG with completion."
  691. (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
  692. (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var)))
  693. (headers-w-values (org-babel-combine-header-arg-lists
  694. org-babel-common-header-args-w-values lang-headers))
  695. (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
  696. (header (org-completing-read "Header Arg: " headers))
  697. (args (cdr (assoc (intern header) headers-w-values)))
  698. (arg (when (and args (listp args))
  699. (org-completing-read
  700. (format "%s: " header)
  701. (mapcar #'symbol-name (apply #'append args))))))
  702. (insert (concat header " " (or arg "")))
  703. (cons header arg)))
  704. (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
  705. ;;;###autoload
  706. (defun org-babel-load-in-session (&optional arg info)
  707. "Load the body of the current source-code block.
  708. Evaluate the header arguments for the source block before
  709. entering the session. After loading the body this pops open the
  710. session."
  711. (interactive)
  712. (let* ((info (or info (org-babel-get-src-block-info)))
  713. (lang (nth 0 info))
  714. (params (nth 2 info))
  715. (body (if (not info)
  716. (user-error "No src code block at point")
  717. (setf (nth 1 info)
  718. (if (org-babel-noweb-p params :eval)
  719. (org-babel-expand-noweb-references info)
  720. (nth 1 info)))))
  721. (session (cdr (assoc :session params)))
  722. (dir (cdr (assoc :dir params)))
  723. (default-directory
  724. (or (and dir (file-name-as-directory dir)) default-directory))
  725. (cmd (intern (concat "org-babel-load-session:" lang))))
  726. (unless (fboundp cmd)
  727. (error "No org-babel-load-session function for %s!" lang))
  728. (pop-to-buffer (funcall cmd session body params))
  729. (end-of-line 1)))
  730. ;;;###autoload
  731. (defun org-babel-initiate-session (&optional arg info)
  732. "Initiate session for current code block.
  733. If called with a prefix argument then resolve any variable
  734. references in the header arguments and assign these variables in
  735. the session. Copy the body of the code block to the kill ring."
  736. (interactive "P")
  737. (let* ((info (or info (org-babel-get-src-block-info (not arg))))
  738. (lang (nth 0 info))
  739. (body (nth 1 info))
  740. (params (nth 2 info))
  741. (session (cdr (assoc :session params)))
  742. (dir (cdr (assoc :dir params)))
  743. (default-directory
  744. (or (and dir (file-name-as-directory dir)) default-directory))
  745. (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
  746. (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
  747. (if (and (stringp session) (string= session "none"))
  748. (error "This block is not using a session!"))
  749. (unless (fboundp init-cmd)
  750. (error "No org-babel-initiate-session function for %s!" lang))
  751. (with-temp-buffer (insert (org-babel-trim body))
  752. (copy-region-as-kill (point-min) (point-max)))
  753. (when arg
  754. (unless (fboundp prep-cmd)
  755. (error "No org-babel-prep-session function for %s!" lang))
  756. (funcall prep-cmd session params))
  757. (funcall init-cmd session params)))
  758. ;;;###autoload
  759. (defun org-babel-switch-to-session (&optional arg info)
  760. "Switch to the session of the current code block.
  761. Uses `org-babel-initiate-session' to start the session. If called
  762. with a prefix argument then this is passed on to
  763. `org-babel-initiate-session'."
  764. (interactive "P")
  765. (pop-to-buffer (org-babel-initiate-session arg info))
  766. (end-of-line 1))
  767. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  768. ;;;###autoload
  769. (defun org-babel-switch-to-session-with-code (&optional arg info)
  770. "Switch to code buffer and display session."
  771. (interactive "P")
  772. (let ((swap-windows
  773. (lambda ()
  774. (let ((other-window-buffer (window-buffer (next-window))))
  775. (set-window-buffer (next-window) (current-buffer))
  776. (set-window-buffer (selected-window) other-window-buffer))
  777. (other-window 1)))
  778. (info (org-babel-get-src-block-info))
  779. (org-src-window-setup 'reorganize-frame))
  780. (save-excursion
  781. (org-babel-switch-to-session arg info))
  782. (org-edit-src-code)
  783. (funcall swap-windows)))
  784. (defmacro org-babel-do-in-edit-buffer (&rest body)
  785. "Evaluate BODY in edit buffer if there is a code block at point.
  786. Return t if a code block was found at point, nil otherwise."
  787. `(let ((org-src-window-setup 'switch-invisibly))
  788. (when (and (org-babel-where-is-src-block-head)
  789. (org-edit-src-code nil nil nil))
  790. (unwind-protect (progn ,@body)
  791. (if (org-bound-and-true-p org-edit-src-from-org-mode)
  792. (org-edit-src-exit)))
  793. t)))
  794. (def-edebug-spec org-babel-do-in-edit-buffer (body))
  795. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  796. "Read key sequence and execute the command in edit buffer.
  797. Enter a key sequence to be executed in the language major-mode
  798. edit buffer. For example, TAB will alter the contents of the
  799. Org-mode code block according to the effect of TAB in the
  800. language major-mode buffer. For languages that support
  801. interactive sessions, this can be used to send code from the Org
  802. buffer to the session for evaluation using the native major-mode
  803. evaluation mechanisms."
  804. (interactive "kEnter key-sequence to execute in edit buffer: ")
  805. (org-babel-do-in-edit-buffer
  806. (call-interactively
  807. (key-binding (or key (read-key-sequence nil))))))
  808. (defvar org-bracket-link-regexp)
  809. ;;;###autoload
  810. (defun org-babel-open-src-block-result (&optional re-run)
  811. "If `point' is on a src block then open the results of the
  812. source code block, otherwise return nil. With optional prefix
  813. argument RE-RUN the source-code block is evaluated even if
  814. results already exist."
  815. (interactive "P")
  816. (let ((info (org-babel-get-src-block-info)))
  817. (when info
  818. (save-excursion
  819. ;; go to the results, if there aren't any then run the block
  820. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  821. (progn (org-babel-execute-src-block)
  822. (org-babel-where-is-src-block-result))))
  823. (end-of-line 1)
  824. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  825. ;; open the results
  826. (if (looking-at org-bracket-link-regexp)
  827. ;; file results
  828. (org-open-at-point)
  829. (let ((r (org-babel-format-result
  830. (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
  831. (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
  832. (delete-region (point-min) (point-max))
  833. (insert r)))
  834. t))))
  835. ;;;###autoload
  836. (defmacro org-babel-map-src-blocks (file &rest body)
  837. "Evaluate BODY forms on each source-block in FILE.
  838. If FILE is nil evaluate BODY forms on source blocks in current
  839. buffer. During evaluation of BODY the following local variables
  840. are set relative to the currently matched code block.
  841. full-block ------- string holding the entirety of the code block
  842. beg-block -------- point at the beginning of the code block
  843. end-block -------- point at the end of the matched code block
  844. lang ------------- string holding the language of the code block
  845. beg-lang --------- point at the beginning of the lang
  846. end-lang --------- point at the end of the lang
  847. switches --------- string holding the switches
  848. beg-switches ----- point at the beginning of the switches
  849. end-switches ----- point at the end of the switches
  850. header-args ------ string holding the header-args
  851. beg-header-args -- point at the beginning of the header-args
  852. end-header-args -- point at the end of the header-args
  853. body ------------- string holding the body of the code block
  854. beg-body --------- point at the beginning of the body
  855. end-body --------- point at the end of the body"
  856. (declare (indent 1))
  857. (let ((tempvar (make-symbol "file")))
  858. `(let* ((,tempvar ,file)
  859. (visited-p (or (null ,tempvar)
  860. (get-file-buffer (expand-file-name ,tempvar))))
  861. (point (point)) to-be-removed)
  862. (save-window-excursion
  863. (when ,tempvar (find-file ,tempvar))
  864. (setq to-be-removed (current-buffer))
  865. (goto-char (point-min))
  866. (while (re-search-forward org-babel-src-block-regexp nil t)
  867. (goto-char (match-beginning 0))
  868. (let ((full-block (match-string 0))
  869. (beg-block (match-beginning 0))
  870. (end-block (match-end 0))
  871. (lang (match-string 2))
  872. (beg-lang (match-beginning 2))
  873. (end-lang (match-end 2))
  874. (switches (match-string 3))
  875. (beg-switches (match-beginning 3))
  876. (end-switches (match-end 3))
  877. (header-args (match-string 4))
  878. (beg-header-args (match-beginning 4))
  879. (end-header-args (match-end 4))
  880. (body (match-string 5))
  881. (beg-body (match-beginning 5))
  882. (end-body (match-end 5)))
  883. ,@body
  884. (goto-char end-block))))
  885. (unless visited-p (kill-buffer to-be-removed))
  886. (goto-char point))))
  887. (def-edebug-spec org-babel-map-src-blocks (form body))
  888. ;;;###autoload
  889. (defmacro org-babel-map-inline-src-blocks (file &rest body)
  890. "Evaluate BODY forms on each inline source-block in FILE.
  891. If FILE is nil evaluate BODY forms on source blocks in current
  892. buffer."
  893. (declare (indent 1))
  894. (let ((tempvar (make-symbol "file")))
  895. `(let* ((,tempvar ,file)
  896. (visited-p (or (null ,tempvar)
  897. (get-file-buffer (expand-file-name ,tempvar))))
  898. (point (point)) to-be-removed)
  899. (save-window-excursion
  900. (when ,tempvar (find-file ,tempvar))
  901. (setq to-be-removed (current-buffer))
  902. (goto-char (point-min))
  903. (while (re-search-forward org-babel-inline-src-block-regexp nil t)
  904. (goto-char (match-beginning 1))
  905. (save-match-data ,@body)
  906. (goto-char (match-end 0))))
  907. (unless visited-p (kill-buffer to-be-removed))
  908. (goto-char point))))
  909. (def-edebug-spec org-babel-map-inline-src-blocks (form body))
  910. (defvar org-babel-lob-one-liner-regexp)
  911. ;;;###autoload
  912. (defmacro org-babel-map-call-lines (file &rest body)
  913. "Evaluate BODY forms on each call line in FILE.
  914. If FILE is nil evaluate BODY forms on source blocks in current
  915. buffer."
  916. (declare (indent 1))
  917. (let ((tempvar (make-symbol "file")))
  918. `(let* ((,tempvar ,file)
  919. (visited-p (or (null ,tempvar)
  920. (get-file-buffer (expand-file-name ,tempvar))))
  921. (point (point)) to-be-removed)
  922. (save-window-excursion
  923. (when ,tempvar (find-file ,tempvar))
  924. (setq to-be-removed (current-buffer))
  925. (goto-char (point-min))
  926. (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
  927. (goto-char (match-beginning 1))
  928. (save-match-data ,@body)
  929. (goto-char (match-end 0))))
  930. (unless visited-p (kill-buffer to-be-removed))
  931. (goto-char point))))
  932. (def-edebug-spec org-babel-map-call-lines (form body))
  933. ;;;###autoload
  934. (defmacro org-babel-map-executables (file &rest body)
  935. (declare (indent 1))
  936. (let ((tempvar (make-symbol "file"))
  937. (rx (make-symbol "rx")))
  938. `(let* ((,tempvar ,file)
  939. (,rx (concat "\\(" org-babel-src-block-regexp
  940. "\\|" org-babel-inline-src-block-regexp
  941. "\\|" org-babel-lob-one-liner-regexp "\\)"))
  942. (visited-p (or (null ,tempvar)
  943. (get-file-buffer (expand-file-name ,tempvar))))
  944. (point (point)) to-be-removed)
  945. (save-window-excursion
  946. (when ,tempvar (find-file ,tempvar))
  947. (setq to-be-removed (current-buffer))
  948. (goto-char (point-min))
  949. (while (re-search-forward ,rx nil t)
  950. (goto-char (match-beginning 1))
  951. (when (looking-at org-babel-inline-src-block-regexp)(forward-char 1))
  952. (save-match-data ,@body)
  953. (goto-char (match-end 0))))
  954. (unless visited-p (kill-buffer to-be-removed))
  955. (goto-char point))))
  956. (def-edebug-spec org-babel-map-executables (form body))
  957. ;;;###autoload
  958. (defun org-babel-execute-buffer (&optional arg)
  959. "Execute source code blocks in a buffer.
  960. Call `org-babel-execute-src-block' on every source block in
  961. the current buffer."
  962. (interactive "P")
  963. (org-babel-eval-wipe-error-buffer)
  964. (org-save-outline-visibility t
  965. (org-babel-map-executables nil
  966. (if (looking-at org-babel-lob-one-liner-regexp)
  967. (org-babel-lob-execute-maybe)
  968. (org-babel-execute-src-block arg)))))
  969. ;;;###autoload
  970. (defun org-babel-execute-subtree (&optional arg)
  971. "Execute source code blocks in a subtree.
  972. Call `org-babel-execute-src-block' on every source block in
  973. the current subtree."
  974. (interactive "P")
  975. (save-restriction
  976. (save-excursion
  977. (org-narrow-to-subtree)
  978. (org-babel-execute-buffer arg)
  979. (widen))))
  980. ;;;###autoload
  981. (defun org-babel-sha1-hash (&optional info)
  982. "Generate an sha1 hash based on the value of info."
  983. (interactive)
  984. (let ((print-level nil)
  985. (info (or info (org-babel-get-src-block-info))))
  986. (setf (nth 2 info)
  987. (sort (copy-sequence (nth 2 info))
  988. (lambda (a b) (string< (car a) (car b)))))
  989. (let* ((rm (lambda (lst)
  990. (dolist (p '("replace" "silent" "none"
  991. "append" "prepend"))
  992. (setq lst (remove p lst)))
  993. lst))
  994. (norm (lambda (arg)
  995. (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
  996. (copy-sequence (cdr arg))
  997. (cdr arg))))
  998. (when (and v (not (and (sequencep v)
  999. (not (consp v))
  1000. (= (length v) 0))))
  1001. (cond
  1002. ((and (listp v) ; lists are sorted
  1003. (member (car arg) '(:result-params)))
  1004. (sort (funcall rm v) #'string<))
  1005. ((and (stringp v) ; strings are sorted
  1006. (member (car arg) '(:results :exports)))
  1007. (mapconcat #'identity (sort (funcall rm (split-string v))
  1008. #'string<) " "))
  1009. (t v)))))))
  1010. ((lambda (hash)
  1011. (when (org-called-interactively-p 'interactive) (message hash)) hash)
  1012. (let ((it (format "%s-%s"
  1013. (mapconcat
  1014. #'identity
  1015. (delq nil (mapcar (lambda (arg)
  1016. (let ((normalized (funcall norm arg)))
  1017. (when normalized
  1018. (format "%S" normalized))))
  1019. (nth 2 info))) ":")
  1020. (nth 1 info))))
  1021. (sha1 it))))))
  1022. (defun org-babel-current-result-hash ()
  1023. "Return the current in-buffer hash."
  1024. (org-babel-where-is-src-block-result)
  1025. (org-no-properties (match-string 5)))
  1026. (defun org-babel-set-current-result-hash (hash)
  1027. "Set the current in-buffer hash to HASH."
  1028. (org-babel-where-is-src-block-result)
  1029. (save-excursion (goto-char (match-beginning 3))
  1030. ;; (mapc #'delete-overlay (overlays-at (point)))
  1031. (replace-match hash nil nil nil 3)
  1032. (org-babel-hide-hash)))
  1033. (defun org-babel-hide-hash ()
  1034. "Hide the hash in the current results line.
  1035. Only the initial `org-babel-hash-show' characters of the hash
  1036. will remain visible."
  1037. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  1038. (save-excursion
  1039. (when (and (re-search-forward org-babel-result-regexp nil t)
  1040. (match-string 5))
  1041. (let* ((start (match-beginning 5))
  1042. (hide-start (+ org-babel-hash-show start))
  1043. (end (match-end 5))
  1044. (hash (match-string 5))
  1045. ov1 ov2)
  1046. (setq ov1 (make-overlay start hide-start))
  1047. (setq ov2 (make-overlay hide-start end))
  1048. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  1049. (overlay-put ov1 'babel-hash hash)))))
  1050. (defun org-babel-hide-all-hashes ()
  1051. "Hide the hash in the current buffer.
  1052. Only the initial `org-babel-hash-show' characters of each hash
  1053. will remain visible. This function should be called as part of
  1054. the `org-mode-hook'."
  1055. (save-excursion
  1056. (while (and (not org-babel-hash-show-time)
  1057. (re-search-forward org-babel-result-regexp nil t))
  1058. (goto-char (match-beginning 0))
  1059. (org-babel-hide-hash)
  1060. (goto-char (match-end 0)))))
  1061. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  1062. (defun org-babel-hash-at-point (&optional point)
  1063. "Return the value of the hash at POINT.
  1064. The hash is also added as the last element of the kill ring.
  1065. This can be called with C-c C-c."
  1066. (interactive)
  1067. (let ((hash (car (delq nil (mapcar
  1068. (lambda (ol) (overlay-get ol 'babel-hash))
  1069. (overlays-at (or point (point))))))))
  1070. (when hash (kill-new hash) (message hash))))
  1071. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  1072. (defun org-babel-result-hide-spec ()
  1073. "Hide portions of results lines.
  1074. Add `org-babel-hide-result' as an invisibility spec for hiding
  1075. portions of results lines."
  1076. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  1077. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  1078. (defvar org-babel-hide-result-overlays nil
  1079. "Overlays hiding results.")
  1080. (defun org-babel-result-hide-all ()
  1081. "Fold all results in the current buffer."
  1082. (interactive)
  1083. (org-babel-show-result-all)
  1084. (save-excursion
  1085. (while (re-search-forward org-babel-result-regexp nil t)
  1086. (save-excursion (goto-char (match-beginning 0))
  1087. (org-babel-hide-result-toggle-maybe)))))
  1088. (defun org-babel-show-result-all ()
  1089. "Unfold all results in the current buffer."
  1090. (mapc 'delete-overlay org-babel-hide-result-overlays)
  1091. (setq org-babel-hide-result-overlays nil))
  1092. ;;;###autoload
  1093. (defun org-babel-hide-result-toggle-maybe ()
  1094. "Toggle visibility of result at point."
  1095. (interactive)
  1096. (let ((case-fold-search t))
  1097. (if (save-excursion
  1098. (beginning-of-line 1)
  1099. (looking-at org-babel-result-regexp))
  1100. (progn (org-babel-hide-result-toggle)
  1101. t) ;; to signal that we took action
  1102. nil))) ;; to signal that we did not
  1103. (defun org-babel-hide-result-toggle (&optional force)
  1104. "Toggle the visibility of the current result."
  1105. (interactive)
  1106. (save-excursion
  1107. (beginning-of-line)
  1108. (if (re-search-forward org-babel-result-regexp nil t)
  1109. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  1110. (end (progn
  1111. (while (looking-at org-babel-multi-line-header-regexp)
  1112. (forward-line 1))
  1113. (goto-char (- (org-babel-result-end) 1)) (point)))
  1114. ov)
  1115. (if (memq t (mapcar (lambda (overlay)
  1116. (eq (overlay-get overlay 'invisible)
  1117. 'org-babel-hide-result))
  1118. (overlays-at start)))
  1119. (if (or (not force) (eq force 'off))
  1120. (mapc (lambda (ov)
  1121. (when (member ov org-babel-hide-result-overlays)
  1122. (setq org-babel-hide-result-overlays
  1123. (delq ov org-babel-hide-result-overlays)))
  1124. (when (eq (overlay-get ov 'invisible)
  1125. 'org-babel-hide-result)
  1126. (delete-overlay ov)))
  1127. (overlays-at start)))
  1128. (setq ov (make-overlay start end))
  1129. (overlay-put ov 'invisible 'org-babel-hide-result)
  1130. ;; make the block accessible to isearch
  1131. (overlay-put
  1132. ov 'isearch-open-invisible
  1133. (lambda (ov)
  1134. (when (member ov org-babel-hide-result-overlays)
  1135. (setq org-babel-hide-result-overlays
  1136. (delq ov org-babel-hide-result-overlays)))
  1137. (when (eq (overlay-get ov 'invisible)
  1138. 'org-babel-hide-result)
  1139. (delete-overlay ov))))
  1140. (push ov org-babel-hide-result-overlays)))
  1141. (error "Not looking at a result line"))))
  1142. ;; org-tab-after-check-for-cycling-hook
  1143. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  1144. ;; Remove overlays when changing major mode
  1145. (add-hook 'org-mode-hook
  1146. (lambda () (org-add-hook 'change-major-mode-hook
  1147. 'org-babel-show-result-all 'append 'local)))
  1148. (defvar org-file-properties)
  1149. (defun org-babel-params-from-properties (&optional lang)
  1150. "Retrieve parameters specified as properties.
  1151. Return an association list of any source block params which
  1152. may be specified in the properties of the current outline entry."
  1153. (save-match-data
  1154. (let (val sym)
  1155. (org-babel-parse-multiple-vars
  1156. (delq nil
  1157. (mapcar
  1158. (lambda (header-arg)
  1159. (and (setq val (org-entry-get (point) header-arg t))
  1160. (cons (intern (concat ":" header-arg))
  1161. (org-babel-read val))))
  1162. (mapcar
  1163. #'symbol-name
  1164. (mapcar
  1165. #'car
  1166. (org-babel-combine-header-arg-lists
  1167. org-babel-common-header-args-w-values
  1168. (progn
  1169. (setq sym (intern (concat "org-babel-header-args:" lang)))
  1170. (and (boundp sym) (eval sym))))))))))))
  1171. (defvar org-src-preserve-indentation)
  1172. (defun org-babel-parse-src-block-match ()
  1173. "Parse the results from a match of the `org-babel-src-block-regexp'."
  1174. (let* ((block-indentation (length (match-string 1)))
  1175. (lang (org-no-properties (match-string 2)))
  1176. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  1177. (switches (match-string 3))
  1178. (body (org-no-properties
  1179. (let* ((body (match-string 5))
  1180. (sub-length (- (length body) 1)))
  1181. (if (and (> sub-length 0)
  1182. (string= "\n" (substring body sub-length)))
  1183. (substring body 0 sub-length)
  1184. (or body "")))))
  1185. (preserve-indentation (or org-src-preserve-indentation
  1186. (save-match-data
  1187. (string-match "-i\\>" switches)))))
  1188. (list lang
  1189. ;; get block body less properties, protective commas, and indentation
  1190. (with-temp-buffer
  1191. (save-match-data
  1192. (insert (org-unescape-code-in-string body))
  1193. (unless preserve-indentation (org-do-remove-indentation))
  1194. (buffer-string)))
  1195. (org-babel-merge-params
  1196. org-babel-default-header-args
  1197. (org-babel-params-from-properties lang)
  1198. (if (boundp lang-headers) (eval lang-headers) nil)
  1199. (org-babel-parse-header-arguments
  1200. (org-no-properties (or (match-string 4) ""))))
  1201. switches
  1202. block-indentation)))
  1203. (defun org-babel-parse-inline-src-block-match ()
  1204. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  1205. (let* ((lang (org-no-properties (match-string 2)))
  1206. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  1207. (list lang
  1208. (org-unescape-code-in-string (org-no-properties (match-string 5)))
  1209. (org-babel-merge-params
  1210. org-babel-default-inline-header-args
  1211. (org-babel-params-from-properties lang)
  1212. (if (boundp lang-headers) (eval lang-headers) nil)
  1213. (org-babel-parse-header-arguments
  1214. (org-no-properties (or (match-string 4) "")))))))
  1215. (defun org-babel-balanced-split (string alts)
  1216. "Split STRING on instances of ALTS.
  1217. ALTS is a cons of two character options where each option may be
  1218. either the numeric code of a single character or a list of
  1219. character alternatives. For example to split on balanced
  1220. instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
  1221. (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
  1222. (matched (lambda (ch last)
  1223. (if (consp alts)
  1224. (and (funcall matches ch (cdr alts))
  1225. (funcall matches last (car alts)))
  1226. (funcall matches ch alts))))
  1227. (balance 0) (last 0)
  1228. quote partial lst)
  1229. (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
  1230. (setq balance (+ balance
  1231. (cond ((or (equal 91 ch) (equal 40 ch)) 1)
  1232. ((or (equal 93 ch) (equal 41 ch)) -1)
  1233. (t 0))))
  1234. (when (and (equal 34 ch) (not (equal 92 last)))
  1235. (setq quote (not quote)))
  1236. (setq partial (cons ch partial))
  1237. (when (and (= balance 0) (not quote) (funcall matched ch last))
  1238. (setq lst (cons (apply #'string (nreverse
  1239. (if (consp alts)
  1240. (cddr partial)
  1241. (cdr partial))))
  1242. lst))
  1243. (setq partial nil))
  1244. (setq last ch))
  1245. (string-to-list string))
  1246. (nreverse (cons (apply #'string (nreverse partial)) lst))))
  1247. (defun org-babel-join-splits-near-ch (ch list)
  1248. "Join splits where \"=\" is on either end of the split."
  1249. (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
  1250. (first= (lambda (str) (= ch (aref str 0)))))
  1251. (reverse
  1252. (org-reduce (lambda (acc el)
  1253. (let ((head (car acc)))
  1254. (if (and head (or (funcall last= head) (funcall first= el)))
  1255. (cons (concat head el) (cdr acc))
  1256. (cons el acc))))
  1257. list :initial-value nil))))
  1258. (defun org-babel-parse-header-arguments (arg-string)
  1259. "Parse a string of header arguments returning an alist."
  1260. (when (> (length arg-string) 0)
  1261. (org-babel-parse-multiple-vars
  1262. (delq nil
  1263. (mapcar
  1264. (lambda (arg)
  1265. (if (string-match
  1266. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  1267. arg)
  1268. (cons (intern (match-string 1 arg))
  1269. (org-babel-read (org-babel-chomp (match-string 2 arg))))
  1270. (cons (intern (org-babel-chomp arg)) nil)))
  1271. ((lambda (raw)
  1272. (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))
  1273. (org-babel-balanced-split arg-string '((32 9) . 58))))))))
  1274. (defun org-babel-parse-multiple-vars (header-arguments)
  1275. "Expand multiple variable assignments behind a single :var keyword.
  1276. This allows expression of multiple variables with one :var as
  1277. shown below.
  1278. #+PROPERTY: var foo=1, bar=2"
  1279. (let (results)
  1280. (mapc (lambda (pair)
  1281. (if (eq (car pair) :var)
  1282. (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
  1283. (org-babel-join-splits-near-ch
  1284. 61 (org-babel-balanced-split (cdr pair) 32)))
  1285. (push pair results)))
  1286. header-arguments)
  1287. (nreverse results)))
  1288. (defun org-babel-process-params (params)
  1289. "Expand variables in PARAMS and add summary parameters."
  1290. (let* ((processed-vars (mapcar (lambda (el)
  1291. (if (consp (cdr el))
  1292. (cdr el)
  1293. (org-babel-ref-parse (cdr el))))
  1294. (org-babel-get-header params :var)))
  1295. (vars-and-names (if (and (assoc :colname-names params)
  1296. (assoc :rowname-names params))
  1297. (list processed-vars)
  1298. (org-babel-disassemble-tables
  1299. processed-vars
  1300. (cdr (assoc :hlines params))
  1301. (cdr (assoc :colnames params))
  1302. (cdr (assoc :rownames params)))))
  1303. (raw-result (or (cdr (assoc :results params)) ""))
  1304. (result-params (append
  1305. (split-string (if (stringp raw-result)
  1306. raw-result
  1307. (eval raw-result)))
  1308. (cdr (assoc :result-params params)))))
  1309. (append
  1310. (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
  1311. (list
  1312. (cons :colname-names (or (cdr (assoc :colname-names params))
  1313. (cadr vars-and-names)))
  1314. (cons :rowname-names (or (cdr (assoc :rowname-names params))
  1315. (caddr vars-and-names)))
  1316. (cons :result-params result-params)
  1317. (cons :result-type (cond ((member "output" result-params) 'output)
  1318. ((member "value" result-params) 'value)
  1319. (t 'value))))
  1320. (org-babel-get-header params :var 'other))))
  1321. ;; row and column names
  1322. (defun org-babel-del-hlines (table)
  1323. "Remove all 'hlines from TABLE."
  1324. (remove 'hline table))
  1325. (defun org-babel-get-colnames (table)
  1326. "Return the column names of TABLE.
  1327. Return a cons cell, the `car' of which contains the TABLE less
  1328. colnames, and the `cdr' of which contains a list of the column
  1329. names."
  1330. (if (equal 'hline (nth 1 table))
  1331. (cons (cddr table) (car table))
  1332. (cons (cdr table) (car table))))
  1333. (defun org-babel-get-rownames (table)
  1334. "Return the row names of TABLE.
  1335. Return a cons cell, the `car' of which contains the TABLE less
  1336. colnames, and the `cdr' of which contains a list of the column
  1337. names. Note: this function removes any hlines in TABLE."
  1338. (let* ((trans (lambda (table) (apply #'mapcar* #'list table)))
  1339. (width (apply 'max
  1340. (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  1341. (table (funcall trans (mapcar (lambda (row)
  1342. (if (not (equal row 'hline))
  1343. row
  1344. (setq row '())
  1345. (dotimes (n width)
  1346. (setq row (cons 'hline row)))
  1347. row))
  1348. table))))
  1349. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  1350. (funcall trans (cdr table)))
  1351. (remove 'hline (car table)))))
  1352. (defun org-babel-put-colnames (table colnames)
  1353. "Add COLNAMES to TABLE if they exist."
  1354. (if colnames (apply 'list colnames 'hline table) table))
  1355. (defun org-babel-put-rownames (table rownames)
  1356. "Add ROWNAMES to TABLE if they exist."
  1357. (if rownames
  1358. (mapcar (lambda (row)
  1359. (if (listp row)
  1360. (cons (or (pop rownames) "") row)
  1361. row)) table)
  1362. table))
  1363. (defun org-babel-pick-name (names selector)
  1364. "Select one out of an alist of row or column names.
  1365. SELECTOR can be either a list of names in which case those names
  1366. will be returned directly, or an index into the list NAMES in
  1367. which case the indexed names will be return."
  1368. (if (listp selector)
  1369. selector
  1370. (when names
  1371. (if (and selector (symbolp selector) (not (equal t selector)))
  1372. (cdr (assoc selector names))
  1373. (if (integerp selector)
  1374. (nth (- selector 1) names)
  1375. (cdr (car (last names))))))))
  1376. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  1377. "Parse tables for further processing.
  1378. Process the variables in VARS according to the HLINES,
  1379. ROWNAMES and COLNAMES header arguments. Return a list consisting
  1380. of the vars, cnames and rnames."
  1381. (let (cnames rnames)
  1382. (list
  1383. (mapcar
  1384. (lambda (var)
  1385. (when (listp (cdr var))
  1386. (when (and (not (equal colnames "no"))
  1387. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  1388. (not (member 'hline (cddr (cdr var)))))))
  1389. (let ((both (org-babel-get-colnames (cdr var))))
  1390. (setq cnames (cons (cons (car var) (cdr both))
  1391. cnames))
  1392. (setq var (cons (car var) (car both)))))
  1393. (when (and rownames (not (equal rownames "no")))
  1394. (let ((both (org-babel-get-rownames (cdr var))))
  1395. (setq rnames (cons (cons (car var) (cdr both))
  1396. rnames))
  1397. (setq var (cons (car var) (car both)))))
  1398. (when (and hlines (not (equal hlines "yes")))
  1399. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  1400. var)
  1401. vars)
  1402. (reverse cnames) (reverse rnames))))
  1403. (defun org-babel-reassemble-table (table colnames rownames)
  1404. "Add column and row names to a table.
  1405. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  1406. to the table for reinsertion to org-mode."
  1407. (if (listp table)
  1408. ((lambda (table)
  1409. (if (and colnames (listp (car table)) (= (length (car table))
  1410. (length colnames)))
  1411. (org-babel-put-colnames table colnames) table))
  1412. (if (and rownames (= (length table) (length rownames)))
  1413. (org-babel-put-rownames table rownames) table))
  1414. table))
  1415. (defun org-babel-where-is-src-block-head ()
  1416. "Find where the current source block begins.
  1417. Return the point at the beginning of the current source
  1418. block. Specifically at the beginning of the #+BEGIN_SRC line.
  1419. If the point is not on a source block then return nil."
  1420. (let ((initial (point)) (case-fold-search t) top bottom)
  1421. (or
  1422. (save-excursion ;; on a source name line or a #+header line
  1423. (beginning-of-line 1)
  1424. (and (or (looking-at org-babel-src-name-regexp)
  1425. (looking-at org-babel-multi-line-header-regexp))
  1426. (progn
  1427. (while (and (forward-line 1)
  1428. (or (looking-at org-babel-src-name-regexp)
  1429. (looking-at org-babel-multi-line-header-regexp))))
  1430. (looking-at org-babel-src-block-regexp))
  1431. (point)))
  1432. (save-excursion ;; on a #+begin_src line
  1433. (beginning-of-line 1)
  1434. (and (looking-at org-babel-src-block-regexp)
  1435. (point)))
  1436. (save-excursion ;; inside a src block
  1437. (and
  1438. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  1439. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  1440. (< top initial) (< initial bottom)
  1441. (progn (goto-char top) (beginning-of-line 1)
  1442. (looking-at org-babel-src-block-regexp))
  1443. (point))))))
  1444. ;;;###autoload
  1445. (defun org-babel-goto-src-block-head ()
  1446. "Go to the beginning of the current code block."
  1447. (interactive)
  1448. ((lambda (head)
  1449. (if head (goto-char head) (error "Not currently in a code block")))
  1450. (org-babel-where-is-src-block-head)))
  1451. ;;;###autoload
  1452. (defun org-babel-goto-named-src-block (name)
  1453. "Go to a named source-code block."
  1454. (interactive
  1455. (let ((completion-ignore-case t)
  1456. (case-fold-search t)
  1457. (under-point (thing-at-point 'line)))
  1458. (list (org-icompleting-read
  1459. "source-block name: " (org-babel-src-block-names) nil t
  1460. (cond
  1461. ;; noweb
  1462. ((string-match (org-babel-noweb-wrap) under-point)
  1463. (let ((block-name (match-string 1 under-point)))
  1464. (string-match "[^(]*" block-name)
  1465. (match-string 0 block-name)))
  1466. ;; #+call:
  1467. ((string-match org-babel-lob-one-liner-regexp under-point)
  1468. (let ((source-info (car (org-babel-lob-get-info))))
  1469. (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
  1470. (let ((source-name (match-string 1 source-info)))
  1471. source-name))))
  1472. ;; #+results:
  1473. ((string-match (concat "#\\+" org-babel-results-keyword
  1474. "\\:\s+\\([^\\(]*\\)") under-point)
  1475. (match-string 1 under-point))
  1476. ;; symbol-at-point
  1477. ((and (thing-at-point 'symbol))
  1478. (org-babel-find-named-block (thing-at-point 'symbol))
  1479. (thing-at-point 'symbol))
  1480. (""))))))
  1481. (let ((point (org-babel-find-named-block name)))
  1482. (if point
  1483. ;; taken from `org-open-at-point'
  1484. (progn (org-mark-ring-push) (goto-char point) (org-show-context))
  1485. (message "source-code block '%s' not found in this buffer" name))))
  1486. (defun org-babel-find-named-block (name)
  1487. "Find a named source-code block.
  1488. Return the location of the source block identified by source
  1489. NAME, or nil if no such block exists. Set match data according to
  1490. org-babel-named-src-block-regexp."
  1491. (save-excursion
  1492. (let ((case-fold-search t)
  1493. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  1494. (goto-char (point-min))
  1495. (when (or (re-search-forward regexp nil t)
  1496. (re-search-backward regexp nil t))
  1497. (match-beginning 0)))))
  1498. (defun org-babel-src-block-names (&optional file)
  1499. "Returns the names of source blocks in FILE or the current buffer."
  1500. (save-excursion
  1501. (when file (find-file file)) (goto-char (point-min))
  1502. (let ((case-fold-search t) names)
  1503. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  1504. (setq names (cons (match-string 3) names)))
  1505. names)))
  1506. ;;;###autoload
  1507. (defun org-babel-goto-named-result (name)
  1508. "Go to a named result."
  1509. (interactive
  1510. (let ((completion-ignore-case t))
  1511. (list (org-icompleting-read "source-block name: "
  1512. (org-babel-result-names) nil t))))
  1513. (let ((point (org-babel-find-named-result name)))
  1514. (if point
  1515. ;; taken from `org-open-at-point'
  1516. (progn (goto-char point) (org-show-context))
  1517. (message "result '%s' not found in this buffer" name))))
  1518. (defun org-babel-find-named-result (name &optional point)
  1519. "Find a named result.
  1520. Return the location of the result named NAME in the current
  1521. buffer or nil if no such result exists."
  1522. (save-excursion
  1523. (let ((case-fold-search t))
  1524. (goto-char (or point (point-min)))
  1525. (catch 'is-a-code-block
  1526. (when (re-search-forward
  1527. (concat org-babel-result-regexp
  1528. "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]") nil t)
  1529. (when (and (string= "name" (downcase (match-string 1)))
  1530. (or (beginning-of-line 1)
  1531. (looking-at org-babel-src-block-regexp)
  1532. (looking-at org-babel-multi-line-header-regexp)))
  1533. (throw 'is-a-code-block (org-babel-find-named-result name (point))))
  1534. (beginning-of-line 0) (point))))))
  1535. (defun org-babel-result-names (&optional file)
  1536. "Returns the names of results in FILE or the current buffer."
  1537. (save-excursion
  1538. (when file (find-file file)) (goto-char (point-min))
  1539. (let ((case-fold-search t) names)
  1540. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1541. (setq names (cons (match-string 4) names)))
  1542. names)))
  1543. ;;;###autoload
  1544. (defun org-babel-next-src-block (&optional arg)
  1545. "Jump to the next source block.
  1546. With optional prefix argument ARG, jump forward ARG many source blocks."
  1547. (interactive "p")
  1548. (org-next-block arg nil org-babel-src-block-regexp))
  1549. ;;;###autoload
  1550. (defun org-babel-previous-src-block (&optional arg)
  1551. "Jump to the previous source block.
  1552. With optional prefix argument ARG, jump backward ARG many source blocks."
  1553. (interactive "p")
  1554. (org-previous-block arg org-babel-src-block-regexp))
  1555. (defvar org-babel-load-languages)
  1556. ;;;###autoload
  1557. (defun org-babel-mark-block ()
  1558. "Mark current src block."
  1559. (interactive)
  1560. ((lambda (head)
  1561. (when head
  1562. (save-excursion
  1563. (goto-char head)
  1564. (looking-at org-babel-src-block-regexp))
  1565. (push-mark (match-end 5) nil t)
  1566. (goto-char (match-beginning 5))))
  1567. (org-babel-where-is-src-block-head)))
  1568. (defun org-babel-demarcate-block (&optional arg)
  1569. "Wrap or split the code in the region or on the point.
  1570. When called from inside of a code block the current block is
  1571. split. When called from outside of a code block a new code block
  1572. is created. In both cases if the region is demarcated and if the
  1573. region is not active then the point is demarcated."
  1574. (interactive "P")
  1575. (let ((info (org-babel-get-src-block-info 'light))
  1576. (headers (progn (org-babel-where-is-src-block-head)
  1577. (match-string 4)))
  1578. (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
  1579. (if info
  1580. (mapc
  1581. (lambda (place)
  1582. (save-excursion
  1583. (goto-char place)
  1584. (let ((lang (nth 0 info))
  1585. (indent (make-string (nth 5 info) ? )))
  1586. (when (string-match "^[[:space:]]*$"
  1587. (buffer-substring (point-at-bol)
  1588. (point-at-eol)))
  1589. (delete-region (point-at-bol) (point-at-eol)))
  1590. (insert (concat
  1591. (if (looking-at "^") "" "\n")
  1592. indent "#+end_src\n"
  1593. (if arg stars indent) "\n"
  1594. indent "#+begin_src " lang
  1595. (if (> (length headers) 1)
  1596. (concat " " headers) headers)
  1597. (if (looking-at "[\n\r]")
  1598. ""
  1599. (concat "\n" (make-string (current-column) ? )))))))
  1600. (move-end-of-line 2))
  1601. (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
  1602. (let ((start (point))
  1603. (lang (org-icompleting-read "Lang: "
  1604. (mapcar (lambda (el) (symbol-name (car el)))
  1605. org-babel-load-languages)))
  1606. (body (delete-and-extract-region
  1607. (if (org-region-active-p) (mark) (point)) (point))))
  1608. (insert (concat (if (looking-at "^") "" "\n")
  1609. (if arg (concat stars "\n") "")
  1610. "#+begin_src " lang "\n"
  1611. body
  1612. (if (or (= (length body) 0)
  1613. (string-match "[\r\n]$" body)) "" "\n")
  1614. "#+end_src\n"))
  1615. (goto-char start) (move-end-of-line 1)))))
  1616. (defvar org-babel-lob-one-liner-regexp)
  1617. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1618. "Find where the current source block results begin.
  1619. Return the point at the beginning of the result of the current
  1620. source block. Specifically at the beginning of the results line.
  1621. If no result exists for this block then create a results line
  1622. following the source block."
  1623. (save-excursion
  1624. (let* ((case-fold-search t)
  1625. (on-lob-line (save-excursion
  1626. (beginning-of-line 1)
  1627. (looking-at org-babel-lob-one-liner-regexp)))
  1628. (inlinep (when (org-babel-get-inline-src-block-matches)
  1629. (match-end 0)))
  1630. (name (if on-lob-line
  1631. (mapconcat #'identity (butlast (org-babel-lob-get-info))
  1632. "")
  1633. (nth 4 (or info (org-babel-get-src-block-info 'light)))))
  1634. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1635. found beg end)
  1636. (when head (goto-char head))
  1637. (org-with-wide-buffer
  1638. (setq
  1639. found ;; was there a result (before we potentially insert one)
  1640. (or
  1641. inlinep
  1642. (and
  1643. ;; named results:
  1644. ;; - return t if it is found, else return nil
  1645. ;; - if it does not need to be rebuilt, then don't set end
  1646. ;; - if it does need to be rebuilt then do set end
  1647. name (setq beg (org-babel-find-named-result name))
  1648. (prog1 beg
  1649. (when (and hash (not (string= hash (match-string 5))))
  1650. (goto-char beg) (setq end beg) ;; beginning of result
  1651. (forward-line 1)
  1652. (delete-region end (org-babel-result-end)) nil)))
  1653. (and
  1654. ;; unnamed results:
  1655. ;; - return t if it is found, else return nil
  1656. ;; - if it is found, and the hash doesn't match, delete and set end
  1657. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1658. (progn (end-of-line 1)
  1659. (if (eobp) (insert "\n") (forward-char 1))
  1660. (setq end (point))
  1661. (or (and
  1662. (not name)
  1663. (progn ;; unnamed results line already exists
  1664. (catch 'non-comment
  1665. (while (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1666. (beginning-of-line 1)
  1667. (cond
  1668. ((looking-at (concat org-babel-result-regexp "\n"))
  1669. (throw 'non-comment t))
  1670. ((looking-at "^[ \t]*#") (end-of-line 1))
  1671. (t (throw 'non-comment nil))))))
  1672. (let ((this-hash (match-string 5)))
  1673. (prog1 (point)
  1674. ;; must remove and rebuild if hash!=old-hash
  1675. (if (and hash (not (string= hash this-hash)))
  1676. (prog1 nil
  1677. (forward-line 1)
  1678. (delete-region
  1679. end (org-babel-result-end)))
  1680. (setq end nil)))))))))))
  1681. (if (not (and insert end)) found
  1682. (goto-char end)
  1683. (unless beg
  1684. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1685. (insert (concat
  1686. (when (wholenump indent) (make-string indent ? ))
  1687. "#+" org-babel-results-keyword
  1688. (when hash
  1689. (if org-babel-hash-show-time
  1690. (concat
  1691. "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash"]")
  1692. (concat "["hash"]")))
  1693. ":"
  1694. (when name (concat " " name)) "\n"))
  1695. (unless beg (insert "\n") (backward-char))
  1696. (beginning-of-line 0)
  1697. (if hash (org-babel-hide-hash))
  1698. (point)))))
  1699. (defvar org-block-regexp)
  1700. (defun org-babel-read-result ()
  1701. "Read the result at `point' into emacs-lisp."
  1702. (let ((case-fold-search t) result-string)
  1703. (cond
  1704. ((org-at-table-p) (org-babel-read-table))
  1705. ((org-at-item-p) (org-babel-read-list))
  1706. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1707. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1708. ((looking-at "^[ \t]*: ")
  1709. (setq result-string
  1710. (org-babel-trim
  1711. (mapconcat (lambda (line)
  1712. (if (and (> (length line) 1)
  1713. (string-match "^[ \t]*: \\(.+\\)" line))
  1714. (match-string 1 line)
  1715. line))
  1716. (split-string
  1717. (buffer-substring
  1718. (point) (org-babel-result-end)) "[\r\n]+")
  1719. "\n")))
  1720. (or (org-babel-number-p result-string) result-string))
  1721. ((looking-at org-babel-result-regexp)
  1722. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1723. (defun org-babel-read-table ()
  1724. "Read the table at `point' into emacs-lisp."
  1725. (mapcar (lambda (row)
  1726. (if (and (symbolp row) (equal row 'hline)) row
  1727. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
  1728. (org-table-to-lisp)))
  1729. (defun org-babel-read-list ()
  1730. "Read the list at `point' into emacs-lisp."
  1731. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
  1732. (mapcar #'cadr (cdr (org-list-parse-list)))))
  1733. (defvar org-link-types-re)
  1734. (defun org-babel-read-link ()
  1735. "Read the link at `point' into emacs-lisp.
  1736. If the path of the link is a file path it is expanded using
  1737. `expand-file-name'."
  1738. (let* ((case-fold-search t)
  1739. (raw (and (looking-at org-bracket-link-regexp)
  1740. (org-no-properties (match-string 1))))
  1741. (type (and (string-match org-link-types-re raw)
  1742. (match-string 1 raw))))
  1743. (cond
  1744. ((not type) (expand-file-name raw))
  1745. ((string= type "file")
  1746. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1747. (expand-file-name (match-string 2 raw))))
  1748. (t raw))))
  1749. (defun org-babel-format-result (result &optional sep)
  1750. "Format RESULT for writing to file."
  1751. (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
  1752. (if (listp result)
  1753. ;; table result
  1754. (orgtbl-to-generic
  1755. result (list :sep (or sep "\t") :fmt echo-res))
  1756. ;; scalar result
  1757. (funcall echo-res result))))
  1758. (defun org-babel-insert-result
  1759. (result &optional result-params info hash indent lang)
  1760. "Insert RESULT into the current buffer.
  1761. By default RESULT is inserted after the end of the
  1762. current source block. With optional argument RESULT-PARAMS
  1763. controls insertion of results in the org-mode file.
  1764. RESULT-PARAMS can take the following values:
  1765. replace - (default option) insert results after the source block
  1766. replacing any previously inserted results
  1767. silent -- no results are inserted into the Org-mode buffer but
  1768. the results are echoed to the minibuffer and are
  1769. ingested by Emacs (a potentially time consuming
  1770. process)
  1771. file ---- the results are interpreted as a file path, and are
  1772. inserted into the buffer using the Org-mode file syntax
  1773. list ---- the results are interpreted as an Org-mode list.
  1774. raw ----- results are added directly to the Org-mode file. This
  1775. is a good option if you code block will output org-mode
  1776. formatted text.
  1777. drawer -- results are added directly to the Org-mode file as with
  1778. \"raw\", but are wrapped in a RESULTS drawer, allowing
  1779. them to later be replaced or removed automatically.
  1780. org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
  1781. They are not comma-escaped when inserted, but Org syntax
  1782. here will be discarded when exporting the file.
  1783. html ---- results are added inside of a #+BEGIN_HTML block. This
  1784. is a good option if you code block will output html
  1785. formatted text.
  1786. latex --- results are added inside of a #+BEGIN_LATEX block.
  1787. This is a good option if you code block will output
  1788. latex formatted text.
  1789. code ---- the results are extracted in the syntax of the source
  1790. code of the language being evaluated and are added
  1791. inside of a #+BEGIN_SRC block with the source-code
  1792. language set appropriately. Note this relies on the
  1793. optional LANG argument."
  1794. (if (stringp result)
  1795. (progn
  1796. (setq result (org-no-properties result))
  1797. (when (member "file" result-params)
  1798. (setq result (org-babel-result-to-file
  1799. result (when (assoc :file-desc (nth 2 info))
  1800. (or (cdr (assoc :file-desc (nth 2 info)))
  1801. result))))))
  1802. (unless (listp result) (setq result (format "%S" result))))
  1803. (if (and result-params (member "silent" result-params))
  1804. (progn
  1805. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1806. result)
  1807. (save-excursion
  1808. (let* ((inlinep
  1809. (save-excursion
  1810. (when (or (org-babel-get-inline-src-block-matches)
  1811. (org-babel-get-lob-one-liner-matches))
  1812. (goto-char (match-end 0))
  1813. (insert (if (listp result) "\n" " "))
  1814. (point))))
  1815. (existing-result (unless inlinep
  1816. (org-babel-where-is-src-block-result
  1817. t info hash indent)))
  1818. (results-switches
  1819. (cdr (assoc :results_switches (nth 2 info))))
  1820. (visible-beg (copy-marker (point-min)))
  1821. (visible-end (copy-marker (point-max)))
  1822. ;; When results exist outside of the current visible
  1823. ;; region of the buffer, be sure to widen buffer to
  1824. ;; update them.
  1825. (outside-scope-p (and existing-result
  1826. (or (> visible-beg existing-result)
  1827. (<= visible-end existing-result))))
  1828. beg end)
  1829. (when (and (stringp result) ; ensure results end in a newline
  1830. (not inlinep)
  1831. (> (length result) 0)
  1832. (not (or (string-equal (substring result -1) "\n")
  1833. (string-equal (substring result -1) "\r"))))
  1834. (setq result (concat result "\n")))
  1835. (unwind-protect
  1836. (progn
  1837. (when outside-scope-p (widen))
  1838. (if (not existing-result)
  1839. (setq beg (or inlinep (point)))
  1840. (goto-char existing-result)
  1841. (save-excursion
  1842. (re-search-forward "#" nil t)
  1843. (setq indent (- (current-column) 1)))
  1844. (forward-line 1)
  1845. (setq beg (point))
  1846. (cond
  1847. ((member "replace" result-params)
  1848. (delete-region (point) (org-babel-result-end)))
  1849. ((member "append" result-params)
  1850. (goto-char (org-babel-result-end)) (setq beg (point-marker)))
  1851. ((member "prepend" result-params)))) ; already there
  1852. (setq results-switches
  1853. (if results-switches (concat " " results-switches) ""))
  1854. (let ((wrap (lambda (start finish &optional no-escape)
  1855. (goto-char end) (insert (concat finish "\n"))
  1856. (goto-char beg) (insert (concat start "\n"))
  1857. (unless no-escape
  1858. (org-escape-code-in-region (min (point) end) end))
  1859. (goto-char end) (goto-char (point-at-eol))
  1860. (setq end (point-marker))))
  1861. (proper-list-p (lambda (it) (and (listp it) (null (cdr (last it)))))))
  1862. ;; insert results based on type
  1863. (cond
  1864. ;; do nothing for an empty result
  1865. ((null result))
  1866. ;; insert a list if preferred
  1867. ((member "list" result-params)
  1868. (insert
  1869. (org-babel-trim
  1870. (org-list-to-generic
  1871. (cons 'unordered
  1872. (mapcar
  1873. (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
  1874. (if (listp result) result (list result))))
  1875. '(:splicep nil :istart "- " :iend "\n")))
  1876. "\n"))
  1877. ;; assume the result is a table if it's not a string
  1878. ((funcall proper-list-p result)
  1879. (goto-char beg)
  1880. (insert (concat (orgtbl-to-orgtbl
  1881. (if (or (eq 'hline (car result))
  1882. (and (listp (car result))
  1883. (listp (cdr (car result)))))
  1884. result (list result))
  1885. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1886. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1887. ((and (listp result) (not (funcall proper-list-p result)))
  1888. (insert (format "%s\n" result)))
  1889. ((member "file" result-params)
  1890. (when inlinep (goto-char inlinep))
  1891. (insert result))
  1892. (t (goto-char beg) (insert result)))
  1893. (when (funcall proper-list-p result) (goto-char (org-table-end)))
  1894. (setq end (point-marker))
  1895. ;; possibly wrap result
  1896. (cond
  1897. ((assoc :wrap (nth 2 info))
  1898. (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
  1899. (funcall wrap (concat "#+BEGIN_" name)
  1900. (concat "#+END_" (car (org-split-string name))))))
  1901. ((member "html" result-params)
  1902. (funcall wrap "#+BEGIN_HTML" "#+END_HTML"))
  1903. ((member "latex" result-params)
  1904. (funcall wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
  1905. ((member "org" result-params)
  1906. (goto-char beg) (if (org-at-table-p) (org-cycle))
  1907. (funcall wrap "#+BEGIN_SRC org" "#+END_SRC"))
  1908. ((member "code" result-params)
  1909. (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
  1910. "#+END_SRC"))
  1911. ((member "raw" result-params)
  1912. (goto-char beg) (if (org-at-table-p) (org-cycle)))
  1913. ((or (member "drawer" result-params)
  1914. ;; Stay backward compatible with <7.9.2
  1915. (member "wrap" result-params))
  1916. (goto-char beg) (if (org-at-table-p) (org-cycle))
  1917. (funcall wrap ":RESULTS:" ":END:" 'no-escape))
  1918. ((and (not (funcall proper-list-p result))
  1919. (not (member "file" result-params)))
  1920. (org-babel-examplize-region beg end results-switches)
  1921. (setq end (point)))))
  1922. ;; possibly indent the results to match the #+results line
  1923. (when (and (not inlinep) (numberp indent) indent (> indent 0)
  1924. ;; in this case `table-align' does the work for us
  1925. (not (and (listp result)
  1926. (member "append" result-params))))
  1927. (indent-rigidly beg end indent))
  1928. (if (null result)
  1929. (if (member "value" result-params)
  1930. (message "Code block returned no value.")
  1931. (message "Code block produced no output."))
  1932. (message "Code block evaluation complete.")))
  1933. (when outside-scope-p (narrow-to-region visible-beg visible-end))
  1934. (set-marker visible-beg nil)
  1935. (set-marker visible-end nil))))))
  1936. (defun org-babel-remove-result (&optional info)
  1937. "Remove the result of the current source block."
  1938. (interactive)
  1939. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1940. (when location
  1941. (setq start (- location 1))
  1942. (save-excursion
  1943. (goto-char location) (forward-line 1)
  1944. (delete-region start (org-babel-result-end))))))
  1945. (defun org-babel-result-end ()
  1946. "Return the point at the end of the current set of results."
  1947. (save-excursion
  1948. (cond
  1949. ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
  1950. ((org-at-item-p) (let* ((struct (org-list-struct))
  1951. (prvs (org-list-prevs-alist struct)))
  1952. (org-list-get-list-end (point-at-bol) struct prvs)))
  1953. ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
  1954. (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
  1955. (forward-char 1) (point)))
  1956. (t
  1957. (let ((case-fold-search t))
  1958. (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
  1959. (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
  1960. nil t)
  1961. (forward-char 1))
  1962. (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1963. (forward-line 1))))
  1964. (point)))))
  1965. (defun org-babel-result-to-file (result &optional description)
  1966. "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
  1967. If the `default-directory' is different from the containing
  1968. file's directory then expand relative links."
  1969. (when (stringp result)
  1970. (format "[[file:%s]%s]"
  1971. (if (and default-directory
  1972. buffer-file-name
  1973. (not (string= (expand-file-name default-directory)
  1974. (expand-file-name
  1975. (file-name-directory buffer-file-name)))))
  1976. (expand-file-name result default-directory)
  1977. result)
  1978. (if description (concat "[" description "]") ""))))
  1979. (defvar org-babel-capitalize-examplize-region-markers nil
  1980. "Make true to capitalize begin/end example markers inserted by code blocks.")
  1981. (defun org-babel-examplize-region (beg end &optional results-switches)
  1982. "Comment out region using the inline '==' or ': ' org example quote."
  1983. (interactive "*r")
  1984. (let ((chars-between (lambda (b e)
  1985. (not (string-match "^[\\s]*$" (buffer-substring b e)))))
  1986. (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
  1987. (upcase str) str))))
  1988. (if (or (funcall chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
  1989. (funcall chars-between end (save-excursion (goto-char end) (point-at-eol))))
  1990. (save-excursion
  1991. (goto-char beg)
  1992. (insert (format "=%s=" (prog1 (buffer-substring beg end)
  1993. (delete-region beg end)))))
  1994. (let ((size (count-lines beg end)))
  1995. (save-excursion
  1996. (cond ((= size 0)) ; do nothing for an empty result
  1997. ((< size org-babel-min-lines-for-block-output)
  1998. (goto-char beg)
  1999. (dotimes (n size)
  2000. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  2001. (t
  2002. (goto-char beg)
  2003. (insert (if results-switches
  2004. (format "%s%s\n"
  2005. (funcall maybe-cap "#+begin_example")
  2006. results-switches)
  2007. (funcall maybe-cap "#+begin_example\n")))
  2008. (if (markerp end) (goto-char end) (forward-char (- end beg)))
  2009. (insert (funcall maybe-cap "#+end_example\n")))))))))
  2010. (defun org-babel-update-block-body (new-body)
  2011. "Update the body of the current code block to NEW-BODY."
  2012. (if (not (org-babel-where-is-src-block-head))
  2013. (error "Not in a source block")
  2014. (save-match-data
  2015. (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
  2016. (indent-rigidly (match-beginning 5) (match-end 5) 2)))
  2017. (defun org-babel-merge-params (&rest plists)
  2018. "Combine all parameter association lists in PLISTS.
  2019. Later elements of PLISTS override the values of previous elements.
  2020. This takes into account some special considerations for certain
  2021. parameters when merging lists."
  2022. (let* ((results-exclusive-groups
  2023. (mapcar (lambda (group) (mapcar #'symbol-name group))
  2024. (cdr (assoc 'results org-babel-common-header-args-w-values))))
  2025. (exports-exclusive-groups
  2026. (mapcar (lambda (group) (mapcar #'symbol-name group))
  2027. (cdr (assoc 'exports org-babel-common-header-args-w-values))))
  2028. (variable-index 0)
  2029. (e-merge (lambda (exclusive-groups &rest result-params)
  2030. ;; maintain exclusivity of mutually exclusive parameters
  2031. (let (output)
  2032. (mapc (lambda (new-params)
  2033. (mapc (lambda (new-param)
  2034. (mapc (lambda (exclusive-group)
  2035. (when (member new-param exclusive-group)
  2036. (mapcar (lambda (excluded-param)
  2037. (setq output
  2038. (delete
  2039. excluded-param
  2040. output)))
  2041. exclusive-group)))
  2042. exclusive-groups)
  2043. (setq output (org-uniquify
  2044. (cons new-param output))))
  2045. new-params))
  2046. result-params)
  2047. output)))
  2048. params results exports tangle noweb cache vars shebang comments padline)
  2049. (mapc
  2050. (lambda (plist)
  2051. (mapc
  2052. (lambda (pair)
  2053. (case (car pair)
  2054. (:var
  2055. (let ((name (if (listp (cdr pair))
  2056. (cadr pair)
  2057. (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  2058. (cdr pair))
  2059. (intern (match-string 1 (cdr pair)))))))
  2060. (if name
  2061. (setq vars
  2062. (append
  2063. (if (member name (mapcar #'car vars))
  2064. (delq nil
  2065. (mapcar
  2066. (lambda (p)
  2067. (unless (equal (car p) name) p))
  2068. vars))
  2069. vars)
  2070. (list (cons name pair))))
  2071. ;; if no name is given and we already have named variables
  2072. ;; then assign to named variables in order
  2073. (if (and vars (nth variable-index vars))
  2074. (prog1 (setf (cddr (nth variable-index vars))
  2075. (concat (symbol-name
  2076. (car (nth variable-index vars)))
  2077. "=" (cdr pair)))
  2078. (incf variable-index))
  2079. (error "Variable \"%s\" must be assigned a default value"
  2080. (cdr pair))))))
  2081. (:results
  2082. (setq results (funcall e-merge results-exclusive-groups
  2083. results
  2084. (split-string
  2085. (let ((r (cdr pair)))
  2086. (if (stringp r) r (eval r)))))))
  2087. (:file
  2088. (when (cdr pair)
  2089. (setq results (funcall e-merge results-exclusive-groups
  2090. results '("file")))
  2091. (unless (or (member "both" exports)
  2092. (member "none" exports)
  2093. (member "code" exports))
  2094. (setq exports (funcall e-merge exports-exclusive-groups
  2095. exports '("results"))))
  2096. (setq params (cons pair (assq-delete-all (car pair) params)))))
  2097. (:exports
  2098. (setq exports (funcall e-merge exports-exclusive-groups
  2099. exports (split-string (cdr pair)))))
  2100. (:tangle ;; take the latest -- always overwrite
  2101. (setq tangle (or (list (cdr pair)) tangle)))
  2102. (:noweb
  2103. (setq noweb (funcall e-merge
  2104. '(("yes" "no" "tangle" "no-export"
  2105. "strip-export" "eval"))
  2106. noweb
  2107. (split-string (or (cdr pair) "")))))
  2108. (:cache
  2109. (setq cache (funcall e-merge '(("yes" "no")) cache
  2110. (split-string (or (cdr pair) "")))))
  2111. (:padline
  2112. (setq padline (funcall e-merge '(("yes" "no")) padline
  2113. (split-string (or (cdr pair) "")))))
  2114. (:shebang ;; take the latest -- always overwrite
  2115. (setq shebang (or (list (cdr pair)) shebang)))
  2116. (:comments
  2117. (setq comments (funcall e-merge '(("yes" "no")) comments
  2118. (split-string (or (cdr pair) "")))))
  2119. (t ;; replace: this covers e.g. :session
  2120. (setq params (cons pair (assq-delete-all (car pair) params))))))
  2121. plist))
  2122. plists)
  2123. (setq vars (reverse vars))
  2124. (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
  2125. (mapc
  2126. (lambda (hd)
  2127. (let ((key (intern (concat ":" (symbol-name hd))))
  2128. (val (eval hd)))
  2129. (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
  2130. '(results exports tangle noweb padline cache shebang comments))
  2131. params))
  2132. (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
  2133. "Set to true to use regular expressions to expand noweb references.
  2134. This results in much faster noweb reference expansion but does
  2135. not properly allow code blocks to inherit the \":noweb-ref\"
  2136. header argument from buffer or subtree wide properties.")
  2137. (defun org-babel-noweb-p (params context)
  2138. "Check if PARAMS require expansion in CONTEXT.
  2139. CONTEXT may be one of :tangle, :export or :eval."
  2140. (let* (intersect
  2141. (intersect (lambda (as bs)
  2142. (when as
  2143. (if (member (car as) bs)
  2144. (car as)
  2145. (funcall intersect (cdr as) bs))))))
  2146. (funcall intersect (case context
  2147. (:tangle '("yes" "tangle" "no-export" "strip-export"))
  2148. (:eval '("yes" "no-export" "strip-export" "eval"))
  2149. (:export '("yes")))
  2150. (split-string (or (cdr (assoc :noweb params)) "")))))
  2151. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  2152. "Expand Noweb references in the body of the current source code block.
  2153. For example the following reference would be replaced with the
  2154. body of the source-code block named 'example-block'.
  2155. <<example-block>>
  2156. Note that any text preceding the <<foo>> construct on a line will
  2157. be interposed between the lines of the replacement text. So for
  2158. example if <<foo>> is placed behind a comment, then the entire
  2159. replacement text will also be commented.
  2160. This function must be called from inside of the buffer containing
  2161. the source-code block which holds BODY.
  2162. In addition the following syntax can be used to insert the
  2163. results of evaluating the source-code block named 'example-block'.
  2164. <<example-block()>>
  2165. Any optional arguments can be passed to example-block by placing
  2166. the arguments inside the parenthesis following the convention
  2167. defined by `org-babel-lob'. For example
  2168. <<example-block(a=9)>>
  2169. would set the value of argument \"a\" equal to \"9\". Note that
  2170. these arguments are not evaluated in the current source-code
  2171. block but are passed literally to the \"example-block\"."
  2172. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  2173. (info (or info (org-babel-get-src-block-info)))
  2174. (lang (nth 0 info))
  2175. (body (nth 1 info))
  2176. (ob-nww-start org-babel-noweb-wrap-start)
  2177. (ob-nww-end org-babel-noweb-wrap-end)
  2178. (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
  2179. (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
  2180. ":noweb-ref[ \t]+" "\\)"))
  2181. (new-body "")
  2182. (nb-add (lambda (text) (setq new-body (concat new-body text))))
  2183. (c-wrap (lambda (text)
  2184. (with-temp-buffer
  2185. (funcall (intern (concat lang "-mode")))
  2186. (comment-region (point) (progn (insert text) (point)))
  2187. (org-babel-trim (buffer-string)))))
  2188. index source-name evaluate prefix blocks-in-buffer)
  2189. (with-temp-buffer
  2190. (org-set-local 'org-babel-noweb-wrap-start ob-nww-start)
  2191. (org-set-local 'org-babel-noweb-wrap-end ob-nww-end)
  2192. (insert body) (goto-char (point-min))
  2193. (setq index (point))
  2194. (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
  2195. (save-match-data (setf source-name (match-string 1)))
  2196. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  2197. (save-match-data
  2198. (setq prefix
  2199. (buffer-substring (match-beginning 0)
  2200. (save-excursion
  2201. (beginning-of-line 1) (point)))))
  2202. ;; add interval to new-body (removing noweb reference)
  2203. (goto-char (match-beginning 0))
  2204. (funcall nb-add (buffer-substring index (point)))
  2205. (goto-char (match-end 0))
  2206. (setq index (point))
  2207. (funcall nb-add
  2208. (with-current-buffer parent-buffer
  2209. (save-restriction
  2210. (widen)
  2211. (mapconcat ;; interpose PREFIX between every line
  2212. #'identity
  2213. (split-string
  2214. (if evaluate
  2215. (let ((raw (org-babel-ref-resolve source-name)))
  2216. (if (stringp raw) raw (format "%S" raw)))
  2217. (or
  2218. ;; retrieve from the library of babel
  2219. (nth 2 (assoc (intern source-name)
  2220. org-babel-library-of-babel))
  2221. ;; return the contents of headlines literally
  2222. (save-excursion
  2223. (when (org-babel-ref-goto-headline-id source-name)
  2224. (org-babel-ref-headline-body)))
  2225. ;; find the expansion of reference in this buffer
  2226. (let ((rx (concat rx-prefix source-name "[ \t\n]"))
  2227. expansion)
  2228. (save-excursion
  2229. (goto-char (point-min))
  2230. (if org-babel-use-quick-and-dirty-noweb-expansion
  2231. (while (re-search-forward rx nil t)
  2232. (let* ((i (org-babel-get-src-block-info 'light))
  2233. (body (org-babel-expand-noweb-references i))
  2234. (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
  2235. "\n"))
  2236. (full (if comment
  2237. ((lambda (cs)
  2238. (concat (funcall c-wrap (car cs)) "\n"
  2239. body "\n"
  2240. (funcall c-wrap (cadr cs))))
  2241. (org-babel-tangle-comment-links i))
  2242. body)))
  2243. (setq expansion (cons sep (cons full expansion)))))
  2244. (org-babel-map-src-blocks nil
  2245. (let ((i (org-babel-get-src-block-info 'light)))
  2246. (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
  2247. (nth 4 i))
  2248. source-name)
  2249. (let* ((body (org-babel-expand-noweb-references i))
  2250. (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
  2251. "\n"))
  2252. (full (if comment
  2253. ((lambda (cs)
  2254. (concat (funcall c-wrap (car cs)) "\n"
  2255. body "\n"
  2256. (funcall c-wrap (cadr cs))))
  2257. (org-babel-tangle-comment-links i))
  2258. body)))
  2259. (setq expansion
  2260. (cons sep (cons full expansion)))))))))
  2261. (and expansion
  2262. (mapconcat #'identity (nreverse (cdr expansion)) "")))
  2263. ;; possibly raise an error if named block doesn't exist
  2264. (if (member lang org-babel-noweb-error-langs)
  2265. (error "%s" (concat
  2266. (org-babel-noweb-wrap source-name)
  2267. "could not be resolved (see "
  2268. "`org-babel-noweb-error-langs')"))
  2269. "")))
  2270. "[\n\r]") (concat "\n" prefix))))))
  2271. (funcall nb-add (buffer-substring index (point-max))))
  2272. new-body))
  2273. (defun org-babel-script-escape (str &optional force)
  2274. "Safely convert tables into elisp lists."
  2275. (let (in-single in-double out)
  2276. ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
  2277. (if (or force
  2278. (and (stringp str)
  2279. (> (length str) 2)
  2280. (or (and (string-equal "[" (substring str 0 1))
  2281. (string-equal "]" (substring str -1)))
  2282. (and (string-equal "{" (substring str 0 1))
  2283. (string-equal "}" (substring str -1)))
  2284. (and (string-equal "(" (substring str 0 1))
  2285. (string-equal ")" (substring str -1))))))
  2286. (org-babel-read
  2287. (concat
  2288. "'"
  2289. (progn
  2290. (mapc
  2291. (lambda (ch)
  2292. (setq
  2293. out
  2294. (case ch
  2295. (91 (if (or in-double in-single) ; [
  2296. (cons 91 out)
  2297. (cons 40 out)))
  2298. (93 (if (or in-double in-single) ; ]
  2299. (cons 93 out)
  2300. (cons 41 out)))
  2301. (123 (if (or in-double in-single) ; {
  2302. (cons 123 out)
  2303. (cons 40 out)))
  2304. (125 (if (or in-double in-single) ; }
  2305. (cons 125 out)
  2306. (cons 41 out)))
  2307. (44 (if (or in-double in-single) ; ,
  2308. (cons 44 out) (cons 32 out)))
  2309. (39 (if in-double ; '
  2310. (cons 39 out)
  2311. (setq in-single (not in-single)) (cons 34 out)))
  2312. (34 (if in-single ; "
  2313. (append (list 34 32) out)
  2314. (setq in-double (not in-double)) (cons 34 out)))
  2315. (t (cons ch out)))))
  2316. (string-to-list str))
  2317. (apply #'string (reverse out)))))
  2318. str))))
  2319. (defun org-babel-read (cell &optional inhibit-lisp-eval)
  2320. "Convert the string value of CELL to a number if appropriate.
  2321. Otherwise if cell looks like lisp (meaning it starts with a
  2322. \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
  2323. return it unmodified as a string. Optional argument NO-LISP-EVAL
  2324. inhibits lisp evaluation for situations in which is it not
  2325. appropriate."
  2326. (if (and (stringp cell) (not (equal cell "")))
  2327. (or (org-babel-number-p cell)
  2328. (if (and (not inhibit-lisp-eval)
  2329. (member (substring cell 0 1) '("(" "'" "`" "[")))
  2330. (eval (read cell))
  2331. (if (string= (substring cell 0 1) "\"")
  2332. (read cell)
  2333. (progn (set-text-properties 0 (length cell) nil cell) cell))))
  2334. cell))
  2335. (defun org-babel-number-p (string)
  2336. "If STRING represents a number return its value."
  2337. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  2338. (string-match "[0-9]+" string)
  2339. (= (length (substring string (match-beginning 0)
  2340. (match-end 0)))
  2341. (length string)))
  2342. (string-to-number string)))
  2343. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  2344. "Read the results located at FILE-NAME into an elisp table.
  2345. If the table is trivial, then return it as a scalar."
  2346. (let (result)
  2347. (save-window-excursion
  2348. (with-temp-buffer
  2349. (condition-case err
  2350. (progn
  2351. (org-table-import file-name separator)
  2352. (delete-file file-name)
  2353. (setq result (mapcar (lambda (row)
  2354. (mapcar #'org-babel-string-read row))
  2355. (org-table-to-lisp))))
  2356. (error (message "Error reading results: %s" err) nil)))
  2357. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  2358. (if (consp (car result))
  2359. (if (null (cdr (car result)))
  2360. (caar result)
  2361. result)
  2362. (car result))
  2363. result))))
  2364. (defun org-babel-string-read (cell)
  2365. "Strip nested \"s from around strings."
  2366. (org-babel-read (or (and (stringp cell)
  2367. (string-match "\\\"\\(.+\\)\\\"" cell)
  2368. (match-string 1 cell))
  2369. cell) t))
  2370. (defun org-babel-chomp (string &optional regexp)
  2371. "Strip trailing spaces and carriage returns from STRING.
  2372. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  2373. overwritten by specifying a regexp as a second argument."
  2374. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  2375. (while (and (> (length string) 0)
  2376. (string-match regexp (substring string -1)))
  2377. (setq string (substring string 0 -1)))
  2378. string))
  2379. (defun org-babel-trim (string &optional regexp)
  2380. "Strip leading and trailing spaces and carriage returns from STRING.
  2381. Like `org-babel-chomp' only it runs on both the front and back
  2382. of the string."
  2383. (org-babel-chomp (org-reverse-string
  2384. (org-babel-chomp (org-reverse-string string) regexp))
  2385. regexp))
  2386. (defun org-babel-tramp-handle-call-process-region
  2387. (start end program &optional delete buffer display &rest args)
  2388. "Use Tramp to handle `call-process-region'.
  2389. Fixes a bug in `tramp-handle-call-process-region'."
  2390. (if (and (featurep 'tramp) (file-remote-p default-directory))
  2391. (let ((tmpfile (tramp-compat-make-temp-file "")))
  2392. (write-region start end tmpfile)
  2393. (when delete (delete-region start end))
  2394. (unwind-protect
  2395. ;; (apply 'call-process program tmpfile buffer display args)
  2396. ;; bug in tramp
  2397. (apply 'process-file program tmpfile buffer display args)
  2398. (delete-file tmpfile)))
  2399. ;; org-babel-call-process-region-original is the original emacs
  2400. ;; definition. It is in scope from the let binding in
  2401. ;; org-babel-execute-src-block
  2402. (apply org-babel-call-process-region-original
  2403. start end program delete buffer display args)))
  2404. (defun org-babel-local-file-name (file)
  2405. "Return the local name component of FILE."
  2406. (if (file-remote-p file)
  2407. (let (localname)
  2408. (with-parsed-tramp-file-name file nil
  2409. localname))
  2410. file))
  2411. (defun org-babel-process-file-name (name &optional no-quote-p)
  2412. "Prepare NAME to be used in an external process.
  2413. If NAME specifies a remote location, the remote portion of the
  2414. name is removed, since in that case the process will be executing
  2415. remotely. The file name is then processed by `expand-file-name'.
  2416. Unless second argument NO-QUOTE-P is non-nil, the file name is
  2417. additionally processed by `shell-quote-argument'"
  2418. ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
  2419. (expand-file-name (org-babel-local-file-name name))))
  2420. (defvar org-babel-temporary-directory)
  2421. (unless (or noninteractive (boundp 'org-babel-temporary-directory))
  2422. (defvar org-babel-temporary-directory
  2423. (or (and (boundp 'org-babel-temporary-directory)
  2424. (file-exists-p org-babel-temporary-directory)
  2425. org-babel-temporary-directory)
  2426. (make-temp-file "babel-" t))
  2427. "Directory to hold temporary files created to execute code blocks.
  2428. Used by `org-babel-temp-file'. This directory will be removed on
  2429. Emacs shutdown."))
  2430. (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
  2431. "Call the code to parse raw string results according to RESULT-PARAMS."
  2432. (declare (indent 1)
  2433. (debug (form form &rest form)))
  2434. `(unless (member "none" ,result-params)
  2435. (if (or (member "scalar" ,result-params)
  2436. (member "verbatim" ,result-params)
  2437. (member "html" ,result-params)
  2438. (member "code" ,result-params)
  2439. (member "pp" ,result-params)
  2440. (and (member "output" ,result-params)
  2441. (not (member "table" ,result-params))))
  2442. ,scalar-form
  2443. ,@table-forms)))
  2444. (defun org-babel-temp-file (prefix &optional suffix)
  2445. "Create a temporary file in the `org-babel-temporary-directory'.
  2446. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  2447. value of `temporary-file-directory' temporarily set to the value
  2448. of `org-babel-temporary-directory'."
  2449. (if (file-remote-p default-directory)
  2450. (let ((prefix
  2451. (concat (file-remote-p default-directory)
  2452. (expand-file-name prefix temporary-file-directory))))
  2453. (make-temp-file prefix nil suffix))
  2454. (let ((temporary-file-directory
  2455. (or (and (boundp 'org-babel-temporary-directory)
  2456. (file-exists-p org-babel-temporary-directory)
  2457. org-babel-temporary-directory)
  2458. temporary-file-directory)))
  2459. (make-temp-file prefix nil suffix))))
  2460. (defun org-babel-remove-temporary-directory ()
  2461. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  2462. (when (and (boundp 'org-babel-temporary-directory)
  2463. (file-exists-p org-babel-temporary-directory))
  2464. ;; taken from `delete-directory' in files.el
  2465. (condition-case nil
  2466. (progn
  2467. (mapc (lambda (file)
  2468. ;; This test is equivalent to
  2469. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  2470. ;; but more efficient
  2471. (if (eq t (car (file-attributes file)))
  2472. (delete-directory file)
  2473. (delete-file file)))
  2474. ;; We do not want to delete "." and "..".
  2475. (directory-files org-babel-temporary-directory 'full
  2476. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  2477. (delete-directory org-babel-temporary-directory))
  2478. (error
  2479. (message "Failed to remove temporary Org-babel directory %s"
  2480. (if (boundp 'org-babel-temporary-directory)
  2481. org-babel-temporary-directory
  2482. "[directory not defined]"))))))
  2483. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  2484. (provide 'ob-core)
  2485. ;; Local variables:
  2486. ;; generated-autoload-file: "org-loaddefs.el"
  2487. ;; End:
  2488. ;;; ob-core.el ends here