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