ob.el 87 KB

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