tastyminerals
tastyminerals

Reputation: 6538

How to add comments to multiple lines in VIM?

I know how to comment out multiple lines in VIM, but what if I wanted to add comments in the end of each line? For example:

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

Now with added comments:

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

Upvotes: 0

Views: 867

Answers (1)

romainl
romainl

Reputation: 196546

  1. Append your comment to the first line:

    A -- your comment goes here<Esc>
    
  2. Move the cursor to the next line you want to add a comment to.

  3. Repeat the last edit:

    .
    
  4. And so on…

In your example:

A -- your comment goes here<Esc>
j.
jj.

Another method, but in a single step:

:,+3v/end/norm A -- your comment goes here<CR>

That command is easier to understand if it is explained from right to left:

  • The :normal command allows you to execute a sequence of normal mode commands from command-line mode. Here, we use it to append the comment to the given line, just like in the first step of the multi-step method.

  • v/pattern/command is a companion to the :global command. It means "run the given command on every line in the given range that doesn't match pattern". Here, we run our :normal command on every line in the given range that doesn't contain end.

  • ,+3 is the range of lines on which we want to run the :v command. It is a shortened version of .,+3 which means "the current line and the next three lines".

Upvotes: 5

Related Questions