ob-ruby.el 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. ;;; ob-ruby.el --- Babel Functions for Ruby -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2022 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  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 ruby source code.
  19. ;;; Requirements:
  20. ;; - ruby and irb executables :: https://www.ruby-lang.org/
  21. ;;
  22. ;; - ruby-mode :: Can be installed through ELPA, or from
  23. ;; https://github.com/eschulte/rinari/raw/master/util/ruby-mode.el
  24. ;;
  25. ;; - inf-ruby mode :: Can be installed through ELPA, or from
  26. ;; https://github.com/eschulte/rinari/raw/master/util/inf-ruby.el
  27. ;;; Code:
  28. (require 'org-macs)
  29. (org-assert-version)
  30. (require 'ob)
  31. (require 'org-macs)
  32. (declare-function run-ruby-or-pop-to-buffer "ext:inf-ruby" (command &optional name buffer))
  33. (declare-function inf-ruby-buffer "ext:inf-ruby" ())
  34. (declare-function xmp "ext:rcodetools" (&optional option))
  35. (defvar inf-ruby-default-implementation)
  36. (defvar inf-ruby-implementations)
  37. (defvar org-babel-tangle-lang-exts)
  38. (add-to-list 'org-babel-tangle-lang-exts '("ruby" . "rb"))
  39. (defvar org-babel-default-header-args:ruby '())
  40. (defvar org-babel-ruby-command "ruby"
  41. "Name of command to use for executing ruby code.
  42. It's possible to override it by using a header argument `:ruby'")
  43. (defcustom org-babel-ruby-hline-to "nil"
  44. "Replace hlines in incoming tables with this when translating to ruby."
  45. :group 'org-babel
  46. :version "24.4"
  47. :package-version '(Org . "8.0")
  48. :type 'string)
  49. (defcustom org-babel-ruby-nil-to 'hline
  50. "Replace nil in ruby tables with this before returning."
  51. :group 'org-babel
  52. :version "24.4"
  53. :package-version '(Org . "8.0")
  54. :type 'symbol)
  55. (defun org-babel-execute:ruby (body params)
  56. "Execute a block of Ruby code with Babel.
  57. This function is called by `org-babel-execute-src-block'."
  58. (let* ((session (org-babel-ruby-initiate-session
  59. (cdr (assq :session params)) params))
  60. (result-params (cdr (assq :result-params params)))
  61. (result-type (cdr (assq :result-type params)))
  62. (org-babel-ruby-command
  63. (or (cdr (assq :ruby params))
  64. org-babel-ruby-command))
  65. (full-body (org-babel-expand-body:generic
  66. body params (org-babel-variable-assignments:ruby params)))
  67. (result (if (member "xmp" result-params)
  68. (with-temp-buffer
  69. (require 'rcodetools)
  70. (insert full-body)
  71. (xmp (cdr (assq :xmp-option params)))
  72. (buffer-string))
  73. (org-babel-ruby-evaluate
  74. session full-body result-type result-params))))
  75. (org-babel-reassemble-table
  76. (org-babel-result-cond result-params
  77. result
  78. (org-babel-ruby-table-or-string result))
  79. (org-babel-pick-name (cdr (assq :colname-names params))
  80. (cdr (assq :colnames params)))
  81. (org-babel-pick-name (cdr (assq :rowname-names params))
  82. (cdr (assq :rownames params))))))
  83. (defun org-babel-prep-session:ruby (session params)
  84. "Prepare SESSION according to the header arguments specified in PARAMS."
  85. ;; (message "params=%S" params) ;; debugging
  86. (let* ((session (org-babel-ruby-initiate-session session))
  87. (var-lines (org-babel-variable-assignments:ruby params)))
  88. (org-babel-comint-in-buffer session
  89. (sit-for .5) (goto-char (point-max))
  90. (mapc (lambda (var)
  91. (insert var) (comint-send-input nil t)
  92. (org-babel-comint-wait-for-output session)
  93. (sit-for .1) (goto-char (point-max)))
  94. var-lines))
  95. session))
  96. (defun org-babel-load-session:ruby (session body params)
  97. "Load BODY into SESSION."
  98. (save-window-excursion
  99. (let ((buffer (org-babel-prep-session:ruby 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)))
  104. ;; helper functions
  105. (defun org-babel-variable-assignments:ruby (params)
  106. "Return list of ruby statements assigning the block's variables."
  107. (mapcar
  108. (lambda (pair)
  109. (format "%s=%s"
  110. (car pair)
  111. (org-babel-ruby-var-to-ruby (cdr pair))))
  112. (org-babel--get-vars params)))
  113. (defun org-babel-ruby-var-to-ruby (var)
  114. "Convert VAR into a ruby variable.
  115. Convert an elisp value into a string of ruby source code
  116. specifying a variable of the same value."
  117. (if (listp var)
  118. (concat "[" (mapconcat #'org-babel-ruby-var-to-ruby var ", ") "]")
  119. (if (eq var 'hline)
  120. org-babel-ruby-hline-to
  121. (format "%S" var))))
  122. (defun org-babel-ruby-table-or-string (results)
  123. "Convert RESULTS into an appropriate elisp value.
  124. If RESULTS look like a table, then convert them into an
  125. Emacs-lisp table, otherwise return the results as a string."
  126. (let ((res (org-babel-script-escape results)))
  127. (if (listp res)
  128. (mapcar (lambda (el) (if (not el)
  129. org-babel-ruby-nil-to el))
  130. res)
  131. res)))
  132. (defun org-babel-ruby-initiate-session (&optional session params)
  133. "Initiate a ruby session.
  134. If there is not a current inferior-process-buffer in SESSION
  135. then create one. Return the initialized session."
  136. (unless (string= session "none")
  137. (require 'inf-ruby)
  138. (let* ((command (cdr (or (assq :ruby params)
  139. (assoc inf-ruby-default-implementation
  140. inf-ruby-implementations))))
  141. (buffer (get-buffer (format "*%s*" session)))
  142. (session-buffer (or buffer (save-window-excursion
  143. (run-ruby-or-pop-to-buffer
  144. (if (functionp command)
  145. (funcall command)
  146. command)
  147. (or session "ruby")
  148. (unless session
  149. (inf-ruby-buffer)))
  150. (current-buffer)))))
  151. (if (org-babel-comint-buffer-livep session-buffer)
  152. (progn (sit-for .25) session-buffer)
  153. (sit-for .5)
  154. (org-babel-ruby-initiate-session session)))))
  155. (defvar org-babel-ruby-eoe-indicator ":org_babel_ruby_eoe"
  156. "String to indicate that evaluation has completed.")
  157. (defvar org-babel-ruby-f-write
  158. "File.open('%s','w'){|f| f.write((_.class == String) ? _ : _.inspect)}")
  159. (defvar org-babel-ruby-pp-f-write
  160. "File.open('%s','w'){|f| $stdout = f; pp(results); $stdout = orig_out}")
  161. (defvar org-babel-ruby-wrapper-method
  162. "
  163. def main()
  164. %s
  165. end
  166. results = main()
  167. File.open('%s', 'w'){ |f| f.write((results.class == String) ? results : results.inspect) }
  168. ")
  169. (defvar org-babel-ruby-pp-wrapper-method
  170. "
  171. require 'pp'
  172. def main()
  173. %s
  174. end
  175. results = main()
  176. File.open('%s', 'w') do |f|
  177. $stdout = f
  178. pp results
  179. end
  180. ")
  181. (defun org-babel-ruby-evaluate
  182. (buffer body &optional result-type result-params)
  183. "Pass BODY to the Ruby process in BUFFER.
  184. If RESULT-TYPE equals `output' then return a list of the outputs
  185. of the statements in BODY, if RESULT-TYPE equals `value' then
  186. return the value of the last statement in BODY, as elisp."
  187. (if (not buffer)
  188. ;; external process evaluation
  189. (pcase result-type
  190. (`output (org-babel-eval org-babel-ruby-command body))
  191. (`value (let ((tmp-file (org-babel-temp-file "ruby-")))
  192. (org-babel-eval
  193. org-babel-ruby-command
  194. (format (if (member "pp" result-params)
  195. org-babel-ruby-pp-wrapper-method
  196. org-babel-ruby-wrapper-method)
  197. body (org-babel-process-file-name tmp-file 'noquote)))
  198. (org-babel-eval-read-file tmp-file))))
  199. ;; comint session evaluation
  200. (pcase result-type
  201. (`output
  202. (let ((eoe-string (format "puts \"%s\"" org-babel-ruby-eoe-indicator)))
  203. ;; Force the session to be ready before the actual session
  204. ;; code is run. There is some problem in comint that will
  205. ;; sometimes show the prompt after the input has already
  206. ;; been inserted and that throws off the extraction of the
  207. ;; result for Babel.
  208. (org-babel-comint-with-output
  209. (buffer org-babel-ruby-eoe-indicator t eoe-string)
  210. (insert eoe-string) (comint-send-input nil t))
  211. ;; Now we can start the evaluation.
  212. (mapconcat
  213. #'identity
  214. (butlast
  215. (split-string
  216. (mapconcat
  217. #'org-trim
  218. (org-babel-comint-with-output
  219. (buffer org-babel-ruby-eoe-indicator t body)
  220. (mapc
  221. (lambda (line)
  222. (insert (org-babel-chomp line)) (comint-send-input nil t))
  223. (list "conf.echo=false;_org_prompt_mode=conf.prompt_mode;conf.prompt_mode=:NULL"
  224. body
  225. "conf.prompt_mode=_org_prompt_mode;conf.echo=true"
  226. eoe-string)))
  227. "\n") "[\r\n]") 4) "\n")))
  228. (`value
  229. (let* ((tmp-file (org-babel-temp-file "ruby-"))
  230. (ppp (or (member "code" result-params)
  231. (member "pp" result-params))))
  232. (org-babel-comint-with-output
  233. (buffer org-babel-ruby-eoe-indicator t body)
  234. (when ppp (insert "require 'pp';") (comint-send-input nil t))
  235. (mapc
  236. (lambda (line)
  237. (insert (org-babel-chomp line)) (comint-send-input nil t))
  238. (append
  239. (list body)
  240. (if (not ppp)
  241. (list (format org-babel-ruby-f-write
  242. (org-babel-process-file-name tmp-file 'noquote)))
  243. (list
  244. "results=_" "require 'pp'" "orig_out = $stdout"
  245. (format org-babel-ruby-pp-f-write
  246. (org-babel-process-file-name tmp-file 'noquote))))
  247. (list org-babel-ruby-eoe-indicator)))
  248. (comint-send-input nil t))
  249. (org-babel-eval-read-file tmp-file))))))
  250. (provide 'ob-ruby)
  251. ;;; ob-ruby.el ends here