ob-core.el 118 KB

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