ob-core.el 120 KB

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