fangwen
fangwen

Reputation: 93

indent ruby code on the fly in emacs

How to make Emacs automatically reindent Ruby code on the fly?

for example, with this in Emacs,

def hello
  puts "hello"
  en

After I type 'd', I want it to turn into this,

def hello
  puts "hello"
end

This is the default in Vim, but how can I achieve that in Emacs?

Upvotes: 6

Views: 2419

Answers (4)

tobe
tobe

Reputation: 1741

It won't work because Ruby doesn't know whether you want to type "end" of any variables started with "end". So typing Tab to re-indent it is necessary. And the following configuration works well for me.

; auto indent                                                                                                                                                                                                       
(define-key global-map (kbd "RET") 'newline-and-indent)
(add-hook 'ruby-mode-hook (lambda () (local-set-key "\r" 'newline-and-indent)))

Upvotes: 0

hbin
hbin

Reputation: 2737

Try Auto-indent-mode!

  1. Return automatically indents the code appropriately (if enabled)
  2. Pasting/Yanking indents the appropriately
  3. Killing line will take off unneeded spaces (if enabled)
  4. On visit file, indent appropriately, but DONT SAVE. (Pretend like nothing happened, if enabled)
  5. On save, optionally unttabify, remove trailing white-spaces, and definitely indent the file (if enabled).

Upvotes: 0

Bozhidar Batsov
Bozhidar Batsov

Reputation: 56595

ruby-electric is old news. Emacs 24 has a built-in minor mode called electric-indent-mode that automatically inserts newlines after some chars and you can of course remap the RETURN key to newline-and-indent (it's mapped only to indent by default). In Emacs 24 you can get matching delims with electric-pairs-mode and ruby-end mode will insert automatically end for you when needed. You can have a look at the prelude-ruby.el for more details.

Upvotes: 4

Michael Kohl
Michael Kohl

Reputation: 66837

If you add ruby-electric (also part of Rinari) you get the following:

  • Correctly indented "end" when you write "class", "def", "module" etc.
  • Matching delimiters when you type the opening one.

If you don't want to add extra modes, the end will be indented correctly once you press Enter. Or you press Tab to re-indent the current line.

Upvotes: 2

Related Questions