ob.el 87 KB

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