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

github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'main/src/addins/Xml/Editor')
-rw-r--r--main/src/addins/Xml/Editor/BaseXmlEditorExtension.cs264
-rw-r--r--main/src/addins/Xml/Editor/XmlDocumentParser.cs12
-rw-r--r--main/src/addins/Xml/Editor/XmlEditorService.cs670
-rw-r--r--main/src/addins/Xml/Editor/XmlParsedDocument.cs18
-rw-r--r--main/src/addins/Xml/Editor/XmlTextEditorExtension.cs683
5 files changed, 944 insertions, 703 deletions
diff --git a/main/src/addins/Xml/Editor/BaseXmlEditorExtension.cs b/main/src/addins/Xml/Editor/BaseXmlEditorExtension.cs
index f0395d0aea..75a9fdf5de 100644
--- a/main/src/addins/Xml/Editor/BaseXmlEditorExtension.cs
+++ b/main/src/addins/Xml/Editor/BaseXmlEditorExtension.cs
@@ -34,10 +34,7 @@ using System.Linq;
using Gtk;
-using ICSharpCode.NRefactory;
-using ICSharpCode.NRefactory.TypeSystem;
-using Mono.TextEditor;
using MonoDevelop.Components;
using MonoDevelop.Core;
using MonoDevelop.DesignerSupport;
@@ -45,10 +42,14 @@ 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;
namespace MonoDevelop.Xml.Editor
{
@@ -65,18 +66,17 @@ namespace MonoDevelop.Xml.Editor
#region Setup and teardown
- public override bool ExtendsEditor (MonoDevelop.Ide.Gui.Document doc, IEditableTextBuffer editor)
+ public override bool IsValidInContext (DocumentContext context)
{
//can only attach if there is not already an attached BaseXmlEditorExtension
- return doc.GetContent<BaseXmlEditorExtension> () == null;
+ return context.GetContent<BaseXmlEditorExtension> () == null;
}
protected virtual XmlRootState CreateRootState ()
{
return new XmlRootState ();
}
-
- public override void Initialize ()
+ protected override void Initialize ()
{
base.Initialize ();
@@ -89,11 +89,11 @@ namespace MonoDevelop.Xml.Editor
var parser = new XmlParser (CreateRootState (), false);
tracker = new DocumentStateTracker<XmlParser> (parser, Editor);
+ DocumentContext.DocumentParsed += UpdateParsedDocument;
+ Editor.CaretPositionChanged += HandleCaretPositionChanged;
- Document.DocumentParsed += UpdateParsedDocument;
-
- if (Document.ParsedDocument != null) {
- lastCU = Document.ParsedDocument;
+ if (DocumentContext.ParsedDocument != null) {
+ lastCU = DocumentContext.ParsedDocument;
OnParsedDocumentUpdated ();
}
@@ -105,7 +105,7 @@ namespace MonoDevelop.Xml.Editor
void HandleProjectChanged (object sender, ProjectFileEventArgs e)
{
- if (e.Any (f => f.ProjectFile.FilePath == Document.FileName))
+ if (e.Any (f => f.ProjectFile.FilePath == DocumentContext.Name))
UpdateOwnerProjects ();
}
@@ -115,37 +115,39 @@ namespace MonoDevelop.Xml.Editor
ownerProjects = new List<DotNetProject> ();
return;
}
- var projects = new HashSet<DotNetProject> (IdeApp.Workspace.GetAllItems<DotNetProject> ().Where (p => p.IsFileInProject (Document.FileName)));
+ 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 = Document.Project as DotNetProject;
+ 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 = Document.Project != null ? ownerProjects.FirstOrDefault (p => p.ParentSolution == Document.Project.ParentSolution) : null;
+ var pp = DocumentContext.Project != null ? ownerProjects.FirstOrDefault (p => p.ParentSolution == DocumentContext.Project.ParentSolution) : null;
if (pp != null)
- Document.AttachToProject (pp);
+ DocumentContext.AttachToProject (pp);
}
}
- if (Document.Project == null && ownerProjects.Count > 0)
- Document.AttachToProject (ownerProjects[0]);
+ if (DocumentContext.Project == null && ownerProjects.Count > 0)
+ DocumentContext.AttachToProject (ownerProjects[0]);
UpdatePath ();
}
void UpdateParsedDocument (object sender, EventArgs args)
{
- lastCU = Document.ParsedDocument;
+ lastCU = DocumentContext.ParsedDocument;
OnParsedDocumentUpdated ();
}
public override void Dispose ()
{
+ Editor.CaretPositionChanged -= HandleCaretPositionChanged;
+
if (tracker != null) {
tracker = null;
base.Dispose ();
}
- Document.DocumentParsed -= UpdateParsedDocument;
+ DocumentContext.DocumentParsed -= UpdateParsedDocument;
if (IdeApp.Workspace != null) {
IdeApp.Workspace.FileAddedToProject -= HandleProjectChanged;
@@ -183,34 +185,17 @@ namespace MonoDevelop.Xml.Editor
protected ParsedDocument CU {
get { return lastCU; }
}
-
- protected ITextBuffer Buffer {
- get {
- if (Document == null)
- throw new InvalidOperationException ("Editor extension not yet initialized");
- return Document.GetContent<ITextBuffer> ();
- }
- }
-
- protected IEditableTextBuffer EditableBuffer {
- get {
- if (Document == null)
- throw new InvalidOperationException ("Editor extension not yet initialized");
- return Document.GetContent<IEditableTextBuffer> ();
- }
- }
-
+
protected DocumentStateTracker<XmlParser> Tracker {
get { return tracker; }
}
- protected string GetBufferText (DomRegion region)
+ protected string GetBufferText (DocumentRegion region)
{
- ITextBuffer buf = Buffer;
- int start = buf.GetPositionFromLineColumn (region.BeginLine, region.BeginColumn);
- int end = buf.GetPositionFromLineColumn (region.EndLine, region.EndColumn);
+ int start = Editor.LocationToOffset (region.BeginLine, region.BeginColumn);
+ int end = Editor.LocationToOffset (region.EndLine, region.EndColumn);
if (end > start && start >= 0)
- return buf.GetText (start, end);
+ return Editor.GetTextBetween (start, end);
return null;
}
@@ -219,7 +204,12 @@ namespace MonoDevelop.Xml.Editor
public override string CompletionLanguage {
get { return "Xml"; }
}
-
+
+ protected FilePath FileName {
+ get {
+ return Editor.FileName;
+ }
+ }
protected XDocType DocType {
get { return docType; }
set {
@@ -234,29 +224,24 @@ namespace MonoDevelop.Xml.Editor
{
}
- public override bool KeyPress (Gdk.Key key, char keyChar, Gdk.ModifierType modifier)
+ public override bool KeyPress (KeyDescriptor descriptor)
{
- if (Document.Editor.Options.IndentStyle == IndentStyle.Smart) {
- var newLine = Editor.Caret.Line + 1;
- var ret = base.KeyPress (key, keyChar, modifier);
- if (key == Gdk.Key.Return && Editor.Caret.Line == newLine) {
+ 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) {
- int newCaretOffset = Editor.Caret.Offset;
- if (newCaretOffset > seg.Offset) {
- newCaretOffset += (indent.Length - oldIndent.Length);
- }
using (var undo = Editor.OpenUndoGroup ()) {
- Editor.Replace (seg.Offset, oldIndent.Length, indent);
- Editor.Caret.Offset = newCaretOffset;
+ Editor.ReplaceText (seg.Offset, oldIndent.Length, indent);
}
}
}
return ret;
}
- return base.KeyPress (key, keyChar, modifier);
+ return base.KeyPress (descriptor);
}
#region Code completion
@@ -266,31 +251,29 @@ namespace MonoDevelop.Xml.Editor
int pos = completionContext.TriggerOffset;
if (pos <= 0)
return null;
- int triggerWordLength = 0;
-
tracker.UpdateEngine ();
- return HandleCodeCompletion (completionContext, true, ref triggerWordLength);
+ var task = HandleCodeCompletion (completionContext, true, default(CancellationToken));
+ return task != null ? task.Result : null;
}
- public override ICompletionDataList HandleCodeCompletion (
- CodeCompletionContext completionContext, char completionChar, ref int triggerWordLength)
+ 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, ref triggerWordLength);
+ return HandleCodeCompletion (completionContext, false, token);
}
return null;
}
- protected virtual ICompletionDataList HandleCodeCompletion (
- CodeCompletionContext completionContext, bool forced, ref int triggerWordLength)
+ protected virtual Task<ICompletionDataList> HandleCodeCompletion (
+ CodeCompletionContext completionContext, bool forced, CancellationToken token)
{
- IEditableTextBuffer buf = EditableBuffer;
+ 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 TextLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset);
+ 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);
@@ -299,13 +282,13 @@ namespace MonoDevelop.Xml.Editor
tracker.Engine.CurrentStateLength, previousChar, currentChar, forced);
//closing tag completion
- if (tracker.Engine.CurrentState is XmlRootState && currentChar == '>')
- return ClosingTagCompletion (buf, currentLocation);
+ if (tracker.Engine.CurrentState is XmlRootState && currentChar == '>')
+ return Task.FromResult (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.InsertText (buf.CursorPosition, ">");
+ buf.InsertAtCaret (">");
return null;
}
@@ -331,7 +314,7 @@ namespace MonoDevelop.Xml.Editor
list.Add ("&").CompletionText = "amp;";
GetEntityCompletions (list);
- return list;
+ return Task.FromResult ((ICompletionDataList)list);
}
//doctype completion
@@ -339,7 +322,7 @@ namespace MonoDevelop.Xml.Editor
if (tracker.Engine.CurrentStateLength == 1) {
CompletionDataList list = GetDocTypeCompletions ();
if (list != null && list.Count > 0)
- return list;
+ return Task.FromResult ((ICompletionDataList)list);
}
return null;
}
@@ -359,9 +342,13 @@ namespace MonoDevelop.Xml.Editor
return null;
//if triggered by first letter of value or forced, grab those letters
- triggerWordLength = Tracker.Engine.CurrentStateLength - 1;
- return GetAttributeValueCompletions (attributedOb, att);
+ var result = GetAttributeValueCompletions (attributedOb, att);
+ if (result != null) {
+ result.TriggerWordLength = Tracker.Engine.CurrentStateLength - 1;
+ return Task.FromResult ((ICompletionDataList)result);
+ }
+ return null;
}
}
@@ -380,17 +367,18 @@ namespace MonoDevelop.Xml.Editor
if (attributedOb.Name.IsValid && (forced ||
(char.IsWhiteSpace (previousChar) && char.IsLetter (currentChar))))
{
-
- if (!forced)
- triggerWordLength = 1;
-
var existingAtts = new Dictionary<string,string> (StringComparer.OrdinalIgnoreCase);
foreach (XAttribute att in attributedOb.Attributes) {
existingAtts [att.Name.FullName] = att.Value ?? string.Empty;
}
-
- return GetAttributeCompletions (attributedOb, existingAtts);
+ var result = GetAttributeCompletions (attributedOb, existingAtts);
+ if (result != null) {
+ if (!forced)
+ result.TriggerWordLength = 1;
+ return Task.FromResult ((ICompletionDataList)result);
+ }
+ return null;
}
}
@@ -405,48 +393,79 @@ namespace MonoDevelop.Xml.Editor
var list = new CompletionDataList ();
GetElementCompletions (list);
AddCloseTag (list, Tracker.Engine.Nodes);
- return list.Count > 0? list : null;
+ return Task.FromResult ((ICompletionDataList)(list.Count > 0? list : null));
}
if (forced && Tracker.Engine.CurrentState is XmlRootState) {
var list = new CompletionDataList ();
- MonoDevelop.Ide.CodeTemplates.CodeTemplateService.AddCompletionDataForFileName (Document.Name, list);
- return list.Count > 0? list : null;
+ MonoDevelop.Ide.CodeTemplates.CodeTemplateService.AddCompletionDataForFileName (DocumentContext.Name, list);
+ return Task.FromResult ((ICompletionDataList)(list.Count > 0? list : null));
}
return null;
- }
-
- protected virtual ICompletionDataList ClosingTagCompletion (IEditableTextBuffer buf, TextLocation 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.CursorPosition, tag);
- buf.CursorPosition -= 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 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 void GetElementCompletions (CompletionDataList list)
@@ -475,7 +494,7 @@ namespace MonoDevelop.Xml.Editor
protected string GetLineIndent (int line)
{
- var seg = Editor.Document.GetLine (line);
+ var seg = Editor.GetLine (line);
//reset the tracker to the beginning of the line
Tracker.UpdateEngine (seg.Offset);
@@ -592,7 +611,7 @@ namespace MonoDevelop.Xml.Editor
PathEntry[] currentPath;
bool pathUpdateQueued;
- public override void CursorPositionChanged ()
+ void HandleCaretPositionChanged (object sender, EventArgs e)
{
if (pathUpdateQueued)
return;
@@ -602,7 +621,6 @@ namespace MonoDevelop.Xml.Editor
UpdatePath ();
return false;
});
-
}
public void SelectPath (int depth)
@@ -662,16 +680,16 @@ namespace MonoDevelop.Xml.Editor
//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 DomRegion (s, e));
+ EditorSelect (new DocumentRegion (s, e));
} else {
LoggingService.LogDebug ("No end tag found for selection");
}
}
- protected void EditorSelect (DomRegion region)
+ protected void EditorSelect (DocumentRegion region)
{
- int s = Editor.Document.LocationToOffset (region.BeginLine, region.BeginColumn);
- int e = Editor.Document.LocationToOffset (region.EndLine, region.EndColumn);
+ 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);
@@ -743,7 +761,7 @@ namespace MonoDevelop.Xml.Editor
public void ActivateItem (int n)
{
- ext.Document.AttachToProject (ext.ownerProjects [n]);
+ ext.DocumentContext.AttachToProject (ext.ownerProjects [n]);
}
public int IconCount {
@@ -842,7 +860,7 @@ namespace MonoDevelop.Xml.Editor
var path = new List<PathEntry> ();
if (ownerProjects.Count > 1) {
// Current project if there is more than one
- path.Add (new PathEntry (ImageService.GetIcon (Document.Project.StockIcon), GLib.Markup.EscapeText (Document.Project.Name)) { Tag = Document.Project });
+ 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++) {
@@ -999,7 +1017,7 @@ namespace MonoDevelop.Xml.Editor
var el = n as XElement;
if (el != null && el.IsClosed && el.ClosingTag.Region.End > region.End) {
- region = new DomRegion (region.Begin, el.ClosingTag.Region.End);
+ region = new DocumentRegion (region.Begin, el.ClosingTag.Region.End);
}
EditorSelect (region);
}
diff --git a/main/src/addins/Xml/Editor/XmlDocumentParser.cs b/main/src/addins/Xml/Editor/XmlDocumentParser.cs
index 5f17fead35..d97ef44b69 100644
--- a/main/src/addins/Xml/Editor/XmlDocumentParser.cs
+++ b/main/src/addins/Xml/Editor/XmlDocumentParser.cs
@@ -31,20 +31,22 @@ using System.IO;
using MonoDevelop.Ide.TypeSystem;
using MonoDevelop.Xml.Parser;
+using MonoDevelop.Core.Text;
namespace MonoDevelop.Xml.Editor
{
class XmlDocumentParser : TypeSystemParser
{
- public override ParsedDocument Parse (bool storeAst, string fileName, TextReader content, MonoDevelop.Projects.Project project = null)
+ public override System.Threading.Tasks.Task<ParsedDocument> Parse (ParseOptions parseOptions, System.Threading.CancellationToken cancellationToken)
{
- var doc = new XmlParsedDocument (fileName);
+ var doc = new XmlParsedDocument (parseOptions.FileName);
doc.Flags |= ParsedDocumentFlags.NonSerializable;
try {
var xmlParser = new XmlParser (new XmlRootState (), true);
- xmlParser.Parse (content);
+ xmlParser.Parse (parseOptions.Content.CreateReader ());
doc.XDocument = xmlParser.Nodes.GetRoot ();
- doc.Add (xmlParser.Errors);
+ // TODO error conversion!
+ //doc.Add (xmlParser.Errors);
if (doc.XDocument != null && doc.XDocument.RootElement != null) {
if (!doc.XDocument.RootElement.IsEnded)
@@ -54,7 +56,7 @@ namespace MonoDevelop.Xml.Editor
catch (Exception ex) {
MonoDevelop.Core.LoggingService.LogError ("Unhandled error parsing xml document", ex);
}
- return doc;
+ return System.Threading.Tasks.Task.FromResult((ParsedDocument)doc);
}
}
}
diff --git a/main/src/addins/Xml/Editor/XmlEditorService.cs b/main/src/addins/Xml/Editor/XmlEditorService.cs
index 7e0201ef57..4b388eb528 100644
--- a/main/src/addins/Xml/Editor/XmlEditorService.cs
+++ b/main/src/addins/Xml/Editor/XmlEditorService.cs
@@ -1,42 +1,48 @@
-//
-// MonoDevelop XML Editor
-//
-// Copyright (C) 2006-2007 Matthew Ward
-//
-// 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
+//
+// MonoDevelop XML Editor
+//
+// Copyright (C) 2006-2007 Matthew Ward
+//
+// 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
-using System.Text;
-using System.Xml;
-using System.Xml.Schema;
+using System.Text;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.XPath;
+using System.Xml.Xsl;
+using MonoDevelop.Components;
+using Gtk;
+using MonoDevelop.Components.Extensions;
+using MonoDevelop.Ide.Editor;
using System.Xml.XPath;
using System.Xml.Xsl;
using MonoDevelop.Components;
using MonoDevelop.Components.Extensions;
-using MonoDevelop.Core;
-using MonoDevelop.Ide;
-using MonoDevelop.Ide.Gui;
-using MonoDevelop.Ide.Tasks;
-using MonoDevelop.Projects;
+using MonoDevelop.Core;
+using MonoDevelop.Ide;
+using MonoDevelop.Ide.Gui;
+using MonoDevelop.Ide.Tasks;
+using MonoDevelop.Projects;
using MonoDevelop.Xml.Completion;
namespace MonoDevelop.Xml.Editor
@@ -44,7 +50,7 @@ namespace MonoDevelop.Xml.Editor
static class XmlEditorService
{
#region Task management
- public static void AddTask(string fileName, string message, int column, int line, TaskSeverity taskType)
+ public static void AddTask(string fileName, string message, int column, int line, TaskSeverity taskType)
{
// HACK: Use a compiler error since we cannot add an error
// task otherwise (task type property is read-only and
@@ -55,23 +61,23 @@ namespace MonoDevelop.Xml.Editor
error.ErrorText = message;
error.FileName = fileName;
error.IsWarning = false;
-
+
//Task task = new Task(fileName, message, column, line);
TaskListEntry task = new TaskListEntry (error);
- TaskService.Errors.Add(task);
- }
- #endregion
-
+ TaskService.Errors.Add(task);
+ }
+ #endregion
+
#region View tracking
-
- public static XmlTextEditorExtension ActiveEditor {
- get {
- Document doc = IdeApp.Workbench.ActiveDocument;
- if (doc != null)
- return doc.GetContent<XmlTextEditorExtension>();
- return null;
- }
- }
+
+ public static XmlTextEditorExtension ActiveEditor {
+ get {
+ Document doc = IdeApp.Workbench.ActiveDocument;
+ if (doc != null)
+ return doc.GetContent<XmlTextEditorExtension>();
+ return null;
+ }
+ }
public static ReadOnlyCollection<XmlTextEditorExtension> OpenXmlEditorViews {
get {
@@ -89,8 +95,8 @@ namespace MonoDevelop.Xml.Editor
get {
return ActiveEditor != null;
}
- }
- #endregion
+ }
+ #endregion
/*
public static bool IsXslOutputViewContentActive {
@@ -103,339 +109,339 @@ namespace MonoDevelop.Xml.Editor
public static ProgressMonitor GetMonitor ()
{
return IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor ("XML", "md-xml-file-icon", true, true);
- }
-
+ }
+
#region Formatting utilities
/// <summary>
/// Creates a XmlTextWriter using the current text editor
/// properties for indentation.
/// </summary>
- public static XmlTextWriter CreateXmlTextWriter (Document doc, TextWriter textWriter)
+ public static XmlTextWriter CreateXmlTextWriter (TextEditor doc, TextWriter textWriter)
{
- XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
- xmlWriter.Formatting = System.Xml.Formatting.Indented;
- if (doc.Editor.TabsToSpaces) {
- xmlWriter.Indentation = doc.Editor.Options.TabSize;
- xmlWriter.IndentChar = ' ';
- } else {
- xmlWriter.Indentation = 1;
- xmlWriter.IndentChar = '\t';
- }
+ XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
+ xmlWriter.Formatting = System.Xml.Formatting.Indented;
+ if (doc.Options.TabsToSpaces) {
+ xmlWriter.Indentation = doc.Options.TabSize;
+ xmlWriter.IndentChar = ' ';
+ } else {
+ xmlWriter.Indentation = 1;
+ xmlWriter.IndentChar = '\t';
+ }
return xmlWriter;
- }
-
- public static XmlTextWriter CreateXmlTextWriter (Document doc)
- {
- return CreateXmlTextWriter (doc, new EncodedStringWriter (Encoding.UTF8));
- }
-
+ }
+
+ public static XmlTextWriter CreateXmlTextWriter (TextEditor doc)
+ {
+ return CreateXmlTextWriter (doc, new EncodedStringWriter (Encoding.UTF8));
+ }
+
#endregion
- /// <summary>
- /// Runs an XSL transform on the input xml.
- /// </summary>
- /// <param name="input">The input xml to transform.</param>
- /// <param name="transform">The transform xml.</param>
- /// <returns>The output of the transform.</returns>
- public static string Transform (string input, string transform)
- {
- StringReader inputString = new StringReader (input);
- XPathDocument sourceDocument = new XPathDocument (inputString);
-
- StringReader transformString = new StringReader (transform);
- XPathDocument transformDocument = new XPathDocument (transformString);
-
- XslCompiledTransform xslTransform = new XslCompiledTransform ();
+ /// <summary>
+ /// Runs an XSL transform on the input xml.
+ /// </summary>
+ /// <param name="input">The input xml to transform.</param>
+ /// <param name="transform">The transform xml.</param>
+ /// <returns>The output of the transform.</returns>
+ public static string Transform (string input, string transform)
+ {
+ StringReader inputString = new StringReader (input);
+ XPathDocument sourceDocument = new XPathDocument (inputString);
+
+ StringReader transformString = new StringReader (transform);
+ XPathDocument transformDocument = new XPathDocument (transformString);
+
+ XslCompiledTransform xslTransform = new XslCompiledTransform ();
xslTransform.Load (transformDocument, null, new XmlUrlResolver ());
-
- MemoryStream outputStream = new MemoryStream ();
- XmlTextWriter writer = new XmlTextWriter (outputStream, Encoding.UTF8);
-
- xslTransform.Transform (sourceDocument, writer);
-
- int preambleLength = Encoding.UTF8.GetPreamble ().Length;
- byte[] outputBytes = outputStream.ToArray ();
- return UTF8Encoding.UTF8.GetString (outputBytes, preambleLength, outputBytes.Length - preambleLength);
- }
-
- public static string CreateSchema (Document doc, string xml)
- {
- using (System.Data.DataSet dataSet = new System.Data.DataSet()) {
- dataSet.ReadXml(new StringReader (xml), System.Data.XmlReadMode.InferSchema);
- using (EncodedStringWriter writer = new EncodedStringWriter (Encoding.UTF8)) {
- using (XmlTextWriter xmlWriter = XmlEditorService.CreateXmlTextWriter (doc, writer)) {
- dataSet.WriteXmlSchema(xmlWriter);
- return writer.ToString();
+
+ MemoryStream outputStream = new MemoryStream ();
+ XmlTextWriter writer = new XmlTextWriter (outputStream, Encoding.UTF8);
+
+ xslTransform.Transform (sourceDocument, writer);
+
+ int preambleLength = Encoding.UTF8.GetPreamble ().Length;
+ byte[] outputBytes = outputStream.ToArray ();
+ return UTF8Encoding.UTF8.GetString (outputBytes, preambleLength, outputBytes.Length - preambleLength);
+ }
+
+ public static string CreateSchema (TextEditor doc, string xml)
+ {
+ using (System.Data.DataSet dataSet = new System.Data.DataSet()) {
+ dataSet.ReadXml(new StringReader (xml), System.Data.XmlReadMode.InferSchema);
+ using (EncodedStringWriter writer = new EncodedStringWriter (Encoding.UTF8)) {
+ using (XmlTextWriter xmlWriter = XmlEditorService.CreateXmlTextWriter (doc, writer)) {
+ dataSet.WriteXmlSchema(xmlWriter);
+ return writer.ToString();
}
- }
- }
- }
-
- public static string GenerateFileName (string sourceName, string extensionFormat)
- {
- return GenerateFileName (
- Path.Combine (Path.GetDirectoryName (sourceName), Path.GetFileNameWithoutExtension (sourceName)) +
- extensionFormat);
- }
-
- // newNameFormat should be a string format for the new filename such as
- // "/some/path/oldname{0}.xsd", where {0} is the index that will be incremented until a
- // non-existing file is found.
- public static string GenerateFileName (string newNameFormat)
- {
- string generatedFilename = string.Format (newNameFormat, "");
+ }
+ }
+ }
+
+ public static string GenerateFileName (string sourceName, string extensionFormat)
+ {
+ return GenerateFileName (
+ Path.Combine (Path.GetDirectoryName (sourceName), Path.GetFileNameWithoutExtension (sourceName)) +
+ extensionFormat);
+ }
+
+ // newNameFormat should be a string format for the new filename such as
+ // "/some/path/oldname{0}.xsd", where {0} is the index that will be incremented until a
+ // non-existing file is found.
+ public static string GenerateFileName (string newNameFormat)
+ {
+ string generatedFilename = string.Format (newNameFormat, "");
int count = 1;
while (File.Exists (generatedFilename)) {
- generatedFilename = string.Format (newNameFormat, count);
- ++count;
- }
- return generatedFilename;
- }
-
- #region Validation
-
- /// <summary>
- /// Checks that the xml in this view is well-formed.
- /// </summary>
+ generatedFilename = string.Format (newNameFormat, count);
+ ++count;
+ }
+ return generatedFilename;
+ }
+
+ #region Validation
+
+ /// <summary>
+ /// Checks that the xml in this view is well-formed.
+ /// </summary>
public static XmlDocument ValidateWellFormedness (ProgressMonitor monitor, string xml, string fileName)
- {
+ {
monitor.BeginTask (GettextCatalog.GetString ("Validating XML..."), 1);
- bool error = false;
- XmlDocument doc = null;
+ bool error = false;
+ XmlDocument doc = null;
try {
- doc = new XmlDocument ();
- doc.LoadXml (xml);
- } catch (XmlException ex) {
- monitor.ReportError (ex.Message, ex);
- AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskSeverity.Error);
- error = true;
- }
+ doc = new XmlDocument ();
+ doc.LoadXml (xml);
+ } catch (XmlException ex) {
+ monitor.ReportError (ex.Message, ex);
+ AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskSeverity.Error);
+ error = true;
+ }
- if (error) {
+ if (error) {
monitor.Log.WriteLine (GettextCatalog.GetString ("Validation failed."));
TaskService.ShowErrors ();
- } else {
- monitor.Log.WriteLine (GettextCatalog.GetString ("XML is valid."));
- }
-
- monitor.EndTask ();
+ } else {
+ monitor.Log.WriteLine (GettextCatalog.GetString ("XML is valid."));
+ }
+
+ monitor.EndTask ();
return error? null: doc;
- }
-
- /// <summary>
- /// Validates the xml against known schemas.
+ }
+
+ /// <summary>
+ /// Validates the xml against known schemas.
/// </summary>
public static XmlDocument ValidateXml (ProgressMonitor monitor, string xml, string fileName)
{
monitor.BeginTask (GettextCatalog.GetString ("Validating XML..."), 1);
- bool error = false;
- XmlDocument doc = null;
- StringReader stringReader = new StringReader (xml);
-
- XmlReaderSettings settings = new XmlReaderSettings ();
- settings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints
- | XmlSchemaValidationFlags.ProcessInlineSchema
- | XmlSchemaValidationFlags.ProcessSchemaLocation
- | XmlSchemaValidationFlags.ReportValidationWarnings;
- settings.ValidationType = ValidationType.Schema;
- settings.DtdProcessing = DtdProcessing.Parse;
-
- ValidationEventHandler validationHandler = delegate (object sender, System.Xml.Schema.ValidationEventArgs args) {
- if (args.Severity == XmlSeverityType.Warning) {
- monitor.Log.WriteLine (args.Message);
- AddTask (fileName, args.Exception.Message, args.Exception.LinePosition, args.Exception.LineNumber,TaskSeverity.Warning);
- } else {
- AddTask (fileName, args.Exception.Message, args.Exception.LinePosition, args.Exception.LineNumber,TaskSeverity.Error);
- monitor.Log.WriteLine (args.Message);
- error = true;
- }
- };
- settings.ValidationEventHandler += validationHandler;
-
+ bool error = false;
+ XmlDocument doc = null;
+ StringReader stringReader = new StringReader (xml);
+
+ XmlReaderSettings settings = new XmlReaderSettings ();
+ settings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints
+ | XmlSchemaValidationFlags.ProcessInlineSchema
+ | XmlSchemaValidationFlags.ProcessSchemaLocation
+ | XmlSchemaValidationFlags.ReportValidationWarnings;
+ settings.ValidationType = ValidationType.Schema;
+ settings.DtdProcessing = DtdProcessing.Parse;
+
+ ValidationEventHandler validationHandler = delegate (object sender, System.Xml.Schema.ValidationEventArgs args) {
+ if (args.Severity == XmlSeverityType.Warning) {
+ monitor.Log.WriteLine (args.Message);
+ AddTask (fileName, args.Exception.Message, args.Exception.LinePosition, args.Exception.LineNumber,TaskSeverity.Warning);
+ } else {
+ AddTask (fileName, args.Exception.Message, args.Exception.LinePosition, args.Exception.LineNumber,TaskSeverity.Error);
+ monitor.Log.WriteLine (args.Message);
+ error = true;
+ }
+ };
+ settings.ValidationEventHandler += validationHandler;
+
try {
- foreach (XmlSchemaCompletionData sd in XmlSchemaManager.SchemaCompletionDataItems)
- settings.Schemas.Add (sd.Schema);
- settings.Schemas.Compile ();
-
- XmlReader reader = XmlReader.Create (stringReader, settings);
- doc = new XmlDocument();
- doc.Load (reader);
-
- } catch (XmlSchemaException ex) {
- monitor.ReportError (ex.Message, ex);
- AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
- error = true;
- }
- catch (XmlException ex) {
- monitor.ReportError (ex.Message, ex);
- AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
- error = true;
- }
- finally {
- if (stringReader != null)
- stringReader.Dispose ();
- settings.ValidationEventHandler -= validationHandler;
+ foreach (XmlSchemaCompletionData sd in XmlSchemaManager.SchemaCompletionDataItems)
+ settings.Schemas.Add (sd.Schema);
+ settings.Schemas.Compile ();
+
+ XmlReader reader = XmlReader.Create (stringReader, settings);
+ doc = new XmlDocument();
+ doc.Load (reader);
+
+ } catch (XmlSchemaException ex) {
+ monitor.ReportError (ex.Message, ex);
+ AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
+ error = true;
+ }
+ catch (XmlException ex) {
+ monitor.ReportError (ex.Message, ex);
+ AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
+ error = true;
+ }
+ finally {
+ if (stringReader != null)
+ stringReader.Dispose ();
+ settings.ValidationEventHandler -= validationHandler;
}
- if (error) {
+ if (error) {
monitor.Log.WriteLine (GettextCatalog.GetString ("Validation failed."));
TaskService.ShowErrors ();
} else {
- monitor.Log.WriteLine (GettextCatalog.GetString ("XML is valid."));
- }
-
- monitor.EndTask ();
- return error? null: doc;
- }
-
- /// <summary>
- /// Validates the schema.
+ monitor.Log.WriteLine (GettextCatalog.GetString ("XML is valid."));
+ }
+
+ monitor.EndTask ();
+ return error? null: doc;
+ }
+
+ /// <summary>
+ /// Validates the schema.
/// </summary>
public static XmlSchema ValidateSchema (ProgressMonitor monitor, string xml, string fileName)
{
monitor.BeginTask (GettextCatalog.GetString ("Validating schema..."), 1);
- bool error = false;
- XmlSchema schema = null;
- try {
- StringReader stringReader = new StringReader (xml);
- XmlTextReader xmlReader = new XmlTextReader (stringReader);
+ bool error = false;
+ XmlSchema schema = null;
+ try {
+ StringReader stringReader = new StringReader (xml);
+ XmlTextReader xmlReader = new XmlTextReader (stringReader);
xmlReader.XmlResolver = null;
-
- ValidationEventHandler callback = delegate (object source, ValidationEventArgs args) {
- if (args.Severity == XmlSeverityType.Warning) {
- monitor.ReportWarning (args.Message);
- } else {
- monitor.ReportError (args.Message, args.Exception);
- error = true;
- }
- AddTask (fileName, args.Message, args.Exception.LinePosition, args.Exception.LineNumber,
- (args.Severity == XmlSeverityType.Warning)? TaskSeverity.Warning : TaskSeverity.Error);
+
+ ValidationEventHandler callback = delegate (object source, ValidationEventArgs args) {
+ if (args.Severity == XmlSeverityType.Warning) {
+ monitor.ReportWarning (args.Message);
+ } else {
+ monitor.ReportError (args.Message, args.Exception);
+ error = true;
+ }
+ AddTask (fileName, args.Message, args.Exception.LinePosition, args.Exception.LineNumber,
+ (args.Severity == XmlSeverityType.Warning)? TaskSeverity.Warning : TaskSeverity.Error);
};
- schema = XmlSchema.Read (xmlReader, callback);
- XmlSchemaSet sset = new XmlSchemaSet ();
- sset.Add (schema);
- sset.ValidationEventHandler += callback;
+ schema = XmlSchema.Read (xmlReader, callback);
+ XmlSchemaSet sset = new XmlSchemaSet ();
+ sset.Add (schema);
+ sset.ValidationEventHandler += callback;
sset.Compile ();
- }
- catch (XmlSchemaException ex) {
- monitor.ReportError (ex.Message, ex);
- AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
- error = true;
- }
- catch (XmlException ex) {
- monitor.ReportError (ex.Message, ex);
- AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
- error = true;
- }
+ }
+ catch (XmlSchemaException ex) {
+ monitor.ReportError (ex.Message, ex);
+ AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
+ error = true;
+ }
+ catch (XmlException ex) {
+ monitor.ReportError (ex.Message, ex);
+ AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
+ error = true;
+ }
- if (error) {
+ if (error) {
monitor.Log.WriteLine (GettextCatalog.GetString ("Validation failed."));
TaskService.ShowErrors ();
} else {
- monitor.Log.WriteLine (GettextCatalog.GetString ("Schema is valid."));
- }
-
- monitor.EndTask ();
- return error? null: schema;
- }
-
- public static XslCompiledTransform ValidateStylesheet (ProgressMonitor monitor, string xml, string fileName)
- {
+ monitor.Log.WriteLine (GettextCatalog.GetString ("Schema is valid."));
+ }
+
+ monitor.EndTask ();
+ return error? null: schema;
+ }
+
+ public static XslCompiledTransform ValidateStylesheet (ProgressMonitor monitor, string xml, string fileName)
+ {
monitor.BeginTask (GettextCatalog.GetString ("Validating stylesheet..."), 1);
- bool error = true;
- XslCompiledTransform xslt = null;
-
- try {
- StringReader reader = new StringReader (xml);
- XPathDocument doc = new XPathDocument (reader);
- xslt = new XslCompiledTransform ();
- xslt.Load (doc, null, new XmlUrlResolver ());
- error = false;
- } catch (XsltCompileException ex) {
- monitor.ReportError (ex.Message, ex);
- AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
- }
- catch (XsltException ex) {
- monitor.ReportError (ex.Message, ex);
- AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
- }
- catch (XmlException ex) {
- monitor.ReportError (ex.Message, ex);
- AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
- }
-
- if (error) {
+ bool error = true;
+ XslCompiledTransform xslt = null;
+
+ try {
+ StringReader reader = new StringReader (xml);
+ XPathDocument doc = new XPathDocument (reader);
+ xslt = new XslCompiledTransform ();
+ xslt.Load (doc, null, new XmlUrlResolver ());
+ error = false;
+ } catch (XsltCompileException ex) {
+ monitor.ReportError (ex.Message, ex);
+ AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
+ }
+ catch (XsltException ex) {
+ monitor.ReportError (ex.Message, ex);
+ AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
+ }
+ catch (XmlException ex) {
+ monitor.ReportError (ex.Message, ex);
+ AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error);
+ }
+
+ if (error) {
monitor.Log.WriteLine (GettextCatalog.GetString ("Validation failed."));
TaskService.ShowErrors ();
} else {
- monitor.Log.WriteLine (GettextCatalog.GetString ("Stylesheet is valid."));
- }
- return error? null: xslt;
- }
-
- #endregion
-
- #region File browsing utilities
-
- /// <summary>Allows the user to browse the file system for a stylesheet.</summary>
- /// <returns>The stylesheet filename the user selected; otherwise null.</returns>
- public static string BrowseForStylesheetFile ()
- {
- var dlg = new SelectFileDialog (GettextCatalog.GetString ("Select XSLT Stylesheet")) {
- TransientFor = IdeApp.Workbench.RootWindow,
- };
- dlg.AddFilter (new SelectFileDialogFilter (
- GettextCatalog.GetString ("XML Files"),
- new string[] { "*.xml" },
- new string[] { "text/xml", "application/xml" }
- ));
- dlg.AddFilter (new SelectFileDialogFilter(
- GettextCatalog.GetString ("XSL Files"),
- new string[] { "*.xslt", "*.xsl" },
- new string[] { "text/x-xslt" }
- ));
- dlg.AddAllFilesFilter ();
-
- if (dlg.Run ())
- return dlg.SelectedFile;
- return null;
- }
-
- /// <summary>Allows the user to browse the file system for a schema.</summary>
- /// <returns>The schema filename the user selected; otherwise null.</returns>
- public static string BrowseForSchemaFile ()
- {
- var dlg = new SelectFileDialog (GettextCatalog.GetString ("Select XML Schema"));
- dlg.AddFilter (new SelectFileDialogFilter (
- GettextCatalog.GetString ("XML Files"),
- new string[] { "*.xsd" },
- new string[] { "text/xml", "application/xml" }
- ));
- dlg.AddAllFilesFilter ();
-
- if (dlg.Run ())
- return dlg.SelectedFile;
- return null;
- }
-
- #endregion
-
- class EncodedStringWriter : StringWriter
- {
- readonly Encoding encoding;
-
- public EncodedStringWriter(Encoding encoding)
- {
- this.encoding = encoding;
- }
-
- public override Encoding Encoding {
- get {
- return encoding;
- }
- }
+ monitor.Log.WriteLine (GettextCatalog.GetString ("Stylesheet is valid."));
+ }
+ return error? null: xslt;
+ }
+
+ #endregion
+
+ #region File browsing utilities
+
+ /// <summary>Allows the user to browse the file system for a stylesheet.</summary>
+ /// <returns>The stylesheet filename the user selected; otherwise null.</returns>
+ public static string BrowseForStylesheetFile ()
+ {
+ var dlg = new SelectFileDialog (GettextCatalog.GetString ("Select XSLT Stylesheet")) {
+ TransientFor = IdeApp.Workbench.RootWindow,
+ };
+ dlg.AddFilter (new SelectFileDialogFilter (
+ GettextCatalog.GetString ("XML Files"),
+ new string[] { "*.xml" },
+ new string[] { "text/xml", "application/xml" }
+ ));
+ dlg.AddFilter (new SelectFileDialogFilter(
+ GettextCatalog.GetString ("XSL Files"),
+ new string[] { "*.xslt", "*.xsl" },
+ new string[] { "text/x-xslt" }
+ ));
+ dlg.AddAllFilesFilter ();
+
+ if (dlg.Run ())
+ return dlg.SelectedFile;
+ return null;
+ }
+
+ /// <summary>Allows the user to browse the file system for a schema.</summary>
+ /// <returns>The schema filename the user selected; otherwise null.</returns>
+ public static string BrowseForSchemaFile ()
+ {
+ var dlg = new SelectFileDialog (GettextCatalog.GetString ("Select XML Schema"));
+ dlg.AddFilter (new SelectFileDialogFilter (
+ GettextCatalog.GetString ("XML Files"),
+ new string[] { "*.xsd" },
+ new string[] { "text/xml", "application/xml" }
+ ));
+ dlg.AddAllFilesFilter ();
+
+ if (dlg.Run ())
+ return dlg.SelectedFile;
+ return null;
+ }
+
+ #endregion
+
+ class EncodedStringWriter : StringWriter
+ {
+ readonly Encoding encoding;
+
+ public EncodedStringWriter(Encoding encoding)
+ {
+ this.encoding = encoding;
+ }
+
+ public override Encoding Encoding {
+ get {
+ return encoding;
+ }
+ }
}
}
}
diff --git a/main/src/addins/Xml/Editor/XmlParsedDocument.cs b/main/src/addins/Xml/Editor/XmlParsedDocument.cs
index bd6bc32cbf..94de472070 100644
--- a/main/src/addins/Xml/Editor/XmlParsedDocument.cs
+++ b/main/src/addins/Xml/Editor/XmlParsedDocument.cs
@@ -29,8 +29,9 @@
using System;
using System.Collections.Generic;
using MonoDevelop.Ide.TypeSystem;
-using ICSharpCode.NRefactory.TypeSystem;
using MonoDevelop.Xml.Dom;
+using MonoDevelop.Ide.Editor;
+using System.Linq;
namespace MonoDevelop.Xml.Editor
{
@@ -41,19 +42,24 @@ namespace MonoDevelop.Xml.Editor
}
public XDocument XDocument { get; set; }
-
- public override IEnumerable<FoldingRegion> Foldings {
+
+ public override System.Threading.Tasks.Task<IReadOnlyList<FoldingRegion>> GetFoldingsAsync (System.Threading.CancellationToken cancellationToken)
+ {
+ return System.Threading.Tasks.Task.FromResult((IReadOnlyList<FoldingRegion>)Foldings.ToList ());
+ }
+
+ public IEnumerable<FoldingRegion> Foldings {
get {
if (XDocument == null)
yield break;
- foreach (var region in Comments.ToFolds ())
+ foreach (var region in GetCommentsAsync().Result.ToFolds ())
yield return region;
foreach (XNode node in XDocument.AllDescendentNodes) {
if (node is XCData)
{
if (node.Region.EndLine - node.Region.BeginLine > 2)
yield return new FoldingRegion ("<![CDATA[ ]]>", node.Region);
- }
+ }
else if (node is XComment)
{
if (node.Region.EndLine - node.Region.BeginLine > 2)
@@ -65,7 +71,7 @@ namespace MonoDevelop.Xml.Editor
if (el.IsClosed && el.ClosingTag.Region.EndLine - el.Region.BeginLine > 2) {
yield return new FoldingRegion
(string.Format ("<{0}...>", el.Name.FullName),
- new DomRegion (el.Region.Begin, el.ClosingTag.Region.End));
+ new DocumentRegion (el.Region.Begin, el.ClosingTag.Region.End));
}
}
else if (node is XDocType)
diff --git a/main/src/addins/Xml/Editor/XmlTextEditorExtension.cs b/main/src/addins/Xml/Editor/XmlTextEditorExtension.cs
index 58790e1276..d04db17fd2 100644
--- a/main/src/addins/Xml/Editor/XmlTextEditorExtension.cs
+++ b/main/src/addins/Xml/Editor/XmlTextEditorExtension.cs
@@ -32,17 +32,19 @@ using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
-using Mono.TextEditor;
-
using MonoDevelop.Components.Commands;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Ide.Gui.Content;
using MonoDevelop.Ide.Tasks;
+using MonoDevelop.Ide;
+using MonoDevelop.Ide.CodeFormatting;
+using MonoDevelop.Ide.Editor;
using MonoDevelop.Xml.Completion;
using MonoDevelop.Xml.Dom;
using MonoDevelop.Xml.Parser;
+using MonoDevelop.Ide.Editor.Extension;
namespace MonoDevelop.Xml.Editor
{
@@ -56,12 +58,12 @@ namespace MonoDevelop.Xml.Editor
InferredXmlCompletionProvider inferredCompletionData;
bool inferenceQueued;
- public override bool ExtendsEditor (MonoDevelop.Ide.Gui.Document doc, IEditableTextBuffer editor)
+ public override bool IsValidInContext (DocumentContext context)
{
- return IsFileNameHandled (doc.Name) && base.ExtendsEditor (doc, editor);
+ return IsFileNameHandled (context.Name) && base.IsValidInContext (context);
}
- public override void Initialize ()
+ protected override void Initialize ()
{
base.Initialize ();
XmlEditorOptions.XmlFileAssociationChanged += HandleXmlFileAssociationChanged;
@@ -69,16 +71,16 @@ namespace MonoDevelop.Xml.Editor
XmlSchemaManager.UserSchemaRemoved += UserSchemaRemoved;
SetDefaultSchema ();
- var view = Document.GetContent<MonoDevelop.SourceEditor.SourceEditorView> ();
- if (view != null && string.IsNullOrEmpty (view.Document.MimeType)) {
- view.Document.MimeType = ApplicationXmlMimeType;
- Document.ReparseDocument ();
+ //var view = Document.GetContent<MonoDevelop.SourceEditor.SourceEditorView> ();
+ if (string.IsNullOrEmpty (Editor.MimeType)) {
+ Editor.MimeType = ApplicationXmlMimeType;
+ DocumentContext.ReparseDocument ();
}
}
void HandleXmlFileAssociationChanged (object sender, XmlFileAssociationChangedEventArgs e)
{
- var filename = document.FileName;
+ var filename = DocumentContext.Name;
if (filename != null && filename.ToString ().EndsWith (e.Extension, StringComparison.Ordinal))
SetDefaultSchema ();
}
@@ -89,7 +91,8 @@ namespace MonoDevelop.Xml.Editor
if (!disposed) {
disposed = false;
XmlEditorOptions.XmlFileAssociationChanged -= HandleXmlFileAssociationChanged;
- XmlSchemaManager.UserSchemaAdded -= UserSchemaAdded;
+ XmlSchemaManager.UserSchemaAdded -= UserSchemaAdded;
+
XmlSchemaManager.UserSchemaRemoved -= UserSchemaRemoved;
base.Dispose ();
}
@@ -108,18 +111,23 @@ namespace MonoDevelop.Xml.Editor
protected override void GetElementCompletions (CompletionDataList list)
{
- var path = GetElementPath ();
+ var path = GetElementPath ();
+
if (path.Elements.Count > 0) {
IXmlCompletionProvider schema = FindSchema (path);
if (schema == null)
- schema = inferredCompletionData;
- if (schema != null) {
+ schema = inferredCompletionData;
+
+ if (schema != null) {
+
var completionData = schema.GetChildElementCompletionData (path);
if (completionData != null)
list.AddRange (completionData);
- }
+ }
+
} else if (defaultSchemaCompletionData != null) {
- list.AddRange (defaultSchemaCompletionData.GetElementCompletionData (defaultNamespacePrefix));
+ list.AddRange (defaultSchemaCompletionData.GetElementCompletionData (defaultNamespacePrefix));
+
} else if (inferredCompletionData != null) {
list.AddRange (inferredCompletionData.GetElementCompletionData ());
}
@@ -129,12 +137,15 @@ namespace MonoDevelop.Xml.Editor
protected override CompletionDataList GetAttributeCompletions (IAttributedXObject attributedOb,
Dictionary<string, string> existingAtts)
{
- var path = GetElementPath ();
+ var path = GetElementPath ();
+
if (path.Elements.Count > 0) {
IXmlCompletionProvider schema = FindSchema (path);
if (schema == null)
- schema = inferredCompletionData;
- if (schema != null)
+ schema = inferredCompletionData;
+
+ if (schema != null)
+
return schema.GetAttributeCompletionData (path);
}
return null;
@@ -142,10 +153,13 @@ namespace MonoDevelop.Xml.Editor
protected override CompletionDataList GetAttributeValueCompletions (IAttributedXObject attributedOb, XAttribute att)
{
- var path = GetElementPath ();
+ var path = GetElementPath ();
+
if (path.Elements.Count > 0) {
- var schema = FindSchema (path);
- if (schema != null)
+ var schema = FindSchema (path);
+
+ if (schema != null)
+
return schema.GetAttributeValueCompletionData (path, att.Name.FullName);
}
return null;
@@ -170,47 +184,79 @@ namespace MonoDevelop.Xml.Editor
return FindSchema (XmlSchemaManager.SchemaCompletionDataItems, path);
}
- /// <summary>
- /// Finds the schema given the xml element path.
- /// </summary>
- public XmlSchemaCompletionData FindSchema (IXmlSchemaCompletionDataCollection schemaCompletionDataItems, XmlElementPath path)
- {
- if (path.Elements.Count > 0) {
- string namespaceUri = path.Elements[0].Namespace;
- if (namespaceUri.Length > 0) {
- return schemaCompletionDataItems[namespaceUri];
- } else if (defaultSchemaCompletionData != null) {
-
- // Use the default schema namespace if none
- // specified in a xml element path, otherwise
- // we will not find any attribute or element matches
- // later.
- foreach (QualifiedName name in path.Elements) {
- if (name.Namespace.Length == 0) {
- name.Namespace = defaultSchemaCompletionData.NamespaceUri;
- }
- }
- return defaultSchemaCompletionData;
- }
- }
- return null;
+ /// <summary>
+
+ /// Finds the schema given the xml element path.
+
+ /// </summary>
+
+ public XmlSchemaCompletionData FindSchema (IXmlSchemaCompletionDataCollection schemaCompletionDataItems, XmlElementPath path)
+
+ {
+
+ if (path.Elements.Count > 0) {
+
+ string namespaceUri = path.Elements[0].Namespace;
+
+ if (namespaceUri.Length > 0) {
+
+ return schemaCompletionDataItems[namespaceUri];
+
+ } else if (defaultSchemaCompletionData != null) {
+
+
+
+ // Use the default schema namespace if none
+
+ // specified in a xml element path, otherwise
+
+ // we will not find any attribute or element matches
+
+ // later.
+
+ foreach (QualifiedName name in path.Elements) {
+
+ if (name.Namespace.Length == 0) {
+
+ name.Namespace = defaultSchemaCompletionData.NamespaceUri;
+
+ }
+
+ }
+
+ return defaultSchemaCompletionData;
+
+ }
+
+ }
+
+ return null;
+
}
#endregion
#region Schema resolution
- /// <summary>
- /// Gets the XmlSchemaObject that defines the currently selected xml element or attribute.
- /// </summary>
+ /// <summary>
+
+ /// Gets the XmlSchemaObject that defines the currently selected xml element or attribute.
+
+ /// </summary>
+
/// <param name="currentSchemaCompletionData">This is the schema completion data for the schema currently being
- /// displayed. This can be null if the document is not a schema.</param>
- public XmlSchemaObject GetSchemaObjectSelected (XmlSchemaCompletionData currentSchemaCompletionData)
- {
- // Find element under cursor.
+ /// displayed. This can be null if the document is not a schema.</param>
+
+ public XmlSchemaObject GetSchemaObjectSelected (XmlSchemaCompletionData currentSchemaCompletionData)
+
+ {
+
+ // Find element under cursor.
+
XmlElementPath path = GetElementPath ();
- //attribute name under cursor, if valid
+ //attribute name under cursor, if valid
+
string attributeName = null;
XAttribute xatt = Tracker.Engine.Nodes.Peek (0) as XAttribute;
if (xatt != null) {
@@ -219,173 +265,306 @@ namespace MonoDevelop.Xml.Editor
xattName = GetCompleteName ();
}
attributeName = xattName.FullName;
- }
+ }
+
- // Find schema definition object.
- XmlSchemaCompletionData schemaCompletionData = FindSchema (path);
- XmlSchemaObject schemaObject = null;
+ // Find schema definition object.
+
+ XmlSchemaCompletionData schemaCompletionData = FindSchema (path);
+
+ XmlSchemaObject schemaObject = null;
+
if (schemaCompletionData != null) {
- XmlSchemaElement element = schemaCompletionData.FindElement(path);
- schemaObject = element;
+ XmlSchemaElement element = schemaCompletionData.FindElement(path);
+
+ schemaObject = element;
+
if (element != null) {
if (!string.IsNullOrEmpty (attributeName)) {
- XmlSchemaAttribute attribute = schemaCompletionData.FindAttribute(element, attributeName);
+ XmlSchemaAttribute attribute = schemaCompletionData.FindAttribute(element, attributeName);
+
if (attribute != null) {
- if (currentSchemaCompletionData != null) {
- schemaObject = GetSchemaObjectReferenced (currentSchemaCompletionData, element, attribute);
- } else {
- schemaObject = attribute;
- }
- }
- }
- return schemaObject;
- }
- }
- return null;
- }
-
- /// <summary>
- /// If the attribute value found references another item in the schema
- /// return this instead of the attribute schema object. For example, if the
- /// user can select the attribute value and the code will work out the schema object pointed to by the ref
- /// or type attribute:
- ///
- /// xs:element ref="ref-name"
- /// xs:attribute type="type-name"
- /// </summary>
- /// <returns>
- /// The <paramref name="attribute"/> if no schema object was referenced.
- /// </returns>
- XmlSchemaObject GetSchemaObjectReferenced (XmlSchemaCompletionData currentSchemaCompletionData, XmlSchemaElement element, XmlSchemaAttribute attribute)
- {
- XmlSchemaObject schemaObject = null;
- if (IsXmlSchemaNamespace(element)) {
+ if (currentSchemaCompletionData != null) {
+
+ schemaObject = GetSchemaObjectReferenced (currentSchemaCompletionData, element, attribute);
+
+ } else {
+
+ schemaObject = attribute;
+
+ }
+
+ }
+
+ }
+
+ return schemaObject;
+
+ }
+
+ }
+
+ return null;
+
+ }
+
+ /// <summary>
+
+ /// If the attribute value found references another item in the schema
+
+ /// return this instead of the attribute schema object. For example, if the
+
+ /// user can select the attribute value and the code will work out the schema object pointed to by the ref
+
+ /// or type attribute:
+
+ ///
+
+ /// xs:element ref="ref-name"
+
+ /// xs:attribute type="type-name"
+
+ /// </summary>
+
+ /// <returns>
+
+ /// The <paramref name="attribute"/> if no schema object was referenced.
+
+ /// </returns>
+
+ XmlSchemaObject GetSchemaObjectReferenced (XmlSchemaCompletionData currentSchemaCompletionData, XmlSchemaElement element, XmlSchemaAttribute attribute)
+
+ {
+
+ XmlSchemaObject schemaObject = null;
+
+ if (IsXmlSchemaNamespace(element)) {
+
// Find attribute value.
- //fixme implement
- string attributeValue = "";// XmlParser.GetAttributeValueAtIndex(xml, index);
- if (attributeValue.Length == 0) {
- return attribute;
- }
-
- if (attribute.Name == "ref") {
- schemaObject = FindSchemaObjectReference(attributeValue, currentSchemaCompletionData, element.Name);
- } else if (attribute.Name == "type") {
- schemaObject = FindSchemaObjectType(attributeValue, currentSchemaCompletionData, element.Name);
- }
- }
-
- if (schemaObject != null) {
- return schemaObject;
- }
- return attribute;
- }
-
- /// <summary>
- /// Checks whether the element belongs to the XSD namespace.
- /// </summary>
- static bool IsXmlSchemaNamespace (XmlSchemaElement element)
- {
- XmlQualifiedName qualifiedName = element.QualifiedName;
- if (qualifiedName != null) {
- return XmlSchemaManager.IsXmlSchemaNamespace (qualifiedName.Namespace);
- }
- return false;
- }
-
- /// <summary>
- /// Attempts to locate the reference name in the specified schema.
- /// </summary>
- /// <param name="name">The reference to look up.</param>
- /// <param name="schemaCompletionData">The schema completion data to use to
- /// find the reference.</param>
- /// <param name="elementName">The element to determine what sort of reference it is
- /// (e.g. group, attribute, element).</param>
- /// <returns><see langword="null"/> if no match can be found.</returns>
- XmlSchemaObject FindSchemaObjectReference(string name, XmlSchemaCompletionData schemaCompletionData, string elementName)
- {
- QualifiedName qualifiedName = schemaCompletionData.CreateQualifiedName(name);
- XmlSchemaCompletionData qualifiedNameSchema = FindSchema(qualifiedName.Namespace);
- if (qualifiedNameSchema != null) {
- schemaCompletionData = qualifiedNameSchema;
- }
- switch (elementName) {
- case "element":
- return schemaCompletionData.FindElement(qualifiedName);
- case "attribute":
- return schemaCompletionData.FindAttribute(qualifiedName.Name);
- case "group":
- return schemaCompletionData.FindGroup(qualifiedName.Name);
- case "attributeGroup":
- return schemaCompletionData.FindAttributeGroup(qualifiedName.Name);
- }
- return null;
- }
-
- /// <summary>
- /// Attempts to locate the type name in the specified schema.
- /// </summary>
- /// <param name="name">The type to look up.</param>
- /// <param name="schemaCompletionData">The schema completion data to use to
- /// find the type.</param>
- /// <param name="elementName">The element to determine what sort of type it is
- /// (e.g. group, attribute, element).</param>
- /// <returns><see langword="null"/> if no match can be found.</returns>
- XmlSchemaObject FindSchemaObjectType(string name, XmlSchemaCompletionData schemaCompletionData, string elementName)
- {
- QualifiedName qualifiedName = schemaCompletionData.CreateQualifiedName(name);
- XmlSchemaCompletionData qualifiedNameSchema = FindSchema(qualifiedName.Namespace);
- if (qualifiedNameSchema != null) {
- schemaCompletionData = qualifiedNameSchema;
- }
- switch (elementName) {
- case "element":
- return schemaCompletionData.FindComplexType(qualifiedName);
- case "attribute":
- return schemaCompletionData.FindSimpleType(qualifiedName.Name);
- }
- return null;
+ //fixme implement
+
+ string attributeValue = "";// XmlParser.GetAttributeValueAtIndex(xml, index);
+
+ if (attributeValue.Length == 0) {
+
+ return attribute;
+
+ }
+
+
+
+ if (attribute.Name == "ref") {
+
+ schemaObject = FindSchemaObjectReference(attributeValue, currentSchemaCompletionData, element.Name);
+
+ } else if (attribute.Name == "type") {
+
+ schemaObject = FindSchemaObjectType(attributeValue, currentSchemaCompletionData, element.Name);
+
+ }
+
+ }
+
+
+
+ if (schemaObject != null) {
+
+ return schemaObject;
+
+ }
+
+ return attribute;
+
+ }
+
+ /// <summary>
+
+ /// Checks whether the element belongs to the XSD namespace.
+
+ /// </summary>
+
+ static bool IsXmlSchemaNamespace (XmlSchemaElement element)
+
+ {
+
+ XmlQualifiedName qualifiedName = element.QualifiedName;
+
+ if (qualifiedName != null) {
+
+ return XmlSchemaManager.IsXmlSchemaNamespace (qualifiedName.Namespace);
+
+ }
+
+ return false;
+
+ }
+
+ /// <summary>
+
+ /// Attempts to locate the reference name in the specified schema.
+
+ /// </summary>
+
+ /// <param name="name">The reference to look up.</param>
+
+ /// <param name="schemaCompletionData">The schema completion data to use to
+
+ /// find the reference.</param>
+
+ /// <param name="elementName">The element to determine what sort of reference it is
+
+ /// (e.g. group, attribute, element).</param>
+
+ /// <returns><see langword="null"/> if no match can be found.</returns>
+
+ XmlSchemaObject FindSchemaObjectReference(string name, XmlSchemaCompletionData schemaCompletionData, string elementName)
+
+ {
+
+ QualifiedName qualifiedName = schemaCompletionData.CreateQualifiedName(name);
+
+ XmlSchemaCompletionData qualifiedNameSchema = FindSchema(qualifiedName.Namespace);
+
+ if (qualifiedNameSchema != null) {
+
+ schemaCompletionData = qualifiedNameSchema;
+
+ }
+
+ switch (elementName) {
+
+ case "element":
+
+ return schemaCompletionData.FindElement(qualifiedName);
+
+ case "attribute":
+
+ return schemaCompletionData.FindAttribute(qualifiedName.Name);
+
+ case "group":
+
+ return schemaCompletionData.FindGroup(qualifiedName.Name);
+
+ case "attributeGroup":
+
+ return schemaCompletionData.FindAttributeGroup(qualifiedName.Name);
+
+ }
+
+ return null;
+
+ }
+
+
+
+ /// <summary>
+
+ /// Attempts to locate the type name in the specified schema.
+
+ /// </summary>
+
+ /// <param name="name">The type to look up.</param>
+
+ /// <param name="schemaCompletionData">The schema completion data to use to
+
+ /// find the type.</param>
+
+ /// <param name="elementName">The element to determine what sort of type it is
+
+ /// (e.g. group, attribute, element).</param>
+
+ /// <returns><see langword="null"/> if no match can be found.</returns>
+
+ XmlSchemaObject FindSchemaObjectType(string name, XmlSchemaCompletionData schemaCompletionData, string elementName)
+
+ {
+
+ QualifiedName qualifiedName = schemaCompletionData.CreateQualifiedName(name);
+
+ XmlSchemaCompletionData qualifiedNameSchema = FindSchema(qualifiedName.Namespace);
+
+ if (qualifiedNameSchema != null) {
+
+ schemaCompletionData = qualifiedNameSchema;
+
+ }
+
+ switch (elementName) {
+
+ case "element":
+
+ return schemaCompletionData.FindComplexType(qualifiedName);
+
+ case "attribute":
+
+ return schemaCompletionData.FindSimpleType(qualifiedName.Name);
+
+ }
+
+ return null;
+
}
#endregion
#region Settings handling
- void SetDefaultSchema ()
+ void SetDefaultSchema ()
+
{
- var filename = document.FileName;
+ var filename = DocumentContext.Name;
if (filename == null)
return;
-
+
+
defaultSchemaCompletionData = XmlSchemaManager.GetSchemaCompletionDataForFileName (filename);
if (defaultSchemaCompletionData != null)
inferredCompletionData = null;
else
- QueueInference ();
- defaultNamespacePrefix = XmlSchemaManager.GetNamespacePrefixForFileName (filename);
- }
-
- /// Updates the default schema association since the schema may have been added.
- void UserSchemaAdded (object source, EventArgs e)
+ QueueInference ();
+
+ defaultNamespacePrefix = XmlSchemaManager.GetNamespacePrefixForFileName (filename);
+
+ }
+
+
+
+ /// Updates the default schema association since the schema may have been added.
+
+ void UserSchemaAdded (object source, EventArgs e)
+
{
SetDefaultSchema ();
- }
-
- // Updates the default schema association since the schema may have been removed.
- void UserSchemaRemoved (object source, EventArgs e)
- {
- SetDefaultSchema ();
+ }
+
+
+
+ // Updates the default schema association since the schema may have been removed.
+
+ void UserSchemaRemoved (object source, EventArgs e)
+
+ {
+
+ SetDefaultSchema ();
+
}
#endregion
#region Stylesheet handling
- /// <summary>
- /// Gets or sets the stylesheet associated with this xml file.
- /// </summary>
- public string StylesheetFileName {
- get { return stylesheetFileName; }
- set { stylesheetFileName = value; }
+ /// <summary>
+
+ /// Gets or sets the stylesheet associated with this xml file.
+
+ /// </summary>
+
+ public string StylesheetFileName {
+
+ get { return stylesheetFileName; }
+
+ set { stylesheetFileName = value; }
+
}
#endregion
@@ -430,16 +609,17 @@ namespace MonoDevelop.Xml.Editor
#region Smart indent
- public override bool KeyPress (Gdk.Key key, char keyChar, Gdk.ModifierType modifier)
+ public override bool KeyPress (KeyDescriptor descriptor)
{
bool result;
-
- if (Document.Editor.Options.IndentStyle == IndentStyle.Smart && key == Gdk.Key.Return) {
- result = base.KeyPress (key, keyChar, modifier);
- SmartIndentLine (Editor.Caret.Line);
+
+
+ if (Editor.Options.IndentStyle == IndentStyle.Smart && descriptor.SpecialKey == SpecialKey.Return) {
+ result = base.KeyPress (descriptor);
+ SmartIndentLine (Editor.CaretLine);
return result;
}
- return base.KeyPress (key, keyChar, modifier);
+ return base.KeyPress (descriptor);
}
void SmartIndentLine (int line)
@@ -500,8 +680,10 @@ namespace MonoDevelop.Xml.Editor
[CommandHandler (XmlCommands.CreateSchema)]
public void CreateSchemaCommand ()
{
- try {
- TaskService.Errors.Clear ();
+ try {
+
+ TaskService.Errors.Clear ();
+
string xml = Editor.Text;
using (ProgressMonitor monitor = XmlEditorService.GetMonitor ()) {
XmlDocument doc = XmlEditorService.ValidateWellFormedness (monitor, xml, FileName);
@@ -509,7 +691,8 @@ namespace MonoDevelop.Xml.Editor
return;
monitor.BeginTask (GettextCatalog.GetString ("Creating schema..."), 0);
try {
- string schema = XmlEditorService.CreateSchema (Document, xml);
+ string schema = XmlEditorService.CreateSchema (Editor, xml);
+
string fileName = XmlEditorService.GenerateFileName (FileName, "{0}.xsd");
IdeApp.Workbench.NewDocument (fileName, "application/xml", schema);
monitor.ReportSuccess (GettextCatalog.GetString ("Schema created."));
@@ -518,22 +701,30 @@ namespace MonoDevelop.Xml.Editor
LoggingService.LogError (msg, ex);
monitor.ReportError (msg, ex);
}
- }
- } catch (Exception ex) {
- MessageService.ShowError (ex.Message);
+ }
+
+ } catch (Exception ex) {
+
+ MessageService.ShowError (ex.Message);
+
}
}
[CommandHandler (XmlCommands.OpenStylesheet)]
public void OpenStylesheetCommand ()
- {
- if (!string.IsNullOrEmpty (stylesheetFileName)) {
- try {
- IdeApp.Workbench.OpenDocument (stylesheetFileName, Document.Project);
+ {
+
+ if (!string.IsNullOrEmpty (stylesheetFileName)) {
+
+ try {
+
+ IdeApp.Workbench.OpenDocument (stylesheetFileName, DocumentContext.Project);
+
} catch (Exception ex) {
- MessageService.ShowError ("Could not open document.", ex);
- }
- }
+ LoggingService.LogError ("Could not open document.", ex);
+ MessageService.ShowException (ex, "Could not open document.");
+ }
+ }
}
[CommandUpdateHandler (XmlCommands.OpenStylesheet)]
@@ -546,21 +737,28 @@ namespace MonoDevelop.Xml.Editor
public void GoToSchemaDefinitionCommand ()
{
try {
- //try to resolve the schema
- XmlSchemaCompletionData currentSchemaCompletionData = FindSchemaFromFileName (FileName);
- XmlSchemaObject schemaObject = GetSchemaObjectSelected (currentSchemaCompletionData);
-
- // Open schema if resolved
- if (schemaObject != null && schemaObject.SourceUri != null && schemaObject.SourceUri.Length > 0) {
+ //try to resolve the schema
+
+ XmlSchemaCompletionData currentSchemaCompletionData = FindSchemaFromFileName (FileName);
+
+ XmlSchemaObject schemaObject = GetSchemaObjectSelected (currentSchemaCompletionData);
+
+
+
+ // Open schema if resolved
+
+ if (schemaObject != null && schemaObject.SourceUri != null && schemaObject.SourceUri.Length > 0) {
+
string schemaFileName = schemaObject.SourceUri.Replace ("file:/", String.Empty);
IdeApp.Workbench.OpenDocument (
schemaFileName,
- Document.Project,
+ DocumentContext.Project,
Math.Max (1, schemaObject.LineNumber),
Math.Max (1, schemaObject.LinePosition));
}
} catch (Exception ex) {
- MessageService.ShowError ("Could not open document.", ex);
+ MonoDevelop.Core.LoggingService.LogError ("Could not open document.", ex);
+ MessageService.ShowException (ex, "Could not open document.");
}
}
@@ -571,7 +769,8 @@ namespace MonoDevelop.Xml.Editor
using (ProgressMonitor monitor = XmlEditorService.GetMonitor()) {
if (IsSchema)
XmlEditorService.ValidateSchema (monitor, Editor.Text, FileName);
- else
+ else
+
XmlEditorService.ValidateXml (monitor, Editor.Text, FileName);
}
}
@@ -579,17 +778,22 @@ namespace MonoDevelop.Xml.Editor
[CommandHandler (XmlCommands.AssignStylesheet)]
public void AssignStylesheetCommand ()
{
- // Prompt user for filename.
- string fileName = XmlEditorService.BrowseForStylesheetFile ();
- if (!string.IsNullOrEmpty (stylesheetFileName))
+ // Prompt user for filename.
+
+ string fileName = XmlEditorService.BrowseForStylesheetFile ();
+
+ if (!string.IsNullOrEmpty (stylesheetFileName))
+
stylesheetFileName = fileName;
}
[CommandHandler (XmlCommands.RunXslTransform)]
public void RunXslTransformCommand ()
{
- if (string.IsNullOrEmpty (stylesheetFileName)) {
- stylesheetFileName = XmlEditorService.BrowseForStylesheetFile ();
+ if (string.IsNullOrEmpty (stylesheetFileName)) {
+
+ stylesheetFileName = XmlEditorService.BrowseForStylesheetFile ();
+
if (string.IsNullOrEmpty (stylesheetFileName))
return;
}
@@ -616,7 +820,7 @@ namespace MonoDevelop.Xml.Editor
string newFileName = XmlEditorService.GenerateFileName (FileName, "-transformed{0}.xml");
monitor.BeginTask (GettextCatalog.GetString ("Executing transform..."), 1);
- using (XmlTextWriter output = XmlEditorService.CreateXmlTextWriter(Document)) {
+ using (XmlTextWriter output = XmlEditorService.CreateXmlTextWriter(Editor)) {
xslt.Transform (doc, null, output);
IdeApp.Workbench.NewDocument (
newFileName, "application/xml", output.ToString ());
@@ -626,19 +830,24 @@ namespace MonoDevelop.Xml.Editor
} catch (Exception ex) {
string msg = GettextCatalog.GetString ("Could not run transform.");
monitor.ReportError (msg, ex);
- monitor.EndTask ();
+ monitor.EndTask ();
+
}
}
}
- string GetFileContent (string fileName)
+ string GetFileContent (string fileName)
+
{
- MonoDevelop.Projects.Text.IEditableTextFile tf =
- MonoDevelop.Ide.TextFileProvider.Instance.GetEditableTextFile (fileName);
+ var tf =
+ MonoDevelop.Ide.TextFileProvider.Instance.GetReadOnlyTextEditorData (fileName);
if (tf != null)
- return tf.Text;
- System.IO.StreamReader reader = new System.IO.StreamReader (fileName, true);
- return reader.ReadToEnd();
+ return tf.Text;
+
+ System.IO.StreamReader reader = new System.IO.StreamReader (fileName, true);
+
+ return reader.ReadToEnd();
+
}
#endregion
@@ -650,7 +859,7 @@ namespace MonoDevelop.Xml.Editor
return;
if (inferredCompletionData == null
|| (doc.LastWriteTimeUtc - inferredCompletionData.TimeStampUtc).TotalSeconds >= 5
- && doc.Errors.Count <= inferredCompletionData.ErrorCount)
+ && doc.GetErrorsAsync().Result.Count <= inferredCompletionData.ErrorCount)
{
inferenceQueued = true;
System.Threading.ThreadPool.QueueUserWorkItem (delegate {
@@ -658,7 +867,7 @@ namespace MonoDevelop.Xml.Editor
InferredXmlCompletionProvider newData = new InferredXmlCompletionProvider ();
newData.Populate (doc.XDocument);
newData.TimeStampUtc = DateTime.UtcNow;
- newData.ErrorCount = doc.Errors.Count;
+ newData.ErrorCount = doc.GetErrorsAsync().Result.Count;
this.inferenceQueued = false;
this.inferredCompletionData = newData;
} catch (Exception ex) {