ob.el 90 KB

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