ob.el 87 KB

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