ob.el 89 KB

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