如何在VI编辑器中获取当前行的长度?

5

在VI编辑器中,有没有一种方法可以检查光标当前所在行的长度?我尝试在Google上搜索,但我只能找到如何使用“set nu”查看当前打开文件中的行号。

3个回答

7

将当前行写入shell命令:

:.w !wc -c

另外请注意,使用 wc -c 命令计算长度时,包括了 \n。如果不需要它,可以减去一个字符或者使用其他方式。
:.w !tr -d '\n'|wc -c

1
.w 是什么作用? - Mistu4u
1
点号表示当前行。如果没有代表写入的w,当前行将被系统调用的输出所替换。 - Walter A

1
使用$将光标移动到行尾,然后使用<ctrl>g显示行和列信息(以及文件名和编辑状态),类似于: "big.csv" [Modified] line 400 of 866 --46%-- col 504 更进一步,如果使用vim,您可以通过打开标尺:se ruler来启用始终在右下角显示行和列信息。然后,每当光标移动时,您会看到类似以下内容的更新: 400,504       46% 您可以将:se ruler添加到您的.vimrc中,使此设置成为每次启动vim时的默认设置。

0

您可以使用strwidthgetline来获取当前行的长度。请参考:h getline

                            *getline()*
getline({lnum} [, {end}])
        Without {end} the result is a String, which is line {lnum}
        from the current buffer.  Example: >
            getline(1)
<       When {lnum} is a String that doesn't start with a
        digit, line() is called to translate the String into a Number.
        To get the line under the cursor: >
            getline(".")
<       When {lnum} is smaller than 1 or bigger than the number of
        lines in the buffer, an empty string is returned.

来自:h strwidth:

strwidth({expr})                    *strwidth()*
        The result is a Number, which is the number of display cells
        String {expr} occupies.  A Tab character is counted as one
        cell, alternatively use |strdisplaywidth()|.
        When {expr} contains characters with East Asian Width Class
        Ambiguous, this function's return value depends on 'ambiwidth'.
        Also see |strlen()|, |strdisplaywidth()| and |strchars()|.

将所有这些放在一起,你可以这样做

echo strwidth(getline('.'))

输出当前行的长度。当然,您也可以通过更改参数来获取特定行的长度。

echo strwidth(getline(3))   "Length of line 3
echo strwidth(getline('$')) "Length of the last line

你好,我在使用VI打开文件并按下“:”键后应该使用它吗? - Mistu4u
@Mistu4u 是的,这是一个ex命令,所以你需要使用冒号。 - DJMcMayhem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接