aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/TEMP/Tango.Scripting/Tango.Scripting.Editors/Highlighting/Xshd/V1Loader.cs
blob: f3caa7eda958c3635a8d27c2f3818337faa5cc06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)

using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;
using System.Xml;
using System.Xml.Schema;

using Tango.Scripting.Editors.Utils;

namespace Tango.Scripting.Editors.Highlighting.Xshd
{
	/// <summary>
	/// Loads .xshd files, version 1.0.
	/// </summary>
	sealed class V1Loader
	{
		static XmlSchemaSet schemaSet;
		
		static XmlSchemaSet SchemaSet {
			get {
				if (schemaSet == null) {
					schemaSet = HighlightingLoader.LoadSchemaSet(new XmlTextReader(
						Resources.OpenStream("ModeV1.xsd")));
				}
				return schemaSet;
			}
		}
		
		public static XshdSyntaxDefinition LoadDefinition(XmlReader reader, bool skipValidation)
		{
			reader = HighlightingLoader.GetValidatingReader(reader, false, skipValidation ? null : SchemaSet);
			XmlDocument document = new XmlDocument();
			document.Load(reader);
			V1Loader loader = new V1Loader();
			return loader.ParseDefinition(document.DocumentElement);
		}
		
		XshdSyntaxDefinition ParseDefinition(XmlElement syntaxDefinition)
		{
			XshdSyntaxDefinition def = new XshdSyntaxDefinition();
			def.Name = syntaxDefinition.GetAttributeOrNull("name");
			if (syntaxDefinition.HasAttribute("extensions")) {
				def.Extensions.AddRange(syntaxDefinition.GetAttribute("extensions").Split(';', '|'));
			}
			
			XshdRuleSet mainRuleSetElement = null;
			foreach (XmlElement element in syntaxDefinition.GetElementsByTagName("RuleSet")) {
				XshdRuleSet ruleSet = ImportRuleSet(element);
				def.Elements.Add(ruleSet);
				if (ruleSet.Name == null)
					mainRuleSetElement = ruleSet;
				
				if (syntaxDefinition["Digits"] != null) {
					// create digit highlighting rule
					
					const string optionalExponent = @"([eE][+-]?[0-9]+)?";
					const string floatingPoint = @"\.[0-9]+";
					ruleSet.Elements.Add(
						new XshdRule {
							ColorReference = GetColorReference(syntaxDefinition["Digits"]),
							RegexType = XshdRegexType.IgnorePatternWhitespace,
							Regex = @"\b0[xX][0-9a-fA-F]+"
								+ @"|"
								+ @"(\b\d+(" + floatingPoint + ")?"
								+ @"|" + floatingPoint + ")"
								+ optionalExponent
						});
				}
			}
			
			if (syntaxDefinition.HasAttribute("extends") && mainRuleSetElement != null) {
				// convert 'extends="HTML"' to '<Import ruleSet="HTML/" />' in main rule set.
				mainRuleSetElement.Elements.Add(
					new XshdImport { RuleSetReference = new XshdReference<XshdRuleSet>(
						syntaxDefinition.GetAttribute("extends"), string.Empty
					) });
			}
			return def;
		}
		
		static XshdColor GetColorFromElement(XmlElement element)
		{
			if (!element.HasAttribute("bold") && !element.HasAttribute("italic") && !element.HasAttribute("color") && !element.HasAttribute("bgcolor"))
				return null;
			XshdColor color = new XshdColor();
			if (element.HasAttribute("bold"))
				color.FontWeight = XmlConvert.ToBoolean(element.GetAttribute("bold")) ? FontWeights.Bold : FontWeights.Normal;
			if (element.HasAttribute("italic"))
				color.FontStyle = XmlConvert.ToBoolean(element.GetAttribute("italic")) ? FontStyles.Italic : FontStyles.Normal;
			if (element.HasAttribute("color"))
				color.Foreground = ParseColor(element.GetAttribute("color"));
			if (element.HasAttribute("bgcolor"))
				color.Background = ParseColor(element.GetAttribute("bgcolor"));
			return color;
		}
		
		static XshdReference<XshdColor> GetColorReference(XmlElement element)
		{
			XshdColor color = GetColorFromElement(element);
			if (color != null)
				return new XshdReference<XshdColor>(color);
			else
				return new XshdReference<XshdColor>();
		}
		
		static HighlightingBrush ParseColor(string c)
		{
			if (c.StartsWith("#", StringComparison.Ordinal)) {
				int a = 255;
				int offset = 0;
				if (c.Length > 7) {
					offset = 2;
					a = Int32.Parse(c.Substring(1,2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				}
				
				int r = Int32.Parse(c.Substring(1 + offset,2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				int g = Int32.Parse(c.Substring(3 + offset,2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				int b = Int32.Parse(c.Substring(5 + offset,2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				return new SimpleHighlightingBrush(Color.FromArgb((byte)a, (byte)r, (byte)g, (byte)b));
			} else if (c.StartsWith("SystemColors.", StringComparison.Ordinal)) {
				return V2Loader.GetSystemColorBrush(null, c);
			} else {
				return new SimpleHighlightingBrush((Color)V2Loader.ColorConverter.ConvertFromInvariantString(c));
			}
		}
		
		char ruleSetEscapeCharacter;
		
		XshdRuleSet ImportRuleSet(XmlElement element)
		{
			XshdRuleSet ruleSet = new XshdRuleSet();
			ruleSet.Name = element.GetAttributeOrNull("name");
			
			if (element.HasAttribute("escapecharacter")) {
				ruleSetEscapeCharacter = element.GetAttribute("escapecharacter")[0];
			} else {
				ruleSetEscapeCharacter = '\0';
			}
			
			if (element.HasAttribute("reference")) {
				ruleSet.Elements.Add(
					new XshdImport { RuleSetReference = new XshdReference<XshdRuleSet>(
						element.GetAttribute("reference"), string.Empty
					) });
			}
			ruleSet.IgnoreCase = element.GetBoolAttribute("ignorecase");
			
			foreach (XmlElement el in element.GetElementsByTagName("KeyWords")) {
				XshdKeywords keywords = new XshdKeywords();
				keywords.ColorReference = GetColorReference(el);
				// we have to handle old syntax highlighting definitions that contain
				// empty keywords or empty keyword groups
				foreach (XmlElement node in el.GetElementsByTagName("Key")) {
					string word = node.GetAttribute("word");
					if (!string.IsNullOrEmpty(word))
						keywords.Words.Add(word);
				}
				if (keywords.Words.Count > 0) {
					ruleSet.Elements.Add(keywords);
				}
			}
			
			foreach (XmlElement el in element.GetElementsByTagName("Span")) {
				ruleSet.Elements.Add(ImportSpan(el));
			}
			
			foreach (XmlElement el in element.GetElementsByTagName("MarkPrevious")) {
				ruleSet.Elements.Add(ImportMarkPrevNext(el, false));
			}
			foreach (XmlElement el in element.GetElementsByTagName("MarkFollowing")) {
				ruleSet.Elements.Add(ImportMarkPrevNext(el, true));
			}
			
			return ruleSet;
		}
		
		static XshdRule ImportMarkPrevNext(XmlElement el, bool markFollowing)
		{
			bool markMarker = el.GetBoolAttribute("markmarker") ?? false;
			string what = Regex.Escape(el.InnerText);
			const string identifier = @"[\d\w_]+";
			const string whitespace = @"\s*";
			
			string regex;
			if (markFollowing) {
				if (markMarker) {
					regex = what + whitespace + identifier;
				} else {
					regex = "(?<=(" + what + whitespace + "))" + identifier;
				}
			} else {
				if (markMarker) {
					regex = identifier + whitespace + what;
				} else {
					regex = identifier + "(?=(" + whitespace + what + "))";
				}
			}
			return new XshdRule {
				ColorReference = GetColorReference(el),
				Regex = regex,
				RegexType = XshdRegexType.IgnorePatternWhitespace
			};
		}
		
		XshdSpan ImportSpan(XmlElement element)
		{
			XshdSpan span = new XshdSpan();
			if (element.HasAttribute("rule")) {
				span.RuleSetReference = new XshdReference<XshdRuleSet>(null, element.GetAttribute("rule"));
			}
			char escapeCharacter = ruleSetEscapeCharacter;
			if (element.HasAttribute("escapecharacter")) {
				escapeCharacter = element.GetAttribute("escapecharacter")[0];
			}
			span.Multiline = !(element.GetBoolAttribute("stopateol") ?? false);
			
			span.SpanColorReference = GetColorReference(element);
			
			span.BeginRegexType = XshdRegexType.IgnorePatternWhitespace;
			span.BeginRegex = ImportRegex(element["Begin"].InnerText,
			                              element["Begin"].GetBoolAttribute("singleword") ?? false,
			                              element["Begin"].GetBoolAttribute("startofline"));
			span.BeginColorReference = GetColorReference(element["Begin"]);
			
			string endElementText = string.Empty;
			if (element["End"] != null) {
				span.EndRegexType = XshdRegexType.IgnorePatternWhitespace;
				endElementText = element["End"].InnerText;
				span.EndRegex = ImportRegex(endElementText,
				                            element["End"].GetBoolAttribute("singleword") ?? false,
				                            null);
				span.EndColorReference = GetColorReference(element["End"]);
			}
			
			if (escapeCharacter != '\0') {
				XshdRuleSet ruleSet = new XshdRuleSet();
				if (endElementText.Length == 1 && endElementText[0] == escapeCharacter) {
					// ""-style escape
					ruleSet.Elements.Add(new XshdSpan {
					                     	BeginRegex = Regex.Escape(endElementText + endElementText),
					                     	EndRegex = ""
					                     });
				} else {
					// \"-style escape
					ruleSet.Elements.Add(new XshdSpan {
					                     	BeginRegex = Regex.Escape(escapeCharacter.ToString()),
					                     	EndRegex = "."
					                     });
				}
				if (span.RuleSetReference.ReferencedElement != null) {
					ruleSet.Elements.Add(new XshdImport { RuleSetReference = span.RuleSetReference });
				}
				span.RuleSetReference = new XshdReference<XshdRuleSet>(ruleSet);
			}
			return span;
		}
		
		static string ImportRegex(string expr, bool singleWord, bool? startOfLine)
		{
			StringBuilder b = new StringBuilder();
			if (startOfLine != null) {
				if (startOfLine.Value) {
					b.Append(@"(?<=(^\s*))");
				} else {
					b.Append(@"(?<!(^\s*))");
				}
			} else {
				if (singleWord)
					b.Append(@"\b");
			}
			for (int i = 0; i < expr.Length; i++) {
				char c = expr[i];
				if (c == '@') {
					++i;
					if (i == expr.Length)
						throw new HighlightingDefinitionInvalidException("Unexpected end of @ sequence, use @@ to look for a single @.");
					switch (expr[i]) {
						case 'C': // match whitespace or punctuation
							b.Append(@"[^\w\d_]");
							break;
						case '!': // negative lookahead
							{
								StringBuilder whatmatch = new StringBuilder();
								++i;
								while (i < expr.Length && expr[i] != '@') {
									whatmatch.Append(expr[i++]);
								}
								b.Append("(?!(");
								b.Append(Regex.Escape(whatmatch.ToString()));
								b.Append("))");
							}
							break;
						case '-': // negative lookbehind
							{
								StringBuilder whatmatch = new StringBuilder();
								++i;
								while (i < expr.Length && expr[i] != '@') {
									whatmatch.Append(expr[i++]);
								}
								b.Append("(?<!(");
								b.Append(Regex.Escape(whatmatch.ToString()));
								b.Append("))");
							}
							break;
						case '@':
							b.Append("@");
							break;
						default:
							throw new HighlightingDefinitionInvalidException("Unknown character in @ sequence.");
					}
				} else {
					b.Append(Regex.Escape(c.ToString()));
				}
			}
			if (singleWord)
				b.Append(@"\b");
			return b.ToString();
		}
	}
}