ob-core.el 118 KB

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