ob-lua.el: Update library for Org 9.0
[org-mode/org-tableheadings.git] / lisp / ob-lua.el
blob1723fb5908c1f08ea0dcca046a6369b3af917bca
1 ;;; ob-lua.el --- Org Babel functions for Lua evaluation
3 ;; Copyright (C) 2014, 2016 Free Software Foundation, Inc.
5 ;; Authors: Dieter Schoen
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 ;; Requirements:
25 ;; for session support, lua-mode is needed.
26 ;; lua-mode is not part of GNU Emacs/orgmode, but can be obtained
27 ;; from marmalade or melpa.
28 ;; The source respository is here:
29 ;; https://github.com/immerrr/lua-mode
31 ;; However, sessions are not yet working.
33 ;; Org-Babel support for evaluating lua source code.
35 ;;; Code:
36 (require 'ob)
37 (eval-when-compile (require 'cl))
39 (declare-function org-remove-indentation "org" )
40 (declare-function lua-shell "ext:lua-mode" (&optional argprompt))
41 (declare-function lua-toggle-shells "ext:lua-mode" (arg))
42 (declare-function run-lua "ext:lua" (cmd &optional dedicated show))
44 (defvar org-babel-tangle-lang-exts)
45 (add-to-list 'org-babel-tangle-lang-exts '("lua" . "lua"))
47 (defvar org-babel-default-header-args:lua '())
49 (defcustom org-babel-lua-command "lua"
50 "Name of the command for executing Lua code."
51 :version "24.5"
52 :package-version '(Org . "8.3")
53 :group 'org-babel
54 :type 'string)
56 (defcustom org-babel-lua-mode 'lua-mode
57 "Preferred lua mode for use in running lua interactively.
58 This will typically be 'lua-mode."
59 :group 'org-babel
60 :version "24.5"
61 :package-version '(Org . "8.3")
62 :type 'symbol)
64 (defcustom org-babel-lua-hline-to "None"
65 "Replace hlines in incoming tables with this when translating to lua."
66 :group 'org-babel
67 :version "24.5"
68 :package-version '(Org . "8.3")
69 :type 'string)
71 (defcustom org-babel-lua-None-to 'hline
72 "Replace 'None' in lua tables with this before returning."
73 :group 'org-babel
74 :version "24.5"
75 :package-version '(Org . "8.3")
76 :type 'symbol)
78 (defun org-babel-execute:lua (body params)
79 "Execute a block of Lua code with Babel.
80 This function is called by `org-babel-execute-src-block'."
81 (let* ((session (org-babel-lua-initiate-session
82 (cdr (assoc :session params))))
83 (result-params (cdr (assoc :result-params params)))
84 (result-type (cdr (assoc :result-type params)))
85 (return-val (when (and (eq result-type 'value) (not session))
86 (cdr (assoc :return params))))
87 (preamble (cdr (assoc :preamble params)))
88 (full-body
89 (org-babel-expand-body:generic
90 (concat body (if return-val (format "\nreturn %s" return-val) ""))
91 params (org-babel-variable-assignments:lua params)))
92 (result (org-babel-lua-evaluate
93 session full-body result-type result-params preamble)))
94 (org-babel-reassemble-table
95 result
96 (org-babel-pick-name (cdr (assoc :colname-names params))
97 (cdr (assoc :colnames params)))
98 (org-babel-pick-name (cdr (assoc :rowname-names params))
99 (cdr (assoc :rownames params))))))
101 (defun org-babel-prep-session:lua (session params)
102 "Prepare SESSION according to the header arguments in PARAMS.
103 VARS contains resolved variable references"
104 (let* ((session (org-babel-lua-initiate-session session))
105 (var-lines
106 (org-babel-variable-assignments:lua params)))
107 (org-babel-comint-in-buffer session
108 (mapc (lambda (var)
109 (end-of-line 1) (insert var) (comint-send-input)
110 (org-babel-comint-wait-for-output session)) var-lines))
111 session))
113 (defun org-babel-load-session:lua (session body params)
114 "Load BODY into SESSION."
115 (save-window-excursion
116 (let ((buffer (org-babel-prep-session:lua session params)))
117 (with-current-buffer buffer
118 (goto-char (process-mark (get-buffer-process (current-buffer))))
119 (insert (org-babel-chomp body)))
120 buffer)))
122 ;; helper functions
124 (defun org-babel-variable-assignments:lua (params)
125 "Return a list of Lua statements assigning the block's variables."
126 (mapcar
127 (lambda (pair)
128 (format "%s=%s"
129 (car pair)
130 (org-babel-lua-var-to-lua (cdr pair))))
131 (org-babel--get-vars params)))
133 (defun org-babel-lua-var-to-lua (var)
134 "Convert an elisp value to a lua variable.
135 Convert an elisp value, VAR, into a string of lua source code
136 specifying a variable of the same value."
137 (if (listp var)
138 (if (and (= 1 (length var)) (not (listp (car var))))
139 (org-babel-lua-var-to-lua (car var))
140 (if (and
141 (= 2 (length var))
142 (not (listp (car var))))
143 (concat
144 (substring-no-properties (car var))
146 (org-babel-lua-var-to-lua (cdr var)))
147 (concat "{" (mapconcat #'org-babel-lua-var-to-lua var ", ") "}")))
148 (if (equal var 'hline)
149 org-babel-lua-hline-to
150 (format
151 (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
152 (if (stringp var) (substring-no-properties var) var)))))
154 (defun org-babel-lua-table-or-string (results)
155 "Convert RESULTS into an appropriate elisp value.
156 If the results look like a list or tuple, then convert them into an
157 Emacs-lisp table, otherwise return the results as a string."
158 (let ((res (org-babel-script-escape results)))
159 (if (listp res)
160 (mapcar (lambda (el) (if (equal el 'None)
161 org-babel-lua-None-to el))
162 res)
163 res)))
165 (defvar org-babel-lua-buffers '((:default . "*Lua*")))
167 (defun org-babel-lua-session-buffer (session)
168 "Return the buffer associated with SESSION."
169 (cdr (assoc session org-babel-lua-buffers)))
171 (defun org-babel-lua-with-earmuffs (session)
172 (let ((name (if (stringp session) session (format "%s" session))))
173 (if (and (string= "*" (substring name 0 1))
174 (string= "*" (substring name (- (length name) 1))))
175 name
176 (format "*%s*" name))))
178 (defun org-babel-lua-without-earmuffs (session)
179 (let ((name (if (stringp session) session (format "%s" session))))
180 (if (and (string= "*" (substring name 0 1))
181 (string= "*" (substring name (- (length name) 1))))
182 (substring name 1 (- (length name) 1))
183 name)))
185 (defvar lua-default-interpreter)
186 (defvar lua-which-bufname)
187 (defvar lua-shell-buffer-name)
188 (defun org-babel-lua-initiate-session-by-key (&optional session)
189 "Initiate a lua session.
190 If there is not a current inferior-process-buffer in SESSION
191 then create. Return the initialized session."
192 (require org-babel-lua-mode)
193 (save-window-excursion
194 (let* ((session (if session (intern session) :default))
195 (lua-buffer (org-babel-lua-session-buffer session))
196 (cmd (if (member system-type '(cygwin windows-nt ms-dos))
197 (concat org-babel-lua-command " -i")
198 org-babel-lua-command)))
199 (cond
200 ((and (eq 'lua-mode org-babel-lua-mode)
201 (fboundp 'lua-start-process)) ; lua-mode.el
202 ;; Make sure that lua-which-bufname is initialized, as otherwise
203 ;; it will be overwritten the first time a Lua buffer is
204 ;; created.
205 ;;(lua-toggle-shells lua-default-interpreter)
206 ;; `lua-shell' creates a buffer whose name is the value of
207 ;; `lua-which-bufname' with '*'s at the beginning and end
208 (let* ((bufname (if (and lua-process-buffer
209 (buffer-live-p lua-process-buffer))
210 (replace-regexp-in-string ;; zap surrounding *
211 "^\\*\\([^*]+\\)\\*$" "\\1" (buffer-name lua-process-buffer))
212 (concat "Lua-" (symbol-name session))))
213 (lua-which-bufname bufname))
214 (lua-start-process)
215 (setq lua-buffer (org-babel-lua-with-earmuffs bufname))))
217 (error "No function available for running an inferior Lua")))
218 (setq org-babel-lua-buffers
219 (cons (cons session lua-process-buffer)
220 (assq-delete-all session org-babel-lua-buffers)))
221 session)))
223 (defun org-babel-lua-initiate-session (&optional session params)
224 "Create a session named SESSION according to PARAMS."
225 (unless (string= session "none")
226 (error "Sessions currently not supported, work in progress")
227 (org-babel-lua-session-buffer
228 (org-babel-lua-initiate-session-by-key session))))
230 (defvar org-babel-lua-eoe-indicator "--eoe"
231 "A string to indicate that evaluation has completed.")
233 (defvar org-babel-lua-wrapper-method
235 function main()
239 fd=io.open(\"%s\", \"w\")
240 fd:write( main() )
241 fd:close()")
242 (defvar org-babel-lua-pp-wrapper-method
244 -- table to string
245 function t2s(t, indent)
246 if indent == nil then
247 indent = \"\"
249 if type(t) == \"table\" then
250 ts = \"\"
251 for k,v in pairs(t) do
252 if type(v) == \"table\" then
253 ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \\n\" ..
254 t2s(v, indent .. \" \")
255 else
256 ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \" ..
257 t2s(v, indent .. \" \") .. \"\\n\"
260 return ts
261 else
262 return tostring(t)
267 function main()
271 fd=io.open(\"%s\", \"w\")
272 fd:write(t2s(main()))
273 fd:close()")
275 (defun org-babel-lua-evaluate
276 (session body &optional result-type result-params preamble)
277 "Evaluate BODY as Lua code."
278 (if session
279 (org-babel-lua-evaluate-session
280 session body result-type result-params)
281 (org-babel-lua-evaluate-external-process
282 body result-type result-params preamble)))
284 (defun org-babel-lua-evaluate-external-process
285 (body &optional result-type result-params preamble)
286 "Evaluate BODY in external lua process.
287 If RESULT-TYPE equals 'output then return standard output as a
288 string. If RESULT-TYPE equals 'value then return the value of the
289 last statement in BODY, as elisp."
290 (let ((raw
291 (pcase result-type
292 (`output (org-babel-eval org-babel-lua-command
293 (concat (if preamble (concat preamble "\n"))
294 body)))
295 (`value (let ((tmp-file (org-babel-temp-file "lua-")))
296 (org-babel-eval
297 org-babel-lua-command
298 (concat
299 (if preamble (concat preamble "\n") "")
300 (format
301 (if (member "pp" result-params)
302 org-babel-lua-pp-wrapper-method
303 org-babel-lua-wrapper-method)
304 (mapconcat
305 (lambda (line) (format "\t%s" line))
306 (split-string
307 (org-remove-indentation
308 (org-trim body))
309 "[\r\n]") "\n")
310 (org-babel-process-file-name tmp-file 'noquote))))
311 (org-babel-eval-read-file tmp-file))))))
312 (org-babel-result-cond result-params
314 (org-babel-lua-table-or-string (org-trim raw)))))
316 (defun org-babel-lua-evaluate-session
317 (session body &optional result-type result-params)
318 "Pass BODY to the Lua process in SESSION.
319 If RESULT-TYPE equals 'output then return standard output as a
320 string. If RESULT-TYPE equals 'value then return the value of the
321 last statement in BODY, as elisp."
322 (let* ((send-wait (lambda () (comint-send-input nil t) (sleep-for 0 5)))
323 (dump-last-value
324 (lambda
325 (tmp-file pp)
326 (mapc
327 (lambda (statement) (insert statement) (funcall send-wait))
328 (if pp
329 (list
330 "-- table to string
331 function t2s(t, indent)
332 if indent == nil then
333 indent = \"\"
335 if type(t) == \"table\" then
336 ts = \"\"
337 for k,v in pairs(t) do
338 if type(v) == \"table\" then
339 ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \\n\" ..
340 t2s(v, indent .. \" \")
341 else
342 ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \" ..
343 t2s(v, indent .. \" \") .. \"\\n\"
346 return ts
347 else
348 return tostring(t)
352 (format "fd:write(_))
353 fd:close()"
354 (org-babel-process-file-name tmp-file 'noquote)))
355 (list (format "fd=io.open(\"%s\", \"w\")
356 fd:write( _ )
357 fd:close()"
358 (org-babel-process-file-name tmp-file
359 'noquote)))))))
360 (input-body (lambda (body)
361 (mapc (lambda (line) (insert line) (funcall send-wait))
362 (split-string body "[\r\n]"))
363 (funcall send-wait)))
364 (results
365 (case result-type
366 (output
367 (mapconcat
368 #'org-trim
369 (butlast
370 (org-babel-comint-with-output
371 (session org-babel-lua-eoe-indicator t body)
372 (funcall input-body body)
373 (funcall send-wait) (funcall send-wait)
374 (insert org-babel-lua-eoe-indicator)
375 (funcall send-wait))
376 2) "\n"))
377 (value
378 (let ((tmp-file (org-babel-temp-file "lua-")))
379 (org-babel-comint-with-output
380 (session org-babel-lua-eoe-indicator nil body)
381 (let ((comint-process-echoes nil))
382 (funcall input-body body)
383 (funcall dump-last-value tmp-file
384 (member "pp" result-params))
385 (funcall send-wait) (funcall send-wait)
386 (insert org-babel-lua-eoe-indicator)
387 (funcall send-wait)))
388 (org-babel-eval-read-file tmp-file))))))
389 (unless (string= (substring org-babel-lua-eoe-indicator 1 -1) results)
390 (org-babel-result-cond result-params
391 results
392 (org-babel-lua-table-or-string results)))))
394 (defun org-babel-lua-read-string (string)
395 "Strip 's from around Lua string."
396 (if (string-match "^'\\([^\000]+\\)'$" string)
397 (match-string 1 string)
398 string))
400 (provide 'ob-lua)
404 ;;; ob-lua.el ends here