ob.el 99 KB

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