ob.el 99 KB

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