ob-core.el 120 KB

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