How to insert spaces up to column X to line up things in columns?

Vim

Vim Problem Overview


I have my source code for copy operators written as follows.

foo = rhs.foo;
foobar = rhs.foobar;
bar = rhs.bar;
toto = rhs.toto;

I'd like to line things up as follows (more human readable, isn't it?).

foo    = rhs.foo;
foobar = rhs.foobar;
bar    = rhs.bar;
toto   = rhs.toto;

Is there a VIM magic insert-up-to-column-N, or something like that that would allow me to line things up using a couple of keystrokes per line?

Vim Solutions


Solution 1 - Vim

The other answers here are great, especially @nelstrom's comment for Tabular.vim and his excellent screencast.

But if I were feeling too lazy to install any Vim plugins, yet somehow willing to use Vim macros, I'd use macros.

The algorithm:

For each line,
    Add tons of spaces before the symbol =
    Go to the column you want to align to
    Delete all text up to =, thereby shifting the = into the spot you want.

For your example,

foo = rhs.foo;
foobar = rhs.foobar;
bar = rhs.bar;
toto = rhs.toto;

Position the cursor anywhere on the first line and record the macro for that line by typing, in normal mode:

qa0f=100i <Esc>8|dwjq

Which translates to:

  1. qa -- Record a macro in hotkey a
  2. 0 -- Go to the beginning of the line
  3. f= -- Go to the first equals sign
  4. 100i <Esc> -- (There's a single space after the i, and the <Esc> means press escape, don't type "<Esc>".) Insert 100 spaces
  5. 8| -- Go to the 8th column (sorry, you'll have to manually figure out which column to align to)
  6. dw -- Delete until the next non-space character
  7. j -- Go to the next line
  8. q -- Stop recording.

Then run the macro stored at hotkey a, 3 times (for the 3 remaining lines), by putting the cursor on the second line and pressing:

3@a

Solution 2 - Vim

If you are using a unix-like environment, you can use the command line tool column. Mark your lines using visual mode, then:

:'<,'>!column -t

This pastes the selected text into the stdin of the command after '<,'>!. Note that '<,'>! is inserted automatically when you hit : in visual mode.

Solution 3 - Vim

There is a nice plugin which does exactly that and more, called Align.vim

For you case, you would need to select your expression and then type :Align =. It will align everything, using = as a separator and reference.

(There is a lots of options to align, left, right, cyclically, etc)

You can also check Tabular.vim which provides similar features. See the screencast there for a demo.

Solution 4 - Vim

A quick, simple way to proceed is to add X spaces and then delete back to column X. For example, if X=40, type

40a<Space><Esc>d40|

Solution 5 - Vim

An alternative solution is to perform two consecutive substitutions:

%s/=/     =/
%s/\%>7c *//

The trick is the column pattern \%>7c that matches white spaces * only after the 7th column. Here foobar is the longest variable name with 6 characters so we need 7 in the regex.

Solution 6 - Vim

We can use these two functions that I described in the below path for the same scenario : https://stackoverflow.com/a/32478708/3146151

simply put those two functions in your .vimrc or .gvimrc and call the functions as normal function call in your editor whenever you want.

The functions I have posted it here : https://github.com/imbichie/vim-vimrc-/blob/master/MCCB_MCCE.vim

We need to call this function in vim editor and give the Number of Occurrence of the Character or Space that you wants to move and the character inside the '' and the column number.

The number of occurrence can be from the starting of each line (MCCB function) or can be at the end of each line (MCCE function).

for the above example mentioned in the question we can use the MCCB function and the character we can use '=', so the usage will be like this in the vim editor.

:1,4call MCCB(1,'=',8)

So this will move the first = sign to the 8th column from line number 1 to 4.

These are the functions :

" MCCB - Move the Character to the Column from the Begin of line
" This is a function for Moving the specified Character 
" in a given range of lines to a the specified Column from the Begin of the line
" NOTE 1 :- If the specified character and the first character of the line are same
"           then the number of Occurance (num_occr) will be one less than the actual
" NOTE 2 :- Maximum space between the specified character with in the range 
"           of lines should be less than or equal to 80, if we need more than 80
"           then we need to insert more spaces by increasing the value 80 in the 
"           "nmap s 80i <ESC>" line inside the function
" Usage :-  in command mode do it like below
" Eg 1:-    :5,11call MCCB(1, '=', 8)
"           The above command will move the 1st Occurance from the begin of Character =
"           to the 8th Column of the lines from 5 to 11
" Eg 2 :-   :7,10call MCCB(2, '+', 12)
"           The above command will move the 2nd Occurance of Character = to the 12th
"           Column of the lines from 7 to 10
    function! MCCB (num_occr, mv_char, col_num) range
        if (a:firstline <= a:lastline)
            nmap s 80i <ESC>
            let line_num = a:firstline
            while line_num <= a:lastline
                execute "normal " . line_num . "G0" . a:num_occr . "f" . a:mv_char . "s" . a:col_num . "|dw"
                let line_num = line_num + 1
            endwhile
            nunmap s
        else
            execute printf('ERROR : Start line %d is higher thatn End line %d, a:firstline, a:lastline)
        endif
    endfunction
    
" MCCE - Move the Character to the Column from the End of line
" This is a function for Moving the specified Character 
" in a given range of lines to a the specified Column from the End of the line
" NOTE 1 :- If the specified character and the last character of the line are same
"           then the number of Occurance (num_occr) will be one less than the actual
" NOTE 2 :- Maximum space between the specified character with in the range 
"           of lines should be less than or equal to 80, if we need more than 80
"           then we need to insert more spaces by increasing the value 80 in the 
"           "nmap s 80i <ESC>" line inside the function
" Usage :-  in command mode do it like below
" Eg 1:-    :5,11call MCCE(1, ';', 20)
"           The above command will move the 1st Occurance from the End of Character ;
"           to the 20th Column of the lines from 5 to 11
" Eg 2 :-   :7,10call MCCE(5, 'i', 26)
"           The above command will move the 5th Occurance from the End of Character i
"           to the 26th Column of the lines from 7 to 10
    function! MCCE (num_occr, mv_char, col_num) range
        if (a:firstline <= a:lastline)
            nmap s 80i <ESC>
            let line_num = a:firstline
            while line_num <= a:lastline
                execute "normal " . line_num . "G$" . a:num_occr . "F" . a:mv_char . "s" . a:col_num . "|dw"
                let line_num = line_num + 1
            endwhile
            nunmap s
        else
            execute printf('ERROR : Start line %d is higher thatn End line %d, a:firstline, a:lastline)
        endif
    endfunction

Solution 7 - Vim

I know this is old but I thought @talklittle had the right idea, the answer just got verbose. A quicker way is to insert spaces after the = and then remove all spaces after the 10th column like this:

   :1,4 s/^\(.*=\) *\(.*\)$/\1                           \2/
   :1,4 s/^\(.\{10\}\) *\(.*\)$/\1\2/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDidier TrossetView Question on Stackoverflow
Solution 1 - VimTalkLittleView Answer on Stackoverflow
Solution 2 - VimevnuView Answer on Stackoverflow
Solution 3 - VimXavier T.View Answer on Stackoverflow
Solution 4 - VimPatrick SananView Answer on Stackoverflow
Solution 5 - Vimbuilder-7000View Answer on Stackoverflow
Solution 6 - VimimbichieView Answer on Stackoverflow
Solution 7 - VimPete DView Answer on Stackoverflow