ob-core.el 110 KB

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