开发者

Syntax Highlighting in Javascript

I am currently working on some syntax highlighting in Javascript.

To match strings, I would use something like this:

code = code.replace(/("([^"\\]*(\\.[^"\\]*)*)")/gm, "<span class=\"string\">$1</span>"); // string

This would match an integer:

code = code.replace(/(\d+)/gm, "<span class=\"number\">$1</span>");

Now my problem is that an integer within a string would get matched too. It's not a problem of highlighting but of performance, since I could use

code > span.number instead of code span.number.

Any suggestions for preventing this kind of behavior?


I also read through TextMate's Language Grammars which seem really powerful to me. However, I have no idea how I could implement that in Javascript.

Some help would really be appreciated.


I know that there are many good syntax highlighting things around, but none of 开发者_C百科them provides really good support for Objective-C.


If you want to write an objective-C mode for Google Code Prettify I would be happy to incorporate it.

You can see an example mode for OCAML/SML style languages at http://code.google.com/p/google-code-prettify/source/browse/trunk/src/lang-ml.js

Lines like

[PR['PR_STRING'],
 /^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])(?:\'|$))/, null, '"\'']

say that this is a highlighting rule for a string and a string matches the regular expression above (a run of non-quotes or escape sequences inside double quotes or a run of non-single-quotes or escape sequences inside single quotes).

This rule

[PR['PR_LITERAL'],
 /^[+\-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],

matches number literals. A number literal is an optional sign followed by one of a hex literal, a dot followed by a fraction, or an integer part followed by a fraction, and the last two can have an optional exponent at the end.

The code prettify engine takes care of making sure that strings are treated as strings and things that look like numbers inside strings are not mistaken for numbers.


Maybe you would want to take a look at Alex Gorbachev's SyntaxHighlighter. Theres currently no module for Objective C but he provides a manual for developing "custom brushes".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜