ob-core.el 120 KB

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