ob.el 86 KB

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