ob.el 94 KB

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