ob-core.el 120 KB

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