ob-core.el 118 KB

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