ob-core.el 102 KB

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