ob.el 94 KB

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