我正在创建一个新功能来证明文本的合理性。我知道有一些插件,但他们不做我想做的事情所以我决定自己创建一个函数。
之前:
text_text_text_text_____
后:
text__text___text___text
我首先要做的是找到单词的数量和非空格字符的数量(对于我的文本中的每一行):
let @e = '' | redir @e | silent exe i.'s/'.cols.'\(\S\+\)/&/gne' | redir END
if matchstr(@e, 'match') != '' | let nrwords = matchstr(@e, '\d\+\ze') | else | continue | endif
let @e = '' | redir @e | silent exe i.'s/'.cols.'\S/&/gne' | redir END
if matchstr(@e, 'match') != '' | let nonspaces = matchstr(@e, '\d\+\ze') | else | let nonspaces = 0 | endif
然后找到空格:
let spaces = textwidth_I_want - nonspaces
我必须在单词之间划分空格:
let SpacesBetweenWords = spaces/(str2float(nrwords)-1)
但通常是浮点数
体育spaces = 34
nr.words-1 = 10
SpacesBetweenWords = 3.4
我想要做的是划分单词之间的空格,如下所示:
单词之间的空格:
4 3 3 4 3 3 4 3 3 4
并将它们列入一个列表' SpaceList'
然后将它们插入单词
之间 for m in range(1,len(SpaceList))
exe i 's/^'.cols.'\(\S\+\zs\s\+\ze\S\+\)\{'.m.'}/'.repeat(' ', SpaceList[m-1]).'/'
endfor
(cols =我的块选择或整行)
很容易创建一个包含所有整数的列表。在我的例子中
3 3 3 3 3 3 3 3 3 3
(空格= 30)
但是在单词之间仍然有4个空格
我的问题是"我如何在单词数量之间划分这些空格"?
答案 0 :(得分:1)
结果是3.4
,这意味着,您不能在具有相同长度的单词之间建立所有距离。您必须调整textwidth_I_want
值才能使结果为整数,或者将距离设置为3
,并计算仍需要的空格数(10*(3.4-3)=4
)。您可以将这4个空格添加到4个距离。
答案 1 :(得分:0)
使用python找到解决方案
let r = float2nr(SpacesBetweenWords)
let places = nrwords-1
"the extra spaces to put between words
let extraspaces2divide = float2nr(spaces-r*places)
"find randomly with the help of python a serie of (unique) numbers for every space to divide, numbers between 1 and the number of words
exe "py import vim,random; Listvalue = random.sample(xrange(1,".(places+1).",1),".extraspaces2divide.");vim.command(\"let randomlist = '%s'\"% Listvalue)"
"the result of python is a string like this [1, 3, 6, 9]: remove the brackets and spaces and split the result to a list
let randomlist = substitute(randomlist, '[\[\] ]', '', 'g')
"this list is the serie of random numbers (= the place between words) where to add an extra space
let list = sort(split(randomlist, ','))
for s in range(1,nrwords-1)
if (index(list, ''.s.'') != -1)
let r2 = r+1
else
let r2 = r
endif
call add(SpaceList, r2)
endfor