ob-lua.el 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. ;;; ob-lua.el --- Org Babel functions for Lua evaluation -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2014, 2016-2019 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)) var-lines))
  92. session))
  93. (defun org-babel-load-session:lua (session body params)
  94. "Load BODY into SESSION."
  95. (save-window-excursion
  96. (let ((buffer (org-babel-prep-session:lua session params)))
  97. (with-current-buffer buffer
  98. (goto-char (process-mark (get-buffer-process (current-buffer))))
  99. (insert (org-babel-chomp body)))
  100. buffer)))
  101. ;; helper functions
  102. (defun org-babel-variable-assignments:lua (params)
  103. "Return a list of Lua statements assigning the block's variables."
  104. (mapcar
  105. (lambda (pair)
  106. (format "%s=%s"
  107. (car pair)
  108. (org-babel-lua-var-to-lua (cdr pair))))
  109. (org-babel--get-vars params)))
  110. (defun org-babel-lua-var-to-lua (var)
  111. "Convert an elisp value to a lua variable.
  112. Convert an elisp value, VAR, into a string of lua source code
  113. specifying a variable of the same value."
  114. (if (listp var)
  115. (if (and (= 1 (length var)) (not (listp (car var))))
  116. (org-babel-lua-var-to-lua (car var))
  117. (if (and
  118. (= 2 (length var))
  119. (not (listp (car var))))
  120. (concat
  121. (substring-no-properties (car var))
  122. "="
  123. (org-babel-lua-var-to-lua (cdr var)))
  124. (concat "{" (mapconcat #'org-babel-lua-var-to-lua var ", ") "}")))
  125. (if (eq var 'hline)
  126. org-babel-lua-hline-to
  127. (format
  128. (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
  129. (if (stringp var) (substring-no-properties var) var)))))
  130. (defun org-babel-lua-table-or-string (results)
  131. "Convert RESULTS into an appropriate elisp value.
  132. If the results look like a list or tuple, then convert them into an
  133. Emacs-lisp table, otherwise return the results as a string."
  134. (let ((res (org-babel-script-escape results)))
  135. (if (listp res)
  136. (mapcar (lambda (el) (if (eq el 'None)
  137. org-babel-lua-None-to el))
  138. res)
  139. res)))
  140. (defvar org-babel-lua-buffers '((:default . "*Lua*")))
  141. (defun org-babel-lua-session-buffer (session)
  142. "Return the buffer associated with SESSION."
  143. (cdr (assoc session org-babel-lua-buffers)))
  144. (defun org-babel-lua-with-earmuffs (session)
  145. (let ((name (if (stringp session) session (format "%s" session))))
  146. (if (and (string= "*" (substring name 0 1))
  147. (string= "*" (substring name (- (length name) 1))))
  148. name
  149. (format "*%s*" name))))
  150. (defun org-babel-lua-without-earmuffs (session)
  151. (let ((name (if (stringp session) session (format "%s" session))))
  152. (if (and (string= "*" (substring name 0 1))
  153. (string= "*" (substring name (- (length name) 1))))
  154. (substring name 1 (- (length name) 1))
  155. name)))
  156. (defvar lua-default-interpreter)
  157. (defvar lua-which-bufname)
  158. (defvar lua-shell-buffer-name)
  159. (defun org-babel-lua-initiate-session-by-key (&optional session)
  160. "Initiate a lua session.
  161. If there is not a current inferior-process-buffer in SESSION
  162. then create. Return the initialized session."
  163. ;; (require org-babel-lua-mode)
  164. (save-window-excursion
  165. (let* ((session (if session (intern session) :default))
  166. (lua-buffer (org-babel-lua-session-buffer session))
  167. ;; (cmd (if (member system-type '(cygwin windows-nt ms-dos))
  168. ;; (concat org-babel-lua-command " -i")
  169. ;; org-babel-lua-command))
  170. )
  171. (cond
  172. ((and (eq 'lua-mode org-babel-lua-mode)
  173. (fboundp 'lua-start-process)) ; lua-mode.el
  174. ;; Make sure that lua-which-bufname is initialized, as otherwise
  175. ;; it will be overwritten the first time a Lua buffer is
  176. ;; created.
  177. ;;(lua-toggle-shells lua-default-interpreter)
  178. ;; `lua-shell' creates a buffer whose name is the value of
  179. ;; `lua-which-bufname' with '*'s at the beginning and end
  180. (let* ((bufname (if (and lua-buffer (buffer-live-p lua-buffer))
  181. (replace-regexp-in-string ;; zap surrounding *
  182. "^\\*\\([^*]+\\)\\*$" "\\1" (buffer-name lua-buffer))
  183. (concat "Lua-" (symbol-name session))))
  184. (lua-which-bufname bufname))
  185. (lua-start-process)
  186. (setq lua-buffer (org-babel-lua-with-earmuffs bufname))))
  187. (t
  188. (error "No function available for running an inferior Lua")))
  189. (setq org-babel-lua-buffers
  190. (cons (cons session lua-buffer)
  191. (assq-delete-all session org-babel-lua-buffers)))
  192. session)))
  193. (defun org-babel-lua-initiate-session (&optional session _params)
  194. "Create a session named SESSION according to PARAMS."
  195. (unless (string= session "none")
  196. (error "Sessions currently not supported, work in progress")
  197. (org-babel-lua-session-buffer
  198. (org-babel-lua-initiate-session-by-key session))))
  199. (defvar org-babel-lua-eoe-indicator "--eoe"
  200. "A string to indicate that evaluation has completed.")
  201. (defvar org-babel-lua-wrapper-method
  202. "
  203. function main()
  204. %s
  205. end
  206. fd=io.open(\"%s\", \"w\")
  207. fd:write( main() )
  208. fd:close()")
  209. (defvar org-babel-lua-pp-wrapper-method
  210. "
  211. -- table to string
  212. function t2s(t, indent)
  213. if indent == nil then
  214. indent = \"\"
  215. end
  216. if type(t) == \"table\" then
  217. ts = \"\"
  218. for k,v in pairs(t) do
  219. if type(v) == \"table\" then
  220. ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \\n\" ..
  221. t2s(v, indent .. \" \")
  222. else
  223. ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \" ..
  224. t2s(v, indent .. \" \") .. \"\\n\"
  225. end
  226. end
  227. return ts
  228. else
  229. return tostring(t)
  230. end
  231. end
  232. function main()
  233. %s
  234. end
  235. fd=io.open(\"%s\", \"w\")
  236. fd:write(t2s(main()))
  237. fd:close()")
  238. (defun org-babel-lua-evaluate
  239. (session body &optional result-type result-params preamble)
  240. "Evaluate BODY as Lua code."
  241. (if session
  242. (org-babel-lua-evaluate-session
  243. session body result-type result-params)
  244. (org-babel-lua-evaluate-external-process
  245. body result-type result-params preamble)))
  246. (defun org-babel-lua-evaluate-external-process
  247. (body &optional result-type result-params preamble)
  248. "Evaluate BODY in external lua process.
  249. If RESULT-TYPE equals 'output then return standard output as a
  250. string. If RESULT-TYPE equals 'value then return the value of the
  251. last statement in BODY, as elisp."
  252. (let ((raw
  253. (pcase result-type
  254. (`output (org-babel-eval org-babel-lua-command
  255. (concat preamble (and preamble "\n")
  256. body)))
  257. (`value (let ((tmp-file (org-babel-temp-file "lua-")))
  258. (org-babel-eval
  259. org-babel-lua-command
  260. (concat
  261. preamble (and preamble "\n")
  262. (format
  263. (if (member "pp" result-params)
  264. org-babel-lua-pp-wrapper-method
  265. org-babel-lua-wrapper-method)
  266. (mapconcat
  267. (lambda (line) (format "\t%s" line))
  268. (split-string
  269. (org-remove-indentation
  270. (org-trim body))
  271. "[\r\n]") "\n")
  272. (org-babel-process-file-name tmp-file 'noquote))))
  273. (org-babel-eval-read-file tmp-file))))))
  274. (org-babel-result-cond result-params
  275. raw
  276. (org-babel-lua-table-or-string (org-trim raw)))))
  277. (defun org-babel-lua-evaluate-session
  278. (session body &optional result-type result-params)
  279. "Pass BODY to the Lua process in SESSION.
  280. If RESULT-TYPE equals 'output then return standard output as a
  281. string. If RESULT-TYPE equals 'value then return the value of the
  282. last statement in BODY, as elisp."
  283. (let* ((send-wait (lambda () (comint-send-input nil t) (sleep-for 0 5)))
  284. (dump-last-value
  285. (lambda
  286. (tmp-file pp)
  287. (mapc
  288. (lambda (statement) (insert statement) (funcall send-wait))
  289. (if pp
  290. (list
  291. "-- table to string
  292. function t2s(t, indent)
  293. if indent == nil then
  294. indent = \"\"
  295. end
  296. if type(t) == \"table\" then
  297. ts = \"\"
  298. for k,v in pairs(t) do
  299. if type(v) == \"table\" then
  300. ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \\n\" ..
  301. t2s(v, indent .. \" \")
  302. else
  303. ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \" ..
  304. t2s(v, indent .. \" \") .. \"\\n\"
  305. end
  306. end
  307. return ts
  308. else
  309. return tostring(t)
  310. end
  311. end
  312. "
  313. (concat "fd:write(_))
  314. fd:close()"
  315. (org-babel-process-file-name tmp-file 'noquote)))
  316. (list (format "fd=io.open(\"%s\", \"w\")
  317. fd:write( _ )
  318. fd:close()"
  319. (org-babel-process-file-name tmp-file
  320. 'noquote)))))))
  321. (input-body (lambda (body)
  322. (mapc (lambda (line) (insert line) (funcall send-wait))
  323. (split-string body "[\r\n]"))
  324. (funcall send-wait)))
  325. (results
  326. (pcase result-type
  327. (`output
  328. (mapconcat
  329. #'org-trim
  330. (butlast
  331. (org-babel-comint-with-output
  332. (session org-babel-lua-eoe-indicator t body)
  333. (funcall input-body body)
  334. (funcall send-wait) (funcall send-wait)
  335. (insert org-babel-lua-eoe-indicator)
  336. (funcall send-wait))
  337. 2) "\n"))
  338. (`value
  339. (let ((tmp-file (org-babel-temp-file "lua-")))
  340. (org-babel-comint-with-output
  341. (session org-babel-lua-eoe-indicator nil body)
  342. (let ((comint-process-echoes nil))
  343. (funcall input-body body)
  344. (funcall dump-last-value tmp-file
  345. (member "pp" result-params))
  346. (funcall send-wait) (funcall send-wait)
  347. (insert org-babel-lua-eoe-indicator)
  348. (funcall send-wait)))
  349. (org-babel-eval-read-file tmp-file))))))
  350. (unless (string= (substring org-babel-lua-eoe-indicator 1 -1) results)
  351. (org-babel-result-cond result-params
  352. results
  353. (org-babel-lua-table-or-string results)))))
  354. (defun org-babel-lua-read-string (string)
  355. "Strip 's from around Lua string."
  356. (org-unbracket-string "'" "'" string))
  357. (provide 'ob-lua)
  358. ;;; ob-lua.el ends here