0
votes

I make a syntax highlighter and I need to replace all occurrences of special words with this word in tags. For example i had:

@"int main{ bla bla; float=0; bla bla;"

and want to get

@"<\FONT COLOR=FF00FF>int<\FONT> main{ bla bla; <\FONT COLOR=FF00FF>float<\FONT>=0;" etc.

(had to put \ before FONT). I have specialwords array, have this text in html (floated with it, i got it from UITextView contentAsHTMLString ) and want just to put color tags. How to?

Tried stringByReplacingOccurrencesOfString but

pr<\FONT COLOR=FF00FF>int<\FONT>f()

is not what i want.

Trying regexkitlite. [editString replaceOccurrencesOfRegex:[NSString stringWithFormat:@"[^a-zA-z]%@[^a-zA-z]",specialString] withString:[NSString stringWithFormat:@"$0%@$1",specialString] range:NSMakeRange(0, [editString length])];

creates exception (index out of bounds... O_O wtf?) and if i remove $0 and $1 from "withString" it will not replace "int" but " int " (whatever was near the int word too).

1
If you really want a syntax highlighter for arbitrary code-samples (do you only cover C btw?) neither simple replace nor regex will get you there - think e.g. s=" int ";, escaped linebreaks, typedefs, ... I'd either search for existing highlighters or use an existing parser (e.g. the API of clang).Georg Fritzsche

1 Answers

0
votes

First apply color to the "int" occurrences:

NSString *initialString = @"int main{ bla bla; float=0; bla bla;";    
NSString *stringWithColorInt = [initialString stringByReplacingOccurrencesOfString:@"int" withString:@"<FONT COLOR=FF00FF>int<\FONT>" options:NSLiteralSearch range:NSRange(0,[initialString length])];

Then to the "float" occurrences:

NSString *stringWithColorFloat = [stringWithColorInt stringByReplacingOccurrencesOfString:@"float" withString:@"<FONT COLOR=FF00FF>float<\FONT>" options:NSLiteralSearch range:NSRange(0,[stringWithColorInt length])];