ob-core.el 104 KB

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