ob-core.el 119 KB

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