ob-core.el 120 KB

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