如何在VIM中向多行添加注释?

min*_*als 0 vim

我知道如何在VIM中注释多行,但是如果我想在每行的末尾添加注释呢?例如:

function dir.ls(path)
    local i,files = 0,{}
    local pfile = io.popen('ls "'..path..'"')
    for fname in pfile:lines() do
        i = i + 1
        fpath = path..fname
        files[i] = fpath
    end
    pfile:close()
    return files
end
Run Code Online (Sandbox Code Playgroud)

现在添加评论:

function dir.ls(path)
    local i,files = 0,{}
    local pfile = io.popen('ls "'..path..'"')
    for fname in pfile:lines() do
        i = i + 1
        fpath = path..fname  -- your comment goes here
        files[i] = fpath -- your comment goes here
    end
    pfile:close() -- your comment goes here
    return files
end
Run Code Online (Sandbox Code Playgroud)

rom*_*inl 5

  1. 将您的评论附加到第一行:

    A -- your comment goes here<Esc>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将光标移动到要添加注释的下一行.

  3. 重复上一次编辑:

    .
    
    Run Code Online (Sandbox Code Playgroud)
  4. 等等…

在你的例子中:

A -- your comment goes here<Esc>
j.
jj.
Run Code Online (Sandbox Code Playgroud)

另一种方法,但只需一步:

:,+3v/end/norm A -- your comment goes here<CR>
Run Code Online (Sandbox Code Playgroud)

如果从右到左解释该命令更容易理解:

  • :normal命令允许您从命令行模式执行一系列正常模式命令.在这里,我们使用它将注释附加到给定的行,就像在多步方法的第一步中一样.

  • v/pattern/command是该:global命令的伴侣.这意味着"在给定范围内的每一行上运行给定的命令,匹配pattern".在这里,我们:normal在给定范围内不包含的每一行上运行命令end.

  • ,+3是我们要运行:v命令的行的范围.它是一个缩短版本.,+3,意思是"当前行和接下来的三行".