ob-core.el 120 KB

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