ob.el 88 KB

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