ob.el 95 KB

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