ob-core.el 120 KB

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