ob.el 89 KB

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