ob-core.el 120 KB

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