ob.el 93 KB

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