ob-core.el 118 KB

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