6

I'm developing a major mode for a language that has doc comments. They look like this:

(** Foos three bars.
    Better call this as [foo 1 b c].
    Though of course [foo a b 1] works as well. **)
Definition foo a b c := a + b - c.

In that context [ and ] work as sorts of unescapes: anything between them is really code, not comments.

Is there a generic approach this? IOW, is there a way to tell font-lock: in comments, treat anything between [] as code?

I can see a bunch of cool applications for this beyond my major mode: for example doctests in python (where >>> should introduce code), or javadoc, or doxygen, etc.

"""Foos the bars
>>> foo 1 2 3 # should be highlighted as code
0
>>> foo 4 5 6 # should be highlighted as code
3"""

I considered making [ a comment closer, and ] a comment opener, but it looks very brittle: it will confuse navigation commands, and nested comments, and will require a strange comment setup to allow multiple closers per opener; and it won't work outside of comments, either.

12
  • In a way, all font-lock rules apply both to comments and non-comments. The fact that they isn't rendered in a comment because a normal rule don't have an OVERRIDE flag. If you add prepend to the rule, it will add it's highlight on top of the comment face. Commented Feb 17, 2016 at 8:52
  • @Lindydancer: Indeed; only I'm not aware of a way to make the flag conditional, i.e. make it prepend only in [] pairs in comments.
    – Clément
    Commented Feb 17, 2016 at 14:49
  • You can replace the regexp with a function, in that function you can search for the regexp using re-search-forward and skip those cases where the context is wrong. The answer emacs.stackexchange.com/questions/20222/… does something similar (the condition in this case is that something should be highlighted in comments only). Commented Feb 17, 2016 at 15:02
  • @Lindydancer: I'm aware of this, but I don't see how it applies here; is your suggestion to duplicate all font-lock keywords and have one copy for code blocks in comments (with 'prepend and a custom function), and another copy for regular code?
    – Clément
    Commented Feb 17, 2016 at 16:57
  • There is no need to duplicate the rules, just use the condition that the text either is outside of comments or enclosed in brackets in a comment. Commented Feb 17, 2016 at 17:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.