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: https://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 'org-macs)
  22. (require 'shell)
  23. (require 'cl-lib)
  24. (declare-function org-babel-comint-in-buffer "ob-comint" (buffer &rest body)
  25. t)
  26. (declare-function org-babel-comint-wait-for-output "ob-comint" (buffer))
  27. (declare-function org-babel-comint-buffer-livep "ob-comint" (buffer))
  28. (declare-function org-babel-comint-with-output "ob-comint" (meta &rest body)
  29. t)
  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. (eval `(defvar ,(intern (concat "org-babel-default-header-args:" name)) '()))))
  50. (defcustom org-babel-shell-names
  51. '("sh" "bash" "zsh" "fish" "csh" "ash" "dash" "ksh" "mksh" "posh")
  52. "List of names of shell supported by babel shell code blocks.
  53. Call `org-babel-shell-initialize' when modifying this variable
  54. outside the Customize interface."
  55. :group 'org-babel
  56. :type '(repeat (string :tag "Shell name: "))
  57. :set (lambda (symbol value)
  58. (set-default symbol value)
  59. (org-babel-shell-initialize)))
  60. (defun org-babel-execute:shell (body params)
  61. "Execute a block of Shell commands with Babel.
  62. This function is called by `org-babel-execute-src-block'."
  63. (let* ((session (org-babel-sh-initiate-session
  64. (cdr (assq :session params))))
  65. (stdin (let ((stdin (cdr (assq :stdin params))))
  66. (when stdin (org-babel-sh-var-to-string
  67. (org-babel-ref-resolve stdin)))))
  68. (cmdline (cdr (assq :cmdline params)))
  69. (full-body (org-babel-expand-body:generic
  70. body params (org-babel-variable-assignments:shell params))))
  71. (org-babel-reassemble-table
  72. (org-babel-sh-evaluate session full-body params stdin cmdline)
  73. (org-babel-pick-name
  74. (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
  75. (org-babel-pick-name
  76. (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
  77. (defun org-babel-prep-session:shell (session params)
  78. "Prepare SESSION according to the header arguments specified in PARAMS."
  79. (let* ((session (org-babel-sh-initiate-session session))
  80. (var-lines (org-babel-variable-assignments:shell params)))
  81. (org-babel-comint-in-buffer session
  82. (mapc (lambda (var)
  83. (insert var) (comint-send-input nil t)
  84. (org-babel-comint-wait-for-output session)) var-lines))
  85. session))
  86. (defun org-babel-load-session:shell (session body params)
  87. "Load BODY into SESSION."
  88. (save-window-excursion
  89. (let ((buffer (org-babel-prep-session:shell session params)))
  90. (with-current-buffer buffer
  91. (goto-char (process-mark (get-buffer-process (current-buffer))))
  92. (insert (org-babel-chomp body)))
  93. buffer)))
  94. ;;; Helper functions
  95. (defun org-babel--variable-assignments:sh-generic
  96. (varname values &optional sep hline)
  97. "Returns a list of statements declaring the values as a generic variable."
  98. (format "%s=%s" varname (org-babel-sh-var-to-sh values sep hline)))
  99. (defun org-babel--variable-assignments:bash_array
  100. (varname values &optional sep hline)
  101. "Returns a list of statements declaring the values as a bash array."
  102. (format "unset %s\ndeclare -a %s=( %s )"
  103. varname varname
  104. (mapconcat
  105. (lambda (value) (org-babel-sh-var-to-sh value sep hline))
  106. values
  107. " ")))
  108. (defun org-babel--variable-assignments:bash_assoc
  109. (varname values &optional sep hline)
  110. "Returns a list of statements declaring the values as bash associative array."
  111. (format "unset %s\ndeclare -A %s\n%s"
  112. varname varname
  113. (mapconcat
  114. (lambda (items)
  115. (format "%s[%s]=%s"
  116. varname
  117. (org-babel-sh-var-to-sh (car items) sep hline)
  118. (org-babel-sh-var-to-sh (cdr items) sep hline)))
  119. values
  120. "\n")))
  121. (defun org-babel--variable-assignments:bash (varname values &optional sep hline)
  122. "Represents the parameters as useful Bash shell variables."
  123. (pcase values
  124. (`((,_ ,_ . ,_) . ,_) ;two-dimensional array
  125. (org-babel--variable-assignments:bash_assoc varname values sep hline))
  126. (`(,_ . ,_) ;simple list
  127. (org-babel--variable-assignments:bash_array varname values sep hline))
  128. (_ ;scalar value
  129. (org-babel--variable-assignments:sh-generic varname values sep hline))))
  130. (defun org-babel-variable-assignments:shell (params)
  131. "Return list of shell statements assigning the block's variables."
  132. (let ((sep (cdr (assq :separator params)))
  133. (hline (when (string= "yes" (cdr (assq :hlines params)))
  134. (or (cdr (assq :hline-string params))
  135. "hline"))))
  136. (mapcar
  137. (lambda (pair)
  138. (if (string-suffix-p "bash" shell-file-name)
  139. (org-babel--variable-assignments:bash
  140. (car pair) (cdr pair) sep hline)
  141. (org-babel--variable-assignments:sh-generic
  142. (car pair) (cdr pair) sep hline)))
  143. (org-babel--get-vars params))))
  144. (defun org-babel-sh-var-to-sh (var &optional sep hline)
  145. "Convert an elisp value to a shell variable.
  146. Convert an elisp var into a string of shell commands specifying a
  147. var of the same value."
  148. (concat "'" (replace-regexp-in-string
  149. "'" "'\"'\"'"
  150. (org-babel-sh-var-to-string var sep hline))
  151. "'"))
  152. (defun org-babel-sh-var-to-string (var &optional sep hline)
  153. "Convert an elisp value to a string."
  154. (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v)))))
  155. (cond
  156. ((and (listp var) (or (listp (car var)) (eq (car var) 'hline)))
  157. (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var
  158. :hline hline)))
  159. ((listp var)
  160. (mapconcat echo-var var "\n"))
  161. (t (funcall echo-var var)))))
  162. (defun org-babel-sh-initiate-session (&optional session _params)
  163. "Initiate a session named SESSION according to PARAMS."
  164. (when (and session (not (string= session "none")))
  165. (save-window-excursion
  166. (or (org-babel-comint-buffer-livep session)
  167. (progn
  168. (shell session)
  169. ;; Needed for Emacs 23 since the marker is initially
  170. ;; undefined and the filter functions try to use it without
  171. ;; checking.
  172. (set-marker comint-last-output-start (point))
  173. (get-buffer (current-buffer)))))))
  174. (defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'"
  175. "String to indicate that evaluation has completed.")
  176. (defvar org-babel-sh-eoe-output "org_babel_sh_eoe"
  177. "String to indicate that evaluation has completed.")
  178. (defun org-babel-sh-evaluate (session body &optional params stdin cmdline)
  179. "Pass BODY to the Shell process in BUFFER.
  180. If RESULT-TYPE equals `output' then return a list of the outputs
  181. of the statements in BODY, if RESULT-TYPE equals `value' then
  182. return the value of the last statement in BODY."
  183. (let* ((shebang (cdr (assq :shebang params)))
  184. (results
  185. (cond
  186. ((or stdin cmdline) ; external shell script w/STDIN
  187. (let ((script-file (org-babel-temp-file "sh-script-"))
  188. (stdin-file (org-babel-temp-file "sh-stdin-"))
  189. (padline (not (string= "no" (cdr (assq :padline params))))))
  190. (with-temp-file script-file
  191. (when shebang (insert shebang "\n"))
  192. (when padline (insert "\n"))
  193. (insert body))
  194. (set-file-modes script-file #o755)
  195. (with-temp-file stdin-file (insert (or stdin "")))
  196. (with-temp-buffer
  197. (call-process-shell-command
  198. (concat (if shebang script-file
  199. (format "%s %s" shell-file-name script-file))
  200. (and cmdline (concat " " cmdline)))
  201. stdin-file
  202. (current-buffer))
  203. (buffer-string))))
  204. (session ; session evaluation
  205. (mapconcat
  206. #'org-babel-sh-strip-weird-long-prompt
  207. (mapcar
  208. #'org-trim
  209. (butlast
  210. (org-babel-comint-with-output
  211. (session org-babel-sh-eoe-output t body)
  212. (dolist (line (append (split-string (org-trim body) "\n")
  213. (list org-babel-sh-eoe-indicator)))
  214. (insert line)
  215. (comint-send-input nil t)
  216. (while (save-excursion
  217. (goto-char comint-last-input-end)
  218. (not (re-search-forward
  219. comint-prompt-regexp nil t)))
  220. (accept-process-output
  221. (get-buffer-process (current-buffer))))))
  222. 2))
  223. "\n"))
  224. ;; External shell script, with or without a predefined
  225. ;; shebang.
  226. ((org-string-nw-p shebang)
  227. (let ((script-file (org-babel-temp-file "sh-script-"))
  228. (padline (not (equal "no" (cdr (assq :padline params))))))
  229. (with-temp-file script-file
  230. (insert shebang "\n")
  231. (when padline (insert "\n"))
  232. (insert body))
  233. (set-file-modes script-file #o755)
  234. (org-babel-eval script-file "")))
  235. (t
  236. (org-babel-eval shell-file-name (org-trim body))))))
  237. (when results
  238. (let ((result-params (cdr (assq :result-params params))))
  239. (org-babel-result-cond result-params
  240. results
  241. (let ((tmp-file (org-babel-temp-file "sh-")))
  242. (with-temp-file tmp-file (insert results))
  243. (org-babel-import-elisp-from-file tmp-file)))))))
  244. (defun org-babel-sh-strip-weird-long-prompt (string)
  245. "Remove prompt cruft from a string of shell output."
  246. (while (string-match "^% +[\r\n$]+ *" string)
  247. (setq string (substring string (match-end 0))))
  248. string)
  249. (provide 'ob-shell)
  250. ;;; ob-shell.el ends here