Question

I have a big python file as follows:

@login_required
@user_passes_test(lambda u: u.is_superuser)
def foo():
    //function body

@login_required
@user_passes_test(lambda u: u.is_superuser)
def foobar():
    //function body
.
.
.

Like this there are many functions in the file. I want to comment all the lines which contains the pattern login_required or user_passes_test. How to comment those lines?

I use tComment plugin. So I can toggle line comment using gcc key-mapping. Can it be used?

There are also other files in the project which contains similar functions. So how can I comment these lines in all files in the project?

And again if I need to uncomment those lines how do I?

Was it helpful?

Solution

The :global/{pat}/{cmd} command will run a command, {cmd}, on every line matching pattern, {pat}. You can execute your tComment command via the :normal command. All together it looks like this:

:g/@login_required/norm gcc

For more help see:

:h :g
:h :norm

OTHER TIPS

If you want to comment certain lines, then uncomment those same lines later, I'd use some kind of "marker" in the comment to make the job easier.

So to comment, for example:

1,$s/^\(.*@login_require\)/#FOO \1/

Then to uncomment:

1,$s/^#FOO //

You would choose #FOO so as not to be using it anywhere else for another purpose. You can even pick something simpler like ##... really anything that starts with # that you're not already using.

This will not be with VIM, but i think easier way to comment out in all project,multiple files:

sed -i 's/@login_required/#login_required/g' *

or for files in directories:

find ./ -type f -exec sed -i 's/@login_required/#login_required/g' {} \;

Comment lines containing string:

:%s/\(.*string\)/# \1/c
  • %s - global substitute
  • \(.*string\) - pattern to match
  • # \1 - replacement, \1 is for the matched pattern
  • c - confirm before substitution

Similarly, to uncomment:

:%s/# \(.*string\)/\1/c
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top