ob.el 84 KB

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