HomeData EngineeringData DIYAligning Your Code in Vim

Aligning Your Code in Vim

Aligning code, in general, does not provide any value. It’s just to make code look more beautiful and easier to read.

Meet Vim Easy Align.

It’s similar to better align if you’ve used vscode.

Installation & Configuration

You can install using your favorite plugin manager.
Using vim-plug
Plug 'junegunn/vim-easy-align'

And add the following mappings to your

.vimrc

file

xmap ga <Plug>(EasyAlign)
nmap ga <Plug>(EasyAlign)

Feel free to change the default mapping

ga

to something you’re more comfortable with.
Note: If you’re not familiar with

nmap

and

xmap

, they’re used to add mappings for normal and visual mode respectively.

Usage

There are multiple ways to use the plugin. I found the following to be the easiest.
1. Align code in the current block

While in normal mode type

gaip=

Explanation: Start the EasyAlign command (

ga

) for

i

nner

p

aragraph and align around the

=

sign.

Note: don’t forget to press enter to execute the command.
2. Align currently selected code
Assuming that you have something selected while in visual mode.
Type

ga=

Explanation: Start the EasyAlign command (

ga

) and align around the

=

sign.

Options

1. Regular expressions
You can use regular expressions to align anything you want. The only limit is your imagination.

Let’s say for example you want to align javascript module imports around the

from

keyword.

 

You would use the command

ga<Ctrl-x>from

And once again

ga

is used to enter the EasyAlign mode.

After that, press

Ctrl-x

(Control + x) to enter the

regular expression

mode.

Lastly you can enter whatever you want to align your code around (in this case it’s

from

)

2. Align modes
Normally each character has it’s own align mode (left or right).

So, for example,

=

(equal) signs are normally aligned to the right while

:

(colons) are aligned to the left.

But we can change that by using the arrow keys on the keyboard.

Note: I’ll be referring to the right & left arrow keys in commands as

->

and

<-

respectively.

Example:
ga->:

Align right

ga:

Align left (we don’t have to use

<-

since it’s the default for colons)

 

3. Live Interactive Mode
Live interactive mode allows you to see your changes as you type the command.

To use the live interactive mode you can use the command

:LiveEasyAlign

.

Or you could add the following to your

.vimrc

if you prefer shortcuts.

 

" Change <iga> to whatever you like
nmap iga <Plug>(LiveEasyAlign)
xmap iga <Plug>(LiveEasyAlign)

Conclusion

Obviously the plugin contains more options than I could explain in 20 pages.
This article is supposed to be beginner friendly and introduce the basic options.
References

This article has been published from the source link without modifications to the text. Only the headline has been changed.

Source link

Most Popular