Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a line with character x up to column y using Vim

Tags:

vim

How can I fill the remainder of a line with the specified character up to a certain column using Vim? For example, imagine that the cursor is on column four and I want to fill the remainder of the current line with dashes up to column 80. How would I do that?

like image 425
John Topley Avatar asked Jul 29 '10 15:07

John Topley


People also ask

How do I go to a specific character in Vim?

You can type f<character> to put the cursor on the next character and F<character> for the previous one. You can also use ; to repeat the operation and use , to repeat it in opposite direction.

How do I go to a column in vim?

The | command does what you want, as in 3 0 | will take you to column 30. bar | To screen column [count] in the current line. exclusive motion.


3 Answers

You can do 80Ax<Esc>d80| for a simpler solution.

like image 81
Conner Avatar answered Oct 12 '22 07:10

Conner


Here's a function to implement what you ask, and slightly more.

  • It fills the line from its current end of line, rather than the cursor position
  • It forces a single space between what's currently on the line and the repeated chars
  • It allows you to specify any string to fill the rest of the line with
  • It uses vim's textwidth setting to decide how long the line should be (rather than just assuming 80 chars)

The function is defined as follows:

" fill rest of line with characters
function! FillLine( str )
    " set tw to the desired total length
    let tw = &textwidth
    if tw==0 | let tw = 80 | endif
    " strip trailing spaces first
    .s/[[:space:]]*$//
    " calculate total number of 'str's to insert
    let reps = (tw - col("$")) / len(a:str)
    " insert them, if there's room, removing trailing spaces (though forcing
    " there to be one)
    if reps > 0
        .s/$/\=(' '.repeat(a:str, reps))/
    endif
endfunction

Insert that into your .vimrc, and make a mapping to it, e.g.

map <F12> :call FillLine( '-' )

Then you can press F12 to apply the hyphens to the current line

Note: this could probably be easily extended to act on a selection in VISUAL mode, but currently works for single lines only.*

like image 26
drfrogsplat Avatar answered Oct 12 '22 06:10

drfrogsplat


If I understand the question correctly, this can be accomplished like this: in normal mode subtract the cursor's current column position from the desired ending column, then type the result followed by 'i' to enter insert mode, then the character you want to fill the space with. End by returning to normal mode. For example, with the cursor at column four in normal mode, if you wanted to fill the rest of the line up to column 80 with dashes, type 76i- then Esc or Ctrl-[ to return to normal mode. This should result in 76 dashes starting in column 4 and ending in column 79.

like image 5
foven Avatar answered Oct 12 '22 06:10

foven