ob-core.el 118 KB

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