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

前端 未结 9 588
野的像风
野的像风 2020-12-23 18:17

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 fi

相关标签:
9条回答
  • 2020-12-23 18:36

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

    0 讨论(0)
  • 2020-12-23 18:36

    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().
    
    0 讨论(0)
  • 2020-12-23 18:38

    This answer answers your question. Just replace len computation with your desired column number (+/- 1 may be, I never remember), and remove the enclosing double-quotes added by the substitution.

    0 讨论(0)
提交回复
热议问题