ob-shell.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. ;;; ob-shell.el --- Babel Functions for Shell Evaluation -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2018 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; This file is part of GNU Emacs.
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; Org-Babel support for evaluating shell source code.
  19. ;;; Code:
  20. (require 'ob)
  21. (require 'shell)
  22. (require 'cl-lib)
  23. (declare-function org-babel-comint-in-buffer "ob-comint" (buffer &rest body)
  24. t)
  25. (declare-function org-babel-comint-wait-for-output "ob-comint" (buffer))
  26. (declare-function org-babel-comint-buffer-livep "ob-comint" (buffer))
  27. (declare-function org-babel-comint-with-output "ob-comint" (meta &rest body)
  28. t)
  29. (declare-function org-trim "org" (s &optional keep-lead))
  30. (declare-function orgtbl-to-generic "org-table" (table params))
  31. (defvar org-babel-default-header-args:shell '())
  32. (defvar org-babel-shell-names)
  33. (defun org-babel-shell-initialize ()
  34. "Define execution functions associated to shell names.
  35. This function has to be called whenever `org-babel-shell-names'
  36. is modified outside the Customize interface."
  37. (interactive)
  38. (dolist (name org-babel-shell-names)
  39. (eval `(defun ,(intern (concat "org-babel-execute:" name))
  40. (body params)
  41. ,(format "Execute a block of %s commands with Babel." name)
  42. (let ((shell-file-name ,name))
  43. (org-babel-execute:shell body params))))
  44. (eval `(defalias ',(intern (concat "org-babel-variable-assignments:" name))
  45. 'org-babel-variable-assignments:shell
  46. ,(format "Return list of %s statements assigning to the block's \
  47. variables."
  48. name)))))
  49. (defcustom org-babel-shell-names
  50. '("sh" "bash" "csh" "ash" "dash" "ksh" "mksh" "posh")
  51. "List of names of shell supported by babel shell code blocks.
  52. Call `org-babel-shell-initialize' when modifying this variable
  53. outside the Customize interface."
  54. :group 'org-babel
  55. :type '(repeat (string :tag "Shell name: "))
  56. :set (lambda (symbol value)
  57. (set-default symbol value)
  58. (org-babel-shell-initialize)))
  59. (defun org-babel-execute:shell (body params)
  60. "Execute a block of Shell commands with Babel.
  61. This function is called by `org-babel-execute-src-block'."
  62. (let* ((session (org-babel-sh-initiate-session
  63. (cdr (assq :session params))))
  64. (stdin (let ((stdin (cdr (assq :stdin params))))
  65. (when stdin (org-babel-sh-var-to-string
  66. (org-babel-ref-resolve stdin)))))
  67. (cmdline (cdr (assq :cmdline params)))
  68. (full-body (org-babel-expand-body:generic
  69. body params (org-babel-variable-assignments:shell params))))
  70. (org-babel-reassemble-table
  71. (org-babel-sh-evaluate session full-body params stdin cmdline)
  72. (org-babel-pick-name
  73. (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
  74. (org-babel-pick-name
  75. (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
  76. (defun org-babel-prep-session:shell (session params)
  77. "Prepare SESSION according to the header arguments specified in PARAMS."
  78. (let* ((session (org-babel-sh-initiate-session session))
  79. (var-lines (org-babel-variable-assignments:shell params)))
  80. (org-babel-comint-in-buffer session
  81. (mapc (lambda (var)
  82. (insert var) (comint-send-input nil t)
  83. (org-babel-comint-wait-for-output session)) var-lines))
  84. session))
  85. (defun org-babel-load-session:shell (session body params)
  86. "Load BODY into SESSION."
  87. (save-window-excursion
  88. (let ((buffer (org-babel-prep-session:shell session params)))
  89. (with-current-buffer buffer
  90. (goto-char (process-mark (get-buffer-process (current-buffer))))
  91. (insert (org-babel-chomp body)))
  92. buffer)))
  93. ;;; Helper functions
  94. (defun org-babel--variable-assignments:sh-generic
  95. (varname values &optional sep hline)
  96. "Returns a list of statements declaring the values as a generic variable."
  97. (format "%s=%s" varname (org-babel-sh-var-to-sh values sep hline)))
  98. (defun org-babel--variable-assignments:bash_array
  99. (varname values &optional sep hline)
  100. "Returns a list of statements declaring the values as a bash array."
  101. (format "unset %s\ndeclare -a %s=( %s )"
  102. varname varname
  103. (mapconcat
  104. (lambda (value) (org-babel-sh-var-to-sh value sep hline))
  105. values
  106. " ")))
  107. (defun org-babel--variable-assignments:bash_assoc
  108. (varname values &optional sep hline)
  109. "Returns a list of statements declaring the values as bash associative array."
  110. (format "unset %s\ndeclare -A %s\n%s"
  111. varname varname
  112. (mapconcat
  113. (lambda (items)
  114. (format "%s[%s]=%s"
  115. varname
  116. (org-babel-sh-var-to-sh (car items) sep hline)
  117. (org-babel-sh-var-to-sh (cdr items) sep hline)))
  118. values
  119. "\n")))
  120. (defun org-babel--variable-assignments:bash (varname values &optional sep hline)
  121. "Represents the parameters as useful Bash shell variables."
  122. (pcase values
  123. (`((,_ ,_ . ,_) . ,_) ;two-dimensional array
  124. (org-babel--variable-assignments:bash_assoc varname values sep hline))
  125. (`(,_ . ,_) ;simple list
  126. (org-babel--variable-assignments:bash_array varname values sep hline))
  127. (_ ;scalar value
  128. (org-babel--variable-assignments:sh-generic varname values sep hline))))
  129. (defun org-babel-variable-assignments:shell (params)
  130. "Return list of shell statements assigning the block's variables."
  131. (let ((sep (cdr (assq :separator params)))
  132. (hline (when (string= "yes" (cdr (assq :hlines params)))
  133. (or (cdr (assq :hline-string params))
  134. "hline"))))
  135. (mapcar
  136. (lambda (pair)
  137. (if (string-suffix-p "bash" shell-file-name)
  138. (org-babel--variable-assignments:bash
  139. (car pair) (cdr pair) sep hline)
  140. (org-babel--variable-assignments:sh-generic
  141. (car pair) (cdr pair) sep hline)))
  142. (org-babel--get-vars params))))
  143. (defun org-babel-sh-var-to-sh (var &optional sep hline)
  144. "Convert an elisp value to a shell variable.
  145. Convert an elisp var into a string of shell commands specifying a
  146. var of the same value."
  147. (concat "'" (replace-regexp-in-string
  148. "'" "'\"'\"'"
  149. (org-babel-sh-var-to-string var sep hline))
  150. "'"))
  151. (defun org-babel-sh-var-to-string (var &optional sep hline)
  152. "Convert an elisp value to a string."
  153. (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v)))))
  154. (cond
  155. ((and (listp var) (or (listp (car var)) (eq (car var) 'hline)))
  156. (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var
  157. :hline hline)))
  158. ((listp var)
  159. (mapconcat echo-var var "\n"))
  160. (t (funcall echo-var var)))))
  161. (defun org-babel-sh-initiate-session (&optional session _params)
  162. "Initiate a session named SESSION according to PARAMS."
  163. (when (and session (not (string= session "none")))
  164. (save-window-excursion
  165. (or (org-babel-comint-buffer-livep session)
  166. (progn
  167. (shell session)
  168. ;; Needed for Emacs 23 since the marker is initially
  169. ;; undefined and the filter functions try to use it without
  170. ;; checking.
  171. (set-marker comint-last-output-start (point))
  172. (get-buffer (current-buffer)))))))
  173. (defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'"
  174. "String to indicate that evaluation has completed.")
  175. (defvar org-babel-sh-eoe-output "org_babel_sh_eoe"
  176. "String to indicate that evaluation has completed.")
  177. (defun org-babel-sh-evaluate (session body &optional params stdin cmdline)
  178. "Pass BODY to the Shell process in BUFFER.
  179. If RESULT-TYPE equals `output' then return a list of the outputs
  180. of the statements in BODY, if RESULT-TYPE equals `value' then
  181. return the value of the last statement in BODY."
  182. (let ((results
  183. (cond
  184. ((or stdin cmdline) ; external shell script w/STDIN
  185. (let ((script-file (org-babel-temp-file "sh-script-"))
  186. (stdin-file (org-babel-temp-file "sh-stdin-"))
  187. (shebang (cdr (assq :shebang params)))
  188. (padline (not (string= "no" (cdr (assq :padline params))))))
  189. (with-temp-file script-file
  190. (when shebang (insert (concat shebang "\n")))
  191. (when padline (insert "\n"))
  192. (insert body))
  193. (set-file-modes script-file #o755)
  194. (with-temp-file stdin-file (insert (or stdin "")))
  195. (with-temp-buffer
  196. (call-process-shell-command
  197. (concat (if shebang script-file
  198. (format "%s %s" shell-file-name script-file))
  199. (and cmdline (concat " " cmdline)))
  200. stdin-file
  201. (current-buffer))
  202. (buffer-string))))
  203. (session ; session evaluation
  204. (mapconcat
  205. #'org-babel-sh-strip-weird-long-prompt
  206. (mapcar
  207. #'org-trim
  208. (butlast
  209. (org-babel-comint-with-output
  210. (session org-babel-sh-eoe-output t body)
  211. (mapc
  212. (lambda (line)
  213. (insert line)
  214. (comint-send-input nil t)
  215. (while (save-excursion
  216. (goto-char comint-last-input-end)
  217. (not (re-search-forward
  218. comint-prompt-regexp nil t)))
  219. (accept-process-output
  220. (get-buffer-process (current-buffer)))))
  221. (append
  222. (split-string (org-trim body) "\n")
  223. (list org-babel-sh-eoe-indicator))))
  224. 2)) "\n"))
  225. ('otherwise ; external shell script
  226. (if (and (cdr (assq :shebang params))
  227. (> (length (cdr (assq :shebang params))) 0))
  228. (let ((script-file (org-babel-temp-file "sh-script-"))
  229. (shebang (cdr (assq :shebang params)))
  230. (padline (not (equal "no" (cdr (assq :padline params))))))
  231. (with-temp-file script-file
  232. (when shebang (insert (concat shebang "\n")))
  233. (when padline (insert "\n"))
  234. (insert body))
  235. (set-file-modes script-file #o755)
  236. (org-babel-eval script-file ""))
  237. (org-babel-eval shell-file-name (org-trim body)))))))
  238. (when results
  239. (let ((result-params (cdr (assq :result-params params))))
  240. (org-babel-result-cond result-params
  241. results
  242. (let ((tmp-file (org-babel-temp-file "sh-")))
  243. (with-temp-file tmp-file (insert results))
  244. (org-babel-import-elisp-from-file tmp-file)))))))
  245. (defun org-babel-sh-strip-weird-long-prompt (string)
  246. "Remove prompt cruft from a string of shell output."
  247. (while (string-match "^% +[\r\n$]+ *" string)
  248. (setq string (substring string (match-end 0))))
  249. string)
  250. (provide 'ob-shell)
  251. ;;; ob-shell.el ends here