Emacs Ruby Foo

June 21, 2007 at 6:16 pm 11 comments

This tutorial is a bit out dated now.  I have created a new version of it over on my new blog which is an updated version of this one.

In my last post I described how I configured emacs to have a Textmate style code browser pane. Since then I have been doing some Rails hacking and have used it a lot and found it works well. In this post I am going to describe some Ruby specific customisations.

Let there be Syntax Highlighting

For most languages, Emacs will syntax highlight your source code right out of the box. It does this by switching into a language specific mode when you open files with certain extensions. Ruby Mode is not present any of my Emacs installs out of the box, but adding support is trivial.


In the Ruby source distribution, under the misc directory, you will find several files. The one called ruby-mode.el is the one that adds Ruby syntax highlighting support to Emacs.

Download it, place it somewhere in your Emacs load path. On windows I created a directory called C:\emacs-22.1\includes and copied ruby-mode.el into it.

(Edit – While you’re there, download inf-ruby.el and put it in the same directory – its needed later when setting up Rails mode)

First ensure the ‘includes directory’ is in the emacs load path by defining it in your _emacs file (at or near the top as it needs to be declared before you use anything in it):

; directory to put various el files into
(add-to-list 'load-path "C:/emacs-22.1/includes")

Now add the following lines to your _emacs:

; loads ruby mode when a .rb file is opened.
(autoload 'ruby-mode "ruby-mode" "Major mode for editing ruby scripts." t)
(setq auto-mode-alist  (cons '(".rb$" . ruby-mode) auto-mode-alist))
(setq auto-mode-alist  (cons '(".rhtml$" . html-mode) auto-mode-alist))

Now when you open a file with an rb extension, ruby-mode will automatically activate. Also, if you open any rhtml files, html-mode will activate which is useful in Rails apps.

Adding Electric

Before saying anything more about ruby-mode, we may as well install ruby-electric mode. I am still in two minds if I like this feature or not, but I am living with it for now. Basically electric-mode defines ‘electric keys’. For example, if you type a quote, the closing quote will automatically be inserted. Same for {, [, and (. Also typing ‘def ‘ will result in the corresponding end being inserted too. Its easier if you play with it a little to see what I mean!

To install electric-mode, download the ruby-electric.el file from the Ruby misc directory into your include directory, and add the following to your _emacs:

(add-hook 'ruby-mode-hook
            (add-hook 'local-write-file-hooks
                           (untabify (point-min) (point-max))
            (set (make-local-variable 'indent-tabs-mode) 'nil)
            (set (make-local-variable 'tab-width) 2)
            (imenu-add-to-menubar "IMENU")
            (define-key ruby-mode-map "C-m" 'newline-and-indent) ;Not sure if this line is 100% right but it works!
            (require 'ruby-electric)
            (ruby-electric-mode t)

Now, we have Ruby Syntax highlighting, electric keys, and auto-indenting, but we can do more …

Messed up you indentation?

If you let you code get into a bit of a twist, you can fix the indenting by press the TAB key while on the line – give it a try, moving over each line and pressing TAB on each to correct the indents!

Comment a block

If you want to comment out a large section of code, you can select it and the type ALT-x ruby-encomment-region and it will place a ‘#’ symbol at the beginning of each line. ALT-x ruby-decomment-region does the opposite.

Compile and Run Code in Emacs

There are many ways to run code in Emacs. The easiest out-of-the-box way, is to type ALT-x compile. Emacs will prompt for a compile command, which by default is ‘make -k’. Replace this with:

ruby -w my_file_name.rb

The emacs window will split in two and the results of running the script will be in the new window.

If you are writing a text document that includes code snippets, and you want to ensure they are correct, you can select the region and type ALT-| to run it. Again, you need to enter the ruby command to run the code.

Smarter Compile?

All that typing ruby -w filename will start to annoy you after a while – the solution is mode-compile which has some brains built in. It can tell when you are editing a Ruby file (or many other types of file) and run it with the correct compiler/interpreter automatically. Download mode-compile.el and put it in your includes directory. As usual, add the following to your _emacs:

; Install mode-compile to give friendlier compiling support!
(autoload 'mode-compile "mode-compile"
   "Command to compile current buffer file based on the major mode" t)
(global-set-key "C-cc" 'mode-compile)
(autoload 'mode-compile-kill "mode-compile"
 "Command to kill a compilation launched by `mode-compile'" t)
(global-set-key "C-ck" 'mode-compile-kill)

Now you can compile/run code by typing CTRL-c c (and if your code enters a nasty infinite loop, you can kill it with CTRL-c k). The output will again appear in a new split window. If there are any compile errors in the output, you can move the cursor over them and hit return and emacs will jump to the offending line in your source file – pretty neat eh?

That is enough for this post – next time I will add Rails snippets and possibly irb support into our Emacs install.


Entry filed under: emacs.

The Emacs Code Browser Emacs and Rails

11 Comments Add your own

  • 1. Simon  |  July 6, 2007 at 4:50 pm

    Not massively important, but rather than do this

    (setq auto-mode-alist (cons ‘(“.rb$” . ruby-mode) auto-mode-alist))
    (setq auto-mode-alist (cons ‘(“.rhtml$” . html-mode) auto-mode-alist))

    You may find it easier on the eye to use add-to-list, which you’ve used with your load-path elsewhere I think:

    (add-to-list ‘auto-mode-alist ‘(“\\.rb$” . ruby-mode))
    (add-to-list ‘auto-mode-alist ‘(“\\.rhtml$” . html-mode))

    Ignoring the syntactic niceties of add-to-list, note the escaped backslash – auto-mode-alist uses a regular expression to match against filenames – your version would try and open any file ending in rb with ruby-mode, since the dot character is a wildcard unless escaped to make it match literally.

    Thanks for the posting – I’m a long time emacs user who’s been meaning to spend some time configuring ruby/rails editing properly, but I’ve been too lazy so far to do much more than add ruby-mode.

  • 2. Jude  |  August 11, 2007 at 6:22 pm

    I had trouble with smarter compile under Ubuntu until I changed:

    (global-set-key "C-cc" 'mode-compile)
    (global-set-key "C-ck" 'mode-compile-kill)

    to …

    (global-set-key "\C-cc" 'mode-compile)
    (global-set-key "\C-ck" 'mode-compile-kill)

    Thanks for all the tips, they have been immensely helpful.

  • 3. Kyle  |  March 23, 2008 at 12:58 am

    For commenting regions, there is a default shortcut that works in most modes other than those derived from c-mode. If you highlight a region, then press M-;, it will either comment out that block, or uncomment it if it is already commented.

  • 4. Patrick  |  April 14, 2008 at 1:04 pm

    I believe that the line in your .emacs file that reads:

    (define-key ruby-mode-map “C-m” ‘newline-and-indent)

    is incorrect

    I believe that it defines a new prefix character, “capital C”, with one defined character following it, “dash” (also called “takeaway” by my 5 year old since 3-2 means “3 takeaway 2”), with one defined character, “m”. At least that is what it did on my installation of NTEmacs 22.2.1. Instead, I think you want

    (define-key ruby-mode-map “\C-m” ‘newline-and-indent)

    — (notice the backslash before the capital-C)
    if you really want the newline-and-indent behavior.


  • 6. Matt  |  September 24, 2008 at 12:06 am

    Wanted to say thanks for these write ups. Saved me hours head scratching. +1 internets.

  • […] enable this feature use this part of Lisp code I’ve found on Stephen O’Donnell’s Software bits and pieces blog. By the way he has excellent posts about Emacs and […]

  • 8. leon  |  December 19, 2008 at 4:39 pm

    Hi, everything works fine, except for comment region, I got the next error : “Autoloading failed to define function ruby-encomment-region” , although , decomment works perfectly . Do you know maybe the cause of this error?

  • 9. ykk  |  February 4, 2009 at 11:50 pm

    Thanks a lot for this excellent write up

  • 10. vladimir prieto  |  March 29, 2010 at 1:14 pm


    misc directoy link: http://svn.ruby-lang.org/repos/ruby/tags/v1_8_5_35/misc/

  • 11. Rodney  |  November 26, 2010 at 3:59 pm

    I prefer reindent-then-newline-and-indent to newline-and-indent.

    I forget exactly what the difference is now but it does some extra tidying and auto-indenting of code as you type.

    I could not the keymap to work using the “define-key” function. I had to use the following instead:

    (add-hook 'ruby-mode-hook (lambda () (local-set-key "\r" 'reindent-then-newline-and-indent)))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


%d bloggers like this: