ob.el 98 KB

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