ob.el 94 KB

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