0

Often I want to align code like this

// start with
someVariable = someValue
shorter = anotherValue
longerVariable = anotherValue

// turn into
someVariable   = someValue
shorter        = anotherValue
longerVariable = anotherValue

This is easy enough recording with q:

  1. Find longest variable
  2. Observe the = column
  3. Set character on first line in block
  4. q - record
  5. 0 - start at beginning of line
  6. f= - jump to equals sign
  7. 100i<space><esc> - insert a bunch of spaces
  8. <column_position>| - jump to = column
  9. dw - get rid of extra spaces
  10. j - move to next line
  11. q - stop recording

Once that's done, I can quickly align an entire block. It's quick enough to generate, but the problem is it's not reusable for different lengths, unless I add a bunch by default and then use a square selection to trim it.

I'm entirely new to any kind of scripting. Ideally, I'd like to record one little macro and just "pass" it arguments, for both the column and which character I'm aligning (maybe // comments could be aligned).

Is this possible to write a simple, vanilla script to do that? I often use Vim plugins in IDEs so I'd prefer something as vanilla as possible.

8
  • 1
    What do you call "vanilla script"? Vim emulators usually don't support vimscript and most of them have very limited support for Ex commands anyway, so a "script" won't help you. Besides, "vanilla" may mean something wildly different in a vim-tiny from 10 years ago, in the latest vim-huge, and in your Vim emulator. If you can manage to make some variant of this work in your Vim emulator, that's as far as you can get if you insist on going "vanilla". (And those two questions asked a few hours apart are too similar.)
    – romainl
    Commented Jan 25 at 18:58
  • 1
    Does this answer your question? vi.stackexchange.com/q/20658/10604
    – D. Ben Knoble
    Commented Jan 25 at 19:28
  • Cute formatting is a great way to make bad code look good. Good code should look good and bad code should look bad. Just my two cents.
    – Friedrich
    Commented Jan 25 at 21:29
  • @romainl The vim emulators seem to respect my .vimrc, so I guess anything that you can put in there, so I'll try out your linked solution
    – Adam
    Commented Jan 26 at 16:38
  • @D.BenKnoble I saw that one, it's not ideal but it gets the job done. My emulators support :'<,'>normal, but for some reason the count before i is not respected. I can work around that by copying a bunch of spaces in a register.
    – Adam
    Commented Jan 26 at 16:40

1 Answer 1

1

This is a very popular request and since there are no obvious perfect solution there are a number of plugins that address it. Here are some of the popular choices:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.