ob-core.el 122 KB

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