ob-core.el 102 KB

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