ob.el 87 KB

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