ob.el 96 KB

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