ob-lua.el 14 KB

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