ob-core.el 119 KB

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