ob-core.el 116 KB

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