ob-core.el 110 KB

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