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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
|
//
// BaseXmlEditorExtension.cs
//
// Author:
// Michael Hutchinson <mhutchinson@novell.com>
//
// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
//
// 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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Gtk;
using MonoDevelop.Components;
using MonoDevelop.Core;
using MonoDevelop.DesignerSupport;
using MonoDevelop.Ide;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Ide.Gui.Content;
using MonoDevelop.Ide.TypeSystem;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Ide.Editor.Extension;
using MonoDevelop.Projects;
using MonoDevelop.Xml.Completion;
using MonoDevelop.Xml.Dom;
using MonoDevelop.Xml.Parser;
using System.Threading.Tasks;
using System.Threading;
using MonoDevelop.Components.Commands;
using MonoDevelop.Ide.Commands;
namespace MonoDevelop.Xml.Editor
{
public abstract class BaseXmlEditorExtension : CompletionTextEditorExtension, IPathedDocument, IOutlinedDocument
{
DocumentStateTracker<XmlParser> tracker;
ParsedDocument lastCU;
XDocType docType;
MonoDevelop.Ide.Gui.Components.PadTreeView outlineTreeView;
TreeStore outlineTreeStore;
List<DotNetProject> ownerProjects = new List<DotNetProject> ();
#region Setup and teardown
public override bool IsValidInContext (DocumentContext context)
{
//can only attach if there is not already an attached BaseXmlEditorExtension
return context.GetContent<BaseXmlEditorExtension> () == null;
}
protected virtual XmlRootState CreateRootState ()
{
return new XmlRootState ();
}
protected override void Initialize ()
{
base.Initialize ();
// Delay the execution of UpdateOwnerProjects since it may end calling Document.AttachToProject,
// which shouldn't be called while the extension chain is being initialized.
// TODO: Move handling of owner projects to Document
Application.Invoke (delegate {
UpdateOwnerProjects ();
});
var parser = new XmlParser (CreateRootState (), false);
tracker = new DocumentStateTracker<XmlParser> (parser, Editor);
DocumentContext.DocumentParsed += UpdateParsedDocument;
Editor.CaretPositionChanged += HandleCaretPositionChanged;
if (DocumentContext.ParsedDocument != null) {
lastCU = DocumentContext.ParsedDocument;
OnParsedDocumentUpdated ();
}
if (IdeApp.Workspace != null) {
IdeApp.Workspace.FileAddedToProject += HandleProjectChanged;
IdeApp.Workspace.FileRemovedFromProject += HandleProjectChanged;
}
}
void HandleProjectChanged (object sender, ProjectFileEventArgs e)
{
if (e.Any (f => f.ProjectFile.FilePath == DocumentContext.Name))
UpdateOwnerProjects ();
}
void UpdateOwnerProjects ()
{
if (IdeApp.Workspace == null) {
ownerProjects = new List<DotNetProject> ();
return;
}
if (DocumentContext == null) {
return;//This can happen if this object is disposed
}
var projects = new HashSet<DotNetProject> (IdeApp.Workspace.GetAllItems<DotNetProject> ().Where (p => p.IsFileInProject (DocumentContext.Name)));
if (ownerProjects == null || !projects.SetEquals (ownerProjects)) {
ownerProjects = projects.OrderBy (p => p.Name).ToList ();
var dnp = DocumentContext.Project as DotNetProject;
if (ownerProjects.Count > 0 && (dnp == null || !ownerProjects.Contains (dnp))) {
// If the project for the document is not a DotNetProject but there is a project containing this file
// in the current solution, then use that project
var pp = DocumentContext.Project != null ? ownerProjects.FirstOrDefault (p => p.ParentSolution == DocumentContext.Project.ParentSolution) : null;
if (pp != null)
DocumentContext.AttachToProject (pp);
}
}
if (DocumentContext.Project == null && ownerProjects.Count > 0)
DocumentContext.AttachToProject (ownerProjects[0]);
UpdatePath ();
}
void UpdateParsedDocument (object sender, EventArgs args)
{
lastCU = DocumentContext.ParsedDocument;
OnParsedDocumentUpdated ();
}
public override void Dispose ()
{
Editor.CaretPositionChanged -= HandleCaretPositionChanged;
if (tracker != null) {
tracker.Dispose ();
tracker = null;
}
DocumentContext.DocumentParsed -= UpdateParsedDocument;
if (IdeApp.Workspace != null) {
IdeApp.Workspace.FileAddedToProject -= HandleProjectChanged;
IdeApp.Workspace.FileRemovedFromProject -= HandleProjectChanged;
}
base.Dispose ();
}
protected virtual void OnParsedDocumentUpdated ()
{
RefreshOutline ();
//use the doctype to select a completion schema
var doc = CU as XmlParsedDocument;
bool found = false;
if (doc != null && doc.XDocument != null) {
foreach (XNode node in doc.XDocument.Nodes) {
if (node is XDocType) {
DocType = (XDocType)node;
found = true;
break;
}
//cannot validly have a doctype after these nodes
if (node is XElement || node is XCData)
break;
}
if (!found)
DocType = null;
}
}
#endregion
#region Convenience accessors
protected ParsedDocument CU {
get { return lastCU; }
}
protected DocumentStateTracker<XmlParser> Tracker {
get { return tracker; }
}
protected string GetBufferText (DocumentRegion region)
{
int start = Editor.LocationToOffset (region.BeginLine, region.BeginColumn);
int end = Editor.LocationToOffset (region.EndLine, region.EndColumn);
if (end > start && start >= 0)
return Editor.GetTextBetween (start, end);
return null;
}
#endregion
public override string CompletionLanguage {
get { return "Xml"; }
}
protected FilePath FileName {
get {
return Editor.FileName;
}
}
protected XDocType DocType {
get { return docType; }
set {
if (docType == value)
return;
docType = value;
OnDocTypeChanged ();
}
}
protected virtual void OnDocTypeChanged ()
{
}
public override bool KeyPress (KeyDescriptor descriptor)
{
if (Editor.Options.IndentStyle == IndentStyle.Smart) {
var newLine = Editor.CaretLine + 1;
var ret = base.KeyPress (descriptor);
if (descriptor.SpecialKey == SpecialKey.Return && Editor.CaretLine == newLine) {
string indent = GetLineIndent (newLine);
var oldIndent = Editor.GetLineIndent (newLine);
var seg = Editor.GetLine (newLine);
if (oldIndent != indent) {
using (var undo = Editor.OpenUndoGroup ()) {
Editor.ReplaceText (seg.Offset, oldIndent.Length, indent);
}
}
}
return ret;
}
return base.KeyPress (descriptor);
}
#region Code completion
public override Task<ICompletionDataList> CodeCompletionCommand (CodeCompletionContext completionContext)
{
int pos = completionContext.TriggerOffset;
if (pos <= 0)
return null;
tracker.UpdateEngine ();
return HandleCodeCompletion (completionContext, true, default(CancellationToken));
}
public override Task<ICompletionDataList> HandleCodeCompletionAsync (CodeCompletionContext completionContext, char completionChar, CancellationToken token = default(CancellationToken))
{
int pos = completionContext.TriggerOffset;
char ch = CompletionWidget != null ? CompletionWidget.GetChar (pos - 1) : Editor.GetCharAt (pos - 1);
if (pos > 0 && ch == completionChar) {
tracker.UpdateEngine ();
return HandleCodeCompletion (completionContext, false, token);
}
return null;
}
protected virtual async Task<ICompletionDataList> HandleCodeCompletion (
CodeCompletionContext completionContext, bool forced, CancellationToken token)
{
var buf = this.Editor;
// completionChar may be a space even if the current char isn't, when ctrl-space is fired t
var currentLocation = new DocumentLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset);
char currentChar = completionContext.TriggerOffset < 1? ' ' : buf.GetCharAt (completionContext.TriggerOffset - 1);
char previousChar = completionContext.TriggerOffset < 2? ' ' : buf.GetCharAt (completionContext.TriggerOffset - 2);
LoggingService.LogDebug ("Attempting completion for state '{0}'x{1}, previousChar='{2}',"
+ " currentChar='{3}', forced='{4}'", tracker.Engine.CurrentState,
tracker.Engine.CurrentStateLength, previousChar, currentChar, forced);
//closing tag completion
if (tracker.Engine.CurrentState is XmlRootState && currentChar == '>')
return ClosingTagCompletion (buf, currentLocation);
// Auto insert '>' when '/' is typed inside tag state (for quick tag closing)
//FIXME: avoid doing this when the next non-whitespace char is ">" or ignore the next ">" typed
if (XmlEditorOptions.AutoInsertFragments && tracker.Engine.CurrentState is XmlTagState && currentChar == '/') {
buf.InsertAtCaret (">");
return null;
}
//entity completion
if (currentChar == '&' && (tracker.Engine.CurrentState is XmlRootState ||
tracker.Engine.CurrentState is XmlAttributeValueState))
{
var list = new CompletionDataList ();
//TODO: need to tweak semicolon insertion
list.Add ("apos").Description = "'";
list.Add ("quot").Description = "\"";
list.Add ("lt").Description = "<";
list.Add ("gt").Description = ">";
list.Add ("amp").Description = "&";
//not sure about these "completions". they're more like
//shortcuts than completions but they're pretty useful
list.Add ("'").CompletionText = "apos;";
list.Add ("\"").CompletionText = "quot;";
list.Add ("<").CompletionText = "lt;";
list.Add (">").CompletionText = "gt;";
list.Add ("&").CompletionText = "amp;";
var ecList = await GetEntityCompletions (token);
list.AddRange (ecList);
return list;
}
//doctype completion
if (tracker.Engine.CurrentState is XmlDocTypeState) {
if (tracker.Engine.CurrentStateLength == 1) {
CompletionDataList list = await GetDocTypeCompletions (token);
if (list != null && list.Count > 0)
return list;
}
return null;
}
//attribute value completion
//determine whether to trigger completion within attribute values quotes
if ((Tracker.Engine.CurrentState is XmlAttributeValueState)
//trigger on the opening quote
&& ((Tracker.Engine.CurrentStateLength == 1 && (currentChar == '\'' || currentChar == '"'))
//or trigger on first letter of value, if unforced
|| (forced || Tracker.Engine.CurrentStateLength == 2))) {
var att = (XAttribute)Tracker.Engine.Nodes.Peek ();
if (att.IsNamed) {
var attributedOb = Tracker.Engine.Nodes.Peek (1) as IAttributedXObject;
if (attributedOb == null)
return null;
//if triggered by first letter of value or forced, grab those letters
var result = await GetAttributeValueCompletions (attributedOb, att, token);
if (result != null) {
result.TriggerWordLength = Tracker.Engine.CurrentStateLength - 1;
return result;
}
return null;
}
}
//attribute name completion
if ((forced && Tracker.Engine.Nodes.Peek () is IAttributedXObject && !tracker.Engine.Nodes.Peek ().IsEnded)
|| ((Tracker.Engine.CurrentState is XmlNameState
&& Tracker.Engine.CurrentState.Parent is XmlAttributeState) ||
Tracker.Engine.CurrentState is XmlTagState)
&& (Tracker.Engine.CurrentStateLength == 1 || forced)) {
IAttributedXObject attributedOb = (Tracker.Engine.Nodes.Peek () as IAttributedXObject) ??
Tracker.Engine.Nodes.Peek (1) as IAttributedXObject;
if (attributedOb == null)
return null;
//attributes
if (attributedOb.Name.IsValid && (forced ||
(char.IsWhiteSpace (previousChar) && char.IsLetter (currentChar))))
{
var existingAtts = new Dictionary<string,string> (StringComparer.OrdinalIgnoreCase);
foreach (XAttribute att in attributedOb.Attributes) {
existingAtts [att.Name.FullName] = att.Value ?? string.Empty;
}
var result = await GetAttributeCompletions (attributedOb, existingAtts, token);
if (result != null) {
if (!forced)
result.TriggerWordLength = 1;
return result;
}
return null;
}
}
// if (Tracker.Engine.CurrentState is XmlRootState) {
// if (line < 3) {
// cp.Add ("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
// }
//element completion
if (currentChar == '<' && tracker.Engine.CurrentState is XmlRootState ||
(tracker.Engine.CurrentState is XmlNameState && forced)) {
var list = await GetElementCompletions (token);
AddCloseTag (list, Tracker.Engine.Nodes);
return list.Count > 0 ? list : null;
}
if (forced && Tracker.Engine.CurrentState is XmlRootState) {
var list = new CompletionDataList ();
MonoDevelop.Ide.CodeTemplates.CodeTemplateService.AddCompletionDataForFileName (DocumentContext.Name, list);
return list.Count > 0? list : null;
}
return null;
}
protected virtual ICompletionDataList ClosingTagCompletion (TextEditor buf, DocumentLocation currentLocation)
{
//get name of current node in document that's being ended
var el = tracker.Engine.Nodes.Peek () as XElement;
if (el != null && el.Region.End >= currentLocation && !el.IsClosed && el.IsNamed) {
string tag = String.Concat ("</", el.Name.FullName, ">");
if (XmlEditorOptions.AutoCompleteElements) {
// //make sure we have a clean atomic undo so the user can undo the tag insertion
// //independently of the >
// bool wasInAtomicUndo = this.Editor.Document.IsInAtomicUndo;
// if (wasInAtomicUndo)
// this.Editor.Document.EndAtomicUndo ();
using (var undo = buf.OpenUndoGroup ()) {
buf.InsertText (buf.CaretOffset, tag);
buf.CaretOffset -= tag.Length;
}
// if (wasInAtomicUndo)
// this.Editor.Document.BeginAtomicUndo ();
return null;
} else {
var cp = new CompletionDataList ();
cp.Add (new XmlTagCompletionData (tag, 0, true));
return cp;
}
}
return null;
}
protected virtual Task<CompletionDataList> GetElementCompletions (CancellationToken token)
{
return Task.FromResult (new CompletionDataList ());
}
protected virtual Task<CompletionDataList> GetAttributeCompletions (IAttributedXObject attributedOb,
Dictionary<string, string> existingAtts, CancellationToken token)
{
return Task.FromResult (new CompletionDataList ());
}
protected virtual Task<CompletionDataList> GetAttributeValueCompletions (IAttributedXObject attributedOb, XAttribute att, CancellationToken token)
{
return Task.FromResult (new CompletionDataList ());
}
protected virtual Task<CompletionDataList> GetEntityCompletions (CancellationToken token)
{
return Task.FromResult (new CompletionDataList ());
}
protected virtual Task<CompletionDataList> GetDocTypeCompletions (CancellationToken token)
{
return Task.FromResult (new CompletionDataList ());
}
protected string GetLineIndent (int line)
{
var seg = Editor.GetLine (line);
//reset the tracker to the beginning of the line
Tracker.UpdateEngine (seg.Offset);
//calculate the indentation
var startElementDepth = GetElementIndentDepth (Tracker.Engine.Nodes);
var attributeDepth = GetAttributeIndentDepth (Tracker.Engine.Nodes);
//update the tracker to the end of the line
Tracker.UpdateEngine (seg.Offset + seg.Length);
//if end depth is less than start depth, then reduce start depth
//because that means there are closing tags on the line, and they de-indent the line they're on
var endElementDepth = GetElementIndentDepth (Tracker.Engine.Nodes);
var elementDepth = Math.Min (endElementDepth, startElementDepth);
//FIXME: use policies
return new string ('\t', elementDepth + attributeDepth);
}
static int GetElementIndentDepth (NodeStack nodes)
{
return nodes.OfType<XElement> ().Count (el => !el.IsClosed);
}
static int GetAttributeIndentDepth (NodeStack nodes)
{
var node = nodes.Peek ();
if (node is XElement && !node.IsEnded)
return 1;
if (node is XAttribute)
return node.IsEnded? 1 : 2;
return 0;
}
protected IEnumerable<XName> GetParentElementNames (int skip)
{
foreach (XObject obj in tracker.Engine.Nodes) {
if (skip > 0) {
skip--;
continue;
}
var el = obj as XElement;
if (el == null || !el.IsNamed)
yield break;
yield return el.Name;
}
}
protected XName GetParentElementName (int skip)
{
foreach (XObject obj in tracker.Engine.Nodes) {
if (skip > 0) {
skip--;
continue;
}
var el = obj as XElement;
return el != null? el.Name : new XName ();
}
return new XName ();
}
protected XElement GetParentElement (int skip)
{
foreach (XObject obj in tracker.Engine.Nodes) {
if (skip > 0) {
skip--;
continue;
}
return obj as XElement;
}
return null;
}
protected static void AddCloseTag (CompletionDataList completionList, NodeStack stack)
{
//FIXME: search forward to see if tag's closed already
var elements = new List<XElement> ();
foreach (XObject ob in stack) {
var el = ob as XElement;
if (el == null)
continue;
if (!el.IsNamed || el.IsClosed)
return;
if (elements.Count == 0) {
string name = el.Name.FullName;
completionList.Add ("/" + name + ">", Gtk.Stock.GoBack,
GettextCatalog.GetString ("Closing tag for '{0}'", name));
} else {
foreach (XElement listEl in elements) {
if (listEl.Name == el.Name)
return;
}
completionList.Add (new XmlMultipleClosingTagCompletionData (el, elements.ToArray ()));
}
elements.Add (el);
}
}
/// <summary>
/// Adds CDATA and comment begin tags.
/// </summary>
protected static void AddMiscBeginTags (CompletionDataList list)
{
list.Add ("!--", "md-literal", GettextCatalog.GetString ("Comment"));
list.Add ("![CDATA[", "md-literal", GettextCatalog.GetString ("Character data"));
}
#endregion
#region IPathedDocument
PathEntry[] currentPath;
bool pathUpdateQueued;
void HandleCaretPositionChanged (object sender, EventArgs e)
{
if (pathUpdateQueued)
return;
pathUpdateQueued = true;
GLib.Timeout.Add (500, delegate {
pathUpdateQueued = false;
UpdatePath ();
return false;
});
}
public void SelectPath (int depth)
{
SelectPath (depth, false);
}
public void SelectPathContents (int depth)
{
SelectPath (depth, true);
}
void SelectPath (int depth, bool contents)
{
//clone the parser and put it in tree mode
XmlParser treeParser = tracker.Engine.GetTreeParser ();
//locate the node
var path = new List<XObject> (treeParser.Nodes);
//note: list is backwards, and we want ignore the root XDocument
XObject ob = path [path.Count - (depth + 2)];
var node = ob as XNode;
var el = node as XElement;
//hoist this as it may not be cheap to evaluate (P/Invoke), but won't be changing during the loop
int textLen = Editor.Length;
//run the parser until the tag's closed, or we move to its sibling or parent
if (node != null) {
while (node.NextSibling == null &&
treeParser.Position < textLen && treeParser.Nodes.Peek () != ob.Parent)
{
char c = Editor.GetCharAt (treeParser.Position);
treeParser.Push (c);
if (el != null && el.IsClosed && el.ClosingTag.IsComplete)
break;
}
} else {
while (ob.Region.End < ob.Region.Begin &&
treeParser.Position < textLen && treeParser.Nodes.Peek () != ob.Parent)
{
char c = Editor.GetCharAt (treeParser.Position);
treeParser.Push (c);
}
}
if (el == null) {
LoggingService.LogDebug ("Selecting {0}", ob.Region);
EditorSelect (ob.Region);
}
else if (el.IsClosed) {
LoggingService.LogDebug ("Selecting {0}-{1}",
el.Region.Begin, el.ClosingTag.Region.End);
contents &= !el.IsSelfClosing;
//pick out the locations, with some offsets to account for the parsing model
var s = contents? el.Region.End : el.Region.Begin;
var e = contents? el.ClosingTag.Region.Begin : el.ClosingTag.Region.End;
EditorSelect (new DocumentRegion (s, e));
} else {
LoggingService.LogDebug ("No end tag found for selection");
}
}
protected void EditorSelect (DocumentRegion region)
{
int s = Editor.LocationToOffset (region.BeginLine, region.BeginColumn);
int e = Editor.LocationToOffset (region.EndLine, region.EndColumn);
if (s > -1 && e > s) {
Editor.SetSelection (s, e);
Editor.ScrollTo (s);
}
}
public event EventHandler<DocumentPathChangedEventArgs> PathChanged;
public Control CreatePathWidget (int index)
{
if (ownerProjects.Count > 1 && index == 0) {
var window = new DropDownBoxListWindow (new DataProvider (this));
window.FixedRowHeight = 22;
window.MaxVisibleRows = 14;
window.SelectItem (currentPath [index].Tag);
return window;
} else {
if (ownerProjects.Count > 1)
index--;
var menu = new Menu ();
var mi = new MenuItem (GettextCatalog.GetString ("Select"));
mi.Activated += delegate {
SelectPath (index);
};
menu.Add (mi);
mi = new MenuItem (GettextCatalog.GetString ("Select contents"));
mi.Activated += delegate {
SelectPathContents (index);
};
menu.Add (mi);
menu.ShowAll ();
return menu;
}
}
class DataProvider : DropDownBoxListWindow.IListDataProvider
{
readonly BaseXmlEditorExtension ext;
public DataProvider (BaseXmlEditorExtension ext)
{
if (ext == null)
throw new ArgumentNullException ("ext");
this.ext = ext;
}
#region IListDataProvider implementation
public void Reset ()
{
}
public string GetMarkup (int n)
{
return GLib.Markup.EscapeText (ext.ownerProjects [n].Name);
}
public Xwt.Drawing.Image GetIcon (int n)
{
return ImageService.GetIcon (ext.ownerProjects [n].StockIcon, IconSize.Menu);
}
public object GetTag (int n)
{
return ext.ownerProjects [n];
}
public void ActivateItem (int n)
{
ext.DocumentContext.AttachToProject (ext.ownerProjects [n]);
}
public int IconCount {
get {
return ext.ownerProjects.Count;
}
}
#endregion
}
protected void OnPathChanged (PathEntry[] oldPath)
{
if (PathChanged != null)
PathChanged (this, new DocumentPathChangedEventArgs (oldPath));
}
protected XName GetCompleteName ()
{
Debug.Assert (tracker.Engine.CurrentState is XmlNameState);
int end = tracker.Engine.Position;
int start = end - tracker.Engine.CurrentStateLength;
int mid = -1;
int limit = Math.Min (Editor.Length, end + 35);
//try to find the end of the name, but don't go too far
for (; end < limit; end++) {
char c = Editor.GetCharAt (end);
if (c == ':') {
if (mid == -1)
mid = end;
else
break;
} else if (!XmlChar.IsNameChar (c))
break;
}
if (mid > 0 && end > mid + 1) {
return new XName (Editor.GetTextBetween (start, mid), Editor.GetTextBetween (mid + 1, end));
}
return new XName (Editor.GetTextBetween (start, end));
}
/*
protected XNode GetFullNode ()
{
Parser p = (Parser) ((ICloneable)this.tracker.Engine).Clone ();
//run the parser until the tag's closed, or we move to its sibling or parent
if (node != null) {
while (node.NextSibling == null &&
treeParser.Position < textLen && treeParser.Nodes.Peek () != ob.Parent)
{
char c = Editor.GetCharAt (treeParser.Position);
treeParser.Push (c);
if (el != null && el.IsClosed && el.ClosingTag.IsComplete)
break;
}
}
}
*/
protected List<XObject> GetCurrentPath ()
{
if (tracker == null)
return null;
tracker.UpdateEngine ();
var path = new List<XObject> (tracker.Engine.Nodes);
//remove the root XDocument
path.RemoveAt (path.Count - 1);
//complete incomplete XName if present
if (tracker.Engine.CurrentState is XmlNameState && path[0] is INamedXObject) {
path [0] = path [0].ShallowCopy ();
XName completeName = GetCompleteName ();
((INamedXObject)path[0]).Name = completeName;
}
path.Reverse ();
return path;
}
void UpdatePath ()
{
//update timeout could get called after disposed
if (tracker == null)
return;
List<XObject> l = GetCurrentPath ();
//build the list
var path = new List<PathEntry> ();
if (ownerProjects.Count > 1) {
// Current project if there is more than one
path.Add (new PathEntry (ImageService.GetIcon (DocumentContext.Project.StockIcon), GLib.Markup.EscapeText (DocumentContext.Project.Name)) { Tag = DocumentContext.Project });
}
if (l != null) {
for (int i = 0; i < l.Count; i++) {
path.Add (new PathEntry (GLib.Markup.EscapeText (l [i].FriendlyPathRepresentation ?? "<>")));
}
}
PathEntry[] oldPath = currentPath;
currentPath = path.ToArray ();
OnPathChanged (oldPath);
}
public PathEntry[] CurrentPath {
get { return currentPath; }
}
#endregion
#region IOutlinedDocument
bool refreshingOutline;
Widget IOutlinedDocument.GetOutlineWidget ()
{
if (outlineTreeView != null)
return outlineTreeView;
outlineTreeStore = new TreeStore (typeof (object));
outlineTreeView = new MonoDevelop.Ide.Gui.Components.PadTreeView (outlineTreeStore);
System.Reflection.PropertyInfo prop = typeof (TreeView).GetProperty ("EnableTreeLines");
if (prop != null)
prop.SetValue (outlineTreeView, true, null);
outlineTreeView.Realized += delegate { refillOutlineStore (); };
InitializeOutlineColumns (outlineTreeView);
outlineTreeView.HeadersVisible = false;
outlineTreeView.Selection.Changed += delegate {
TreeIter iter;
if (!outlineTreeView.Selection.GetSelected (out iter))
return;
OutlineSelectionChanged (outlineTreeStore.GetValue (iter, 0));
};
refillOutlineStore ();
var sw = new CompactScrolledWindow ();
sw.Add (outlineTreeView);
sw.ShowAll ();
return sw;
}
IEnumerable<Widget> IOutlinedDocument.GetToolbarWidgets ()
{
return null;
}
protected virtual void InitializeOutlineColumns (MonoDevelop.Ide.Gui.Components.PadTreeView outlineTree)
{
outlineTree.TextRenderer.Xpad = 0;
outlineTree.TextRenderer.Ypad = 0;
outlineTree.AppendColumn ("Node", outlineTree.TextRenderer, new TreeCellDataFunc (outlineTreeDataFunc));
}
protected virtual void OutlineSelectionChanged (object selection)
{
SelectNode ((XNode)selection);
}
void RefreshOutline ()
{
if (refreshingOutline || outlineTreeView == null )
return;
refreshingOutline = true;
GLib.Timeout.Add (3000, refillOutlineStoreIdleHandler);
}
bool refillOutlineStoreIdleHandler ()
{
refreshingOutline = false;
refillOutlineStore ();
return false;
}
protected virtual void RefillOutlineStore (ParsedDocument doc, TreeStore store)
{
XDocument xdoc = ((XmlParsedDocument)doc).XDocument;
if (xdoc == null)
return;
BuildTreeChildren (store, TreeIter.Zero, xdoc);
}
void refillOutlineStore ()
{
DispatchService.AssertGuiThread ();
Gdk.Threads.Enter ();
refreshingOutline = false;
if (outlineTreeStore == null || !outlineTreeView.IsRealized)
return;
outlineTreeStore.Clear ();
if (CU != null) {
DateTime start = DateTime.Now;
RefillOutlineStore (CU, outlineTreeStore);
outlineTreeView.ExpandAll ();
outlineTreeView.ExpandAll ();
LoggingService.LogDebug ("Built outline in {0}ms", (DateTime.Now - start).Milliseconds);
}
Gdk.Threads.Leave ();
}
void IOutlinedDocument.ReleaseOutlineWidget ()
{
if (outlineTreeView == null)
return;
var w = (ScrolledWindow) outlineTreeView.Parent;
w.Destroy ();
outlineTreeView.Destroy ();
outlineTreeStore.Dispose ();
outlineTreeStore = null;
outlineTreeView = null;
}
static void BuildTreeChildren (TreeStore store, TreeIter parent, XContainer p)
{
foreach (XNode n in p.Nodes) {
TreeIter childIter;
if (!parent.Equals (TreeIter.Zero))
childIter = store.AppendValues (parent, n);
else
childIter = store.AppendValues (n);
var c = n as XContainer;
if (c != null && c.FirstChild != null)
BuildTreeChildren (store, childIter, c);
}
}
void outlineTreeDataFunc (TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
{
var txtRenderer = (CellRendererText) cell;
var n = (XNode) model.GetValue (iter, 0);
txtRenderer.Text = n.FriendlyPathRepresentation;
}
public void SelectNode (XNode n)
{
var region = n.Region;
var el = n as XElement;
if (el != null && el.IsClosed && el.ClosingTag.Region.End > region.End) {
region = new DocumentRegion (region.Begin, el.ClosingTag.Region.End);
}
EditorSelect (region);
}
#endregion
[CommandUpdateHandler (EditCommands.AddCodeComment)]
[CommandUpdateHandler (EditCommands.RemoveCodeComment)]
[CommandUpdateHandler (EditCommands.ToggleCodeComment)]
void ToggleCodeCommentCommandUpdate (CommandInfo info)
{
info.Enabled = true;
info.Visible = true;
}
bool IsInComment ()
{
Tracker.UpdateEngine ();
if (Tracker.Engine.CurrentState is XmlCommentState) {
return true;
}
//If we are not in comment, try parsing 3 letters so in case we are just after
//"<" of <!-- we come inside... and state changes into XmlCommentState
var engineClone = Tracker.Engine.GetTreeParser ();
int j = 0;
for (int i = engineClone.Position; i < Editor.Length && j < 3; i++, j++) {
engineClone.Push (Editor.GetCharAt (engineClone.Position));
}
return engineClone.CurrentState is XmlCommentState;
}
[CommandHandler (EditCommands.AddCodeComment)]
public void AddCodeCommentCommand ()
{
if (!IsInComment ()) {
ToggleCodeCommentCommandInternal (false);
}
}
[CommandHandler (EditCommands.RemoveCodeComment)]
public void RemoveCodeCommentCommand ()
{
if (IsInComment ()) {
ToggleCodeCommentCommandInternal (true);
}
}
[CommandHandler (EditCommands.ToggleCodeComment)]
public void ToggleCodeCommentCommand ()
{
ToggleCodeCommentCommandInternal (IsInComment ());
}
void ToggleCodeCommentCommandInternal (bool remove)
{
if (remove) {
//We are guarenteed we are inside comment start
var treeParser = Tracker.Engine.GetTreeParser ();
XComment commentNode = treeParser.Nodes.Peek () as XComment;
//Keep parsing XML until end of file or until comment node is ended
for (int i = treeParser.Position; i < Editor.Length; i++) {
treeParser.Push (Editor.GetCharAt (i));
if (commentNode != null) {
if (commentNode.IsEnded) {
break;
}
} else {
commentNode = treeParser.Nodes.Peek () as XComment;
}
}
//Comment doesn't close until end of file
if (commentNode == null || !commentNode.IsEnded) {
return;
}
var startOffset = Editor.LocationToOffset (commentNode.Region.Begin);
var endOffset = Editor.LocationToOffset (commentNode.Region.End) - 3 - 4;//-3 because End is after "-->", -4 because removed "<!--" just before
using (Editor.OpenUndoGroup ()) {
Editor.RemoveText (startOffset, 4);//4 equals "<!--"
Editor.RemoveText (endOffset, 3);//3 equals "-->"
}
} else {
using (Editor.OpenUndoGroup ()) {
if (Editor.IsSomethingSelected) {
//end variable is also used because inserting start deselectes text and Editor.SelectionRange.EndOffset becomes invalid
var end = Editor.SelectionRange.EndOffset + 4;//+4 equals "<!--" inserted in next line
Editor.InsertText (Editor.SelectionRange.Offset, "<!--");
Editor.InsertText (end, "-->");
} else {
var currentLine = Editor.GetLine (Editor.CaretLine);
Editor.InsertText (currentLine.Offset, "<!--");
Editor.InsertText (currentLine.EndOffset, "-->");//currentLine.EndOffset updates automaticlly
}
}
}
}
}
}
|