ob-core.el 121 KB

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