ob.el 95 KB

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