ob.el 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223
  1. ;;; ob.el --- working with code blocks in org-mode
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 7.7
  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. (defvar org-babel-call-process-region-original)
  24. (defvar org-src-lang-modes)
  25. (defvar org-babel-library-of-babel)
  26. (declare-function show-all "outline" ())
  27. (declare-function tramp-compat-make-temp-file "tramp-compat"
  28. (filename &optional dir-flag))
  29. (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
  30. (declare-function tramp-file-name-user "tramp" (vec))
  31. (declare-function tramp-file-name-host "tramp" (vec))
  32. (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
  33. (declare-function org-icompleting-read "org" (&rest args))
  34. (declare-function org-edit-src-code "org-src"
  35. (&optional context code edit-buffer-name quietp))
  36. (declare-function org-edit-src-exit "org-src" (&optional context))
  37. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  38. (declare-function org-save-outline-visibility "org" (use-markers &rest body))
  39. (declare-function org-outline-overlay-data "org" (&optional use-markers))
  40. (declare-function org-set-outline-overlay-data "org" (data))
  41. (declare-function org-narrow-to-subtree "org" ())
  42. (declare-function org-entry-get "org"
  43. (pom property &optional inherit literal-nil))
  44. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  45. (declare-function org-do-remove-indentation "org" (&optional n))
  46. (declare-function org-show-context "org" (&optional key))
  47. (declare-function org-at-table-p "org" (&optional table-type))
  48. (declare-function org-cycle "org" (&optional arg))
  49. (declare-function org-uniquify "org" (list))
  50. (declare-function org-current-level "org" ())
  51. (declare-function org-table-import "org-table" (file arg))
  52. (declare-function org-add-hook "org-compat"
  53. (hook function &optional append local))
  54. (declare-function org-table-align "org-table" ())
  55. (declare-function org-table-end "org-table" (&optional table-type))
  56. (declare-function orgtbl-to-generic "org-table" (table params))
  57. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  58. (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
  59. (declare-function org-babel-lob-get-info "ob-lob" nil)
  60. (declare-function org-babel-map-call-lines "ob-lob" (file &rest body))
  61. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  62. (declare-function org-babel-ref-parse "ob-ref" (assignment))
  63. (declare-function org-babel-ref-resolve "ob-ref" (ref))
  64. (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
  65. (declare-function org-babel-ref-headline-body "ob-ref" ())
  66. (declare-function org-babel-lob-execute-maybe "ob-lob" ())
  67. (declare-function org-number-sequence "org-compat" (from &optional to inc))
  68. (declare-function org-at-item-p "org-list" ())
  69. (declare-function org-list-parse-list "org-list" (&optional delete))
  70. (declare-function org-list-to-generic "org-list" (LIST PARAMS))
  71. (declare-function org-list-struct "org-list" ())
  72. (declare-function org-list-prevs-alist "org-list" (struct))
  73. (declare-function org-list-get-list-end "org-list" (item struct prevs))
  74. (defgroup org-babel nil
  75. "Code block evaluation and management in `org-mode' documents."
  76. :tag "Babel"
  77. :group 'org)
  78. (defcustom org-confirm-babel-evaluate t
  79. "Confirm before evaluation.
  80. Require confirmation before interactively evaluating code
  81. blocks in Org-mode buffers. The default value of this variable
  82. is t, meaning confirmation is required for any code block
  83. evaluation. This variable can be set to nil to inhibit any
  84. future confirmation requests. This variable can also be set to a
  85. function which takes two arguments the language of the code block
  86. and the body of the code block. Such a function should then
  87. return a non-nil value if the user should be prompted for
  88. execution or nil if no prompt is required.
  89. Warning: Disabling confirmation may result in accidental
  90. evaluation of potentially harmful code. It may be advisable
  91. remove code block execution from C-c C-c as further protection
  92. against accidental code block evaluation. The
  93. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  94. remove code block execution from the C-c C-c keybinding."
  95. :group 'org-babel
  96. :type '(choice boolean function))
  97. ;; don't allow this variable to be changed through file settings
  98. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  99. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  100. "Remove code block evaluation from the C-c C-c key binding."
  101. :group 'org-babel
  102. :type 'boolean)
  103. (defvar org-babel-src-name-regexp
  104. "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
  105. "Regular expression used to match a source name line.")
  106. (defvar org-babel-multi-line-header-regexp
  107. "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
  108. "Regular expression used to match multi-line header arguments.")
  109. (defvar org-babel-src-name-w-name-regexp
  110. (concat org-babel-src-name-regexp
  111. "\\("
  112. org-babel-multi-line-header-regexp
  113. "\\)*"
  114. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
  115. "Regular expression matching source name lines with a name.")
  116. (defvar org-babel-src-block-regexp
  117. (concat
  118. ;; (1) indentation (2) lang
  119. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  120. ;; (3) switches
  121. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  122. ;; (4) header arguments
  123. "\\([^\n]*\\)\n"
  124. ;; (5) body
  125. "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
  126. "Regexp used to identify code blocks.")
  127. (defvar org-babel-inline-src-block-regexp
  128. (concat
  129. ;; (1) replacement target (2) lang
  130. "[^-[:alnum:]]\\(src_\\([^ \f\t\n\r\v]+\\)"
  131. ;; (3,4) (unused, headers)
  132. "\\(\\|\\[\\(.*?\\)\\]\\)"
  133. ;; (5) body
  134. "{\\([^\f\n\r\v]+?\\)}\\)")
  135. "Regexp used to identify inline src-blocks.")
  136. (defun org-babel-get-header (params key &optional others)
  137. "Select only header argument of type KEY from a list.
  138. Optional argument OTHERS indicates that only the header that do
  139. not match KEY should be returned."
  140. (delq nil
  141. (mapcar
  142. (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
  143. params)))
  144. (defun org-babel-get-src-block-info (&optional light)
  145. "Get information on the current source block.
  146. Optional argument LIGHT does not resolve remote variable
  147. references; a process which could likely result in the execution
  148. of other code blocks.
  149. Returns a list
  150. (language body header-arguments-alist switches name indent)."
  151. (let ((case-fold-search t) head info name indent)
  152. ;; full code block
  153. (if (setq head (org-babel-where-is-src-block-head))
  154. (save-excursion
  155. (goto-char head)
  156. (setq info (org-babel-parse-src-block-match))
  157. (setq indent (car (last info)))
  158. (setq info (butlast info))
  159. (while (and (forward-line -1)
  160. (looking-at org-babel-multi-line-header-regexp))
  161. (setf (nth 2 info)
  162. (org-babel-merge-params
  163. (nth 2 info)
  164. (org-babel-parse-header-arguments (match-string 1)))))
  165. (when (looking-at org-babel-src-name-w-name-regexp)
  166. (setq name (org-babel-clean-text-properties (match-string 4)))
  167. (when (match-string 6)
  168. (setf (nth 2 info) ;; merge functional-syntax vars and header-args
  169. (org-babel-merge-params
  170. (mapcar (lambda (ref) (cons :var ref))
  171. (org-babel-ref-split-args (match-string 6)))
  172. (nth 2 info))))))
  173. ;; inline source block
  174. (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t)
  175. (looking-at org-babel-inline-src-block-regexp))
  176. (setq info (org-babel-parse-inline-src-block-match))))
  177. ;; resolve variable references and add summary parameters
  178. (when (and info (not light))
  179. (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
  180. (when info (append info (list name indent)))))
  181. (defun org-babel-confirm-evaluate (info)
  182. "Confirm evaluation of the code block INFO.
  183. This behavior can be suppressed by setting the value of
  184. `org-confirm-babel-evaluate' to nil, in which case all future
  185. interactive code block evaluations will proceed without any
  186. confirmation from the user.
  187. Note disabling confirmation may result in accidental evaluation
  188. of potentially harmful code."
  189. (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
  190. (when (assoc :noeval (nth 2 info)) "no")))
  191. (query (cond ((equal eval "query") t)
  192. ((functionp org-confirm-babel-evaluate)
  193. (funcall org-confirm-babel-evaluate
  194. (nth 0 info) (nth 1 info)))
  195. (t org-confirm-babel-evaluate))))
  196. (if (or (equal eval "never") (equal eval "no")
  197. (and query
  198. (not (yes-or-no-p
  199. (format "Evaluate this%scode block%son your system? "
  200. (if info (format " %s " (nth 0 info)) " ")
  201. (if (nth 4 info)
  202. (format " (%s) " (nth 4 info)) " "))))))
  203. (prog1 nil (message "Evaluation %s"
  204. (if (or (equal eval "never") (equal eval "no"))
  205. "Disabled" "Aborted")))
  206. t)))
  207. ;;;###autoload
  208. (defun org-babel-execute-safely-maybe ()
  209. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  210. (org-babel-execute-maybe)))
  211. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
  212. ;;;###autoload
  213. (defun org-babel-execute-maybe ()
  214. (interactive)
  215. (or (org-babel-execute-src-block-maybe)
  216. (org-babel-lob-execute-maybe)))
  217. (defun org-babel-execute-src-block-maybe ()
  218. "Conditionally execute a source block.
  219. Detect if this is context for a Babel src-block and if so
  220. then run `org-babel-execute-src-block'."
  221. (interactive)
  222. (let ((info (org-babel-get-src-block-info)))
  223. (if info
  224. (progn (org-babel-eval-wipe-error-buffer)
  225. (org-babel-execute-src-block current-prefix-arg info) t) nil)))
  226. ;;;###autoload
  227. (defun org-babel-view-src-block-info ()
  228. "Display information on the current source block.
  229. This includes header arguments, language and name, and is largely
  230. a window into the `org-babel-get-src-block-info' function."
  231. (interactive)
  232. (let ((info (org-babel-get-src-block-info 'light)))
  233. (flet ((full (it) (> (length it) 0))
  234. (printf (fmt &rest args) (princ (apply #'format fmt args))))
  235. (when info
  236. (with-help-window (help-buffer)
  237. (let ((name (nth 4 info))
  238. (lang (nth 0 info))
  239. (switches (nth 3 info))
  240. (header-args (nth 2 info)))
  241. (when name (printf "Name: %s\n" name))
  242. (when lang (printf "Lang: %s\n" lang))
  243. (when (full switches) (printf "Switches: %s\n" switches))
  244. (printf "Header Arguments:\n")
  245. (dolist (pair (sort header-args
  246. (lambda (a b) (string< (symbol-name (car a))
  247. (symbol-name (car b))))))
  248. (when (full (cdr pair))
  249. (printf "\t%S%s\t%s\n"
  250. (car pair)
  251. (if (> (length (format "%S" (car pair))) 7) "" "\t")
  252. (cdr pair))))))))))
  253. ;;;###autoload
  254. (defun org-babel-expand-src-block-maybe ()
  255. "Conditionally expand a source block.
  256. Detect if this is context for a org-babel src-block and if so
  257. then run `org-babel-expand-src-block'."
  258. (interactive)
  259. (let ((info (org-babel-get-src-block-info)))
  260. (if info
  261. (progn (org-babel-expand-src-block current-prefix-arg info) t)
  262. nil)))
  263. ;;;###autoload
  264. (defun org-babel-load-in-session-maybe ()
  265. "Conditionally load a source block in a session.
  266. Detect if this is context for a org-babel src-block and if so
  267. then run `org-babel-load-in-session'."
  268. (interactive)
  269. (let ((info (org-babel-get-src-block-info)))
  270. (if info
  271. (progn (org-babel-load-in-session current-prefix-arg info) t)
  272. nil)))
  273. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  274. ;;;###autoload
  275. (defun org-babel-pop-to-session-maybe ()
  276. "Conditionally pop to a session.
  277. Detect if this is context for a org-babel src-block and if so
  278. then run `org-babel-pop-to-session'."
  279. (interactive)
  280. (let ((info (org-babel-get-src-block-info)))
  281. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  282. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  283. (defconst org-babel-header-arg-names
  284. '(cache cmdline colnames dir exports file noweb results
  285. session tangle var eval noeval comments no-expand shebang
  286. padline noweb-ref)
  287. "Common header arguments used by org-babel.
  288. Note that individual languages may define their own language
  289. specific header arguments as well.")
  290. (defvar org-babel-default-header-args
  291. '((:session . "none") (:results . "replace") (:exports . "code")
  292. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no")
  293. (:padnewline . "yes"))
  294. "Default arguments to use when evaluating a source block.")
  295. (defvar org-babel-default-inline-header-args
  296. '((:session . "none") (:results . "replace") (:exports . "results"))
  297. "Default arguments to use when evaluating an inline source block.")
  298. (defvar org-babel-data-names '("TBLNAME" "RESNAME" "RESULTS" "DATA"))
  299. (defvar org-babel-result-regexp
  300. (concat "^[ \t]*#\\+"
  301. (regexp-opt org-babel-data-names t)
  302. "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
  303. "Regular expression used to match result lines.
  304. If the results are associated with a hash key then the hash will
  305. be saved in the second match data.")
  306. (defvar org-babel-result-w-name-regexp
  307. (concat org-babel-result-regexp
  308. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  309. (defvar org-babel-min-lines-for-block-output 10
  310. "The minimum number of lines for block output.
  311. If number of lines of output is equal to or exceeds this
  312. value, the output is placed in a #+begin_example...#+end_example
  313. block. Otherwise the output is marked as literal by inserting
  314. colons at the starts of the lines. This variable only takes
  315. effect if the :results output option is in effect.")
  316. (defvar org-babel-noweb-error-langs nil
  317. "Languages for which Babel will raise literate programming errors.
  318. List of languages for which errors should be raised when the
  319. source code block satisfying a noweb reference in this language
  320. can not be resolved.")
  321. (defvar org-babel-hash-show 4
  322. "Number of initial characters to show of a hidden results hash.")
  323. (defvar org-babel-after-execute-hook nil
  324. "Hook for functions to be called after `org-babel-execute-src-block'")
  325. (defun org-babel-named-src-block-regexp-for-name (name)
  326. "This generates a regexp used to match a src block named NAME."
  327. (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
  328. (substring org-babel-src-block-regexp 1)))
  329. ;;; functions
  330. (defvar call-process-region)
  331. ;;;###autoload
  332. (defun org-babel-execute-src-block (&optional arg info params)
  333. "Execute the current source code block.
  334. Insert the results of execution into the buffer. Source code
  335. execution and the collection and formatting of results can be
  336. controlled through a variety of header arguments.
  337. With prefix argument ARG, force re-execution even if a an
  338. existing result cached in the buffer would otherwise have been
  339. returned.
  340. Optionally supply a value for INFO in the form returned by
  341. `org-babel-get-src-block-info'.
  342. Optionally supply a value for PARAMS which will be merged with
  343. the header arguments specified at the front of the source code
  344. block."
  345. (interactive)
  346. (let ((info (or info (org-babel-get-src-block-info))))
  347. (when (org-babel-confirm-evaluate info)
  348. (let* ((lang (nth 0 info))
  349. (params (if params
  350. (org-babel-process-params
  351. (org-babel-merge-params (nth 2 info) params))
  352. (nth 2 info)))
  353. (cache? (and (not arg) (cdr (assoc :cache params))
  354. (string= "yes" (cdr (assoc :cache params)))))
  355. (result-params (cdr (assoc :result-params params)))
  356. (new-hash (when cache? (org-babel-sha1-hash info)))
  357. (old-hash (when cache? (org-babel-current-result-hash)))
  358. (body (setf (nth 1 info)
  359. (let ((noweb (cdr (assoc :noweb params))))
  360. (if (and noweb
  361. (or (string= "yes" noweb)
  362. (string= "tangle" noweb)))
  363. (org-babel-expand-noweb-references info)
  364. (nth 1 info)))))
  365. (dir (cdr (assoc :dir params)))
  366. (default-directory
  367. (or (and dir (file-name-as-directory dir)) default-directory))
  368. (org-babel-call-process-region-original
  369. (if (boundp 'org-babel-call-process-region-original)
  370. org-babel-call-process-region-original
  371. (symbol-function 'call-process-region)))
  372. (indent (car (last info)))
  373. result cmd)
  374. (unwind-protect
  375. (flet ((call-process-region (&rest args)
  376. (apply 'org-babel-tramp-handle-call-process-region args)))
  377. (flet ((lang-check (f)
  378. (let ((f (intern (concat "org-babel-execute:" f))))
  379. (when (fboundp f) f))))
  380. (setq cmd
  381. (or (lang-check lang)
  382. (lang-check (symbol-name
  383. (cdr (assoc lang org-src-lang-modes))))
  384. (error "No org-babel-execute function for %s!" lang))))
  385. (if (and (not arg) new-hash (equal new-hash old-hash))
  386. (save-excursion ;; return cached result
  387. (goto-char (org-babel-where-is-src-block-result nil info))
  388. (end-of-line 1) (forward-char 1)
  389. (setq result (org-babel-read-result))
  390. (message (replace-regexp-in-string
  391. "%" "%%" (format "%S" result))) result)
  392. (message "executing %s code block%s..."
  393. (capitalize lang)
  394. (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
  395. (setq result
  396. ((lambda (result)
  397. (if (and (eq (cdr (assoc :result-type params)) 'value)
  398. (or (member "vector" result-params)
  399. (member "table" result-params))
  400. (not (listp result)))
  401. (list (list result)) result))
  402. (funcall cmd body params)))
  403. ;; if non-empty result and :file then write to :file
  404. (when (cdr (assoc :file params))
  405. (when result
  406. (with-temp-file (cdr (assoc :file params))
  407. (insert
  408. (org-babel-format-result
  409. result (cdr (assoc :sep (nth 2 info)))))))
  410. (setq result (cdr (assoc :file params))))
  411. (org-babel-insert-result
  412. result result-params info new-hash indent lang)
  413. (run-hooks 'org-babel-after-execute-hook)
  414. result))
  415. (setq call-process-region 'org-babel-call-process-region-original))))))
  416. (defun org-babel-expand-body:generic (body params &optional var-lines)
  417. "Expand BODY with PARAMS.
  418. Expand a block of code with org-babel according to it's header
  419. arguments. This generic implementation of body expansion is
  420. called for languages which have not defined their own specific
  421. org-babel-expand-body:lang function."
  422. (mapconcat #'identity (append var-lines (list body)) "\n"))
  423. ;;;###autoload
  424. (defun org-babel-expand-src-block (&optional arg info params)
  425. "Expand the current source code block.
  426. Expand according to the source code block's header
  427. arguments and pop open the results in a preview buffer."
  428. (interactive)
  429. (let* ((info (or info (org-babel-get-src-block-info)))
  430. (lang (nth 0 info))
  431. (params (setf (nth 2 info)
  432. (sort (org-babel-merge-params (nth 2 info) params)
  433. (lambda (el1 el2) (string< (symbol-name (car el1))
  434. (symbol-name (car el2)))))))
  435. (body (setf (nth 1 info)
  436. (if (and (cdr (assoc :noweb params))
  437. (string= "yes" (cdr (assoc :noweb params))))
  438. (org-babel-expand-noweb-references info) (nth 1 info))))
  439. (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
  440. (assignments-cmd (intern (concat "org-babel-variable-assignments:"
  441. lang)))
  442. (expanded
  443. (if (fboundp expand-cmd) (funcall expand-cmd body params)
  444. (org-babel-expand-body:generic
  445. body params (and (fboundp assignments-cmd)
  446. (funcall assignments-cmd params))))))
  447. (org-edit-src-code
  448. nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
  449. (defun org-babel-edit-distance (s1 s2)
  450. "Return the edit (levenshtein) distance between strings S1 S2."
  451. (let* ((l1 (length s1))
  452. (l2 (length s2))
  453. (dist (map 'vector (lambda (_) (make-vector (1+ l2) nil))
  454. (number-sequence 1 (1+ l1)))))
  455. (flet ((in (i j) (aref (aref dist i) j))
  456. (mmin (&rest lst) (apply #'min (remove nil lst))))
  457. (setf (aref (aref dist 0) 0) 0)
  458. (dolist (i (number-sequence 1 l1))
  459. (dolist (j (number-sequence 1 l2))
  460. (setf (aref (aref dist i) j)
  461. (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
  462. (mmin (in (1- i) j) (in i (1- j)) (in (1- i) (1- j)))))))
  463. (in l1 l2))))
  464. ;;;###autoload
  465. (defun org-babel-check-src-block ()
  466. "Check for misspelled header arguments in the current code block."
  467. (interactive)
  468. ;; TODO: report malformed code block
  469. ;; TODO: report incompatible combinations of header arguments
  470. (let ((too-close 2)) ;; <- control closeness to report potential match
  471. (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
  472. (and (org-babel-where-is-src-block-head)
  473. (org-babel-parse-header-arguments
  474. (org-babel-clean-text-properties
  475. (match-string 4))))))
  476. (dolist (name (mapcar #'symbol-name org-babel-header-arg-names))
  477. (when (and (not (string= header name))
  478. (<= (org-babel-edit-distance header name) too-close))
  479. (error "supplied header \"%S\" is suspiciously close to \"%S\""
  480. header name))))
  481. (message "No suspicious header arguments found.")))
  482. ;;;###autoload
  483. (defun org-babel-load-in-session (&optional arg info)
  484. "Load the body of the current source-code block.
  485. Evaluate the header arguments for the source block before
  486. entering the session. After loading the body this pops open the
  487. session."
  488. (interactive)
  489. (let* ((info (or info (org-babel-get-src-block-info)))
  490. (lang (nth 0 info))
  491. (params (nth 2 info))
  492. (body (setf (nth 1 info)
  493. (if (and (cdr (assoc :noweb params))
  494. (string= "yes" (cdr (assoc :noweb params))))
  495. (org-babel-expand-noweb-references info)
  496. (nth 1 info))))
  497. (session (cdr (assoc :session params)))
  498. (dir (cdr (assoc :dir params)))
  499. (default-directory
  500. (or (and dir (file-name-as-directory dir)) default-directory))
  501. (cmd (intern (concat "org-babel-load-session:" lang))))
  502. (unless (fboundp cmd)
  503. (error "No org-babel-load-session function for %s!" lang))
  504. (pop-to-buffer (funcall cmd session body params))
  505. (end-of-line 1)))
  506. ;;;###autoload
  507. (defun org-babel-initiate-session (&optional arg info)
  508. "Initiate session for current code block.
  509. If called with a prefix argument then resolve any variable
  510. references in the header arguments and assign these variables in
  511. the session. Copy the body of the code block to the kill ring."
  512. (interactive "P")
  513. (let* ((info (or info (org-babel-get-src-block-info (not arg))))
  514. (lang (nth 0 info))
  515. (body (nth 1 info))
  516. (params (nth 2 info))
  517. (session (cdr (assoc :session params)))
  518. (dir (cdr (assoc :dir params)))
  519. (default-directory
  520. (or (and dir (file-name-as-directory dir)) default-directory))
  521. (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
  522. (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
  523. (if (and (stringp session) (string= session "none"))
  524. (error "This block is not using a session!"))
  525. (unless (fboundp init-cmd)
  526. (error "No org-babel-initiate-session function for %s!" lang))
  527. (with-temp-buffer (insert (org-babel-trim body))
  528. (copy-region-as-kill (point-min) (point-max)))
  529. (when arg
  530. (unless (fboundp prep-cmd)
  531. (error "No org-babel-prep-session function for %s!" lang))
  532. (funcall prep-cmd session params))
  533. (funcall init-cmd session params)))
  534. ;;;###autoload
  535. (defun org-babel-switch-to-session (&optional arg info)
  536. "Switch to the session of the current code block.
  537. Uses `org-babel-initiate-session' to start the session. If called
  538. with a prefix argument then this is passed on to
  539. `org-babel-initiate-session'."
  540. (interactive "P")
  541. (pop-to-buffer (org-babel-initiate-session arg info))
  542. (end-of-line 1))
  543. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  544. ;;;###autoload
  545. (defun org-babel-switch-to-session-with-code (&optional arg info)
  546. "Switch to code buffer and display session."
  547. (interactive "P")
  548. (flet ((swap-windows
  549. ()
  550. (let ((other-window-buffer (window-buffer (next-window))))
  551. (set-window-buffer (next-window) (current-buffer))
  552. (set-window-buffer (selected-window) other-window-buffer))
  553. (other-window 1)))
  554. (let ((info (org-babel-get-src-block-info))
  555. (org-src-window-setup 'reorganize-frame))
  556. (save-excursion
  557. (org-babel-switch-to-session arg info))
  558. (org-edit-src-code))
  559. (swap-windows)))
  560. (defmacro org-babel-do-in-edit-buffer (&rest body)
  561. "Evaluate BODY in edit buffer if there is a code block at point.
  562. Return t if a code block was found at point, nil otherwise."
  563. `(let ((org-src-window-setup 'switch-invisibly))
  564. (when (and (org-babel-where-is-src-block-head)
  565. (org-edit-src-code nil nil nil))
  566. (unwind-protect (progn ,@body)
  567. (if (org-bound-and-true-p org-edit-src-from-org-mode)
  568. (org-edit-src-exit)))
  569. t)))
  570. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  571. "Read key sequence and execute the command in edit buffer.
  572. Enter a key sequence to be executed in the language major-mode
  573. edit buffer. For example, TAB will alter the contents of the
  574. Org-mode code block according to the effect of TAB in the
  575. language major-mode buffer. For languages that support
  576. interactive sessions, this can be used to send code from the Org
  577. buffer to the session for evaluation using the native major-mode
  578. evaluation mechanisms."
  579. (interactive "kEnter key-sequence to execute in edit buffer: ")
  580. (org-babel-do-in-edit-buffer
  581. (call-interactively
  582. (key-binding (or key (read-key-sequence nil))))))
  583. (defvar org-bracket-link-regexp)
  584. ;;;###autoload
  585. (defun org-babel-open-src-block-result (&optional re-run)
  586. "If `point' is on a src block then open the results of the
  587. source code block, otherwise return nil. With optional prefix
  588. argument RE-RUN the source-code block is evaluated even if
  589. results already exist."
  590. (interactive "P")
  591. (let ((info (org-babel-get-src-block-info)))
  592. (when info
  593. (save-excursion
  594. ;; go to the results, if there aren't any then run the block
  595. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  596. (progn (org-babel-execute-src-block)
  597. (org-babel-where-is-src-block-result))))
  598. (end-of-line 1)
  599. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  600. ;; open the results
  601. (if (looking-at org-bracket-link-regexp)
  602. ;; file results
  603. (org-open-at-point)
  604. (let ((r (org-babel-format-result
  605. (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
  606. (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
  607. (delete-region (point-min) (point-max))
  608. (insert r)))
  609. t))))
  610. ;;;###autoload
  611. (defmacro org-babel-map-src-blocks (file &rest body)
  612. "Evaluate BODY forms on each source-block in FILE.
  613. If FILE is nil evaluate BODY forms on source blocks in current
  614. buffer. During evaluation of BODY the following local variables
  615. are set relative to the currently matched code block.
  616. full-block ------- string holding the entirety of the code block
  617. beg-block -------- point at the beginning of the code block
  618. end-block -------- point at the end of the matched code block
  619. lang ------------- string holding the language of the code block
  620. beg-lang --------- point at the beginning of the lang
  621. end-lang --------- point at the end of the lang
  622. switches --------- string holding the switches
  623. beg-switches ----- point at the beginning of the switches
  624. end-switches ----- point at the end of the switches
  625. header-args ------ string holding the header-args
  626. beg-header-args -- point at the beginning of the header-args
  627. end-header-args -- point at the end of the header-args
  628. body ------------- string holding the body of the code block
  629. beg-body --------- point at the beginning of the body
  630. end-body --------- point at the end of the body"
  631. (declare (indent 1))
  632. (let ((tempvar (make-symbol "file")))
  633. `(let* ((,tempvar ,file)
  634. (visited-p (or (null ,tempvar)
  635. (get-file-buffer (expand-file-name ,tempvar))))
  636. (point (point)) to-be-removed)
  637. (save-window-excursion
  638. (when ,tempvar (find-file ,tempvar))
  639. (setq to-be-removed (current-buffer))
  640. (goto-char (point-min))
  641. (while (re-search-forward org-babel-src-block-regexp nil t)
  642. (goto-char (match-beginning 0))
  643. (let ((full-block (match-string 0))
  644. (beg-block (match-beginning 0))
  645. (end-block (match-end 0))
  646. (lang (match-string 2))
  647. (beg-lang (match-beginning 2))
  648. (end-lang (match-end 2))
  649. (switches (match-string 3))
  650. (beg-switches (match-beginning 3))
  651. (end-switches (match-end 3))
  652. (header-args (match-string 4))
  653. (beg-header-args (match-beginning 4))
  654. (end-header-args (match-end 4))
  655. (body (match-string 5))
  656. (beg-body (match-beginning 5))
  657. (end-body (match-end 5)))
  658. ,@body
  659. (goto-char end-block))))
  660. (unless visited-p (kill-buffer to-be-removed))
  661. (goto-char point))))
  662. (defmacro org-babel-map-regexp (regexp file &rest body)
  663. "Evaluate BODY forms on each match of REGEXP in FILE.
  664. If FILE is nil evaluate BODY forms on source blocks in current
  665. buffer."
  666. (declare (indent 2))
  667. (let ((tempvar (make-symbol "file")))
  668. `(let* ((,tempvar ,file)
  669. (visited-p (or (null ,tempvar)
  670. (get-file-buffer (expand-file-name ,tempvar))))
  671. (point (point)) to-be-removed)
  672. (save-window-excursion
  673. (when ,tempvar (find-file ,tempvar))
  674. (setq to-be-removed (current-buffer))
  675. (goto-char (point-min))
  676. (while (re-search-forward ,regexp nil t)
  677. (goto-char (match-beginning 1))
  678. (save-match-data ,@body)
  679. (goto-char (match-end 0))))
  680. (unless visited-p (kill-buffer to-be-removed))
  681. (goto-char point))))
  682. ;;;###autoload
  683. (defmacro org-babel-map-inline-src-blocks (file &rest body)
  684. "Evaluate BODY forms on each inline source-block in FILE.
  685. If FILE is nil evaluate BODY forms on source blocks in current
  686. buffer."
  687. (declare (indent 1))
  688. `(org-babel-map-regexp ,org-babel-inline-src-block-regexp ,file ,@body))
  689. ;;;###autoload
  690. (defun org-babel-execute-buffer (&optional arg)
  691. "Execute source code blocks in a buffer.
  692. Call `org-babel-execute-src-block' on every source block in
  693. the current buffer."
  694. (interactive "P")
  695. (org-babel-eval-wipe-error-buffer)
  696. (org-save-outline-visibility t
  697. (org-babel-map-src-blocks nil
  698. (org-babel-execute-src-block arg))
  699. (org-babel-map-inline-src-blocks nil
  700. (org-babel-execute-src-block arg))))
  701. ;;;###autoload
  702. (defun org-babel-execute-subtree (&optional arg)
  703. "Execute source code blocks in a subtree.
  704. Call `org-babel-execute-src-block' on every source block in
  705. the current subtree."
  706. (interactive "P")
  707. (save-restriction
  708. (save-excursion
  709. (org-narrow-to-subtree)
  710. (org-babel-execute-buffer arg)
  711. (widen))))
  712. ;;;###autoload
  713. (defun org-babel-sha1-hash (&optional info)
  714. "Generate an sha1 hash based on the value of info."
  715. (interactive)
  716. (let ((print-level nil)
  717. (info (or info (org-babel-get-src-block-info))))
  718. (setf (nth 2 info)
  719. (sort (copy-sequence (nth 2 info))
  720. (lambda (a b) (string< (car a) (car b)))))
  721. (labels ((rm (lst)
  722. (dolist (p '("replace" "silent" "append" "prepend"))
  723. (setq lst (remove p lst)))
  724. lst)
  725. (norm (arg)
  726. (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
  727. (copy-seq (cdr arg))
  728. (cdr arg))))
  729. (when (and v (not (and (sequencep v)
  730. (not (consp v))
  731. (= (length v) 0))))
  732. (cond
  733. ((and (listp v) ; lists are sorted
  734. (member (car arg) '(:result-params)))
  735. (sort (rm v) #'string<))
  736. ((and (stringp v) ; strings are sorted
  737. (member (car arg) '(:results :exports)))
  738. (mapconcat #'identity (sort (rm (split-string v))
  739. #'string<) " "))
  740. (t v))))))
  741. ((lambda (hash)
  742. (when (org-called-interactively-p 'interactive) (message hash)) hash)
  743. (let ((it (format "%s-%s"
  744. (mapconcat
  745. #'identity
  746. (delq nil (mapcar (lambda (arg)
  747. (let ((normalized (norm arg)))
  748. (when normalized
  749. (format "%S" normalized))))
  750. (nth 2 info))) ":")
  751. (nth 1 info))))
  752. (sha1 it))))))
  753. (defun org-babel-current-result-hash ()
  754. "Return the in-buffer hash associated with INFO."
  755. (org-babel-where-is-src-block-result)
  756. (org-babel-clean-text-properties (match-string 3)))
  757. (defun org-babel-hide-hash ()
  758. "Hide the hash in the current results line.
  759. Only the initial `org-babel-hash-show' characters of the hash
  760. will remain visible."
  761. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  762. (save-excursion
  763. (when (and (re-search-forward org-babel-result-regexp nil t)
  764. (match-string 3))
  765. (let* ((start (match-beginning 3))
  766. (hide-start (+ org-babel-hash-show start))
  767. (end (match-end 3))
  768. (hash (match-string 3))
  769. ov1 ov2)
  770. (setq ov1 (make-overlay start hide-start))
  771. (setq ov2 (make-overlay hide-start end))
  772. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  773. (overlay-put ov1 'babel-hash hash)))))
  774. (defun org-babel-hide-all-hashes ()
  775. "Hide the hash in the current buffer.
  776. Only the initial `org-babel-hash-show' characters of each hash
  777. will remain visible. This function should be called as part of
  778. the `org-mode-hook'."
  779. (save-excursion
  780. (while (re-search-forward org-babel-result-regexp nil t)
  781. (goto-char (match-beginning 0))
  782. (org-babel-hide-hash)
  783. (goto-char (match-end 0)))))
  784. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  785. (defun org-babel-hash-at-point (&optional point)
  786. "Return the value of the hash at POINT.
  787. The hash is also added as the last element of the kill ring.
  788. This can be called with C-c C-c."
  789. (interactive)
  790. (let ((hash (car (delq nil (mapcar
  791. (lambda (ol) (overlay-get ol 'babel-hash))
  792. (overlays-at (or point (point))))))))
  793. (when hash (kill-new hash) (message hash))))
  794. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  795. (defun org-babel-result-hide-spec ()
  796. "Hide portions of results lines.
  797. Add `org-babel-hide-result' as an invisibility spec for hiding
  798. portions of results lines."
  799. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  800. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  801. (defvar org-babel-hide-result-overlays nil
  802. "Overlays hiding results.")
  803. (defun org-babel-result-hide-all ()
  804. "Fold all results in the current buffer."
  805. (interactive)
  806. (org-babel-show-result-all)
  807. (save-excursion
  808. (while (re-search-forward org-babel-result-regexp nil t)
  809. (save-excursion (goto-char (match-beginning 0))
  810. (org-babel-hide-result-toggle-maybe)))))
  811. (defun org-babel-show-result-all ()
  812. "Unfold all results in the current buffer."
  813. (mapc 'delete-overlay org-babel-hide-result-overlays)
  814. (setq org-babel-hide-result-overlays nil))
  815. ;;;###autoload
  816. (defun org-babel-hide-result-toggle-maybe ()
  817. "Toggle visibility of result at point."
  818. (interactive)
  819. (let ((case-fold-search t))
  820. (if (save-excursion
  821. (beginning-of-line 1)
  822. (looking-at org-babel-result-regexp))
  823. (progn (org-babel-hide-result-toggle)
  824. t) ;; to signal that we took action
  825. nil))) ;; to signal that we did not
  826. (defun org-babel-hide-result-toggle (&optional force)
  827. "Toggle the visibility of the current result."
  828. (interactive)
  829. (save-excursion
  830. (beginning-of-line)
  831. (if (re-search-forward org-babel-result-regexp nil t)
  832. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  833. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  834. ov)
  835. (if (memq t (mapcar (lambda (overlay)
  836. (eq (overlay-get overlay 'invisible)
  837. 'org-babel-hide-result))
  838. (overlays-at start)))
  839. (if (or (not force) (eq force 'off))
  840. (mapc (lambda (ov)
  841. (when (member ov org-babel-hide-result-overlays)
  842. (setq org-babel-hide-result-overlays
  843. (delq ov org-babel-hide-result-overlays)))
  844. (when (eq (overlay-get ov 'invisible)
  845. 'org-babel-hide-result)
  846. (delete-overlay ov)))
  847. (overlays-at start)))
  848. (setq ov (make-overlay start end))
  849. (overlay-put ov 'invisible 'org-babel-hide-result)
  850. ;; make the block accessible to isearch
  851. (overlay-put
  852. ov 'isearch-open-invisible
  853. (lambda (ov)
  854. (when (member ov org-babel-hide-result-overlays)
  855. (setq org-babel-hide-result-overlays
  856. (delq ov org-babel-hide-result-overlays)))
  857. (when (eq (overlay-get ov 'invisible)
  858. 'org-babel-hide-result)
  859. (delete-overlay ov))))
  860. (push ov org-babel-hide-result-overlays)))
  861. (error "Not looking at a result line"))))
  862. ;; org-tab-after-check-for-cycling-hook
  863. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  864. ;; Remove overlays when changing major mode
  865. (add-hook 'org-mode-hook
  866. (lambda () (org-add-hook 'change-major-mode-hook
  867. 'org-babel-show-result-all 'append 'local)))
  868. (defvar org-file-properties)
  869. (defun org-babel-params-from-properties (&optional lang)
  870. "Retrieve parameters specified as properties.
  871. Return an association list of any source block params which
  872. may be specified in the properties of the current outline entry."
  873. (save-match-data
  874. (let (val sym)
  875. (delq nil
  876. (mapcar
  877. (lambda (header-arg)
  878. (and (setq val
  879. (or (org-entry-get (point) header-arg t)
  880. (org-entry-get (point) (concat ":" header-arg) t)))
  881. (cons (intern (concat ":" header-arg))
  882. (org-babel-read val))))
  883. (mapcar
  884. 'symbol-name
  885. (append
  886. org-babel-header-arg-names
  887. (progn
  888. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  889. (and (boundp sym) (eval sym))))))))))
  890. (defun org-babel-params-from-buffer ()
  891. "Retrieve per-buffer parameters.
  892. Return an association list of any source block params which
  893. may be specified in the current buffer."
  894. (let (local-properties)
  895. (save-match-data
  896. (save-excursion
  897. (save-restriction
  898. (widen)
  899. (goto-char (point-min))
  900. (while (re-search-forward
  901. (org-make-options-regexp (list "BABEL" "PROPERTIES")) nil t)
  902. (setq local-properties
  903. (org-babel-merge-params
  904. local-properties
  905. (org-babel-parse-header-arguments
  906. (org-match-string-no-properties 2)))))
  907. local-properties)))))
  908. (defvar org-src-preserve-indentation)
  909. (defun org-babel-parse-src-block-match ()
  910. "Parse the results from a match of the `org-babel-src-block-regexp'."
  911. (let* ((block-indentation (length (match-string 1)))
  912. (lang (org-babel-clean-text-properties (match-string 2)))
  913. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  914. (switches (match-string 3))
  915. (body (org-babel-clean-text-properties
  916. (let* ((body (match-string 5))
  917. (sub-length (- (length body) 1)))
  918. (if (string= "\n" (substring body sub-length))
  919. (substring body 0 sub-length)
  920. body))))
  921. (preserve-indentation (or org-src-preserve-indentation
  922. (string-match "-i\\>" switches))))
  923. (list lang
  924. ;; get block body less properties, protective commas, and indentation
  925. (with-temp-buffer
  926. (save-match-data
  927. (insert (org-babel-strip-protective-commas body))
  928. (unless preserve-indentation (org-do-remove-indentation))
  929. (buffer-string)))
  930. (org-babel-merge-params
  931. org-babel-default-header-args
  932. (org-babel-params-from-buffer)
  933. (org-babel-params-from-properties lang)
  934. (if (boundp lang-headers) (eval lang-headers) nil)
  935. (org-babel-parse-header-arguments
  936. (org-babel-clean-text-properties (or (match-string 4) ""))))
  937. switches
  938. block-indentation)))
  939. (defun org-babel-parse-inline-src-block-match ()
  940. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  941. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  942. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  943. (list lang
  944. (org-babel-strip-protective-commas
  945. (org-babel-clean-text-properties (match-string 5)))
  946. (org-babel-merge-params
  947. org-babel-default-inline-header-args
  948. (org-babel-params-from-buffer)
  949. (org-babel-params-from-properties lang)
  950. (if (boundp lang-headers) (eval lang-headers) nil)
  951. (org-babel-parse-header-arguments
  952. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  953. (defun org-babel-parse-header-arguments (arg-string)
  954. "Parse a string of header arguments returning an alist."
  955. (when (> (length arg-string) 0)
  956. (delq nil
  957. (mapcar
  958. (lambda (arg)
  959. (if (string-match
  960. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  961. arg)
  962. (cons (intern (match-string 1 arg))
  963. (org-babel-read (org-babel-chomp (match-string 2 arg))))
  964. (cons (intern (org-babel-chomp arg)) nil)))
  965. (let ((balance 0) (partial nil) (lst nil) (last 0))
  966. (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
  967. (setq balance (+ balance
  968. (cond ((equal 91 ch) 1)
  969. ((equal 93 ch) -1)
  970. (t 0))))
  971. (setq partial (cons ch partial))
  972. (when (and (= ch 58) (= balance 0)
  973. (or (= last 32) (= last 9)))
  974. (setq lst (cons (apply #'string (nreverse (cddr partial)))
  975. lst))
  976. (setq partial (list ch)))
  977. (setq last ch))
  978. (string-to-list arg-string))
  979. (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
  980. (defun org-babel-process-params (params)
  981. "Expand variables in PARAMS and add summary parameters."
  982. (let* ((vars-and-names (org-babel-disassemble-tables
  983. (mapcar (lambda (el)
  984. (if (consp (cdr el))
  985. (cdr el) (org-babel-ref-parse (cdr el))))
  986. (org-babel-get-header params :var))
  987. (cdr (assoc :hlines params))
  988. (cdr (assoc :colnames params))
  989. (cdr (assoc :rownames params))))
  990. (raw-result (or (cdr (assoc :results params)) ""))
  991. (result-params (append
  992. (split-string (if (stringp raw-result)
  993. raw-result
  994. (eval raw-result)))
  995. (cdr (assoc :result-params params)))))
  996. (append
  997. (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
  998. (list
  999. (cons :colname-names (or (cdr (assoc :colname-names params))
  1000. (cadr vars-and-names)))
  1001. (cons :rowname-names (or (cdr (assoc :rowname-names params))
  1002. (caddr vars-and-names)))
  1003. (cons :result-params result-params)
  1004. (cons :result-type (cond ((member "output" result-params) 'output)
  1005. ((member "value" result-params) 'value)
  1006. (t 'value))))
  1007. (org-babel-get-header params :var 'other))))
  1008. ;; row and column names
  1009. (defun org-babel-del-hlines (table)
  1010. "Remove all 'hlines from TABLE."
  1011. (remove 'hline table))
  1012. (defun org-babel-get-colnames (table)
  1013. "Return the column names of TABLE.
  1014. Return a cons cell, the `car' of which contains the TABLE less
  1015. colnames, and the `cdr' of which contains a list of the column
  1016. names."
  1017. (if (equal 'hline (nth 1 table))
  1018. (cons (cddr table) (car table))
  1019. (cons (cdr table) (car table))))
  1020. (defun org-babel-get-rownames (table)
  1021. "Return the row names of TABLE.
  1022. Return a cons cell, the `car' of which contains the TABLE less
  1023. colnames, and the `cdr' of which contains a list of the column
  1024. names. Note: this function removes any hlines in TABLE."
  1025. (flet ((trans (table) (apply #'mapcar* #'list table)))
  1026. (let* ((width (apply 'max
  1027. (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  1028. (table (trans (mapcar (lambda (row)
  1029. (if (not (equal row 'hline))
  1030. row
  1031. (setq row '())
  1032. (dotimes (n width)
  1033. (setq row (cons 'hline row)))
  1034. row))
  1035. table))))
  1036. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  1037. (trans (cdr table)))
  1038. (remove 'hline (car table))))))
  1039. (defun org-babel-put-colnames (table colnames)
  1040. "Add COLNAMES to TABLE if they exist."
  1041. (if colnames (apply 'list colnames 'hline table) table))
  1042. (defun org-babel-put-rownames (table rownames)
  1043. "Add ROWNAMES to TABLE if they exist."
  1044. (if rownames
  1045. (mapcar (lambda (row)
  1046. (if (listp row)
  1047. (cons (or (pop rownames) "") row)
  1048. row)) table)
  1049. table))
  1050. (defun org-babel-pick-name (names selector)
  1051. "Select one out of an alist of row or column names.
  1052. SELECTOR can be either a list of names in which case those names
  1053. will be returned directly, or an index into the list NAMES in
  1054. which case the indexed names will be return."
  1055. (if (listp selector)
  1056. selector
  1057. (when names
  1058. (if (and selector (symbolp selector) (not (equal t selector)))
  1059. (cdr (assoc selector names))
  1060. (if (integerp selector)
  1061. (nth (- selector 1) names)
  1062. (cdr (car (last names))))))))
  1063. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  1064. "Parse tables for further processing.
  1065. Process the variables in VARS according to the HLINES,
  1066. ROWNAMES and COLNAMES header arguments. Return a list consisting
  1067. of the vars, cnames and rnames."
  1068. (let (cnames rnames)
  1069. (list
  1070. (mapcar
  1071. (lambda (var)
  1072. (when (listp (cdr var))
  1073. (when (and (not (equal colnames "no"))
  1074. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  1075. (not (member 'hline (cddr (cdr var)))))))
  1076. (let ((both (org-babel-get-colnames (cdr var))))
  1077. (setq cnames (cons (cons (car var) (cdr both))
  1078. cnames))
  1079. (setq var (cons (car var) (car both)))))
  1080. (when (and rownames (not (equal rownames "no")))
  1081. (let ((both (org-babel-get-rownames (cdr var))))
  1082. (setq rnames (cons (cons (car var) (cdr both))
  1083. rnames))
  1084. (setq var (cons (car var) (car both)))))
  1085. (when (and hlines (not (equal hlines "yes")))
  1086. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  1087. var)
  1088. vars)
  1089. cnames rnames)))
  1090. (defun org-babel-reassemble-table (table colnames rownames)
  1091. "Add column and row names to a table.
  1092. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  1093. to the table for reinsertion to org-mode."
  1094. (if (listp table)
  1095. ((lambda (table)
  1096. (if (and colnames (listp (car table)) (= (length (car table))
  1097. (length colnames)))
  1098. (org-babel-put-colnames table colnames) table))
  1099. (if (and rownames (= (length table) (length rownames)))
  1100. (org-babel-put-rownames table rownames) table))
  1101. table))
  1102. (defun org-babel-where-is-src-block-head ()
  1103. "Find where the current source block begins.
  1104. Return the point at the beginning of the current source
  1105. block. Specifically at the beginning of the #+BEGIN_SRC line.
  1106. If the point is not on a source block then return nil."
  1107. (let ((initial (point)) top bottom)
  1108. (or
  1109. (save-excursion ;; on a source name line or a #+header line
  1110. (beginning-of-line 1)
  1111. (and (or (looking-at org-babel-src-name-regexp)
  1112. (looking-at org-babel-multi-line-header-regexp))
  1113. (progn
  1114. (while (and (forward-line 1)
  1115. (looking-at org-babel-multi-line-header-regexp)))
  1116. (looking-at org-babel-src-block-regexp))
  1117. (point)))
  1118. (save-excursion ;; on a #+begin_src line
  1119. (beginning-of-line 1)
  1120. (and (looking-at org-babel-src-block-regexp)
  1121. (point)))
  1122. (save-excursion ;; inside a src block
  1123. (and
  1124. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  1125. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  1126. (< top initial) (< initial bottom)
  1127. (progn (goto-char top) (beginning-of-line 1)
  1128. (looking-at org-babel-src-block-regexp))
  1129. (point))))))
  1130. ;;;###autoload
  1131. (defun org-babel-goto-src-block-head ()
  1132. "Go to the beginning of the current code block."
  1133. (interactive)
  1134. ((lambda (head)
  1135. (if head (goto-char head) (error "not currently in a code block")))
  1136. (org-babel-where-is-src-block-head)))
  1137. ;;;###autoload
  1138. (defun org-babel-goto-named-src-block (name)
  1139. "Go to a named source-code block."
  1140. (interactive
  1141. (let ((completion-ignore-case t))
  1142. (list (org-icompleting-read "source-block name: "
  1143. (org-babel-src-block-names) nil t))))
  1144. (let ((point (org-babel-find-named-block name)))
  1145. (if point
  1146. ;; taken from `org-open-at-point'
  1147. (progn (goto-char point) (org-show-context))
  1148. (message "source-code block '%s' not found in this buffer" name))))
  1149. (defun org-babel-find-named-block (name)
  1150. "Find a named source-code block.
  1151. Return the location of the source block identified by source
  1152. NAME, or nil if no such block exists. Set match data according to
  1153. org-babel-named-src-block-regexp."
  1154. (save-excursion
  1155. (let ((case-fold-search t)
  1156. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  1157. (goto-char (point-min))
  1158. (when (or (re-search-forward regexp nil t)
  1159. (re-search-backward regexp nil t))
  1160. (match-beginning 0)))))
  1161. (defun org-babel-src-block-names (&optional file)
  1162. "Returns the names of source blocks in FILE or the current buffer."
  1163. (save-excursion
  1164. (when file (find-file file)) (goto-char (point-min))
  1165. (let (names)
  1166. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  1167. (setq names (cons (match-string 4) names)))
  1168. names)))
  1169. ;;;###autoload
  1170. (defun org-babel-goto-named-result (name)
  1171. "Go to a named result."
  1172. (interactive
  1173. (let ((completion-ignore-case t))
  1174. (list (org-icompleting-read "source-block name: "
  1175. (org-babel-result-names) nil t))))
  1176. (let ((point (org-babel-find-named-result name)))
  1177. (if point
  1178. ;; taken from `org-open-at-point'
  1179. (progn (goto-char point) (org-show-context))
  1180. (message "result '%s' not found in this buffer" name))))
  1181. (defun org-babel-find-named-result (name)
  1182. "Find a named result.
  1183. Return the location of the result named NAME in the current
  1184. buffer or nil if no such result exists."
  1185. (save-excursion
  1186. (goto-char (point-min))
  1187. (when (re-search-forward
  1188. (concat org-babel-result-regexp
  1189. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  1190. (beginning-of-line 0) (point))))
  1191. (defun org-babel-result-names (&optional file)
  1192. "Returns the names of results in FILE or the current buffer."
  1193. (save-excursion
  1194. (when file (find-file file)) (goto-char (point-min))
  1195. (let (names)
  1196. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1197. (setq names (cons (match-string 4) names)))
  1198. names)))
  1199. ;;;###autoload
  1200. (defun org-babel-next-src-block (&optional arg)
  1201. "Jump to the next source block.
  1202. With optional prefix argument ARG, jump forward ARG many source blocks."
  1203. (interactive "P")
  1204. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  1205. (condition-case nil
  1206. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  1207. (error (error "No further code blocks")))
  1208. (goto-char (match-beginning 0)) (org-show-context))
  1209. ;;;###autoload
  1210. (defun org-babel-previous-src-block (&optional arg)
  1211. "Jump to the previous source block.
  1212. With optional prefix argument ARG, jump backward ARG many source blocks."
  1213. (interactive "P")
  1214. (condition-case nil
  1215. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  1216. (error (error "No previous code blocks")))
  1217. (goto-char (match-beginning 0)) (org-show-context))
  1218. (defvar org-babel-load-languages)
  1219. ;;;###autoload
  1220. (defun org-babel-mark-block ()
  1221. "Mark current src block"
  1222. (interactive)
  1223. ((lambda (head)
  1224. (when head
  1225. (save-excursion
  1226. (goto-char head)
  1227. (looking-at org-babel-src-block-regexp))
  1228. (push-mark (match-end 5) nil t)
  1229. (goto-char (match-beginning 5))))
  1230. (org-babel-where-is-src-block-head)))
  1231. ;;;###autoload
  1232. (defun org-babel-demarcate-block (&optional arg)
  1233. "Wrap or split the code in the region or on the point.
  1234. When called from inside of a code block the current block is
  1235. split. When called from outside of a code block a new code block
  1236. is created. In both cases if the region is demarcated and if the
  1237. region is not active then the point is demarcated."
  1238. (interactive "P")
  1239. (let ((info (org-babel-get-src-block-info 'light))
  1240. (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
  1241. (if info
  1242. (mapc
  1243. (lambda (place)
  1244. (save-excursion
  1245. (goto-char place)
  1246. (let ((lang (nth 0 info))
  1247. (indent (make-string (nth 5 info) ? )))
  1248. (when (string-match "^[[:space:]]*$"
  1249. (buffer-substring (point-at-bol)
  1250. (point-at-eol)))
  1251. (delete-region (point-at-bol) (point-at-eol)))
  1252. (insert (concat (if (looking-at "^") "" "\n")
  1253. indent "#+end_src\n"
  1254. (if arg stars indent) "\n"
  1255. indent "#+begin_src " lang
  1256. (if (looking-at "[\n\r]") "" "\n")))))
  1257. (move-end-of-line 2))
  1258. (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
  1259. (let ((start (point))
  1260. (lang (org-icompleting-read "Lang: "
  1261. (mapcar (lambda (el) (symbol-name (car el)))
  1262. org-babel-load-languages)))
  1263. (body (delete-and-extract-region
  1264. (if (region-active-p) (mark) (point)) (point))))
  1265. (insert (concat (if (looking-at "^") "" "\n")
  1266. (if arg (concat stars "\n") "")
  1267. "#+begin_src " lang "\n"
  1268. body
  1269. (if (or (= (length body) 0)
  1270. (string-match "[\r\n]$" body)) "" "\n")
  1271. "#+end_src\n"))
  1272. (goto-char start) (move-end-of-line 1)))))
  1273. ;;;###autoload
  1274. (defun org-babel-kill-results (arg)
  1275. "Remove the results from the current code block or call line.
  1276. When called with prefix argument remove all results in the current file."
  1277. (interactive "P")
  1278. (if (null arg)
  1279. (org-babel-remove-result)
  1280. (org-babel-map-call-lines nil (org-babel-remove-result))
  1281. (org-babel-map-src-blocks nil (org-babel-remove-result))
  1282. (org-babel-map-inline-src-blocks nil (org-babel-remove-result))))
  1283. (defvar org-babel-lob-one-liner-regexp)
  1284. (defvar org-babel-inline-lob-one-liner-regexp)
  1285. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1286. "Find where the current source block results begin.
  1287. Return the point at the beginning of the result of the current
  1288. source block. Specifically at the beginning of the results line.
  1289. If no result exists for this block then create a results line
  1290. following the source block."
  1291. (save-excursion
  1292. (let* ((on-lob-line (save-excursion
  1293. (beginning-of-line 1)
  1294. (looking-at org-babel-lob-one-liner-regexp)))
  1295. (inlinep (save-excursion
  1296. (re-search-backward "[ \f\t\n\r\v]" nil t)
  1297. (when (looking-at org-babel-inline-src-block-regexp)
  1298. (match-end 0))))
  1299. (name (if on-lob-line
  1300. (nth 0 (org-babel-lob-get-info))
  1301. (nth 4 (or info (org-babel-get-src-block-info)))))
  1302. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1303. found beg end)
  1304. (when head (goto-char head))
  1305. (setq
  1306. found ;; was there a result (before we potentially insert one)
  1307. (or
  1308. inlinep
  1309. (and
  1310. ;; named results:
  1311. ;; - return t if it is found, else return nil
  1312. ;; - if it does not need to be rebuilt, then don't set end
  1313. ;; - if it does need to be rebuilt then do set end
  1314. name (setq beg (org-babel-find-named-result name))
  1315. (prog1 beg
  1316. (when (and hash (not (string= hash (match-string 3))))
  1317. (goto-char beg) (setq end beg) ;; beginning of result
  1318. (forward-line 1)
  1319. (delete-region end (org-babel-result-end)) nil)))
  1320. (and
  1321. ;; unnamed results:
  1322. ;; - return t if it is found, else return nil
  1323. ;; - if it is found, and the hash doesn't match, delete and set end
  1324. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1325. (progn (end-of-line 1)
  1326. (if (eobp) (insert "\n") (forward-char 1))
  1327. (setq end (point))
  1328. (or (and (not name)
  1329. (progn ;; unnamed results line already exists
  1330. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1331. (beginning-of-line 1)
  1332. (looking-at
  1333. (concat org-babel-result-regexp "\n")))
  1334. (prog1 (point)
  1335. ;; must remove and rebuild if hash!=old-hash
  1336. (if (and hash (not (string= hash (match-string 3))))
  1337. (prog1 nil
  1338. (forward-line 1)
  1339. (delete-region
  1340. end (org-babel-result-end)))
  1341. (setq end nil)))))))))
  1342. (if (and insert end)
  1343. (progn
  1344. (goto-char end)
  1345. (unless beg
  1346. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1347. (insert (concat
  1348. (if indent
  1349. (mapconcat
  1350. (lambda (el) " ")
  1351. (org-number-sequence 1 indent) "")
  1352. "")
  1353. "#+results"
  1354. (when hash (concat "["hash"]"))
  1355. ":"
  1356. (when name (concat " " name)) "\n"))
  1357. (unless beg (insert "\n") (backward-char))
  1358. (beginning-of-line 0)
  1359. (if hash (org-babel-hide-hash))
  1360. (point))
  1361. found))))
  1362. (defvar org-block-regexp)
  1363. (defun org-babel-read-result ()
  1364. "Read the result at `point' into emacs-lisp."
  1365. (let ((case-fold-search t) result-string)
  1366. (cond
  1367. ((org-at-table-p) (org-babel-read-table))
  1368. ((org-at-item-p) (org-babel-read-list))
  1369. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1370. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1371. ((looking-at "^[ \t]*: ")
  1372. (setq result-string
  1373. (org-babel-trim
  1374. (mapconcat (lambda (line)
  1375. (if (and (> (length line) 1)
  1376. (string-match "^[ \t]*: \\(.+\\)" line))
  1377. (match-string 1 line)
  1378. line))
  1379. (split-string
  1380. (buffer-substring
  1381. (point) (org-babel-result-end)) "[\r\n]+")
  1382. "\n")))
  1383. (or (org-babel-number-p result-string) result-string))
  1384. ((looking-at org-babel-result-regexp)
  1385. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1386. (defun org-babel-read-table ()
  1387. "Read the table at `point' into emacs-lisp."
  1388. (mapcar (lambda (row)
  1389. (if (and (symbolp row) (equal row 'hline)) row
  1390. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
  1391. (org-table-to-lisp)))
  1392. (defun org-babel-read-list ()
  1393. "Read the list at `point' into emacs-lisp."
  1394. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
  1395. (mapcar #'cadr (cdr (org-list-parse-list)))))
  1396. (defvar org-link-types-re)
  1397. (defun org-babel-read-link ()
  1398. "Read the link at `point' into emacs-lisp.
  1399. If the path of the link is a file path it is expanded using
  1400. `expand-file-name'."
  1401. (let* ((case-fold-search t)
  1402. (raw (and (looking-at org-bracket-link-regexp)
  1403. (org-babel-clean-text-properties (match-string 1))))
  1404. (type (and (string-match org-link-types-re raw)
  1405. (match-string 1 raw))))
  1406. (cond
  1407. ((not type) (expand-file-name raw))
  1408. ((string= type "file")
  1409. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1410. (expand-file-name (match-string 2 raw))))
  1411. (t raw))))
  1412. (defun org-babel-format-result (result &optional sep)
  1413. "Format RESULT for writing to file."
  1414. (flet ((echo-res (result)
  1415. (if (stringp result) result (format "%S" result))))
  1416. (if (listp result)
  1417. ;; table result
  1418. (orgtbl-to-generic
  1419. result
  1420. (list
  1421. :sep (or sep "\t")
  1422. :fmt 'echo-res))
  1423. ;; scalar result
  1424. (echo-res result))))
  1425. (defun org-babel-insert-result
  1426. (result &optional result-params info hash indent lang)
  1427. "Insert RESULT into the current buffer.
  1428. By default RESULT is inserted after the end of the
  1429. current source block. With optional argument RESULT-PARAMS
  1430. controls insertion of results in the org-mode file.
  1431. RESULT-PARAMS can take the following values...
  1432. replace - (default option) insert results after the source block
  1433. replacing any previously inserted results
  1434. silent -- no results are inserted
  1435. file ---- the results are interpreted as a file path, and are
  1436. inserted into the buffer using the Org-mode file syntax
  1437. list ---- the results are interpreted as an Org-mode list.
  1438. raw ----- results are added directly to the Org-mode file. This
  1439. is a good option if you code block will output org-mode
  1440. formatted text.
  1441. org ----- similar in effect to raw, only the results are wrapped
  1442. in an org code block. Similar to the raw option, on
  1443. export the results will be interpreted as org-formatted
  1444. text, however by wrapping the results in an org code
  1445. block they can be replaced upon re-execution of the
  1446. code block.
  1447. html ---- results are added inside of a #+BEGIN_HTML block. This
  1448. is a good option if you code block will output html
  1449. formatted text.
  1450. latex --- results are added inside of a #+BEGIN_LATEX block.
  1451. This is a good option if you code block will output
  1452. latex formatted text.
  1453. code ---- the results are extracted in the syntax of the source
  1454. code of the language being evaluated and are added
  1455. inside of a #+BEGIN_SRC block with the source-code
  1456. language set appropriately. Note this relies on the
  1457. optional LANG argument."
  1458. (if (stringp result)
  1459. (progn
  1460. (setq result (org-babel-clean-text-properties result))
  1461. (when (member "file" result-params)
  1462. (setq result (org-babel-result-to-file result))))
  1463. (unless (listp result) (setq result (format "%S" result))))
  1464. (if (and result-params (member "silent" result-params))
  1465. (progn
  1466. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1467. result)
  1468. (save-excursion
  1469. (let* ((inlinep
  1470. (save-excursion
  1471. (or (= (point) (point-at-bol))
  1472. (re-search-backward "[ \f\t\n\r\v]" nil t))
  1473. (when (or (looking-at org-babel-inline-src-block-regexp)
  1474. (looking-at org-babel-inline-lob-one-liner-regexp))
  1475. (goto-char (match-end 0))
  1476. (insert (if (listp result) "\n" " "))
  1477. (point))))
  1478. (existing-result (unless inlinep
  1479. (org-babel-where-is-src-block-result
  1480. t info hash indent)))
  1481. (results-switches
  1482. (cdr (assoc :results_switches (nth 2 info))))
  1483. beg end)
  1484. (when (and (stringp result) ; ensure results end in a newline
  1485. (not inlinep)
  1486. (> (length result) 0)
  1487. (not (or (string-equal (substring result -1) "\n")
  1488. (string-equal (substring result -1) "\r"))))
  1489. (setq result (concat result "\n")))
  1490. (if (not existing-result)
  1491. (setq beg (or inlinep (point)))
  1492. (goto-char existing-result)
  1493. (save-excursion
  1494. (re-search-forward "#" nil t)
  1495. (setq indent (- (current-column) 1)))
  1496. (forward-line 1)
  1497. (setq beg (point))
  1498. (cond
  1499. ((member "replace" result-params)
  1500. (delete-region (point) (org-babel-result-end)))
  1501. ((member "append" result-params)
  1502. (goto-char (org-babel-result-end)) (setq beg (point-marker)))
  1503. ((member "prepend" result-params)))) ; already there
  1504. (setq results-switches
  1505. (if results-switches (concat " " results-switches) ""))
  1506. ;; insert results based on type
  1507. (cond
  1508. ;; do nothing for an empty result
  1509. ((= (length result) 0))
  1510. ;; insert a list if preferred
  1511. ((member "list" result-params)
  1512. (insert
  1513. (org-babel-trim
  1514. (org-list-to-generic
  1515. (cons 'unordered
  1516. (mapcar
  1517. (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
  1518. (if (listp result) result (list result))))
  1519. '(:splicep nil :istart "- " :iend "\n")))
  1520. "\n"))
  1521. ;; assume the result is a table if it's not a string
  1522. ((not (stringp result))
  1523. (goto-char beg)
  1524. (insert (concat (orgtbl-to-orgtbl
  1525. (if (or (eq 'hline (car result))
  1526. (and (listp (car result))
  1527. (listp (cdr (car result)))))
  1528. result (list result))
  1529. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1530. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1531. ((member "file" result-params)
  1532. (insert result))
  1533. (t (goto-char beg) (insert result)))
  1534. (when (listp result) (goto-char (org-table-end)))
  1535. (setq end (point-marker))
  1536. ;; possibly wrap result
  1537. (flet ((wrap (start finish)
  1538. (goto-char beg) (insert (concat start "\n"))
  1539. (goto-char end) (insert (concat finish "\n"))
  1540. (setq end (point-marker))))
  1541. (cond
  1542. ((member "html" result-params)
  1543. (wrap "#+BEGIN_HTML" "#+END_HTML"))
  1544. ((member "latex" result-params)
  1545. (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
  1546. ((member "code" result-params)
  1547. (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
  1548. "#+END_SRC"))
  1549. ((member "org" result-params)
  1550. (wrap "#+BEGIN_ORG" "#+END_ORG"))
  1551. ((member "raw" result-params)
  1552. (goto-char beg) (if (org-at-table-p) (org-cycle)))
  1553. ((member "wrap" result-params)
  1554. (when (and (stringp result) (not (member "file" result-params)))
  1555. (org-babel-examplize-region beg end results-switches))
  1556. (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
  1557. ((and (stringp result) (not (member "file" result-params)))
  1558. (org-babel-examplize-region beg end results-switches)
  1559. (setq end (point)))))
  1560. ;; possibly indent the results to match the #+results line
  1561. (when (and (not inlinep) (numberp indent) indent (> indent 0)
  1562. ;; in this case `table-align' does the work for us
  1563. (not (and (listp result)
  1564. (member "append" result-params))))
  1565. (indent-rigidly beg end indent))))
  1566. (if (= (length result) 0)
  1567. (if (member "value" result-params)
  1568. (message "Code block returned no value.")
  1569. (message "Code block produced no output."))
  1570. (message "Code block evaluation complete."))))
  1571. (defun org-babel-remove-result (&optional info)
  1572. "Remove the result of the current source block."
  1573. (interactive)
  1574. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1575. (when location
  1576. (save-excursion
  1577. (goto-char location) (setq start (point)) (forward-line 1)
  1578. (delete-region start (org-babel-result-end))))))
  1579. (defun org-babel-result-end ()
  1580. "Return the point at the end of the current set of results"
  1581. (save-excursion
  1582. (cond
  1583. ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
  1584. ((org-at-item-p) (let* ((struct (org-list-struct))
  1585. (prvs (org-list-prevs-alist struct)))
  1586. (org-list-get-list-end (point-at-bol) struct prvs)))
  1587. (t
  1588. (let ((case-fold-search t)
  1589. (blocks-re (regexp-opt
  1590. (list "latex" "html" "example" "src" "result" "org"))))
  1591. (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
  1592. (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
  1593. (forward-char 1))
  1594. (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1595. (forward-line 1))))
  1596. (point)))))
  1597. (defun org-babel-result-to-file (result)
  1598. "Convert RESULT into an `org-mode' link.
  1599. If the `default-directory' is different from the containing
  1600. file's directory then expand relative links."
  1601. (flet ((cond-exp (file)
  1602. (if (and default-directory
  1603. buffer-file-name
  1604. (not (string= (expand-file-name default-directory)
  1605. (expand-file-name
  1606. (file-name-directory buffer-file-name)))))
  1607. (expand-file-name file default-directory)
  1608. file)))
  1609. (if (stringp result)
  1610. (format "[[file:%s]]" (cond-exp result))
  1611. (when (and (listp result) (= 2 (length result))
  1612. (stringp (car result)) (stringp (cadr result)))
  1613. (format "[[file:%s][%s]]" (car result) (cadr result))))))
  1614. (defun org-babel-examplize-region (beg end &optional results-switches)
  1615. "Comment out region using the inline '==' or ': ' org example quote."
  1616. (interactive "*r")
  1617. (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
  1618. (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
  1619. (chars-between end (save-excursion (goto-char end) (point-at-eol))))
  1620. (save-excursion
  1621. (goto-char beg)
  1622. (insert (format "=%s=" (prog1 (buffer-substring beg end)
  1623. (delete-region beg end)))))
  1624. (let ((size (count-lines beg end)))
  1625. (save-excursion
  1626. (cond ((= size 0)) ; do nothing for an empty result
  1627. ((< size org-babel-min-lines-for-block-output)
  1628. (goto-char beg)
  1629. (dotimes (n size)
  1630. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1631. (t
  1632. (goto-char beg)
  1633. (insert (if results-switches
  1634. (format "#+begin_example%s\n" results-switches)
  1635. "#+begin_example\n"))
  1636. (if (markerp end) (goto-char end) (forward-char (- end beg)))
  1637. (insert "#+end_example\n"))))))))
  1638. (defun org-babel-update-block-body (new-body)
  1639. "Update the body of the current code block to NEW-BODY."
  1640. (if (not (org-babel-where-is-src-block-head))
  1641. (error "not in source block")
  1642. (save-match-data
  1643. (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
  1644. (indent-rigidly (match-beginning 5) (match-end 5) 2)))
  1645. (defun org-babel-merge-params (&rest plists)
  1646. "Combine all parameter association lists in PLISTS.
  1647. Later elements of PLISTS override the values of previous elements.
  1648. This takes into account some special considerations for certain
  1649. parameters when merging lists."
  1650. (let ((results-exclusive-groups
  1651. '(("file" "list" "vector" "table" "scalar" "verbatim" "raw" "org"
  1652. "html" "latex" "code" "pp" "wrap")
  1653. ("replace" "silent" "append" "prepend")
  1654. ("output" "value")))
  1655. (exports-exclusive-groups
  1656. '(("code" "results" "both" "none")))
  1657. (variable-index 0)
  1658. params results exports tangle noweb cache vars shebang comments padline)
  1659. (flet ((e-merge (exclusive-groups &rest result-params)
  1660. ;; maintain exclusivity of mutually exclusive parameters
  1661. (let (output)
  1662. (mapc (lambda (new-params)
  1663. (mapc (lambda (new-param)
  1664. (mapc (lambda (exclusive-group)
  1665. (when (member new-param exclusive-group)
  1666. (mapcar (lambda (excluded-param)
  1667. (setq output
  1668. (delete
  1669. excluded-param
  1670. output)))
  1671. exclusive-group)))
  1672. exclusive-groups)
  1673. (setq output (org-uniquify
  1674. (cons new-param output))))
  1675. new-params))
  1676. result-params)
  1677. output)))
  1678. (mapc
  1679. (lambda (plist)
  1680. (mapc
  1681. (lambda (pair)
  1682. (case (car pair)
  1683. (:var
  1684. (let ((name (if (listp (cdr pair))
  1685. (cadr pair)
  1686. (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1687. (cdr pair))
  1688. (intern (match-string 1 (cdr pair)))))))
  1689. (if name
  1690. (setq vars
  1691. (append
  1692. (if (member name (mapcar #'car vars))
  1693. (delq nil
  1694. (mapcar
  1695. (lambda (p)
  1696. (unless (equal (car p) name) p))
  1697. vars))
  1698. vars)
  1699. (list (cons name pair))))
  1700. ;; if no name is given, then assign to variables in order
  1701. (prog1 (setf (cddr (nth variable-index vars))
  1702. (concat (symbol-name
  1703. (car (nth variable-index vars)))
  1704. "=" (cdr pair)))
  1705. (incf variable-index)))))
  1706. (:results
  1707. (setq results (e-merge results-exclusive-groups
  1708. results
  1709. (split-string
  1710. (let ((r (cdr pair)))
  1711. (if (stringp r) r (eval r)))))))
  1712. (:file
  1713. (when (cdr pair)
  1714. (setq results (e-merge results-exclusive-groups
  1715. results '("file")))
  1716. (unless (or (member "both" exports)
  1717. (member "none" exports)
  1718. (member "code" exports))
  1719. (setq exports (e-merge exports-exclusive-groups
  1720. exports '("results"))))
  1721. (setq params (cons pair (assq-delete-all (car pair) params)))))
  1722. (:exports
  1723. (setq exports (e-merge exports-exclusive-groups
  1724. exports (split-string (cdr pair)))))
  1725. (:tangle ;; take the latest -- always overwrite
  1726. (setq tangle (or (list (cdr pair)) tangle)))
  1727. (:noweb
  1728. (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
  1729. (split-string (or (cdr pair) "")))))
  1730. (:cache
  1731. (setq cache (e-merge '(("yes" "no")) cache
  1732. (split-string (or (cdr pair) "")))))
  1733. (:padline
  1734. (setq padline (e-merge '(("yes" "no")) padline
  1735. (split-string (or (cdr pair) "")))))
  1736. (:shebang ;; take the latest -- always overwrite
  1737. (setq shebang (or (list (cdr pair)) shebang)))
  1738. (:comments
  1739. (setq comments (e-merge '(("yes" "no")) comments
  1740. (split-string (or (cdr pair) "")))))
  1741. (t ;; replace: this covers e.g. :session
  1742. (setq params (cons pair (assq-delete-all (car pair) params))))))
  1743. plist))
  1744. plists))
  1745. (setq vars (reverse vars))
  1746. (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
  1747. (mapc
  1748. (lambda (hd)
  1749. (let ((key (intern (concat ":" (symbol-name hd))))
  1750. (val (eval hd)))
  1751. (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
  1752. '(results exports tangle noweb padline cache shebang comments))
  1753. params))
  1754. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1755. "Expand Noweb references in the body of the current source code block.
  1756. For example the following reference would be replaced with the
  1757. body of the source-code block named 'example-block'.
  1758. <<example-block>>
  1759. Note that any text preceding the <<foo>> construct on a line will
  1760. be interposed between the lines of the replacement text. So for
  1761. example if <<foo>> is placed behind a comment, then the entire
  1762. replacement text will also be commented.
  1763. This function must be called from inside of the buffer containing
  1764. the source-code block which holds BODY.
  1765. In addition the following syntax can be used to insert the
  1766. results of evaluating the source-code block named 'example-block'.
  1767. <<example-block()>>
  1768. Any optional arguments can be passed to example-block by placing
  1769. the arguments inside the parenthesis following the convention
  1770. defined by `org-babel-lob'. For example
  1771. <<example-block(a=9)>>
  1772. would set the value of argument \"a\" equal to \"9\". Note that
  1773. these arguments are not evaluated in the current source-code
  1774. block but are passed literally to the \"example-block\"."
  1775. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1776. (info (or info (org-babel-get-src-block-info)))
  1777. (lang (nth 0 info))
  1778. (body (nth 1 info))
  1779. (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
  1780. (new-body "") index source-name evaluate prefix blocks-in-buffer)
  1781. (flet ((nb-add (text) (setq new-body (concat new-body text)))
  1782. (c-wrap (text)
  1783. (with-temp-buffer
  1784. (funcall (intern (concat lang "-mode")))
  1785. (comment-region (point) (progn (insert text) (point)))
  1786. (org-babel-trim (buffer-string))))
  1787. (blocks () ;; return the info lists of all blocks in this buffer
  1788. (let (infos)
  1789. (save-restriction
  1790. (widen)
  1791. (org-babel-map-src-blocks nil
  1792. (setq infos (cons (org-babel-get-src-block-info 'light)
  1793. infos))))
  1794. (reverse infos))))
  1795. (with-temp-buffer
  1796. (insert body) (goto-char (point-min))
  1797. (setq index (point))
  1798. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1799. (save-match-data (setf source-name (match-string 1)))
  1800. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1801. (save-match-data
  1802. (setq prefix
  1803. (buffer-substring (match-beginning 0)
  1804. (save-excursion
  1805. (beginning-of-line 1) (point)))))
  1806. ;; add interval to new-body (removing noweb reference)
  1807. (goto-char (match-beginning 0))
  1808. (nb-add (buffer-substring index (point)))
  1809. (goto-char (match-end 0))
  1810. (setq index (point))
  1811. (nb-add
  1812. (with-current-buffer parent-buffer
  1813. (mapconcat ;; interpose PREFIX between every line
  1814. #'identity
  1815. (split-string
  1816. (if evaluate
  1817. (let ((raw (org-babel-ref-resolve source-name)))
  1818. (if (stringp raw) raw (format "%S" raw)))
  1819. (or
  1820. ;; retrieve from the library of babel
  1821. (nth 2 (assoc (intern source-name)
  1822. org-babel-library-of-babel))
  1823. ;; return the contents of headlines literally
  1824. (save-excursion
  1825. (when (org-babel-ref-goto-headline-id source-name)
  1826. (org-babel-ref-headline-body)))
  1827. ;; find the expansion of reference in this buffer
  1828. (mapconcat
  1829. (lambda (i)
  1830. (when (string= source-name
  1831. (or (cdr (assoc :noweb-ref (nth 2 i)))
  1832. (nth 4 i)))
  1833. (let ((body (org-babel-expand-noweb-references i)))
  1834. (if comment
  1835. ((lambda (cs)
  1836. (concat (c-wrap (car cs)) "\n"
  1837. body "\n" (c-wrap (cadr cs))))
  1838. (org-babel-tangle-comment-links i))
  1839. body))))
  1840. (or blocks-in-buffer
  1841. (setq blocks-in-buffer (blocks)))
  1842. "")
  1843. ;; possibly raise an error if named block doesn't exist
  1844. (if (member lang org-babel-noweb-error-langs)
  1845. (error "%s" (concat
  1846. "<<" source-name ">> "
  1847. "could not be resolved (see "
  1848. "`org-babel-noweb-error-langs')"))
  1849. "")))
  1850. "[\n\r]") (concat "\n" prefix)))))
  1851. (nb-add (buffer-substring index (point-max)))))
  1852. new-body))
  1853. (defun org-babel-clean-text-properties (text)
  1854. "Strip all properties from text return."
  1855. (when text
  1856. (set-text-properties 0 (length text) nil text) text))
  1857. (defun org-babel-strip-protective-commas (body)
  1858. "Strip protective commas from bodies of source blocks."
  1859. (when body
  1860. (replace-regexp-in-string "^,#" "#" body)))
  1861. (defun org-babel-script-escape (str &optional force)
  1862. "Safely convert tables into elisp lists."
  1863. (let (in-single in-double out)
  1864. ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
  1865. (if (or force
  1866. (and (stringp str)
  1867. (> (length str) 2)
  1868. (or (and (string-equal "[" (substring str 0 1))
  1869. (string-equal "]" (substring str -1)))
  1870. (and (string-equal "{" (substring str 0 1))
  1871. (string-equal "}" (substring str -1)))
  1872. (and (string-equal "(" (substring str 0 1))
  1873. (string-equal ")" (substring str -1))))))
  1874. (org-babel-read
  1875. (concat
  1876. "'"
  1877. (progn
  1878. (mapc
  1879. (lambda (ch)
  1880. (setq
  1881. out
  1882. (case ch
  1883. (91 (if (or in-double in-single) ; [
  1884. (cons 91 out)
  1885. (cons 40 out)))
  1886. (93 (if (or in-double in-single) ; ]
  1887. (cons 93 out)
  1888. (cons 41 out)))
  1889. (123 (if (or in-double in-single) ; {
  1890. (cons 123 out)
  1891. (cons 40 out)))
  1892. (125 (if (or in-double in-single) ; }
  1893. (cons 125 out)
  1894. (cons 41 out)))
  1895. (44 (if (or in-double in-single) ; ,
  1896. (cons 44 out) (cons 32 out)))
  1897. (39 (if in-double ; '
  1898. (cons 39 out)
  1899. (setq in-single (not in-single)) (cons 34 out)))
  1900. (34 (if in-single ; "
  1901. (append (list 34 32) out)
  1902. (setq in-double (not in-double)) (cons 34 out)))
  1903. (t (cons ch out)))))
  1904. (string-to-list str))
  1905. (apply #'string (reverse out)))))
  1906. str))))
  1907. (defun org-babel-read (cell &optional inhibit-lisp-eval)
  1908. "Convert the string value of CELL to a number if appropriate.
  1909. Otherwise if cell looks like lisp (meaning it starts with a
  1910. \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
  1911. return it unmodified as a string. Optional argument NO-LISP-EVAL
  1912. inhibits lisp evaluation for situations in which is it not
  1913. appropriate."
  1914. (if (and (stringp cell) (not (equal cell "")))
  1915. (or (org-babel-number-p cell)
  1916. (if (and (not inhibit-lisp-eval)
  1917. (member (substring cell 0 1) '("(" "'" "`" "[")))
  1918. (eval (read cell))
  1919. (if (string= (substring cell 0 1) "\"")
  1920. (read cell)
  1921. (progn (set-text-properties 0 (length cell) nil cell) cell))))
  1922. cell))
  1923. (defun org-babel-number-p (string)
  1924. "If STRING represents a number return it's value."
  1925. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1926. (= (length (substring string (match-beginning 0)
  1927. (match-end 0)))
  1928. (length string)))
  1929. (string-to-number string)))
  1930. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1931. "Read the results located at FILE-NAME into an elisp table.
  1932. If the table is trivial, then return it as a scalar."
  1933. (let (result)
  1934. (save-window-excursion
  1935. (with-temp-buffer
  1936. (condition-case nil
  1937. (progn
  1938. (org-table-import file-name separator)
  1939. (delete-file file-name)
  1940. (setq result (mapcar (lambda (row)
  1941. (mapcar #'org-babel-string-read row))
  1942. (org-table-to-lisp))))
  1943. (error nil)))
  1944. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1945. (if (consp (car result))
  1946. (if (null (cdr (car result)))
  1947. (caar result)
  1948. result)
  1949. (car result))
  1950. result))))
  1951. (defun org-babel-string-read (cell)
  1952. "Strip nested \"s from around strings."
  1953. (org-babel-read (or (and (stringp cell)
  1954. (string-match "\\\"\\(.+\\)\\\"" cell)
  1955. (match-string 1 cell))
  1956. cell)))
  1957. (defun org-babel-reverse-string (string)
  1958. "Return the reverse of STRING."
  1959. (apply 'string (reverse (string-to-list string))))
  1960. (defun org-babel-chomp (string &optional regexp)
  1961. "Strip trailing spaces and carriage returns from STRING.
  1962. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1963. overwritten by specifying a regexp as a second argument."
  1964. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1965. (while (and (> (length string) 0)
  1966. (string-match regexp (substring string -1)))
  1967. (setq string (substring string 0 -1)))
  1968. string))
  1969. (defun org-babel-trim (string &optional regexp)
  1970. "Strip leading and trailing spaces and carriage returns from STRING.
  1971. Like `org-babel-chomp' only it runs on both the front and back
  1972. of the string."
  1973. (org-babel-chomp (org-babel-reverse-string
  1974. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1975. regexp))
  1976. (defvar org-babel-org-babel-call-process-region-original nil)
  1977. (defun org-babel-tramp-handle-call-process-region
  1978. (start end program &optional delete buffer display &rest args)
  1979. "Use tramp to handle call-process-region.
  1980. Fixes a bug in `tramp-handle-call-process-region'."
  1981. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1982. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1983. (write-region start end tmpfile)
  1984. (when delete (delete-region start end))
  1985. (unwind-protect
  1986. ;; (apply 'call-process program tmpfile buffer display args)
  1987. ;; bug in tramp
  1988. (apply 'process-file program tmpfile buffer display args)
  1989. (delete-file tmpfile)))
  1990. ;; org-babel-call-process-region-original is the original emacs
  1991. ;; definition. It is in scope from the let binding in
  1992. ;; org-babel-execute-src-block
  1993. (apply org-babel-call-process-region-original
  1994. start end program delete buffer display args)))
  1995. (defun org-babel-local-file-name (file)
  1996. "Return the local name component of FILE."
  1997. (if (file-remote-p file)
  1998. (let (localname)
  1999. (with-parsed-tramp-file-name file nil
  2000. localname))
  2001. file))
  2002. (defun org-babel-process-file-name (name &optional no-quote-p)
  2003. "Prepare NAME to be used in an external process.
  2004. If NAME specifies a remote location, the remote portion of the
  2005. name is removed, since in that case the process will be executing
  2006. remotely. The file name is then processed by
  2007. `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
  2008. the file name is additionally processed by
  2009. `shell-quote-argument'"
  2010. ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
  2011. (expand-file-name (org-babel-local-file-name name))))
  2012. (defvar org-babel-temporary-directory)
  2013. (unless (or noninteractive (boundp 'org-babel-temporary-directory))
  2014. (defvar org-babel-temporary-directory
  2015. (or (and (boundp 'org-babel-temporary-directory)
  2016. (file-exists-p org-babel-temporary-directory)
  2017. org-babel-temporary-directory)
  2018. (make-temp-file "babel-" t))
  2019. "Directory to hold temporary files created to execute code blocks.
  2020. Used by `org-babel-temp-file'. This directory will be removed on
  2021. Emacs shutdown."))
  2022. (defun org-babel-temp-file (prefix &optional suffix)
  2023. "Create a temporary file in the `org-babel-temporary-directory'.
  2024. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  2025. value of `temporary-file-directory' temporarily set to the value
  2026. of `org-babel-temporary-directory'."
  2027. (if (file-remote-p default-directory)
  2028. (make-temp-file
  2029. (concat (file-remote-p default-directory)
  2030. (expand-file-name
  2031. prefix temporary-file-directory)
  2032. nil suffix))
  2033. (let ((temporary-file-directory
  2034. (or (and (boundp 'org-babel-temporary-directory)
  2035. (file-exists-p org-babel-temporary-directory)
  2036. org-babel-temporary-directory)
  2037. temporary-file-directory)))
  2038. (make-temp-file prefix nil suffix))))
  2039. (defun org-babel-remove-temporary-directory ()
  2040. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  2041. (when (and (boundp 'org-babel-temporary-directory)
  2042. (file-exists-p org-babel-temporary-directory))
  2043. ;; taken from `delete-directory' in files.el
  2044. (condition-case nil
  2045. (progn
  2046. (mapc (lambda (file)
  2047. ;; This test is equivalent to
  2048. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  2049. ;; but more efficient
  2050. (if (eq t (car (file-attributes file)))
  2051. (delete-directory file)
  2052. (delete-file file)))
  2053. ;; We do not want to delete "." and "..".
  2054. (directory-files org-babel-temporary-directory 'full
  2055. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  2056. (delete-directory org-babel-temporary-directory))
  2057. (error
  2058. (message "Failed to remove temporary Org-babel directory %s"
  2059. (if (boundp 'org-babel-temporary-directory)
  2060. org-babel-temporary-directory
  2061. "[directory not defined]"))))))
  2062. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  2063. (provide 'ob)
  2064. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  2065. ;;; ob.el ends here