Count 简单Vim编程(vimrc文件)
我正在尝试学习如何使用自己的函数配置.vimrc文件 我想写一个函数,它遍历文件中的每一行并计算字符总数,但忽略所有空格。这是一个编程练习,也是更复杂程序的垫脚石(我知道有其他方法可以使用Vim或外部程序获得示例值) 以下是我目前掌握的情况:Count 简单Vim编程(vimrc文件),count,vim,character,Count,Vim,Character,我正在尝试学习如何使用自己的函数配置.vimrc文件 我想写一个函数,它遍历文件中的每一行并计算字符总数,但忽略所有空格。这是一个编程练习,也是更复杂程序的垫脚石(我知道有其他方法可以使用Vim或外部程序获得示例值) 以下是我目前掌握的情况: function countchars() let line = 0 let count = 0 while line < line("$") " update count here, don't count
function countchars()
let line = 0
let count = 0
while line < line("$")
" update count here, don't count whitespace
let line = getline(".")
return count
endfun
函数countchars()
设直线=0
让计数=0
而第行<第行($)
“在此处更新计数,不计算空白
let line=getline(“.”)
返回计数
结束
我可以用什么函数代码替换注释行?如果我正确理解了这个问题,那么您需要计算一行中非空白字符的数量。一种相当简单的方法是删除空白并查看结果行的长度。因此,类似以下内容:
function! Countchars()
let l = 1
let char_count = 0
while l <= line("$")
let char_count += len(substitute(getline(l), '\s', '', 'g'))
let l += 1
endwhile
return char_count
endfunction
expr
在本例中是getline(l)
其中l
是迭代的行数。getline()
返回行的内容,因此这就是要分析的内容。模式是匹配任何单个空白字符的正则表达式\s
。它被替换为'
,即空字符串。标志g
使其重复替换,重复的次数与在行中找到空白的次数相同
替换完成后,len()
给出非空白字符的数量,并使用+=
将其添加到char\u count
的当前值中
我对您的样本做了一些更改:
- 函数名以大写字母开头(这是用户定义函数的要求:请参见
):帮助用户函数
- 我已将
重命名为count
,因为变量不能与函数同名,并且char\u count
是内置函数count()
- 同样对于
:我将其重命名为line
l
- 文件中的第一行是第1行,而不是第0行,因此我将
初始化为1l
- while循环计算到最后一行,但不包括最后一行,我假设您需要文件中的所有行(这可能与从1开始的行号有关):我将您的代码更改为使用
此方法使用列表:
function! Countchars() let n = 0 for line in getline(1,line('$')) let n += len(split(line,'\zs\s*')) endfor return n endfunction
我想你已经找到了解决办法 仅供参考: 我使用它来计算Vim中没有空格的字符数:%s/\s/&/gn
将返回2,要处理多字节字符,请使用len('ñ')
len(split(getline(l),'\zs\s*))
:help usr_41.txt :help function-list :help user-functions :help substitute()
function! Countchars() let n = 0 for line in getline(1,line('$')) let n += len(split(line,'\zs\s*')) endfor return n endfunction