Match string ignoring comments

232 Views Asked by At

How might I match a string for Font Lock fontification while ignoring comments within that string? e.g.

(setq str-regexp "^foobar$"
      comment-regexp "/\\*[^*]*\\*/")

Now how might I return match data to fontify the string "foobar" in the following buffer text?

foo/*comment*/bar
fo/*comment*/obar
fooba/*comment*/r

I can easily strip the comments from a buffer substring and then match a regular expression within that substring, but I don't know how this could then translate back to buffer markers/points suitable for Font Lock. Any ideas?

3

There are 3 best solutions below

1
sshashank124 On

Maybe you want to remove all the comments from the text:

Use the following regex to match the comments:

((?:\/\*)(.*?)(?:\*\/))

and then replace it with '' to result in only the non-commented text.

Resulting text:

foobar
foobar
foobar

Demo

http://regex101.com/r/lC9vY1

3
Drew On

Try using your match code inside macro with-comments-hidden from library hide-comnts.el.

EmacsWiki page Hide Or Ignore Comments describes the macro and the library briefly.

1
Lindydancer On

Font-lock supports an alternative way to match words. Instead of using a regexp, it allows you to call a function to do the work for it.

In this function, you could match the word letter for letter, skipping comments as you go along. The only requirement of the function is to behave like re-search-forward, that is returning non-nil when a match is found and setting match-data accordingly.

As the matched word will contain comments, you will have to write your font-lock rule so that it will color the word, but leave the comments unchanged. You can do this by using setting the OVERRIDE flag in your rule to keep or append (depending on what you want to do).