1;;; -*-Emacs-Lisp-*-
2;;;
3;;;  $Id: inf-ruby.el 38107 2012-12-01 08:13:04Z nobu $
4;;;  $Author: nobu $
5;;;
6;;; Inferior Ruby Mode - ruby process in a buffer.
7;;;                      adapted from cmuscheme.el
8;;;
9;;; Usage:
10;;;
11;;; (0) check ruby-program-name variable that can run your environment.
12;;;
13;;; (1) modify .emacs to use ruby-mode
14;;;     for example :
15;;;
16;;;    (autoload 'ruby-mode "ruby-mode"
17;;;      "Mode for editing ruby source files" t)
18;;;    (setq auto-mode-alist
19;;;          (append '(("\\.rb$" . ruby-mode)) auto-mode-alist))
20;;;    (setq interpreter-mode-alist (append '(("ruby" . ruby-mode))
21;;;                                  interpreter-mode-alist))
22;;;
23;;; (2) set to load inf-ruby and set inf-ruby key definition in ruby-mode.
24;;;
25;;;    (autoload 'run-ruby "inf-ruby"
26;;;      "Run an inferior Ruby process")
27;;;    (autoload 'inf-ruby-keys "inf-ruby"
28;;;      "Set local key defs for inf-ruby in ruby-mode")
29;;;    (add-hook 'ruby-mode-hook
30;;;          '(lambda ()
31;;;             (inf-ruby-keys)
32;;;    ))
33;;;
34;;; HISTORY
35;;; senda -  8 Apr 1998: Created.
36;;;      $Log$
37;;;      Revision 1.7  2004/07/27 08:11:36  matz
38;;;      * eval.c (rb_eval): copy on write for argument local variable
39;;;        assignment.
40;;;
41;;;      * eval.c (assign): ditto.
42;;;
43;;;      * eval.c (rb_call0): update ruby_frame->argv with the default
44;;;        value used for the optional arguments.
45;;;
46;;;      * object.c (Init_Object): "===" calls rb_obj_equal() directly.
47;;;        [ruby-list:39937]
48;;;
49;;;      Revision 1.6  2002/09/07 14:35:46  nobu
50;;;      * misc/inf-ruby.el (inferior-ruby-error-regexp-alist): regexp
51;;;        alist for error message from ruby.
52;;;
53;;;      * misc/inf-ruby.el (inferior-ruby-mode): fixed for Emacs.
54;;;
55;;;      * misc/inf-ruby.el (ruby-send-region): compilation-parse-errors
56;;;        doesn't parse first line, so insert separators before each
57;;;        evaluations.
58;;;
59;;;      Revision 1.5  2002/08/19 10:05:47  nobu
60;;;      * misc/inf-ruby.el (inf-ruby-keys): ruby-send-definition
61;;;        conflicted with ruby-insert-end.
62;;;
63;;;      * misc/inf-ruby.el (inferior-ruby-mode): compilation-minor-mode.
64;;;
65;;;      * misc/inf-ruby.el (ruby-send-region): send as here document to
66;;;        adjust source file/line.  [ruby-talk:47113], [ruby-dev:17965]
67;;;
68;;;      * misc/inf-ruby.el (ruby-send-terminator): added to make unique
69;;;        terminator.
70;;;
71;;;      Revision 1.4  2002/01/29 07:16:09  matz
72;;;      * file.c (rb_stat_rdev_major): added. [new]
73;;;
74;;;      * file.c (rb_stat_rdev_minor): added. [new]
75;;;
76;;;      * file.c (rb_stat_inspect): print mode in octal.
77;;;
78;;;      Revision 1.3  1999/12/01 09:24:18  matz
79;;;      19991201
80;;;
81;;;      Revision 1.2  1999/08/13 05:45:18  matz
82;;;      1.4.0
83;;;
84;;;      Revision 1.1.1.1.2.1  1999/07/15 07:59:59  matz
85;;;      990715
86;;;
87;;;      Revision 1.1.1.1  1999/01/20 04:59:36  matz
88;;;      ruby 1.3 cycle
89;;;
90;;;      Revision 1.1.2.1  1998/12/16 07:30:36  matz
91;;;      first public release of 1.1d (pre1.2) series
92;;;
93;;;      Revision 1.4  1998/05/20 02:45:58  senda
94;;;      default program to irb
95;;;
96;;;      Revision 1.3  1998/04/10 04:11:30  senda
97;;;      modification by Matsumoto san (1.1b9_09)
98;;;      remove-in-string defined
99;;;      global variable :
100;;;              inferior-ruby-first-prompt-pattern
101;;;            inferior-ruby-prompt-pattern
102;;;      defined
103;;;
104;;;      Revision 1.2  1998/04/09 07:53:42  senda
105;;;      remove M-C-x in inferior-ruby-mode
106;;;
107;;;      Revision 1.1  1998/04/09 07:28:36  senda
108;;;      Initial revision
109;;;
110;;;
111
112(require 'comint)
113(require 'compile)
114(require 'ruby-mode)
115
116;;
117;; you may change these variables
118;;
119;(defvar ruby-program-name "rbc --noreadline"
120;  "*Program invoked by the run-ruby command")
121;
122;(defvar inferior-ruby-first-prompt-pattern "^rbc0> *"
123;  "first prompt regex pattern of ruby interpreter.")
124;
125;(defvar inferior-ruby-prompt-pattern "^\\(rbc.[>*\"'] *\\)+"
126;  "prompt regex pattern of ruby interpreter.")
127
128;;;; for irb
129(defvar ruby-program-name "irb --inf-ruby-mode"
130  "*Program invoked by the run-ruby command")
131
132(defvar inferior-ruby-first-prompt-pattern "^irb(.*)[0-9:]+0> *"
133  "first prompt regex pattern of ruby interpreter.")
134
135(defvar inferior-ruby-prompt-pattern "^\\(irb(.*)[0-9:]+[>*\"'] *\\)+"
136  "prompt regex pattern of ruby interpreter.")
137
138;;
139;; mode variables
140;;
141(defvar inferior-ruby-mode-hook nil
142  "*Hook for customising inferior-ruby mode.")
143(defvar inferior-ruby-mode-map nil
144  "*Mode map for inferior-ruby-mode")
145
146(defconst inferior-ruby-error-regexp-alist
147       '(("SyntaxError: compile error\n^\\([^\(].*\\):\\([1-9][0-9]*\\):" 1 2)
148         ("^\tfrom \\([^\(].*\\):\\([1-9][0-9]*\\)\\(:in `.*'\\)?$" 1 2)))
149
150(cond ((not inferior-ruby-mode-map)
151       (setq inferior-ruby-mode-map
152             (copy-keymap comint-mode-map))
153;       (define-key inferior-ruby-mode-map "\M-\C-x" ;gnu convention
154;                  'ruby-send-definition)
155;       (define-key inferior-ruby-mode-map "\C-x\C-e" 'ruby-send-last-sexp)
156       (define-key inferior-ruby-mode-map "\C-c\C-l" 'ruby-load-file)
157))
158
159(defun inf-ruby-keys ()
160  "Set local key defs for inf-ruby in ruby-mode"
161  (define-key ruby-mode-map "\M-\C-x" 'ruby-send-definition)
162;  (define-key ruby-mode-map "\C-x\C-e" 'ruby-send-last-sexp)
163  (define-key ruby-mode-map "\C-c\C-b" 'ruby-send-block)
164  (define-key ruby-mode-map "\C-c\M-b" 'ruby-send-block-and-go)
165  (define-key ruby-mode-map "\C-c\C-x" 'ruby-send-definition)
166  (define-key ruby-mode-map "\C-c\M-x" 'ruby-send-definition-and-go)
167  (define-key ruby-mode-map "\C-c\C-r" 'ruby-send-region)
168  (define-key ruby-mode-map "\C-c\M-r" 'ruby-send-region-and-go)
169  (define-key ruby-mode-map "\C-c\C-z" 'switch-to-ruby)
170  (define-key ruby-mode-map "\C-c\C-l" 'ruby-load-file)
171  (define-key ruby-mode-map "\C-c\C-s" 'run-ruby)
172)
173
174(defvar ruby-buffer nil "current ruby (actually irb) process buffer.")
175
176(defun inferior-ruby-mode ()
177  "Major mode for interacting with an inferior ruby (irb) process.
178
179The following commands are available:
180\\{inferior-ruby-mode-map}
181
182A ruby process can be fired up with M-x run-ruby.
183
184Customisation: Entry to this mode runs the hooks on comint-mode-hook and
185inferior-ruby-mode-hook (in that order).
186
187You can send text to the inferior ruby process from other buffers containing
188Ruby source.
189    switch-to-ruby switches the current buffer to the ruby process buffer.
190    ruby-send-definition sends the current definition to the ruby process.
191    ruby-send-region sends the current region to the ruby process.
192
193    ruby-send-definition-and-go, ruby-send-region-and-go,
194        switch to the ruby process buffer after sending their text.
195For information on running multiple processes in multiple buffers, see
196documentation for variable ruby-buffer.
197
198Commands:
199Return after the end of the process' output sends the text from the
200    end of process to point.
201Return before the end of the process' output copies the sexp ending at point
202    to the end of the process' output, and sends it.
203Delete converts tabs to spaces as it moves back.
204Tab indents for ruby; with argument, shifts rest
205    of expression rigidly with the current line.
206C-M-q does Tab on each line starting within following expression.
207Paragraphs are separated only by blank lines.  # start comments.
208If you accidentally suspend your process, use \\[comint-continue-subjob]
209to continue it."
210  (interactive)
211  (comint-mode)
212  ;; Customise in inferior-ruby-mode-hook
213  ;(setq comint-prompt-regexp "^[^>\n]*>+ *")
214  (setq comint-prompt-regexp inferior-ruby-prompt-pattern)
215  ;;(scheme-mode-variables)
216  (ruby-mode-variables)
217  (setq major-mode 'inferior-ruby-mode)
218  (setq mode-name "Inferior Ruby")
219  (setq mode-line-process '(":%s"))
220  (use-local-map inferior-ruby-mode-map)
221  (setq comint-input-filter (function ruby-input-filter))
222  (setq comint-get-old-input (function ruby-get-old-input))
223  (make-local-variable 'compilation-error-regexp-alist)
224  (setq compilation-error-regexp-alist inferior-ruby-error-regexp-alist)
225  (compilation-shell-minor-mode t)
226  (run-hooks 'inferior-ruby-mode-hook))
227
228(defvar inferior-ruby-filter-regexp "\\`\\s *\\S ?\\S ?\\s *\\'"
229  "*Input matching this regexp are not saved on the history list.
230Defaults to a regexp ignoring all inputs of 0, 1, or 2 letters.")
231
232(defun ruby-input-filter (str)
233  "Don't save anything matching inferior-ruby-filter-regexp"
234  (not (string-match inferior-ruby-filter-regexp str)))
235
236;; adapted from replace-in-string in XEmacs (subr.el)
237(defun remove-in-string (str regexp)
238  "Remove all matches in STR for REGEXP and returns the new string."
239  (let ((rtn-str "") (start 0) match prev-start)
240    (while (setq match (string-match regexp str start))
241      (setq prev-start start
242            start (match-end 0)
243            rtn-str (concat rtn-str (substring str prev-start match))))
244    (concat rtn-str (substring str start))))
245
246(defun ruby-get-old-input ()
247  "Snarf the sexp ending at point"
248  (save-excursion
249    (let ((end (point)))
250      (re-search-backward inferior-ruby-first-prompt-pattern)
251      (remove-in-string (buffer-substring (point) end)
252                        inferior-ruby-prompt-pattern)
253      )))
254
255(defun ruby-args-to-list (string)
256  (let ((where (string-match "[ \t]" string)))
257    (cond ((null where) (list string))
258          ((not (= where 0))
259           (cons (substring string 0 where)
260                 (ruby-args-to-list (substring string (+ 1 where)
261                                                 (length string)))))
262          (t (let ((pos (string-match "[^ \t]" string)))
263               (if (null pos)
264                   nil
265                 (ruby-args-to-list (substring string pos
266                                                 (length string)))))))))
267
268(defun run-ruby (cmd)
269  "Run an inferior Ruby process, input and output via buffer *ruby*.
270If there is a process already running in `*ruby*', switch to that buffer.
271With argument, allows you to edit the command line (default is value
272of `ruby-program-name').  Runs the hooks `inferior-ruby-mode-hook'
273\(after the `comint-mode-hook' is run).
274\(Type \\[describe-mode] in the process buffer for a list of commands.)"
275
276  (interactive (list (if current-prefix-arg
277                         (read-string "Run Ruby: " ruby-program-name)
278                         ruby-program-name)))
279  (if (not (comint-check-proc "*ruby*"))
280      (let ((cmdlist (ruby-args-to-list cmd)))
281        (set-buffer (apply 'make-comint "ruby" (car cmdlist)
282                           nil (cdr cmdlist)))
283        (inferior-ruby-mode)))
284  (setq ruby-program-name cmd)
285  (setq ruby-buffer "*ruby*")
286  (pop-to-buffer "*ruby*"))
287
288(defconst ruby-send-terminator "--inf-ruby-%x-%d-%d-%d--"
289  "Template for irb here document terminator.
290Must not contain ruby meta characters.")
291
292(defconst ruby-eval-separator "")
293
294(defun ruby-send-region (start end)
295  "Send the current region to the inferior Ruby process."
296  (interactive "r")
297  (let (term (file (buffer-file-name)) line)
298    (save-excursion
299      (save-restriction
300        (widen)
301        (goto-char start)
302        (setq line (+ start (forward-line (- start)) 1))
303        (goto-char start)
304        (while (progn
305                 (setq term (apply 'format ruby-send-terminator (random) (current-time)))
306                 (re-search-forward (concat "^" (regexp-quote term) "$") end t)))))
307    ;; compilation-parse-errors parses from second line.
308    (save-excursion
309      (let ((m (process-mark (ruby-proc))))
310        (set-buffer (marker-buffer m))
311        (goto-char m)
312        (insert ruby-eval-separator "\n")
313        (set-marker m (point))))
314    (comint-send-string (ruby-proc) (format "eval <<'%s', nil, %S, %d\n" term file line))
315    (comint-send-region (ruby-proc) start end)
316    (comint-send-string (ruby-proc) (concat "\n" term "\n"))))
317
318(defun ruby-send-definition ()
319  "Send the current definition to the inferior Ruby process."
320  (interactive)
321  (save-excursion
322    (ruby-end-of-defun)
323    (let ((end (point)))
324      (ruby-beginning-of-defun)
325      (ruby-send-region (point) end))))
326
327;(defun ruby-send-last-sexp ()
328;  "Send the previous sexp to the inferior Ruby process."
329;  (interactive)
330;  (ruby-send-region (save-excursion (backward-sexp) (point)) (point)))
331
332(defun ruby-send-block ()
333  "Send the current block to the inferior Ruby process."
334  (interactive)
335  (save-excursion
336    (ruby-end-of-block)
337    (end-of-line)
338    (let ((end (point)))
339      (ruby-beginning-of-block)
340      (ruby-send-region (point) end))))
341
342(defun switch-to-ruby (eob-p)
343  "Switch to the ruby process buffer.
344With argument, positions cursor at end of buffer."
345  (interactive "P")
346  (if (get-buffer ruby-buffer)
347      (pop-to-buffer ruby-buffer)
348      (error "No current process buffer. See variable ruby-buffer."))
349  (cond (eob-p
350         (push-mark)
351         (goto-char (point-max)))))
352
353(defun ruby-send-region-and-go (start end)
354  "Send the current region to the inferior Ruby process.
355Then switch to the process buffer."
356  (interactive "r")
357  (ruby-send-region start end)
358  (switch-to-ruby t))
359
360(defun ruby-send-definition-and-go ()
361  "Send the current definition to the inferior Ruby.
362Then switch to the process buffer."
363  (interactive)
364  (ruby-send-definition)
365  (switch-to-ruby t))
366
367(defun ruby-send-block-and-go ()
368  "Send the current block to the inferior Ruby.
369Then switch to the process buffer."
370  (interactive)
371  (ruby-send-block)
372  (switch-to-ruby t))
373
374(defvar ruby-source-modes '(ruby-mode)
375  "*Used to determine if a buffer contains Ruby source code.
376If it's loaded into a buffer that is in one of these major modes, it's
377considered a ruby source file by ruby-load-file.
378Used by these commands to determine defaults.")
379
380(defvar ruby-prev-l/c-dir/file nil
381  "Caches the last (directory . file) pair.
382Caches the last pair used in the last ruby-load-file command.
383Used for determining the default in the
384next one.")
385
386(defun ruby-load-file (file-name)
387  "Load a Ruby file into the inferior Ruby process."
388  (interactive (comint-get-source "Load Ruby file: " ruby-prev-l/c-dir/file
389                                  ruby-source-modes t)) ; T because LOAD
390                                                          ; needs an exact name
391  (comint-check-source file-name) ; Check to see if buffer needs saved.
392  (setq ruby-prev-l/c-dir/file (cons (file-name-directory    file-name)
393                                       (file-name-nondirectory file-name)))
394  (comint-send-string (ruby-proc) (concat "(load \""
395                                            file-name
396                                            "\"\)\n")))
397
398(defun ruby-proc ()
399  "Returns the current ruby process. See variable ruby-buffer."
400  (let ((proc (get-buffer-process (if (eq major-mode 'inferior-ruby-mode)
401                                      (current-buffer)
402                                    ruby-buffer))))
403    (or proc
404        (error "No current process. See variable ruby-buffer"))))
405
406;;; Do the user's customisation...
407
408(defvar inf-ruby-load-hook nil
409  "This hook is run when inf-ruby is loaded in.
410This is a good place to put keybindings.")
411
412(run-hooks 'inf-ruby-load-hook)
413
414(provide 'inf-ruby)
415
416;;; inf-ruby.el ends here
417