ob.el 90 KB

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