ob.el 95 KB

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