ob-shell.el 13 KB

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