ob.el 94 KB

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