ob-shell.el (16337B)
1 ;;; ob-shell.el --- Babel Functions for Shell Evaluation -*- lexical-binding: t; -*- 2 3 ;; Copyright (C) 2009-2024 Free Software Foundation, Inc. 4 5 ;; Author: Eric Schulte 6 ;; Maintainer: Matthew Trzcinski <matt@excalamus.com> 7 ;; Keywords: literate programming, reproducible research 8 ;; URL: https://orgmode.org 9 10 ;; This file is part of GNU Emacs. 11 12 ;; GNU Emacs is free software: you can redistribute it and/or modify 13 ;; it under the terms of the GNU General Public License as published by 14 ;; the Free Software Foundation, either version 3 of the License, or 15 ;; (at your option) any later version. 16 17 ;; GNU Emacs is distributed in the hope that it will be useful, 18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 ;; GNU General Public License for more details. 21 22 ;; You should have received a copy of the GNU General Public License 23 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. 24 25 ;;; Commentary: 26 27 ;; Org-Babel support for evaluating shell source code. 28 29 ;;; Code: 30 31 (require 'org-macs) 32 (org-assert-version) 33 34 (require 'ob) 35 (require 'org-macs) 36 (require 'shell) 37 (require 'cl-lib) 38 39 (declare-function org-babel-comint-in-buffer "ob-comint" (buffer &rest body) 40 t) 41 (declare-function org-babel-comint-wait-for-output "ob-comint" (buffer)) 42 (declare-function org-babel-comint-buffer-livep "ob-comint" (buffer)) 43 (declare-function org-babel-comint-with-output "ob-comint" (meta &rest body) 44 t) 45 (declare-function orgtbl-to-generic "org-table" (table params)) 46 47 (defvar org-babel-default-header-args:shell '()) 48 49 (defconst org-babel-header-args:shell 50 '((async . ((yes no)))) 51 "Shell-specific header arguments.") 52 53 (defvar org-babel-shell-names) 54 55 (defconst org-babel-shell-set-prompt-commands 56 '(;; Fish has no PS2 equivalent. 57 ("fish" . "function fish_prompt\n\techo \"%s\"\nend") 58 ;; prompt2 is like PS2 in POSIX shells. 59 ("csh" . "set prompt=\"%s\"\nset prompt2=\"\"") 60 ;; PROMPT_COMMAND can override PS1 settings. Disable it. 61 ;; Disable PS2 to avoid garbage in multi-line inputs. 62 (t . "PROMPT_COMMAND=;PS1=\"%s\";PS2=")) 63 "Alist assigning shells with their prompt setting command. 64 65 Each element of the alist associates a shell type from 66 `org-babel-shell-names' with a template used to create a command to 67 change the default prompt. The template is an argument to `format' 68 that will be called with a single additional argument: prompt string. 69 70 The fallback association template is defined in (t . \"template\") 71 alist element.") 72 73 (defun org-babel-shell-initialize () 74 "Define execution functions associated to shell names. 75 This function has to be called whenever `org-babel-shell-names' 76 is modified outside the Customize interface." 77 (interactive) 78 (dolist (name org-babel-shell-names) 79 (let ((fname (intern (concat "org-babel-execute:" name)))) 80 (defalias fname 81 (lambda (body params) 82 (:documentation 83 (format "Execute a block of %s commands with Babel." name)) 84 (let ((explicit-shell-file-name name) 85 (shell-file-name name)) 86 (org-babel-execute:shell body params)))) 87 (put fname 'definition-name 'org-babel-shell-initialize)) 88 (defalias (intern (concat "org-babel-variable-assignments:" name)) 89 #'org-babel-variable-assignments:shell 90 (format "Return list of %s statements assigning to the block's \ 91 variables." 92 name)) 93 (funcall (if (fboundp 'defvar-1) #'defvar-1 #'set) ;Emacs-29 94 (intern (concat "org-babel-default-header-args:" name)) 95 org-babel-default-header-args:shell) 96 (funcall (if (fboundp 'defvar-1) #'defvar-1 #'set) ;Emacs-29 97 (intern (concat "org-babel-header-args:" name)) 98 org-babel-header-args:shell))) 99 100 (defcustom org-babel-shell-names 101 '("sh" "bash" "zsh" "fish" "csh" "ash" "dash" "ksh" "mksh" "posh") 102 "List of names of shell supported by babel shell code blocks. 103 Call `org-babel-shell-initialize' when modifying this variable 104 outside the Customize interface." 105 :group 'org-babel 106 :type '(repeat (string :tag "Shell name: ")) 107 :set (lambda (symbol value) 108 (set-default-toplevel-value symbol value) 109 (org-babel-shell-initialize))) 110 111 (defcustom org-babel-shell-results-defaults-to-output t 112 "Let shell execution defaults to \":results output\". 113 114 When set to t, use \":results output\" when no :results setting 115 is set. This is especially useful for inline source blocks. 116 117 When set to nil, stick to the convention of using :results value 118 as the default setting when no :results is set, the \"value\" of 119 a shell execution being its exit code." 120 :group 'org-babel 121 :type 'boolean 122 :package-version '(Org . "9.4")) 123 124 (defun org-babel-execute:shell (body params) 125 "Execute Shell BODY according to PARAMS. 126 This function is called by `org-babel-execute-src-block'." 127 (let* ((session (org-babel-sh-initiate-session 128 (cdr (assq :session params)))) 129 (stdin (let ((stdin (cdr (assq :stdin params)))) 130 (when stdin (org-babel-sh-var-to-string 131 (org-babel-ref-resolve stdin))))) 132 (results-params (cdr (assq :result-params params))) 133 (value-is-exit-status 134 (or (and 135 (equal '("replace") results-params) 136 (not org-babel-shell-results-defaults-to-output)) 137 (member "value" results-params))) 138 (cmdline (cdr (assq :cmdline params))) 139 (full-body (concat 140 (org-babel-expand-body:generic 141 body params (org-babel-variable-assignments:shell params)) 142 (when value-is-exit-status "\necho $?")))) 143 (org-babel-reassemble-table 144 (org-babel-sh-evaluate session full-body params stdin cmdline) 145 (org-babel-pick-name 146 (cdr (assq :colname-names params)) (cdr (assq :colnames params))) 147 (org-babel-pick-name 148 (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))) 149 150 (defun org-babel-prep-session:shell (session params) 151 "Prepare SESSION according to the header arguments specified in PARAMS." 152 (let* ((session (org-babel-sh-initiate-session session)) 153 (var-lines (org-babel-variable-assignments:shell params))) 154 (org-babel-comint-in-buffer session 155 (mapc (lambda (var) 156 (insert var) (comint-send-input nil t) 157 (org-babel-comint-wait-for-output session)) 158 var-lines)) 159 session)) 160 161 (defun org-babel-load-session:shell (session body params) 162 "Load BODY into SESSION." 163 (save-window-excursion 164 (let ((buffer (org-babel-prep-session:shell session params))) 165 (with-current-buffer buffer 166 (goto-char (process-mark (get-buffer-process (current-buffer)))) 167 (insert (org-babel-chomp body))) 168 buffer))) 169 170 171 ;;; Helper functions 172 (defun org-babel--variable-assignments:sh-generic 173 (varname values &optional sep hline) 174 "Return a list of statements declaring the values as a generic variable." 175 (format "%s=%s" varname (org-babel-sh-var-to-sh values sep hline))) 176 177 (defun org-babel--variable-assignments:fish 178 (varname values &optional sep hline) 179 "Return a list of statements declaring the values as a fish variable." 180 (format "set %s %s" varname (org-babel-sh-var-to-sh values sep hline))) 181 182 (defun org-babel--variable-assignments:bash_array 183 (varname values &optional sep hline) 184 "Return a list of statements declaring the values as a bash array." 185 (format "unset %s\ndeclare -a %s=( %s )" 186 varname varname 187 (mapconcat 188 (lambda (value) (org-babel-sh-var-to-sh value sep hline)) 189 values 190 " "))) 191 192 (defun org-babel--variable-assignments:bash_assoc 193 (varname values &optional sep hline) 194 "Return a list of statements declaring the values as bash associative array." 195 (format "unset %s\ndeclare -A %s\n%s" 196 varname varname 197 (mapconcat 198 (lambda (items) 199 (format "%s[%s]=%s" 200 varname 201 (org-babel-sh-var-to-sh (car items) sep hline) 202 (org-babel-sh-var-to-sh (cdr items) sep hline))) 203 values 204 "\n"))) 205 206 (defun org-babel--variable-assignments:bash (varname values &optional sep hline) 207 "Represent the parameters as useful Bash shell variables." 208 (pcase values 209 (`((,_ ,_ . ,_) . ,_) ;two-dimensional array 210 (org-babel--variable-assignments:bash_assoc varname values sep hline)) 211 (`(,_ . ,_) ;simple list 212 (org-babel--variable-assignments:bash_array varname values sep hline)) 213 (_ ;scalar value 214 (org-babel--variable-assignments:sh-generic varname values sep hline)))) 215 216 (defun org-babel-variable-assignments:shell (params) 217 "Return list of shell statements assigning the block's variables." 218 (let ((sep (cdr (assq :separator params))) 219 (hline (when (string= "yes" (cdr (assq :hlines params))) 220 (or (cdr (assq :hline-string params)) 221 "hline")))) 222 (mapcar 223 (lambda (pair) 224 (if (string-suffix-p "bash" shell-file-name) 225 (org-babel--variable-assignments:bash 226 (car pair) (cdr pair) sep hline) 227 (if (string-suffix-p "fish" shell-file-name) 228 (org-babel--variable-assignments:fish 229 (car pair) (cdr pair) sep hline) 230 (org-babel--variable-assignments:sh-generic 231 (car pair) (cdr pair) sep hline)))) 232 (org-babel--get-vars params)))) 233 234 (defun org-babel-sh-var-to-sh (var &optional sep hline) 235 "Convert an elisp value to a shell variable. 236 Convert an elisp var into a string of shell commands specifying a 237 var of the same value." 238 (concat "'" (replace-regexp-in-string 239 "'" "'\"'\"'" 240 (org-babel-sh-var-to-string var sep hline)) 241 "'")) 242 243 (defun org-babel-sh-var-to-string (var &optional sep hline) 244 "Convert an elisp value to a string." 245 (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v))))) 246 (cond 247 ((and (listp var) (or (listp (car var)) (eq (car var) 'hline))) 248 (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var 249 :hline hline))) 250 ((listp var) 251 (mapconcat echo-var var "\n")) 252 (t (funcall echo-var var))))) 253 254 (defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'" 255 "String to indicate that evaluation has completed.") 256 (defvar org-babel-sh-eoe-output "org_babel_sh_eoe" 257 "String to indicate that evaluation has completed.") 258 (defvar org-babel-sh-prompt "org_babel_sh_prompt> " 259 "String to set prompt in session shell.") 260 261 (defun org-babel-sh-initiate-session (&optional session _params) 262 "Initiate a session named SESSION according to PARAMS." 263 (when (and session (not (string= session "none"))) 264 (save-window-excursion 265 (or (org-babel-comint-buffer-livep session) 266 (progn 267 (shell session) 268 ;; Set unique prompt for easier analysis of the output. 269 (org-babel-comint-wait-for-output (current-buffer)) 270 (org-babel-comint-input-command 271 (current-buffer) 272 (format 273 (or (cdr (assoc (file-name-nondirectory shell-file-name) 274 org-babel-shell-set-prompt-commands)) 275 (alist-get t org-babel-shell-set-prompt-commands)) 276 org-babel-sh-prompt)) 277 (setq-local 278 org-babel-comint-prompt-regexp-old comint-prompt-regexp 279 comint-prompt-regexp 280 (concat "^" (regexp-quote org-babel-sh-prompt) 281 " *")) 282 ;; Needed for Emacs 23 since the marker is initially 283 ;; undefined and the filter functions try to use it without 284 ;; checking. 285 (set-marker comint-last-output-start (point)) 286 (get-buffer (current-buffer))))))) 287 288 (defconst ob-shell-async-indicator "echo 'ob_comint_async_shell_%s_%s'" 289 "Session output delimiter template. 290 See `org-babel-comint-async-indicator'.") 291 292 (defun ob-shell-async-chunk-callback (string) 293 "Filter applied to results before insertion. 294 See `org-babel-comint-async-chunk-callback'." 295 (replace-regexp-in-string comint-prompt-regexp "" string)) 296 297 (defun org-babel-sh-evaluate (session body &optional params stdin cmdline) 298 "Pass BODY to the Shell process in BUFFER. 299 If RESULT-TYPE equals `output' then return a list of the outputs 300 of the statements in BODY, if RESULT-TYPE equals `value' then 301 return the value of the last statement in BODY." 302 (let* ((shebang (cdr (assq :shebang params))) 303 (async (org-babel-comint-use-async params)) 304 (results-params (cdr (assq :result-params params))) 305 (value-is-exit-status 306 (or (and 307 (equal '("replace") results-params) 308 (not org-babel-shell-results-defaults-to-output)) 309 (member "value" results-params))) 310 (results 311 (cond 312 ((or stdin cmdline) ; external shell script w/STDIN 313 (let ((script-file (org-babel-temp-file "sh-script-")) 314 (stdin-file (org-babel-temp-file "sh-stdin-")) 315 (padline (not (string= "no" (cdr (assq :padline params)))))) 316 (with-temp-file script-file 317 (when shebang (insert shebang "\n")) 318 (when padline (insert "\n")) 319 (insert body)) 320 (set-file-modes script-file #o755) 321 (with-temp-file stdin-file (insert (or stdin ""))) 322 (with-temp-buffer 323 (with-connection-local-variables 324 (apply #'process-file 325 (if shebang (file-local-name script-file) 326 shell-file-name) 327 stdin-file 328 (current-buffer) 329 nil 330 (if shebang (when cmdline (list cmdline)) 331 (list shell-command-switch 332 (concat (file-local-name script-file) " " cmdline))))) 333 (buffer-string)))) 334 (session ; session evaluation 335 (if async 336 (progn 337 (let ((uuid (org-id-uuid))) 338 (org-babel-comint-async-register 339 session 340 (current-buffer) 341 "ob_comint_async_shell_\\(start\\|end\\|file\\)_\\(.+\\)" 342 'ob-shell-async-chunk-callback 343 nil) 344 (org-babel-comint-async-delete-dangling-and-eval 345 session 346 (insert (format ob-shell-async-indicator "start" uuid)) 347 (comint-send-input nil t) 348 (insert (org-trim body)) 349 (comint-send-input nil t) 350 (insert (format ob-shell-async-indicator "end" uuid)) 351 (comint-send-input nil t)) 352 uuid)) 353 (mapconcat 354 #'org-babel-sh-strip-weird-long-prompt 355 (mapcar 356 #'org-trim 357 (butlast ; Remove eoe indicator 358 (org-babel-comint-with-output 359 (session org-babel-sh-eoe-output t body) 360 (insert (org-trim body) "\n" 361 org-babel-sh-eoe-indicator) 362 (comint-send-input nil t)) 363 ;; Remove `org-babel-sh-eoe-indicator' output line. 364 1)) 365 "\n"))) 366 ;; External shell script, with or without a predefined 367 ;; shebang. 368 ((org-string-nw-p shebang) 369 (let ((script-file (org-babel-temp-file "sh-script-")) 370 (padline (not (equal "no" (cdr (assq :padline params)))))) 371 (with-temp-file script-file 372 (insert shebang "\n") 373 (when padline (insert "\n")) 374 (insert body)) 375 (set-file-modes script-file #o755) 376 (if (file-remote-p script-file) 377 ;; Run remote script using its local path as COMMAND. 378 ;; The remote execution is ensured by setting 379 ;; correct `default-directory'. 380 (let ((default-directory (file-name-directory script-file))) 381 (org-babel-eval (file-local-name script-file) "")) 382 (org-babel-eval script-file "")))) 383 (t (org-babel-eval shell-file-name (org-trim body)))))) 384 (when (and results value-is-exit-status) 385 (setq results (car (reverse (split-string results "\n" t))))) 386 (when results 387 (let ((result-params (cdr (assq :result-params params)))) 388 (org-babel-result-cond result-params 389 results 390 (let ((tmp-file (org-babel-temp-file "sh-"))) 391 (with-temp-file tmp-file (insert results)) 392 (org-babel-import-elisp-from-file tmp-file))))))) 393 394 (defun org-babel-sh-strip-weird-long-prompt (string) 395 "Remove prompt cruft from a string of shell output." 396 (while (string-match "^% +[\r\n$]+ *" string) 397 (setq string (substring string (match-end 0)))) 398 string) 399 400 (provide 'ob-shell) 401 402 ;;; ob-shell.el ends here