ob.el 96 KB

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