ob.el 88 KB

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