ob.el 98 KB

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