ob-core.el 110 KB

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