开发者

String formatting (padding) in VIM

String formatting in VIM is giving me headaches.

I guess I feel very used to string formatting in Python where you can specify how output string are going to be delimited, with how many spaces in between and so on.

So I have a VIM plugin that outputs information to a scratch buffer that looks like:

Line: 1 ==>> ErrorName ==>> File Path: /foo

I build that string before appending it to a buffer and everything works fanta开发者_StackOverflowstic. But whenever you have line numbers that are different (digit wise) you get things like this:

Line: 1 ==>> Error ==>> File Path: /foo
Line: 123  ==>> ErrorNameLong ==>> File Path: /foo
Line: 12  ==>> ErrorShort ==>> File Path: /foo

I have tried doing doing tabs instead of spaces but it only makes it worse (the spaces grow even bigger). So my ideal end result would have to be something like this:

Line: 1    ==>> Error         ==>> File Path: /foo
Line: 123  ==>> ErrorNameLong ==>> File Path: /foo
Line: 12   ==>> ErrorShort    ==>> File Path: /foo

I am well aware of plugins that help (e.g. tabular.vim) but since this is a plugin itself, I do not want to require a dependency on a different plugin just for simple string formatting.

These are the things I have tried so far:

  • Tabs (and tabs + spaces)
  • Search and replace with tabs (and tabs with spaces after rendering in buffer)

It seems to me that there must be a good approach to this and I am just missing it.

How can achieve the string formatting I need in VIM?


I use two little functions, nothing fancy, one to add padding after string and one if I want to add in front of string. The PrePad function allows for an optional argument of the padding character, which I sometimes use to pad numbers with preceding 0's.

function! Pad(s,amt)
    return a:s . repeat(' ',a:amt - len(a:s))
endfunction

 "  Pad('abc', 5) == 'abc  '
 "  Pad('ab', 5) ==  'ab   '


function! PrePad(s,amt,...)
    if a:0 > 0
        let char = a:1
    else
        let char = ' '
    endif
    return repeat(char,a:amt - len(a:s)) . a:s
endfunction

" PrePad('832', 4)      == ' 823'
" PrePad('832', 4, '0') == '0823'

It would be simple to Pad() in building your original log messages. Something like:

echo 'Line: ' . Pad(linenum,8) . '==>> ' . Pad(errmsg,12) . '==>> FilePath: ' . path
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜