ob-core.el 118 KB

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