ob-core.el 100 KB

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