ob-core.el 119 KB

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