ob-core.el 115 KB

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