ob-core.el 103 KB

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