ob-core.el 114 KB

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