ob-core.el 105 KB

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