Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add intelligent alignment of assignments and hashes to indent-region in emacs?

When I have the code:

a = 1
foo = 2

and I want to make it look like:

a   = 1
foo = 2

I can use the align-to-equals function defined here:

Emacs hotkey to align equal signs

by selecting the area and running the function. I can alter the function to work for hashes as well by changing the '=' in the function definition to '=>' and have:

bar = { :a => 1,
 :foo => 2 }

be converted to:

bar = { :a   => 1,
        :foo => 2 }

I want this alignment to be done to all of my code when I select the whole buffer and run indent-region. But I want it to be done intelligently - not aligning every single '=' in the buffer to the rightmost '=', but instead doing it for assignment blocks and individual hash literals.

EDIT: To clarify this last part, say I have the following buffer:

a = 1
foo = 2

some_other_code

def fn
  bar = { :a => 1,
   :foo => 2 }
end

I want to do 'C-x h' (select whole buffer), 'M-C-\' (indent-region) and have it look like this:

a   = 1
foo = 2

some_other_code

def fn
  bar = { :a   => 1,
          :foo => 2 }
end
like image 535
Loren Avatar asked Dec 01 '25 01:12

Loren


2 Answers

Try M-x align-regexp =. And same for others as well.

like image 166
vpit3833 Avatar answered Dec 02 '25 16:12

vpit3833


align.el give the align function for this:

in .emacs add

     (push (ruby-hash-string
             (regexp . "\\(\\s-*\\)\\(\"[^\"]*\"\\|:[a-zA-Z]*\\)\\(\\s-*\\)=>\\(\\s-*\\)")
             (group . (1 3 4))
             (repeat . t)
             (modes '(ruby-mode)))
        align-rules-list)

then M-x align will align hashes in ruby-mode. You need to add other group for other thuings you want to align.

like image 23
Rémi Avatar answered Dec 02 '25 16:12

Rémi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!