ob-core.el 105 KB

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