ob-core.el 107 KB

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