Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align text on an equals sign in vim

I tend to align code on equal signs for better readability. From this:

$ = jQuery.sub() Survey = App.Survey Sidebar = App.Sidebar Main = App.Main 

To this:

$       = jQuery.sub() Survey  = App.Survey Sidebar = App.Sidebar Main    = App.Main 

Is there an easy way to do this in vim?

like image 908
iblue Avatar asked Jan 22 '12 21:01

iblue


People also ask

How to Align the text in vim?

Did you know you can center align text in vim? From a visual selection, run :center . This aligns the text on the assumption that the width of the document is textwidth , or 80 characters by default. You can also manually set the range by running :center N , where N is the total width of the line.

How to justify text in vim?

vim This Vim script file defines a new visual command "_j". To justify a block of text, highlight the text in Visual mode and then execute "_j".


2 Answers

The best plugin I found so far is Tabular.vim.

Easiest way to install it is by using the Pathogen plugin, and then cloning the Tabular git repository to ~/.vim/bundle/tabular. Full instructions in the Pathogen README.

After it's installed, using it is just a matter of putting your cursor somewhere in the paragraph you want to align and running:

:Tab /= 
like image 132
drrlvn Avatar answered Oct 10 '22 22:10

drrlvn


For a simple solution that does not involve installing a plugin, just filter through the Unix column command.

Note there are two ways to do this depending on whether your column command supports -o.

GNU column command (Linux etc)

:% ! column -t -s= -o= 

That's it.

BSD column command (Mac OS X etc)

Step one, filter through column -t:

:% ! column -t 

Step two, remove the padding around the delimiter:

:%s/ = /=/ 

Initial text is

$ = jQuery.sub() Survey = App.Survey Sidebar = App.Sidebar Main = App.Main 

After step one it becomes

$        =  jQuery.sub() Survey   =  App.Survey Sidebar  =  App.Sidebar Main     =  App.Main 

And after step two

$       = jQuery.sub() Survey  = App.Survey Sidebar = App.Sidebar Main    = App.Main 

Or, if you want to do it in one step:

:% ! column -t | sed 's/ = /=/' 

For more info, man column.

like image 40
Alex Harvey Avatar answered Oct 10 '22 23:10

Alex Harvey