ob-core.el 119 KB

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