|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RegexTester.UserControls
{
public class SyntaxHighlightRichTextBoxModel
{
private Dictionary<char, char> matchingEndParentheses =
new Dictionary<char, char>{
{'(', ')'},
{'[', ']'},
{'{', '}'}
};
private Dictionary<char, char> matchingStartParentheses =
new Dictionary<char, char> {
{')', '('},
{']', '['},
{'}', '{'}
};
private IDictionary<int, int> GetMatchingParentheses(string value)
{
IDictionary<int, int> result = new Dictionary<int, int>();
Stack<KeyValuePair<char, int>> stack = new Stack<KeyValuePair<char, int>>();
int escapeCount = 0;
char[] chars = value.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if (escapeCount % 2 == 0)
{
if (matchingEndParentheses.ContainsKey(chars[i]))
{
stack.Push(new KeyValuePair<char, int>(chars[i], i));
}
else if (matchingStartParentheses.ContainsKey(chars[i]))
{
if (stack.Count > 0 && matchingEndParentheses[stack.Peek().Key] == chars[i])
{
result.Add(stack.Pop().Value, i);
}
else
{
return result;
}
}
}
escapeCount = chars[i] == '\\' ? escapeCount + 1 : 0;
}
return result;
}
public int GetMatchingParentheses(string value, int index)
{
char[] chars = value.ToCharArray();
IDictionary<int, int> result = GetMatchingParentheses(value);
foreach (KeyValuePair<int, int> pair in result)
{
if (pair.Value == index - 1)
{
return pair.Key;
}
if (pair.Key == index)
{
return pair.Value;
}
}
return -1;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
.NET developer. I wanted to be first an astronaut, then a jet pilot, but when I got a Commodore 64 for Christmas I never looked back. Also I would never have qualified for the first two things and everybody knows computer programmers get all the girls.