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