ob-shell.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. ;;; ob-shell.el --- Babel Functions for Shell Evaluation -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2022 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; URL: 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 'org-macs)
  21. (org-assert-version)
  22. (require 'ob)
  23. (require 'org-macs)
  24. (require 'shell)
  25. (require 'cl-lib)
  26. (declare-function org-babel-comint-in-buffer "ob-comint" (buffer &rest body)
  27. t)
  28. (declare-function org-babel-comint-wait-for-output "ob-comint" (buffer))
  29. (declare-function org-babel-comint-buffer-livep "ob-comint" (buffer))
  30. (declare-function org-babel-comint-with-output "ob-comint" (meta &rest body)
  31. t)
  32. (declare-function orgtbl-to-generic "org-table" (table params))
  33. (defvar org-babel-default-header-args:shell '())
  34. (defvar org-babel-shell-names)
  35. (defconst org-babel-shell-set-prompt-commands
  36. '(("fish" . "function fish_prompt\n\techo \"%s\"\nend")
  37. ("csh" . "set prompt=\"%s\"")
  38. ("posh" . "function prompt { \"%s\" }")
  39. (t . "PS1=\"%s\""))
  40. "Alist assigning shells with their prompt setting command.
  41. Each element of the alist associates a shell type from
  42. `org-babel-shell-names' with a template used to create a command to
  43. change the default prompt. The template is an argument to `format'
  44. that will be called with a single additional argument: prompt string.
  45. The fallback association template is defined in (t . \"template\")
  46. alist element.")
  47. (defvar org-babel-prompt-command)
  48. (defun org-babel-shell-initialize ()
  49. "Define execution functions associated to shell names.
  50. This function has to be called whenever `org-babel-shell-names'
  51. is modified outside the Customize interface."
  52. (interactive)
  53. (dolist (name org-babel-shell-names)
  54. (eval `(defun ,(intern (concat "org-babel-execute:" name))
  55. (body params)
  56. ,(format "Execute a block of %s commands with Babel." name)
  57. (let ((shell-file-name ,name)
  58. (org-babel-prompt-command
  59. (or (alist-get ,name org-babel-shell-set-prompt-commands)
  60. (alist-get t org-babel-shell-set-prompt-commands))))
  61. (org-babel-execute:shell body params))))
  62. (eval `(defalias ',(intern (concat "org-babel-variable-assignments:" name))
  63. 'org-babel-variable-assignments:shell
  64. ,(format "Return list of %s statements assigning to the block's \
  65. variables."
  66. name)))
  67. (eval `(defvar ,(intern (concat "org-babel-default-header-args:" name)) '()))))
  68. (defcustom org-babel-shell-names
  69. '("sh" "bash" "zsh" "fish" "csh" "ash" "dash" "ksh" "mksh" "posh")
  70. "List of names of shell supported by babel shell code blocks.
  71. Call `org-babel-shell-initialize' when modifying this variable
  72. outside the Customize interface."
  73. :group 'org-babel
  74. :type '(repeat (string :tag "Shell name: "))
  75. :set (lambda (symbol value)
  76. (set-default-toplevel-value symbol value)
  77. (org-babel-shell-initialize)))
  78. (defcustom org-babel-shell-results-defaults-to-output t
  79. "Let shell execution defaults to \":results output\".
  80. When set to t, use \":results output\" when no :results setting
  81. is set. This is especially useful for inline source blocks.
  82. When set to nil, stick to the convention of using :results value
  83. as the default setting when no :results is set, the \"value\" of
  84. a shell execution being its exit code."
  85. :group 'org-babel
  86. :type 'boolean
  87. :package-version '(Org . "9.4"))
  88. (defun org-babel-execute:shell (body params)
  89. "Execute a block of Shell commands with Babel.
  90. This function is called by `org-babel-execute-src-block'."
  91. (let* ((session (org-babel-sh-initiate-session
  92. (cdr (assq :session params))))
  93. (stdin (let ((stdin (cdr (assq :stdin params))))
  94. (when stdin (org-babel-sh-var-to-string
  95. (org-babel-ref-resolve stdin)))))
  96. (results-params (cdr (assq :result-params params)))
  97. (value-is-exit-status
  98. (or (and
  99. (equal '("replace") results-params)
  100. (not org-babel-shell-results-defaults-to-output))
  101. (member "value" results-params)))
  102. (cmdline (cdr (assq :cmdline params)))
  103. (full-body (concat
  104. (org-babel-expand-body:generic
  105. body params (org-babel-variable-assignments:shell params))
  106. (when value-is-exit-status "\necho $?"))))
  107. (org-babel-reassemble-table
  108. (org-babel-sh-evaluate session full-body params stdin cmdline)
  109. (org-babel-pick-name
  110. (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
  111. (org-babel-pick-name
  112. (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
  113. (defun org-babel-prep-session:shell (session params)
  114. "Prepare SESSION according to the header arguments specified in PARAMS."
  115. (let* ((session (org-babel-sh-initiate-session session))
  116. (var-lines (org-babel-variable-assignments:shell params)))
  117. (org-babel-comint-in-buffer session
  118. (mapc (lambda (var)
  119. (insert var) (comint-send-input nil t)
  120. (org-babel-comint-wait-for-output session))
  121. var-lines))
  122. session))
  123. (defun org-babel-load-session:shell (session body params)
  124. "Load BODY into SESSION."
  125. (save-window-excursion
  126. (let ((buffer (org-babel-prep-session:shell session params)))
  127. (with-current-buffer buffer
  128. (goto-char (process-mark (get-buffer-process (current-buffer))))
  129. (insert (org-babel-chomp body)))
  130. buffer)))
  131. ;;; Helper functions
  132. (defun org-babel--variable-assignments:sh-generic
  133. (varname values &optional sep hline)
  134. "Return a list of statements declaring the values as a generic variable."
  135. (format "%s=%s" varname (org-babel-sh-var-to-sh values sep hline)))
  136. (defun org-babel--variable-assignments:bash_array
  137. (varname values &optional sep hline)
  138. "Return a list of statements declaring the values as a bash array."
  139. (format "unset %s\ndeclare -a %s=( %s )"
  140. varname varname
  141. (mapconcat
  142. (lambda (value) (org-babel-sh-var-to-sh value sep hline))
  143. values
  144. " ")))
  145. (defun org-babel--variable-assignments:bash_assoc
  146. (varname values &optional sep hline)
  147. "Return a list of statements declaring the values as bash associative array."
  148. (format "unset %s\ndeclare -A %s\n%s"
  149. varname varname
  150. (mapconcat
  151. (lambda (items)
  152. (format "%s[%s]=%s"
  153. varname
  154. (org-babel-sh-var-to-sh (car items) sep hline)
  155. (org-babel-sh-var-to-sh (cdr items) sep hline)))
  156. values
  157. "\n")))
  158. (defun org-babel--variable-assignments:bash (varname values &optional sep hline)
  159. "Represent the parameters as useful Bash shell variables."
  160. (pcase values
  161. (`((,_ ,_ . ,_) . ,_) ;two-dimensional array
  162. (org-babel--variable-assignments:bash_assoc varname values sep hline))
  163. (`(,_ . ,_) ;simple list
  164. (org-babel--variable-assignments:bash_array varname values sep hline))
  165. (_ ;scalar value
  166. (org-babel--variable-assignments:sh-generic varname values sep hline))))
  167. (defun org-babel-variable-assignments:shell (params)
  168. "Return list of shell statements assigning the block's variables."
  169. (let ((sep (cdr (assq :separator params)))
  170. (hline (when (string= "yes" (cdr (assq :hlines params)))
  171. (or (cdr (assq :hline-string params))
  172. "hline"))))
  173. (mapcar
  174. (lambda (pair)
  175. (if (string-suffix-p "bash" shell-file-name)
  176. (org-babel--variable-assignments:bash
  177. (car pair) (cdr pair) sep hline)
  178. (org-babel--variable-assignments:sh-generic
  179. (car pair) (cdr pair) sep hline)))
  180. (org-babel--get-vars params))))
  181. (defun org-babel-sh-var-to-sh (var &optional sep hline)
  182. "Convert an elisp value to a shell variable.
  183. Convert an elisp var into a string of shell commands specifying a
  184. var of the same value."
  185. (concat "'" (replace-regexp-in-string
  186. "'" "'\"'\"'"
  187. (org-babel-sh-var-to-string var sep hline))
  188. "'"))
  189. (defun org-babel-sh-var-to-string (var &optional sep hline)
  190. "Convert an elisp value to a string."
  191. (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v)))))
  192. (cond
  193. ((and (listp var) (or (listp (car var)) (eq (car var) 'hline)))
  194. (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var
  195. :hline hline)))
  196. ((listp var)
  197. (mapconcat echo-var var "\n"))
  198. (t (funcall echo-var var)))))
  199. (defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'"
  200. "String to indicate that evaluation has completed.")
  201. (defvar org-babel-sh-eoe-output "org_babel_sh_eoe"
  202. "String to indicate that evaluation has completed.")
  203. (defvar org-babel-sh-prompt "org_babel_sh_prompt> "
  204. "String to set prompt in session shell.")
  205. (defun org-babel-sh-initiate-session (&optional session _params)
  206. "Initiate a session named SESSION according to PARAMS."
  207. (when (and session (not (string= session "none")))
  208. (save-window-excursion
  209. (or (org-babel-comint-buffer-livep session)
  210. (progn
  211. (shell session)
  212. ;; Set unique prompt for easier analysis of the output.
  213. (org-babel-comint-wait-for-output (current-buffer))
  214. (org-babel-comint-input-command
  215. (current-buffer)
  216. (format org-babel-prompt-command org-babel-sh-prompt))
  217. (setq-local comint-prompt-regexp
  218. (concat "^" (regexp-quote org-babel-sh-prompt)
  219. " *"))
  220. ;; Needed for Emacs 23 since the marker is initially
  221. ;; undefined and the filter functions try to use it without
  222. ;; checking.
  223. (set-marker comint-last-output-start (point))
  224. (get-buffer (current-buffer)))))))
  225. (defun org-babel-sh-evaluate (session body &optional params stdin cmdline)
  226. "Pass BODY to the Shell process in BUFFER.
  227. If RESULT-TYPE equals `output' then return a list of the outputs
  228. of the statements in BODY, if RESULT-TYPE equals `value' then
  229. return the value of the last statement in BODY."
  230. (let* ((shebang (cdr (assq :shebang params)))
  231. (results-params (cdr (assq :result-params params)))
  232. (value-is-exit-status
  233. (or (and
  234. (equal '("replace") results-params)
  235. (not org-babel-shell-results-defaults-to-output))
  236. (member "value" results-params)))
  237. (results
  238. (cond
  239. ((or stdin cmdline) ; external shell script w/STDIN
  240. (let ((script-file (org-babel-temp-file "sh-script-"))
  241. (stdin-file (org-babel-temp-file "sh-stdin-"))
  242. (padline (not (string= "no" (cdr (assq :padline params))))))
  243. (with-temp-file script-file
  244. (when shebang (insert shebang "\n"))
  245. (when padline (insert "\n"))
  246. (insert body))
  247. (set-file-modes script-file #o755)
  248. (with-temp-file stdin-file (insert (or stdin "")))
  249. (with-temp-buffer
  250. (with-connection-local-variables
  251. (apply #'process-file
  252. (if shebang (file-local-name script-file)
  253. shell-file-name)
  254. stdin-file
  255. (current-buffer)
  256. nil
  257. (if shebang (when cmdline (list cmdline))
  258. (list shell-command-switch
  259. (concat (file-local-name script-file) " " cmdline)))))
  260. (buffer-string))))
  261. (session ; session evaluation
  262. (mapconcat
  263. #'org-babel-sh-strip-weird-long-prompt
  264. (mapcar
  265. #'org-trim
  266. (butlast
  267. (org-babel-comint-with-output
  268. (session org-babel-sh-eoe-output t body)
  269. (dolist (line (append (split-string (org-trim body) "\n")
  270. (list org-babel-sh-eoe-indicator)))
  271. (insert line)
  272. (comint-send-input nil t)
  273. (while (save-excursion
  274. (goto-char comint-last-input-end)
  275. (not (re-search-forward
  276. comint-prompt-regexp nil t)))
  277. (accept-process-output
  278. (get-buffer-process (current-buffer))))))
  279. 2))
  280. "\n"))
  281. ;; External shell script, with or without a predefined
  282. ;; shebang.
  283. ((org-string-nw-p shebang)
  284. (let ((script-file (org-babel-temp-file "sh-script-"))
  285. (padline (not (equal "no" (cdr (assq :padline params))))))
  286. (with-temp-file script-file
  287. (insert shebang "\n")
  288. (when padline (insert "\n"))
  289. (insert body))
  290. (set-file-modes script-file #o755)
  291. (org-babel-eval script-file "")))
  292. (t (org-babel-eval shell-file-name (org-trim body))))))
  293. (when (and results value-is-exit-status)
  294. (setq results (car (reverse (split-string results "\n" t)))))
  295. (when results
  296. (let ((result-params (cdr (assq :result-params params))))
  297. (org-babel-result-cond result-params
  298. results
  299. (let ((tmp-file (org-babel-temp-file "sh-")))
  300. (with-temp-file tmp-file (insert results))
  301. (org-babel-import-elisp-from-file tmp-file)))))))
  302. (defun org-babel-sh-strip-weird-long-prompt (string)
  303. "Remove prompt cruft from a string of shell output."
  304. (while (string-match "^% +[\r\n$]+ *" string)
  305. (setq string (substring string (match-end 0))))
  306. string)
  307. (provide 'ob-shell)
  308. ;;; ob-shell.el ends here