ob-lua.el 14 KB

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