ob-core.el 122 KB

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