ob-core.el 107 KB

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