ob-core.el 111 KB

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