Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ValaTextEditorExtension.cs « Gui « ValaBinding « extras - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 058c043e934fb4eb7018d06a288bc733143db245 (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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//
// ValaTextEditorExtension.cs
//
// Authors:
//  Levi Bard <taktaktaktaktaktaktaktaktaktak@gmail.com> 
//
// Copyright (C) 2008 Levi Bard
// Based on CBinding by Marcos David Marin Amador <MarcosMarin@gmail.com>
//
// This source code is licenced under The MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//


using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Threading;

using MonoDevelop.Ide;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Ide.Gui.Content;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Projects.Dom;
using MonoDevelop.Projects.Dom.Output;

using MonoDevelop.Core;
using MonoDevelop.Components;

using Gtk;

using MonoDevelop.ValaBinding.Parser;

namespace MonoDevelop.ValaBinding
{
	public class ValaTextEditorExtension : CompletionTextEditorExtension, IPathedDocument
	{
		// Allowed chars to be next to an identifier
		private static char[] allowedChars = new char[] { ' ', '\t', '\r', '\n', 
			':', '=', '*', '+', '-', '/', '%', ',', '&',
			'|', '^', '{', '}', '[', ']', '(', ')', '\n', '!', '?', '<', '>'
		};
		
		private static char[] operators = new char[] {
			'=', '+', '-', ',', '&', '|',
			'^', '[', '!', '?', '<', '>', ':'
		};
		
		private ProjectInformation Parser {
			get {
				ValaProject project = Document.Project as ValaProject;
				return (null == project)? null: ProjectInformationManager.Instance.Get (project);
			}
		}// Parser
		
		protected Mono.TextEditor.TextEditorData textEditorData{ get; set; }
		
		public override bool KeyPress (Gdk.Key key, char keyChar, Gdk.ModifierType modifier)
		{
			string lineText = Editor.GetLineText (Editor.Caret.Line);
			
			// smart formatting strategy
			if (TextEditorProperties.IndentStyle == IndentStyle.Smart) {
				if (key == Gdk.Key.Return) {
					if (lineText.TrimEnd ().EndsWith ("{")) {
						Editor.InsertAtCaret ("\n" + TextEditorProperties.IndentString + Editor.Document.GetLineIndent (Editor.Caret.Line));
						return false;
					}
				} else if (key == Gdk.Key.braceright && AllWhiteSpace (lineText) 
				    && lineText.StartsWith (TextEditorProperties.IndentString)) {
					if (lineText.Length > 0)
						lineText = lineText.Substring (TextEditorProperties.IndentString.Length);
					var lineSegment = Editor.Document.GetLine (Editor.Caret.Line);
					Editor.Replace (lineSegment.Offset, lineSegment.EditableLength, lineText + "}");
					return false;
				}
			}
			
			return base.KeyPress (key, keyChar, modifier);
		}
		
		/// <summary>
		/// Expression to match instance construction/initialization
		/// </summary>
		private static Regex initializationRegex = new Regex (@"(((?<typename>\w[\w\d\.<>]*)\s+)?(?<variable>\w[\w\d]*)\s*=\s*)?new\s*(?<constructor>\w[\w\d\.<>]*)?", RegexOptions.Compiled);
		
		public override ICompletionDataList HandleCodeCompletion (
		    CodeCompletionContext completionContext, char completionChar)
		{
			string lineText = null;
			ProjectInformation parser = Parser;
			var loc = Editor.Document.OffsetToLocation (completionContext.TriggerOffset);
			int line = loc.Line, column = loc.Column;
			switch (completionChar) {
			case '.': // foo.[complete]
				lineText = Editor.GetLineText (line);
				if (column > lineText.Length){ column = lineText.Length; }
				lineText = lineText.Substring (0, column - 1);
				
				string itemName = GetTrailingSymbol (lineText);
				
				if (string.IsNullOrEmpty (itemName))
					return null;
				
				return GetMembersOfItem (itemName, line, column);
			case '\t':
			case ' ':
				lineText = Editor.GetLineText (line);
				if (0 == lineText.Length){ return null; }
				if (column > lineText.Length){ column = lineText.Length; }
				lineText = lineText.Substring (0, column-1).Trim ();
				
				if (lineText.EndsWith ("new")) {
					return CompleteConstructor (lineText, line, column);
				} else if (lineText.EndsWith ("is")) {
					ValaCompletionDataList list = new ValaCompletionDataList ();
					ThreadPool.QueueUserWorkItem (delegate {
						parser.GetTypesVisibleFrom (Document.FileName, line, column, list);
					});
					return list;
				} else if (0 < lineText.Length) {
					char lastNonWS = lineText[lineText.Length-1];
					if (0 <= Array.IndexOf (operators, lastNonWS) || 
				          (1 == lineText.Length && 0 > Array.IndexOf (allowedChars, lastNonWS))) { 
						return GlobalComplete (completionContext); 
					}
				}
				
				break;
			default:
				if (0 <= Array.IndexOf (operators, completionChar)) {
					return GlobalComplete (completionContext);
				}
				break;
			}
			
			return null;
		}
		
		static string GetTrailingSymbol (string text)
		{
				// remove the trailing '.'
				if (text.EndsWith (".", StringComparison.Ordinal))
					text = text.Substring (0, text.Length-1);
				
				int nameStart = text.LastIndexOfAny (allowedChars);
				return text.Substring (nameStart+1).Trim ();
		}
		
		/// <summary>
		/// Perform constructor-specific completion
		/// </summary>
		private ValaCompletionDataList CompleteConstructor (string lineText, int line, int column)
		{
			ProjectInformation parser = Parser;
			Match match = initializationRegex.Match (lineText);
			ValaCompletionDataList list = new ValaCompletionDataList ();
			
			ThreadPool.QueueUserWorkItem (delegate {
				if (match.Success) {
					// variable initialization
					if (match.Groups["typename"].Success || "var" != match.Groups["typename"].Value) {
						// simultaneous declaration and initialization
						parser.GetConstructorsForType (match.Groups["typename"].Value, Document.FileName, line, column, list);
					} else if (match.Groups["variable"].Success) {
						// initialization of previously declared variable
						parser.GetConstructorsForExpression (match.Groups["variable"].Value, Document.FileName, line, column, list);
					}
					if (0 == list.Count) { 
						// Fallback to known types
						parser.GetTypesVisibleFrom (Document.FileName, line, column, list);
					}
				}
			});
			
			return list;
		}// CompleteConstructor
		
		public override ICompletionDataList CodeCompletionCommand (
		    CodeCompletionContext completionContext)
		{
			if (null == (Document.Project as ValaProject)){ return null; }
			
			int pos = completionContext.TriggerOffset;
			
			ICompletionDataList list = HandleCodeCompletion(completionContext, Editor.GetTextBetween (pos - 1, pos)[0]);
			if (null == list) {
				list = GlobalComplete (completionContext);
			}
			return list;
		}
		
		/// <summary>
		/// Get the members of a symbol
		/// </summary>
		private ValaCompletionDataList GetMembersOfItem (string itemFullName, int line, int column)
		{
			ProjectInformation info = Parser;
			if (null == info){ return null; }
			
			ValaCompletionDataList list = new ValaCompletionDataList ();
			ThreadPool.QueueUserWorkItem (delegate {
				info.Complete (itemFullName, Document.FileName, line, column, list);
			});
			return list;
		}
		
		/// <summary>
		/// Complete all symbols visible from a given location
		/// </summary>
		private ValaCompletionDataList GlobalComplete (CodeCompletionContext context)
		{
			ProjectInformation info = Parser;
			if (null == info){ return null; }
			
			ValaCompletionDataList list = new ValaCompletionDataList ();
			var loc = Editor.Document.OffsetToLocation (context.TriggerOffset);
			ThreadPool.QueueUserWorkItem (delegate {
				info.GetSymbolsVisibleFrom (Document.FileName, loc.Line + 1, loc.Column + 1, list);
			});
			return list;
		}
		
		public override  IParameterDataProvider HandleParameterCompletion (
		    CodeCompletionContext completionContext, char completionChar)
		{
			if (completionChar != '(')
				return null;
			
			ProjectInformation info = Parser;
			if (null == info){ return null; }
			
			int position = Editor.Document.GetLine (Editor.Caret.Line).Offset;
			string lineText = Editor.GetTextBetween (position, Editor.Caret.Offset - 1).TrimEnd ();
			string functionName = string.Empty;
			
			Match match = initializationRegex.Match (lineText);
			if (match.Success && match.Groups["constructor"].Success) {
				string[] tokens = match.Groups["constructor"].Value.Split('.');
				string overload = tokens[tokens.Length-1];
				string typename = (match.Groups["typename"].Success? match.Groups["typename"].Value: null);
				int index = 0;
				
				if (1 == tokens.Length || null == typename) {
					// Ideally if typename is null and token length is longer than 1, 
					// we have an expression like: var w = new x.y.z(); and 
					// we would check whether z is the type or if y.z is an overload for type y
					typename = overload;
				} else if ("var".Equals (typename, StringComparison.Ordinal)) {
					typename = match.Groups["constructor"].Value;
				} else {
					// Foo.Bar bar = new Foo.Bar.blah( ...
					for (string[] typeTokens = typename.Split ('.'); index < typeTokens.Length && index < tokens.Length; ++index) {
						if (!typeTokens[index].Equals (tokens[index], StringComparison.Ordinal)) {
							break;
						}
					}
					List<string> overloadTokens = new List<string> ();
					for (int i=index; i<tokens.Length; ++i) {
						overloadTokens.Add (tokens[i]);
					}
					overload = string.Join (".", overloadTokens.ToArray ());
				} 
				
				// HACK: Generics
				if (0 < (index = overload.IndexOf ("<", StringComparison.Ordinal))) {
					overload = overload.Substring (0, index);
				}
				if (0 < (index = typename.IndexOf ("<", StringComparison.Ordinal))) {
					typename = typename.Substring (0, index);
				}
				
				// Console.WriteLine ("Constructor: type {0}, overload {1}", typename, overload);
				return new ParameterDataProvider (Document, info, typename, overload); 
			} 
			
			int nameStart = lineText.LastIndexOfAny (allowedChars) + 1;
			functionName = lineText.Substring (nameStart).Trim ();
			return (string.IsNullOrEmpty (functionName)? null: new ParameterDataProvider (Document, info, functionName));
		}
		
		private bool AllWhiteSpace (string lineText)
		{
			foreach (char c in lineText)
				if (!char.IsWhiteSpace (c))
					return false;
			
			return true;
		}
		
		#region IPathedDocument implementation
		public event EventHandler<DocumentPathChangedEventArgs> PathChanged;

		public Gtk.Widget CreatePathWidget (int index)
		{
			PathEntry[] path = CurrentPath;
			if (null == path || 0 > index || path.Length <= index) {
				return null;
			}
			
			object tag = path[index].Tag;
			DropDownBoxListWindow.IListDataProvider provider = null;
			if (tag is ICompilationUnit) {
				provider = new CompilationUnitDataProvider (Document);
			} else {
				provider = new DataProvider (Document, tag, GetAmbience ());
			}
			
			DropDownBoxListWindow window = new DropDownBoxListWindow (provider);
			window.SelectItem (tag);
			return window;
		}

		public PathEntry[] CurrentPath {
			get;
			private set;
		}
		
		protected virtual void OnPathChanged (DocumentPathChangedEventArgs args)
		{
			if (null != PathChanged) {
				PathChanged (this, args);
			}
		}
		#endregion
		
		// Yoinked from C# binding
		void UpdatePath (object sender, Mono.TextEditor.DocumentLocationEventArgs e)
		{
			var unit = Document.CompilationUnit;
			if (unit == null)
				return;
				
			var loc = textEditorData.Caret.Location;
			IType type = unit.GetTypeAt (loc.Line, loc.Column);
			List<PathEntry> result = new List<PathEntry> ();
			Ambience amb = GetAmbience ();
			IMember member = null;
			INode node = (INode)unit;
			
			if (type != null && type.ClassType != ClassType.Delegate) {
				member = type.GetMemberAt (loc.Line, loc.Column);
			}
			
			if (null != member) {
				node = member;
			} else if (null != type) {
				node = type;
			}
			
			while (node != null) {
				PathEntry entry;
				if (node is ICompilationUnit) {
					if (!Document.ParsedDocument.UserRegions.Any ())
						break;
					FoldingRegion reg = Document.ParsedDocument.UserRegions.Where (r => r.Region.Contains (loc.Line, loc.Column)).LastOrDefault ();
					if (reg == null) {
						entry = new PathEntry (GettextCatalog.GetString ("No region"));
					} else {
						entry = new PathEntry (CompilationUnitDataProvider.Pixbuf, reg.Name);
					}
					entry.Position = EntryPosition.Right;
				} else {
					entry = new PathEntry (ImageService.GetPixbuf (((IMember)node).StockIcon, IconSize.Menu), amb.GetString ((IMember)node, OutputFlags.IncludeGenerics | OutputFlags.IncludeParameters | OutputFlags.ReformatDelegates));
				}
				entry.Tag = node;
				result.Insert (0, entry);
				node = node.Parent;
			}
			
			PathEntry noSelection = null;
			if (type == null) {
				noSelection = new PathEntry (GettextCatalog.GetString ("No selection")) { Tag = new CustomNode (Document.CompilationUnit) };
			} else if (member == null && type.ClassType != ClassType.Delegate) 
				noSelection = new PathEntry (GettextCatalog.GetString ("No selection")) { Tag = new CustomNode (type) };
			if (noSelection != null) {
				result.Add (noSelection);
			}
			
			var prev = CurrentPath;
			CurrentPath = result.ToArray ();
			OnPathChanged (new DocumentPathChangedEventArgs (prev));
		}
		
		public override void Initialize ()
		{
			base.Initialize ();
			textEditorData = Document.Editor;
			UpdatePath (null, null);
			textEditorData.Caret.PositionChanged += UpdatePath;
			Document.DocumentParsed += delegate { UpdatePath (null, null); };
		}
		
		// Yoinked from C# binding
		class CustomNode : MonoDevelop.Projects.Dom.AbstractNode
		{
			public CustomNode (INode parent)
			{
				this.Parent = parent;
			}
		}
	}
}