我想生成最后2位数的顺序文件名
从当前缓冲区的名称和向上计数。像这样:
08a01 > 08a02 > 08a03 > ...
。
我使用的代码段(thanks for initial advice,Ingo Karkat!)遗漏了零,
产生像08a01 > 08a2 > 08a3 > ...
这样的序列。
if b:current_buffer_name =~ '\d\+$'
let lastDigit = matchstr(b:current_buffer_name, '\d\+$')
let newDigit = lastDigit + 1
let s:new_file_name = substitute(b:current_buffer_name, '\d\+$', newDigit, '')
else
let s:new_file_name = b:current_buffer_name . '01'
如何在函数中告诉Vim它应该向上计数“
零“?我尝试在之前添加let &nrformats-=octal
if -condition(如建议here),但这不起作用。
感谢您的解释!
答案 0 :(得分:3)
试试这个:
更改此行:
let newDigit = lastDigit + 1
成:
let newDigit = printf("%02d", str2nr(lastDigit) + 1)
没有测试,但通过阅读你的代码,它应该可以工作。
它是硬编码的2
,如果你的字符串是foobar0000001
,它将无效。在这种情况下,您需要获取len(lastDigit)
并以printf格式使用它。
答案 1 :(得分:1)
我不知道如果不考虑vim
考虑到数字不是octal
且前导零的话,如何避免这样做。我试过set nrformats-=octal
,但都没有用。这是我的解决方法,将数字分为两部分,一边为零,另一边为前导零的其他数字,并使用printf()
计算其长度:
let last_digits = matchlist(bufname('%'), '\(0\+\)\?\(\d\+\)$')
echo printf('%0' . (len(last_digits[1]) + len(last_digits[2])) . 'd', last_digits[2] + 1)
一些测试:
使用名为08a004562
的缓冲区,last_digits
将是一个列表:
['004562', '00', '4562', '', '', '', '', '', '', '']
,结果将是:
004563
使用名为8a9
的缓冲区,last_digits
将为:
['9', '', '9', '', '', '', '', '', '', '']
结果:
10