ob-core.el 103 KB

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