ob.el 88 KB

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