ob-core.el 120 KB

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