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