Skip to main content
gamedev.net
🔒 Locked

Syntax highlighting algorithm

Started by BeanDog Dec 6, 2005 at 9:15 AM 0 replies 700+ views
Original Post
BeanDog
BeanDog
I'm writing a syntax-highlighted textbox from scratch. It works well now, and I'm writing the highlighting providers right now. The text highlighting function is defined like this (C#):

public class RenderSegment
{
	public String Text;
	public Brush Brush;
}
public RenderSegment [] ProcessLine(String [] Lines, int idx);
I'm writing a provider that reads an XML file defining keywords and their colors. I've got it working, basically, but it's a pretty crappy algorithm. It goes something like this:

String CurrentSegment = ""
for each character in this line
	CurrentSegment += this character

	//Check if this is the last alphanumeric token in
	//a token.
	if(last char in string OR this char is alphanumeric and the next is not)

		//See if this current segment ends with a keyword.
		//This function is itself O(n) on the # of keywords.
		Keyword k = EndsWithKeyword(CurrentSegment);
		if(k != null)
			if(k.Content == CurrentSegment)
				AddSegment(k.Content, k.Color)
			else
				AddSegment(CurrentSegment.Substring(0,
					CurrentSegment.Length-k.Content.Length,
					Black)
				AddSegment(k.Content, k.Color)
			end if
			CurrentSegment = ""
		end if
	end if
next character

if CurrentSegment != ""
	AddSegment(CurrentSegment, Black)
end if

Anyone have a better idea for how to split up a string into segments of highlighted and non-highlighted text, based on keyword tokens? ~BenDilts( void );
nmi
nmi
Use regular expressions or a scanner/parser. Since programming languages analyze the input with a scanner to generate tokens, then pass these tokens to a parser to generate syntax trees, you can search for a scanner for your language (C#). Depending on the token type you can highlight that token.

http://www.antlr.org/grammar/list

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.