ob.el 84 KB

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