ob.el 93 KB

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