ob-core.el 119 KB

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