Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim searching: avoid matches within comments

Tags:

python

regex

vim

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.

like image 575
tyrana4 Avatar asked Feb 10 '16 18:02

tyrana4


2 Answers

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 #).

like image 157
Wiktor Stribiżew Avatar answered Nov 03 '22 17:11

Wiktor Stribiżew


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.

like image 20
muru Avatar answered Nov 03 '22 19:11

muru