ob-core.el 102 KB

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