17

I'm trying to format some python code with the tabular.vim plugin. It's currently a sqlalchemy declarative class, and looks something like this:

id     =  db.Column(db.Integer, primary_key=True)
status    =  db.Column(db.Integer, nullable=False, default=3)
...etc...

I'd like to be able to align only the very first equals sign in the list.

id     =  db.Column(db.Integer, primary_key=True)
status =  db.Column(db.Integer, nullable=False, default=3)
...etc...

Just a regular

: Tabularize /=

seems to match everything, and everything goes crazy.

Thanks very much in advance!

Hoopes
  • 3,943
  • 4
  • 44
  • 60

4 Answers4

26

You can use this command:

:Tabularize /^[^=]*\zs=

The pattern only matches the first =.


You can add these two line to ~/.vim/after/plugin/TabularMaps.vim

AddTabularPattern 1=    /^[^=]*\zs=
AddTabularPattern 1==   /^[^=]*\zs=/r0c0l0

Next time, simply run:

:Tabularize 1=

If you don't need spaces around =, run this:

:Tabularize 1==

kev
  • 155,172
  • 47
  • 273
  • 272
  • This isn't vim builtin function, isn't it ? – FlogFR May 26 '14 at 10:23
  • Nope, it's part of the Tabular plugin: https://github.com/godlygeek/tabular, http://vimcasts.org/episodes/aligning-text-with-tabular-vim/ – bshacklett Mar 07 '17 at 20:22
  • So... how can I handle the last match of the line? I've tried to aligh the final `,` via `/.*,[^,]*\zs`, but doesn't work – Marslo May 10 '21 at 08:14
22

The suggestions above are good, but in this case they are a little too complicated and require too much typing. How about:

:Tab /=.*/

This works just fine -- match the first equal sign and everything after it, aligned left (default, which works just fine!).

DigitalAce69
  • 361
  • 2
  • 3
7

Excellent plugin to do it: vim-easy-align.

FlogFR
  • 729
  • 7
  • 14
2

As per this answer, instead of creating a static mapping for each case, you can do this dynamically by setting up a vim command like this:

command! -nargs=1 -range TabFirst exec <line1> . ',' . <line2> . 'Tabularize /^[^' . escape(<q-args>, '\^$.[?*~') . ']*\zs' . escape(<q-args>, '\^$.[?*~')

With this command, if you wanted to align based on the first = then you could do:

:TabFirst =

Or, if you wanted to align on the first { you could do:

:TabFirst {

This supports range selections as well as Tabularize's smart selection.

Community
  • 1
  • 1
Javid Jamae
  • 8,741
  • 4
  • 47
  • 62