ob.el 85 KB

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