ob.el 89 KB

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