ob-core.el 120 KB

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