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

Viewed 8790

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?

9 Answers

Using the textwidth value is also possible. It allows for different maximum line widths depending on filetype (check :h 'tw'). Here is what I now use, it appends a space after existing line content if present and will prompt for the string to use for the pattern:

function! FillLine() abort
    if &textwidth
        let l:str = input('FillLine>')
        .s/\m\(\S\+\)$/\1 /e  " Add space after content (if present).

        " Calculate how many repetitions will fit.
        let l:lastcol = col('$')-1  " See :h col().
        if l:lastcol > 1
            let l:numstr = float2nr(floor((&textwidth-l:lastcol)/len(l:str)))
        else
            let l:numstr = float2nr(floor(&textwidth/len(l:str)))
        endif

        if l:numstr > 0
            .s/\m$/\=(repeat(l:str, l:numstr))/  " Append repeated pattern.
        endif
    else
        echohl WarningMsg
        echom "FillLine requires nonzero textwidth setting"
        echohl None
    endif
endfunction

You can map it for quick access of course. I like:

nnoremap <Leader>' :call FillLine()<Cr>

Note that the calculation assumes simple ASCII characters are being inserted. For more complicated strings, len(l:str) might not work. From :h strlen():

If you want to count the number of multi-byte characters use strchars().
Also see len(), strdisplaywidth() and strwidth().
Related