Try this mapping.
:inoremap <F2> <CR><C-R>=repeat(' ',col([line('.')-1,'$'])-col('.'))<CR><C-O>:.retab<CR>
When you type F2 (or whatever key you choose for the mapping), Vim will insert a newline (<CR>
) followed by a number of spaces (<C-R>=repeat(' ',...)
) equal to the difference between the column number of the end of the previous line (col([line('.')-1,'$'])
) and the current column number (col('.')
), then will execute :retab
on the current line to replace those spaces by tabs and/or spaces according to your setting of 'expandtab'.
Edit
That mapping requires that you be in insert mode. I was thinking that you would type the map key after typing Hello and before typing World. To go back and insert that newline in normal mode, use this mapping.
nnoremap <F2> i<CR><C-R>=repeat(' ',col([line('.')-1,'$'])-col('.'))<CR><Esc>:.retab<CR>