Using vim searching capabilities, is it possible to avoid matching on a comment block/line.
As an example, I would like to match on 'image' in this python code, but only in the code, not in the comment:
# Export the image
if export_images and i + j % 1000 == 0:
export_image(img_mask, "images/image{}.png".format(image_id))
image_id += 1
Using regular expressions I would do something like this: /^[^#].*(image).*/gm
But it does not seem to work in vim.
You can use
/^[^#].*\zsimage\ze
The \zs
and \ze
signalize the start and end of a match respectively.
- setting the start and end of the match:
\zs \ze
Note that this will not match several "image"s on a line, just the last one.
Also, perhaps, a "negative lookahead" would be better than a negated character class at the beginning:
/^#\@!.*\zsimage\ze
^^^^
The #\@!
is equal to (?!#)
in Python.
And since look-behinds are non-fixed-width in Vim (like (?<=pattern)
in Perl, but Vim allows non-fixed-width patterns), you can match all occurrences of the character sequence image with
/\(^#\@!.*\)\@<=image
And to finally skip matching image on an indented comment line, you just need to match optional (zero or more) whitespace symbol(s) at the beginning of the line:
\(^\(\s*#\)\@!.*\)\@<=image
^^^^^^^^^^^
This \(\s*#\)\@!
is equivalent to Python (?!\s*#)
(match if not followed by zero or more whitespace followed with a #
).
This mailing list post suggest using folds:
To search only in open folds (unfolded text):
:set fdo-=search
To fold #
comments, adapting on this Vi and Vim post (where an autocmd
for Python files is given):
set foldmethod=expr foldexpr=getline(v:lnum)=~'^\s*#'
However, folding by default works only on multiple lines. You need to enable folding of a single line, for single-line comments to be excluded:
set fml=0
After folding everything (zM
, since I did not have anything else to be folded), a search for /image
does not match anything in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With