Beispiel #1
0
        void SetLocationTextData(Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
        {
            CellRendererText cellRendererText = (CellRendererText)cell;
            Change           change           = store.GetValue(iter, objColumn) as Change;

            cellRendererText.Visible = (bool)store.GetValue(iter, statusVisibleColumn);
            TextReplaceChange replaceChange = change as TextReplaceChange;

            if (replaceChange == null)
            {
                cellRendererText.Text = "";
                return;
            }

            var doc = TextEditorFactory.CreateNewDocument();

            doc.Text = TextFileUtility.ReadAllText(replaceChange.FileName);
            var loc = doc.OffsetToLocation(replaceChange.Offset);

            string text = string.Format(GettextCatalog.GetString("(Line:{0}, Column:{1})"), loc.Line, loc.Column);

            if (treeviewPreview.Selection.IterIsSelected(iter))
            {
                cellRendererText.Text = text;
            }
            else
            {
                var color = Style.Text(StateType.Insensitive);
                var c     = string.Format("#{0:X02}{1:X02}{2:X02}", color.Red / 256, color.Green / 256, color.Blue / 256);
                cellRendererText.Markup = "<span foreground=\"" + c + "\">" + text + "</span>";
            }
        }
Beispiel #2
0
        void RequestPopup(Xwt.Rectangle rect)
        {
            var token = popupSrc.Token;

            Task.Run(async delegate {
                try {
                    foreach (var op in await codeAction.GetPreviewOperationsAsync(token))
                    {
                        if (!(op is ApplyChangesOperation ac))
                        {
                            continue;
                        }
                        var changedDocument = ac.ChangedSolution.GetDocument(documentContext.AnalysisDocument.Id);

                        var changedText       = await changedDocument.GetTextAsync(token);
                        var changedTextSource = new StringTextSource(changedText.ToString());
                        changedTextDocument   = TextEditorFactory.CreateNewDocument(changedTextSource, editor.FileName);

                        try {
                            var processor = new DiffProcessor(editor, changedTextDocument);
                            return(processor.Process());
                        } catch (Exception e) {
                            LoggingService.LogError("Error while getting preview list diff.", e);
                        }
                    }
                } catch (OperationCanceledException) { }

                return(new ProcessResult());
            }).ContinueWith(t => {
Beispiel #3
0
        internal async void RequestPopup(Xwt.Rectangle rect)
        {
            var token = popupSrc.Token;

            diff = await Task.Run(async delegate {
                try {
                    foreach (var op in await codeAction.GetPreviewOperationsAsync(token))
                    {
                        var ac = op as ApplyChangesOperation;
                        if (ac == null)
                        {
                            continue;
                        }
                        var changedDocument = ac.ChangedSolution.GetDocument(documentContext.AnalysisDocument.Id);

                        changedTextDocument = TextEditorFactory.CreateNewDocument(new StringTextSource((await changedDocument.GetTextAsync(token)).ToString()), editor.FileName);
                        try {
                            var list = new List <DiffHunk> (editor.GetDiff(changedTextDocument, new DiffOptions(false, true)));
                            if (list.Count > 0)
                            {
                                return(list);
                            }
                        } catch (Exception e) {
                            LoggingService.LogError("Error while getting preview list diff.", e);
                        }
                    }
                } catch (OperationCanceledException) {}
                return(new List <DiffHunk> ());
            });

            if (diff.Count > 0 && !token.IsCancellationRequested)
            {
                ShowPopup(rect, PopupPosition.Left);
            }
        }
Beispiel #4
0
        Import ParseImport(
            HashSet <string> importedFiles, Import import, string projectPath,
            PropertyValueCollector propVals, TaskMetadataBuilder taskBuilder, MSBuildSchemaProvider schemaProvider,
            CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            var           xmlParser = new XmlParser(new XmlRootState(), true);
            ITextDocument textDoc;

            try {
                textDoc = TextEditorFactory.CreateNewDocument(import.Filename, MSBuildTextEditorExtension.MSBuildMimeType);
                xmlParser.Parse(textDoc.CreateReader());
            } catch (Exception ex) {
                LoggingService.LogError("Unhandled error parsing xml document", ex);
                return(import);
            }

            var doc = xmlParser.Nodes.GetRoot();

            import.Document = new MSBuildDocument(import.Filename, false);
            import.Document.Build(
                doc, textDoc, RuntimeInformation, propVals, taskBuilder,
                (imp, sdk) => ResolveImport(importedFiles, null, projectPath, import.Filename, imp, sdk, propVals, taskBuilder, schemaProvider, token)
                );

            import.Document.Schema = schemaProvider.GetSchema(import.Filename, import.Sdk);

            return(import);
        }
Beispiel #5
0
        public override string FormatPlainText(int insertionOffset, string text, byte [] copyData)
        {
            var result = engine.FormatPlainText(indent.Editor, insertionOffset, text, copyData);

            if (DefaultSourceEditorOptions.Instance.OnTheFlyFormatting)
            {
                var tree = indent.DocumentContext.AnalysisDocument.GetSyntaxTreeAsync().WaitAndGetResult(default(CancellationToken));
                tree = tree.WithChangedText(tree.GetText().WithChanges(new TextChange(new TextSpan(insertionOffset, 0), text)));

                var insertedChars = text.Length;
                var startLine     = indent.Editor.GetLineByOffset(insertionOffset);

                var policy    = indent.DocumentContext.GetFormattingPolicy();
                var optionSet = policy.CreateOptions(indent.Editor.Options);
                var span      = new TextSpan(insertionOffset, insertedChars);

                var rules = new List <IFormattingRule> {
                    new PasteFormattingRule()
                };
                rules.AddRange(Formatter.GetDefaultFormattingRules(indent.DocumentContext.AnalysisDocument));

                var root    = tree.GetRoot();
                var changes = Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(span), indent.DocumentContext.RoslynWorkspace, optionSet, rules, default(CancellationToken));
                var doc     = TextEditorFactory.CreateNewDocument();
                doc.Text = text;
                doc.ApplyTextChanges(changes.Where(c => c.Span.Start - insertionOffset < text.Length && c.Span.Start - insertionOffset >= 0).Select(delegate(TextChange c) {
                    return(new TextChange(new TextSpan(c.Span.Start - insertionOffset, c.Span.Length), c.NewText));
                }));
                return(doc.Text);
            }

            return(result);
        }
Beispiel #6
0
        List <(int Offset, int Length, ReferenceUsage Usage)> FindReferences(string docString, MSBuildReferenceKind kind, object reference)
        {
            string filename = "test.csproj";

            var textDoc = TextEditorFactory.CreateNewDocument(new StringTextSource(docString), filename, MSBuildTextEditorExtension.MSBuildMimeType);

            var xmlParser = new XmlParser(new XmlRootState(), true);

            xmlParser.Parse(new StringReader(docString));
            var xdoc = xmlParser.Nodes.GetRoot();


            var doc = MSBuildTestHelpers.CreateEmptyDocument();
            var sb  = new MSBuildSchemaBuilder(true, null, new PropertyValueCollector(false), null, null);

            sb.Run(xdoc, filename, textDoc, doc);

            var collector = MSBuildReferenceCollector.Create(new MSBuildResolveResult {
                ReferenceKind = kind,
                Reference     = reference,
            });

            collector.Run(xdoc, filename, textDoc, doc);
            return(collector.Results);
        }
Beispiel #7
0
        async System.Threading.Tasks.Task <IReadOnlyList <Projection> > GenerateProjections(RazorCSharpParsedDocument razorDocument, Ide.TypeSystem.ParseOptions options, CancellationToken cancellationToken = default(CancellationToken))
        {
            var code = razorDocument.PageInfo.CSharpCode;

            if (string.IsNullOrEmpty(code))
            {
                return(new List <Projection> ());
            }
            var doc             = TextEditorFactory.CreateNewDocument(new StringTextSource(code), razorDocument.PageInfo.ParsedDocument.FileName, "text/x-csharp");
            var currentMappings = razorDocument.PageInfo.GeneratorResults.DesignTimeLineMappings;
            var segments        = new List <ProjectedSegment> ();

            foreach (var map in currentMappings)
            {
                string pattern = "#line " + map.Key + " ";
                var    idx     = razorDocument.PageInfo.CSharpCode.IndexOf(pattern, StringComparison.Ordinal);
                if (idx < 0)
                {
                    continue;
                }
                var line   = doc.GetLineByOffset(idx);
                var offset = line.NextLine.Offset + map.Value.StartGeneratedColumn - 1;

                var seg = new ProjectedSegment(map.Value.StartOffset.Value, offset, map.Value.CodeLength);
                segments.Add(seg);
            }

            var projections = new List <Projection> ();

            projections.Add(new Projection(doc, segments));
            return(projections);
        }
        async void RequestPopup(Xwt.Rectangle rect)
        {
            var token = popupSrc.Token;

            diff = await Task.Run(async delegate {
                try {
                    foreach (var op in await codeAction.GetPreviewOperationsAsync(token))
                    {
                        var ac = op as ApplyChangesOperation;
                        if (ac == null)
                        {
                            continue;
                        }
                        var changedDocument = ac.ChangedSolution.GetDocument(documentContext.AnalysisDocument.Id);

                        changedTextDocument = TextEditorFactory.CreateNewDocument(new StringTextSource((await changedDocument.GetTextAsync(token)).ToString()), editor.FileName);
                        try {
                            var list = new List <DiffHunk> (editor.GetDiff(changedTextDocument, new DiffOptions(false, true)));
                            if (list.Count > 0)
                            {
                                return(list);
                            }
                        } catch (Exception e) {
                            LoggingService.LogError("Error while getting preview list diff.", e);
                        }
                    }
                } catch (OperationCanceledException) {}
                return(new List <DiffHunk> ());
            });

            if (diff.Count > 0 && !token.IsCancellationRequested)
            {
                var pos = PopupPosition.Left;
                if (Platform.IsMac)
                {
                    var screenRect = GtkUtil.ToScreenCoordinates(IdeApp.Workbench.RootWindow, IdeApp.Workbench.RootWindow.GdkWindow, rect.ToGdkRectangle());
                    var geometry   = Screen.GetUsableMonitorGeometry(Screen.GetMonitorAtPoint(screenRect.X, screenRect.Y));
                    var request    = SizeRequest();
                    if (screenRect.X - geometry.X < request.Width)
                    {
                        pos = PopupPosition.Top;
                        if (geometry.Bottom - screenRect.Bottom < request.Height)
                        {
                            pos = PopupPosition.Bottom;
                        }
                    }
                    else
                    {
                        pos = PopupPosition.Right;
                    }
                }
                ShowPopup(rect, pos);
            }
        }
Beispiel #9
0
        static string StripDoubleBlankLines(string content)
        {
            var doc = TextEditorFactory.CreateNewDocument(new StringTextSource(content), "a.cs");

            for (int i = 1; i + 1 <= doc.LineCount; i++)
            {
                if (IsBlankLine(doc, i) && IsBlankLine(doc, i + 1))
                {
                    doc.RemoveText(doc.GetLine(i).SegmentIncludingDelimiter);
                    i--;
                    continue;
                }
            }
            return(doc.Text);
        }
Beispiel #10
0
        string RemoveIndent(string text, string indent)
        {
            var doc = TextEditorFactory.CreateNewDocument();

            doc.Text = text;
            var result = new StringBuilder();

            foreach (var line in doc.GetLines())
            {
                string curLineIndent = line.GetIndentation(doc);
                int    offset        = Math.Min(curLineIndent.Length, indent.Length);
                result.Append(doc.GetTextBetween(line.Offset + offset, line.EndOffsetIncludingDelimiter));
            }
            return(result.ToString());
        }
Beispiel #11
0
            public override Stream CreateFileContent(SolutionFolderItem policyParent, Project project, string language, string fileName, string identifier)
            {
                if (Outer.FormatCode)
                {
                    return(base.CreateFileContent(policyParent, project, language, fileName, identifier));
                }

                var    model = GetTagModel(policyParent, project, language, identifier, fileName);
                string text  = CreateContent(project, model.OverrideTags, language);

                text = ProcessContent(text, model);
                var memoryStream = new MemoryStream();

                byte[] preamble = Encoding.UTF8.GetPreamble();
                memoryStream.Write(preamble, 0, preamble.Length);
                if (AddStandardHeader)
                {
                    string header = StandardHeaderService.GetHeader(policyParent, fileName, true);
                    byte[] bytes  = Encoding.UTF8.GetBytes(header);
                    memoryStream.Write(bytes, 0, bytes.Length);
                }

                var textDocument = TextEditorFactory.CreateNewDocument();

                //var textDocument = new TextDocument ();
                textDocument.Text = text;
                var    textStylePolicy = (policyParent == null) ? PolicyService.GetDefaultPolicy <TextStylePolicy> ("text/plain") : policyParent.Policies.Get <TextStylePolicy> ("text/plain");
                string eolMarker       = TextStylePolicy.GetEolMarker(textStylePolicy.EolMarker);

                byte[] eol    = Encoding.UTF8.GetBytes(eolMarker);
                string indent = (!textStylePolicy.TabsToSpaces) ? null : new string (' ', textStylePolicy.TabWidth);

                foreach (var current in textDocument.GetLines())
                {
                    string line = textDocument.GetTextAt(current.Offset, current.Length);
                    if (indent != null)
                    {
                        line = line.Replace("	", indent);
                    }
                    byte[] bytes = Encoding.UTF8.GetBytes(line);
                    memoryStream.Write(bytes, 0, bytes.Length);
                    memoryStream.Write(eol, 0, eol.Length);
                }
                memoryStream.Position = 0;
                return(memoryStream);
            }
Beispiel #12
0
        string Reindent(string text, string indent)
        {
            var doc = TextEditorFactory.CreateNewDocument();

            doc.Text = text;
            var result = new StringBuilder();

            foreach (var line in doc.GetLines())
            {
                if (result.Length > 0)
                {
                    result.Append(indent);
                }
                result.Append(doc.GetTextAt(line.SegmentIncludingDelimiter));
            }
            return(result.ToString());
        }
Beispiel #13
0
        internal static MonoDevelop.Ide.FindInFiles.SearchResult GetJumpTypePartSearchResult(Microsoft.CodeAnalysis.ISymbol part, Microsoft.CodeAnalysis.Location location)
        {
            var provider = new MonoDevelop.Ide.FindInFiles.FileProvider(location.SourceTree.FilePath);
            var doc      = TextEditorFactory.CreateNewDocument();

            doc.Text = provider.ReadString().ReadToEnd();
            int position = location.SourceSpan.Start;

            while (position + part.Name.Length < doc.Length)
            {
                if (doc.GetTextAt(position, part.Name.Length) == part.Name)
                {
                    break;
                }
                position++;
            }
            return(new MonoDevelop.Ide.FindInFiles.SearchResult(provider, position, part.Name.Length));
        }
        static string StripHeaderAndBlankLines(string text, CodeDomProvider provider)
        {
            var doc = TextEditorFactory.CreateNewDocument();

            doc.Text = text;
            int realStartLine = 0;

            for (int i = 1; i <= doc.LineCount; i++)
            {
                string lineText = doc.GetTextAt(doc.GetLine(i));
                // Microsoft.NET generates "auto-generated" tags where Mono generates "autogenerated" tags.
                if (lineText.Contains("</autogenerated>") || lineText.Contains("</auto-generated>"))
                {
                    realStartLine = i + 2;
                    break;
                }
            }

            // The Mono provider inserts additional blank lines, so strip them out
            // But blank lines might actually be significant in other languages.
            // We reformat the C# generated output to the user's coding style anyway, but the reformatter preserves blank lines
            if (provider is Microsoft.CSharp.CSharpCodeProvider)
            {
                bool previousWasBlank = false;
                for (int i = 1; i <= doc.LineCount; i++)
                {
                    var  line = doc.GetLine(i);
                    bool isBlank, isBracket;
                    CheckLine(doc, line, out isBlank, out isBracket);
                    if (isBlank && previousWasBlank && line.LengthIncludingDelimiter > 0)
                    {
                        doc.RemoveText(line.Offset, line.LengthIncludingDelimiter);
                        i--;
                    }
                    previousWasBlank = isBlank || isBracket;
                }
            }

            int offset = doc.GetLine(realStartLine).Offset;

            return(doc.GetTextAt(offset, doc.Length - offset));
        }
Beispiel #15
0
        void SetDiffCellData(Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
        {
            try {
                CellRendererDiff cellRendererDiff = (CellRendererDiff)cell;
                Change           change           = store.GetValue(iter, objColumn) as Change;
                cellRendererDiff.Visible = !(bool)store.GetValue(iter, statusVisibleColumn);
                if (change == null || !cellRendererDiff.Visible)
                {
                    cellRendererDiff.InitCell(treeviewPreview, false, "", "");
                    return;
                }
                TextReplaceChange replaceChange = change as TextReplaceChange;
                if (replaceChange == null)
                {
                    return;
                }

                var openDocument     = IdeApp.Workbench.GetDocument(replaceChange.FileName);
                var originalDocument = TextEditorFactory.CreateNewDocument();
                originalDocument.FileName = replaceChange.FileName;
                if (openDocument == null)
                {
                    originalDocument.Text = TextFileUtility.ReadAllText(replaceChange.FileName);
                }
                else
                {
                    originalDocument.Text = openDocument.Editor.Text;
                }

                var changedDocument = TextEditorFactory.CreateNewDocument();
                changedDocument.FileName = replaceChange.FileName;
                changedDocument.Text     = originalDocument.Text;

                changedDocument.ReplaceText(replaceChange.Offset, replaceChange.RemovedChars, replaceChange.InsertedText);

                string diffString = originalDocument.GetDiffAsString(changedDocument);

                cellRendererDiff.InitCell(treeviewPreview, true, diffString, replaceChange.FileName);
            } catch (Exception e) {
                Console.WriteLine(e);
            }
        }
Beispiel #16
0
        static string StripHeader(string content)
        {
            var doc = TextEditorFactory.CreateNewDocument(new StringTextSource(content), "");

            while (true)
            {
                string lineText = doc.GetLineText(1);
                if (lineText == null)
                {
                    break;
                }
                if (lineText.StartsWith("//", StringComparison.Ordinal))
                {
                    doc.RemoveText(doc.GetLine(1).SegmentIncludingDelimiter);
                    continue;
                }
                break;
            }
            return(doc.Text);
        }
        public void TestUpdatingProjections()
        {
            var data = new MonoDevelopWorkspace.ProjectionData();

            var projections = new List <Projection> ();
            // Using a real document from the tests dir
            var document = TextEditorFactory.CreateNewDocument("GitIgnore.txt");

            projections.Add(new Projection(document, Array.Empty <ProjectedSegment> ()));

            var initial = new MonoDevelopWorkspace.ProjectionEntry {
                File        = new MonoDevelop.Projects.ProjectFile("name"),
                Projections = projections,
            };

            data.AddProjectionEntry(initial);

            data.UpdateProjectionEntry(initial.File, new List <Projection> ());

            var(projectionFromMap, filePathFromMap) = data.Get("GitIgnore.txt");
            Assert.IsNull(projectionFromMap);
        }
Beispiel #18
0
        public static void FindReferences(Func <MSBuildReferenceCollector> createCollector, MSBuildRootDocument doc)
        {
            var monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, true);

            var tasks = new List <Task> ();

            foreach (var import in doc.GetDescendentImports())
            {
                if (!import.IsResolved || !File.Exists(import.Filename))
                {
                    continue;
                }
                tasks.Add(Task.Run(() => {
                    try {
                        var xmlParser = new XmlParser(new XmlRootState(), true);
                        var textDoc   = TextEditorFactory.CreateNewDocument(import.Filename, MSBuildTextEditorExtension.MSBuildMimeType);
                        xmlParser.Parse(textDoc.CreateReader());
                        var xdoc = xmlParser.Nodes.GetRoot();
                        FindReferences(createCollector(), monitor, import.Filename, xdoc, textDoc, doc);
                    } catch (Exception ex) {
                        monitor.ReportError($"Error searching file {Path.GetFileName (import.Filename)}", ex);
                        LoggingService.LogError($"Error searching MSBuild file {import.Filename}", ex);
                    }
                }));
            }

            tasks.Add(Task.Run(() => {
                try {
                    var textDoc = TextEditorFactory.CreateNewDocument(doc.Text, doc.Filename, MSBuildTextEditorExtension.MSBuildMimeType);
                    FindReferences(createCollector(), monitor, doc.Filename, doc.XDocument, textDoc, doc);
                } catch (Exception ex) {
                    monitor.ReportError($"Error searching file {Path.GetFileName (doc.Filename)}", ex);
                    LoggingService.LogError($"Error searching MSBuild file {doc.Filename}", ex);
                }
            }));

            Task.WhenAll(tasks).ContinueWith(t => monitor?.Dispose());
        }
        // Returns a stream with the content of the file.
        // project and language parameters are optional
        public virtual async Task <Stream> CreateFileContentAsync(SolutionFolderItem policyParent, Project project, string language, string fileName, string identifier)
        {
            var model = CombinedTagModel.GetTagModel(ProjectTagModel, policyParent, project, language, identifier, fileName);

            //HACK: for API compat, CreateContent just gets the override, not the base model
            // but ProcessContent gets the entire model
            string content = CreateContent(project, model.OverrideTags, language);

            content = ProcessContent(content, model);

            string mime      = DesktopService.GetMimeTypeForUri(fileName);
            var    formatter = !string.IsNullOrEmpty(mime) ? CodeFormatterService.GetFormatter(mime) : null;

            if (formatter != null)
            {
                var formatted = formatter.FormatText(policyParent != null ? policyParent.Policies : null, content);
                if (formatted != null)
                {
                    content = formatted;
                }
            }

            var             ms         = new MemoryStream();
            Encoding        encoding   = null;
            TextStylePolicy textPolicy = policyParent != null?policyParent.Policies.Get <TextStylePolicy> (mime ?? "text/plain")
                                             : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> (mime ?? "text/plain");

            string eolMarker = TextStylePolicy.GetEolMarker(textPolicy.EolMarker);

            var ctx = await EditorConfigService.GetEditorConfigContext(fileName);

            if (ctx != null)
            {
                ctx.CurrentConventions.UniversalConventions.TryGetEncoding(out encoding);
                if (ctx.CurrentConventions.UniversalConventions.TryGetLineEnding(out string lineEnding))
                {
                    eolMarker = lineEnding;
                }
            }
            if (encoding == null)
            {
                encoding = System.Text.Encoding.UTF8;
            }
            var bom = encoding.GetPreamble();

            if (bom != null && bom.Length > 0)
            {
                ms.Write(bom, 0, bom.Length);
            }

            byte[] data;
            if (AddStandardHeader)
            {
                string header = StandardHeaderService.GetHeader(policyParent, fileName, true);
                data = encoding.GetBytes(header);
                ms.Write(data, 0, data.Length);
            }

            var doc = TextEditorFactory.CreateNewDocument();

            doc.Text = content;


            byte[] eolMarkerBytes = encoding.GetBytes(eolMarker);

            var           tabToSpaces = textPolicy.TabsToSpaces? new string (' ', textPolicy.TabWidth) : null;
            IDocumentLine lastLine    = null;

            foreach (var line in doc.GetLines())
            {
                var lineText = doc.GetTextAt(line.Offset, line.Length);
                if (tabToSpaces != null)
                {
                    lineText = lineText.Replace("\t", tabToSpaces);
                }
                if (line.LengthIncludingDelimiter > 0)
                {
                    data = encoding.GetBytes(lineText);
                    ms.Write(data, 0, data.Length);
                    ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length);
                }
                lastLine = line;
            }
            if (ctx != null && lastLine != null && lastLine.Length > 0)
            {
                if (ctx.CurrentConventions.UniversalConventions.TryGetRequireFinalNewline(out bool requireNewLine))
                {
                    if (requireNewLine)
                    {
                        ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length);
                    }
                }
            }

            ms.Position = 0;
            return(ms);
        }
Beispiel #20
0
        public static MSBuildRootDocument Parse(
            string filename, ITextSource textSource, MSBuildRootDocument previous,
            MSBuildSchemaProvider schemaProvider, IRuntimeInformation runtimeInfo,
            CancellationToken token)
        {
            var xmlParser = new XmlParser(new XmlRootState(), true);

            try {
                xmlParser.Parse(textSource.CreateReader());
            } catch (Exception ex) {
                LoggingService.LogError("Unhandled error parsing xml document", ex);
            }

            var xdocument = xmlParser.Nodes.GetRoot();

            if (xdocument != null && xdocument.RootElement != null)
            {
                if (!xdocument.RootElement.IsEnded)
                {
                    xdocument.RootElement.End(xmlParser.Location);
                }
            }

            //FIXME: unfortunately the XML parser's regions only have line+col locations, not offsets
            //so we need to create an ITextDocument to extract tag bodies
            //we should fix this by changing the parser to use offsets for the tag locations
            ITextDocument textDoc = textSource as ITextDocument
                                    ?? TextEditorFactory.CreateNewDocument(textSource, filename, MSBuildTextEditorExtension.MSBuildMimeType);

            var propVals = new PropertyValueCollector(true);

            string projectPath = filename;

            var doc = new MSBuildRootDocument(filename);

            doc.XDocument          = xdocument;
            doc.Text               = textDoc;
            doc.RuntimeInformation = runtimeInfo;
            doc.Errors.AddRange(xmlParser.Errors);

            var importedFiles = new HashSet <string> (StringComparer.OrdinalIgnoreCase);

            importedFiles.Add(filename);

            var taskBuilder = new TaskMetadataBuilder(doc);

            try {
                doc.Build(
                    xdocument, textDoc, runtimeInfo, propVals, taskBuilder,
                    (imp, sdk) => doc.ResolveImport(importedFiles, previous, projectPath, filename, imp, sdk, propVals, taskBuilder, schemaProvider, token)
                    );
            } catch (Exception ex) {
                LoggingService.LogError("Error building document", ex);
            }

            try {
                var binpath = doc.RuntimeInformation.GetBinPath();
                foreach (var t in Directory.GetFiles(binpath, "*.tasks"))
                {
                    doc.LoadTasks(importedFiles, previous, t, propVals, taskBuilder, schemaProvider, token);
                }
                foreach (var t in Directory.GetFiles(binpath, "*.overridetasks"))
                {
                    doc.LoadTasks(importedFiles, previous, t, propVals, taskBuilder, schemaProvider, token);
                }
            } catch (Exception ex) {
                LoggingService.LogError("Error resolving tasks", ex);
            }


            try {
                if (previous != null)
                {
                    // try to recover some values that may have been collected from the imports, as they
                    // will not have been re-evaluated
                    var fx = previous.Frameworks.FirstOrDefault();
                    if (fx != null)
                    {
                        propVals.Collect("TargetFramework", fx.GetShortFolderName());
                        propVals.Collect("TargetFrameworkVersion", FrameworkInfoProvider.FormatDisplayVersion(fx.Version));
                        propVals.Collect("TargetFrameworkIdentifier", fx.Framework);
                    }
                }
                doc.Frameworks = propVals.GetFrameworks();
            } catch (Exception ex) {
                LoggingService.LogError("Error determining project framework", ex);
                doc.Frameworks = new List <NuGetFramework> ();
            }

            try {
                doc.Schema = previous?.Schema ?? schemaProvider.GetSchema(filename, null);
            } catch (Exception ex) {
                LoggingService.LogError("Error loading schema", ex);
            }

            try {
                //this has to run in a second pass so that it runs after all the schemas are loaded
                var validator = new MSBuildDocumentValidator();
                validator.Run(doc.XDocument, filename, textDoc, doc);
            } catch (Exception ex) {
                LoggingService.LogError("Error in validation", ex);
            }

            return(doc);
        }
Beispiel #21
0
        public TemplateResult FillVariables(TemplateContext context)
        {
            var    expansion  = CodeTemplateService.GetExpansionObject(this);
            var    result     = new TemplateResult();
            var    sb         = new StringBuilder();
            int    lastOffset = 0;
            string code       = context.Editor.FormatString(context.InsertPosition, context.TemplateCode);

            result.TextLinks = new List <TextLink> ();
            foreach (System.Text.RegularExpressions.Match match in variableRegEx.Matches(code))
            {
                string name = match.Groups [1].Value;
                sb.Append(code, lastOffset, match.Index - lastOffset);
                lastOffset = match.Index + match.Length;
                if (string.IsNullOrEmpty(name))                    // $$ is interpreted as $
                {
                    sb.Append("$");
                }
                else if (name == "end")
                {
                    result.CaretEndOffset = sb.Length;
                }
                else if (name == "selected")
                {
                    if (!string.IsNullOrEmpty(context.SelectedText))
                    {
                        string indent    = GetIndent(sb);
                        string selection = Reindent(context.SelectedText, indent);
                        sb.Append(selection);
                    }
                }
                if (!variableDecarations.ContainsKey(name))
                {
                    continue;
                }
                var  link  = result.TextLinks.Find(l => l.Name == name);
                bool isNew = link == null;
                if (isNew)
                {
                    link = new TextLink(name);
                    if (!string.IsNullOrEmpty(variableDecarations [name].ToolTip))
                    {
                        link.Tooltip = GettextCatalog.GetString(variableDecarations [name].ToolTip);
                    }
                    link.Values = new CodeTemplateListDataProvider(variableDecarations [name].Values);
                    if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                    {
                        link.Values = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    }
                    result.TextLinks.Add(link);
                }
                link.IsEditable   = variableDecarations [name].IsEditable;
                link.IsIdentifier = variableDecarations [name].IsIdentifier;
                if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                {
                    var functionResult = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    if (functionResult != null && functionResult.Count > 0)
                    {
                        string s = (string)functionResult [functionResult.Count - 1];
                        if (s == null)
                        {
                            if (variableDecarations.ContainsKey(name))
                            {
                                s = variableDecarations [name].Default;
                            }
                        }
                        if (s != null)
                        {
                            link.AddLink(new TextSegment(sb.Length, s.Length));
                            if (isNew)
                            {
                                link.GetStringFunc = delegate(Func <string, string> callback) {
                                    return(expansion.RunFunction(context, callback, variableDecarations [name].Function));
                                };
                            }
                            sb.Append(s);
                        }
                    }
                    else
                    {
                        AddDefaultValue(sb, link, name);
                    }
                }
                else
                {
                    AddDefaultValue(sb, link, name);
                }
            }
            sb.Append(code, lastOffset, code.Length - lastOffset);

            // format & indent template code
            var data = TextEditorFactory.CreateNewDocument();

            data.Text         = sb.ToString();
            data.TextChanged += delegate(object sender, MonoDevelop.Core.Text.TextChangeEventArgs e) {
                int delta = e.InsertionLength - e.RemovalLength;

                foreach (var link in result.TextLinks)
                {
                    link.Links = link.Links.AdjustSegments(e).ToList();
                }
                if (result.CaretEndOffset > e.Offset)
                {
                    result.CaretEndOffset += delta;
                }
            };

            IndentCode(data, context.LineIndent);
            result.Code = data.Text;
            return(result);
        }
        // Returns a stream with the content of the file.
        // project and language parameters are optional
        public virtual Stream CreateFileContent(SolutionFolderItem policyParent, Project project, string language, string fileName, string identifier)
        {
            var model = CombinedTagModel.GetTagModel(ProjectTagModel, policyParent, project, language, identifier, fileName);

            //HACK: for API compat, CreateContent just gets the override, not the base model
            // but ProcessContent gets the entire model
            string content = CreateContent(project, model.OverrideTags, language);

            content = ProcessContent(content, model);

            string mime      = DesktopService.GetMimeTypeForUri(fileName);
            var    formatter = !string.IsNullOrEmpty(mime) ? CodeFormatterService.GetFormatter(mime) : null;

            if (formatter != null)
            {
                var formatted = formatter.FormatText(policyParent != null ? policyParent.Policies : null, content);
                if (formatted != null)
                {
                    content = formatted;
                }
            }

            var ms = new MemoryStream();

            var bom = Encoding.UTF8.GetPreamble();

            ms.Write(bom, 0, bom.Length);

            byte[] data;
            if (AddStandardHeader)
            {
                string header = StandardHeaderService.GetHeader(policyParent, fileName, true);
                data = System.Text.Encoding.UTF8.GetBytes(header);
                ms.Write(data, 0, data.Length);
            }

            var doc = TextEditorFactory.CreateNewDocument();

            doc.Text = content;

            TextStylePolicy textPolicy = policyParent != null?policyParent.Policies.Get <TextStylePolicy> ("text/plain")
                                             : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> ("text/plain");

            string eolMarker = TextStylePolicy.GetEolMarker(textPolicy.EolMarker);

            byte[] eolMarkerBytes = System.Text.Encoding.UTF8.GetBytes(eolMarker);

            var tabToSpaces = textPolicy.TabsToSpaces? new string (' ', textPolicy.TabWidth) : null;

            foreach (var line in doc.GetLines())
            {
                var lineText = doc.GetTextAt(line.Offset, line.Length);
                if (tabToSpaces != null)
                {
                    lineText = lineText.Replace("\t", tabToSpaces);
                }
                data = System.Text.Encoding.UTF8.GetBytes(lineText);
                ms.Write(data, 0, data.Length);
                ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length);
            }

            ms.Position = 0;
            return(ms);
        }
Beispiel #23
0
        public static MSBuildRootDocument Parse(
            string filename, ITextSource textSource, MSBuildRootDocument previous,
            MSBuildSchemaProvider schemaProvider, IRuntimeInformation runtimeInfo,
            CancellationToken token)
        {
            var xmlParser = new XmlParser(new XmlRootState(), true);

            try {
                xmlParser.Parse(textSource.CreateReader());
            } catch (Exception ex) {
                LoggingService.LogError("Unhandled error parsing xml document", ex);
            }

            var xdocument = xmlParser.Nodes.GetRoot();

            if (xdocument != null && xdocument.RootElement != null)
            {
                if (!xdocument.RootElement.IsEnded)
                {
                    xdocument.RootElement.End(xmlParser.Location);
                }
            }

            //FIXME: unfortunately the XML parser's regions only have line+col locations, not offsets
            //so we need to create an ITextDocument to extract tag bodies
            //we should fix this by changing the parser to use offsets for the tag locations
            ITextDocument textDoc = textSource as ITextDocument
                                    ?? TextEditorFactory.CreateNewDocument(textSource, filename, MSBuildTextEditorExtension.MSBuildMimeType);

            var propVals = new PropertyValueCollector(true);

            string projectPath = filename;

            var doc = new MSBuildRootDocument(filename)
            {
                XDocument          = xdocument,
                Text               = textDoc,
                RuntimeInformation = runtimeInfo
            };

            doc.Errors.AddRange(xmlParser.Errors);

            try {
                doc.Schema = previous?.Schema ?? schemaProvider.GetSchema(filename, null);
            } catch (Exception ex) {
                LoggingService.LogError("Error loading schema", ex);
            }

            var importedFiles = new HashSet <string> (StringComparer.OrdinalIgnoreCase)
            {
                filename
            };

            var taskBuilder = new TaskMetadataBuilder(doc);

            var extension = Path.GetExtension(filename);

            string MakeRelativeMSBuildPathAbsolute(string path)
            {
                var dir = Path.GetDirectoryName(doc.Filename);

                path = path.Replace('\\', Path.DirectorySeparatorChar);
                return(Path.GetFullPath(Path.Combine(dir, path)));
            }

            Import TryImportFile(string possibleFile)
            {
                try {
                    var fi = new FileInfo(possibleFile);
                    if (fi.Exists)
                    {
                        var imp = doc.GetCachedOrParse(importedFiles, previous, possibleFile, null, fi.LastWriteTimeUtc, projectPath, propVals, taskBuilder, schemaProvider, token);
                        doc.Imports.Add(possibleFile, imp);
                        return(imp);
                    }
                } catch (Exception ex) {
                    LoggingService.LogError($"Error importing '{possibleFile}'", ex);
                }
                return(null);
            }

            Import TryImportSibling(string ifHasThisExtension, string thenTryThisExtension)
            {
                if (string.Equals(ifHasThisExtension, extension, StringComparison.OrdinalIgnoreCase))
                {
                    var siblingFilename = Path.ChangeExtension(filename, thenTryThisExtension);
                    return(TryImportFile(siblingFilename));
                }
                return(null);
            }

            void TryImportIntellisenseImports(MSBuildSchema schema)
            {
                foreach (var intellisenseImport in schema.IntelliSenseImports)
                {
                    TryImportFile(MakeRelativeMSBuildPathAbsolute(intellisenseImport));
                }
            }

            try {
                //if this is a targets file, try to import the props _at the top_
                var propsImport = TryImportSibling(".targets", ".props");

                // this currently only happens in the root file
                // it's a quick hack to allow files to get some basic intellisense by
                // importing the files _that they themselves expect to be imported from_.
                // we also try to load them from the sibling props, as a paired targets/props
                // will likely share a schema file.
                var schema = doc.Schema ?? propsImport?.Document?.Schema;
                if (schema != null)
                {
                    TryImportIntellisenseImports(doc.Schema);
                }

                doc.Build(
                    xdocument, textDoc, runtimeInfo, propVals, taskBuilder,
                    (imp, sdk) => doc.ResolveImport(importedFiles, previous, projectPath, filename, imp, sdk, propVals, taskBuilder, schemaProvider, token)
                    );

                //if this is a props file, try to import the targets _at the bottom_
                var targetsImport = TryImportSibling(".props", ".targets");

                //and if we didn't load intellisense import already, try to load them from the sibling targets
                if (schema == null && targetsImport?.Document?.Schema != null)
                {
                    TryImportIntellisenseImports(targetsImport.Document.Schema);
                }
            } catch (Exception ex) {
                LoggingService.LogError($"Error building document '{projectPath}'", ex);
            }

            try {
                var binpath = doc.RuntimeInformation.GetBinPath();
                foreach (var t in Directory.GetFiles(binpath, "*.tasks"))
                {
                    doc.LoadTasks(importedFiles, previous, t, propVals, taskBuilder, schemaProvider, token);
                }
                foreach (var t in Directory.GetFiles(binpath, "*.overridetasks"))
                {
                    doc.LoadTasks(importedFiles, previous, t, propVals, taskBuilder, schemaProvider, token);
                }
            } catch (Exception ex) {
                LoggingService.LogError("Error resolving tasks", ex);
            }

            try {
                if (previous != null)
                {
                    // try to recover some values that may have been collected from the imports, as they
                    // will not have been re-evaluated
                    var fx = previous.Frameworks.FirstOrDefault();
                    if (fx != null)
                    {
                        propVals.Collect("TargetFramework", fx.GetShortFolderName());
                        propVals.Collect("TargetFrameworkVersion", FrameworkInfoProvider.FormatDisplayVersion(fx.Version));
                        propVals.Collect("TargetFrameworkIdentifier", fx.Framework);
                    }
                }
                doc.Frameworks = propVals.GetFrameworks();
            } catch (Exception ex) {
                LoggingService.LogError("Error determining project framework", ex);
                doc.Frameworks = new List <NuGetFramework> ();
            }

            try {
                //this has to run in a second pass so that it runs after all the schemas are loaded
                var validator = new MSBuildDocumentValidator();
                validator.Run(doc.XDocument, filename, textDoc, doc);
            } catch (Exception ex) {
                LoggingService.LogError("Error in validation", ex);
            }

            return(doc);
        }
Beispiel #24
0
        internal static ProjectFile MigrateToProjectJson(DotNetProject project)
        {
            var projectJsonName = project.BaseDirectory.Combine("project.json");
            var projectJsonFile = new ProjectFile(projectJsonName, BuildAction.None);

            bool          isOpen = false;
            JObject       json;
            ITextDocument file;

            if (System.IO.File.Exists(projectJsonName))
            {
                file = TextFileProvider.Instance.GetTextEditorData(projectJsonFile.FilePath.ToString(), out isOpen);
                using (var tr = file.CreateReader())
                    using (var jr = new Newtonsoft.Json.JsonTextReader(tr)) {
                        json = (JObject)JToken.Load(jr);
                    }
            }
            else
            {
                file          = TextEditorFactory.CreateNewDocument();
                file.FileName = projectJsonName;
                file.Encoding = Encoding.UTF8;
                json          = new JObject(
                    new JProperty("dependencies", new JObject()),
                    new JProperty("frameworks", new JObject())
                    );
            }

            List <string> packages           = null;
            var           packagesConfigFile = project.GetProjectFile(project.BaseDirectory.Combine("packages.config"));

            if (packagesConfigFile != null)
            {
                //NOTE: it might also be open and unsaved, but that's an unimportant edge case, ignore it
                var configDoc = System.Xml.Linq.XDocument.Load(packagesConfigFile.FilePath);
                if (configDoc.Root != null)
                {
                    var deps = (json ["dependencies"] as JObject) ?? ((JObject)(json ["dependencies"] = new JObject()));
                    foreach (var packagelEl in configDoc.Root.Elements("package"))
                    {
                        var packageId      = (string)packagelEl.Attribute("id");
                        var packageVersion = (string)packagelEl.Attribute("version");
                        deps [packageId] = packageVersion;

                        if (packages == null)
                        {
                            packages = new List <string> ();
                        }
                        packages.Add(packageId + "." + packageVersion);
                    }
                }
            }

            var framework = GetPclProfileFullName(project.TargetFramework.Id) ?? NetStandardDefaultFramework;

            json ["frameworks"] = new JObject(
                new JProperty(framework, new JObject())
                );

            file.Text = json.ToString();

            if (!isOpen)
            {
                file.Save();
            }

            project.AddFile(projectJsonFile);
            if (packagesConfigFile != null)
            {
                project.Files.Remove(packagesConfigFile);

                //we have to delete the packages.config, or the NuGet addin will try to retarget its packages
                FileService.DeleteFile(packagesConfigFile.FilePath);

                //remove the package refs nuget put in the file, project.json doesn't use those
                project.References.RemoveRange(project.References.Where(IsFromPackage).ToArray());

                // Remove any imports from NuGet packages. These will be added by NuGet into the generated
                // ProjectName.nuget.props and ProjectName.nuget.targets files when using project.json.
                if (packages != null)
                {
                    foreach (var import in project.MSBuildProject.Imports.ToArray())
                    {
                        if (packages.Any(p => import.Project.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
                        {
                            import.ParentObject.ParentProject.Remove(import);
                        }
                    }
                }
            }

            return(projectJsonFile);
        }
Beispiel #25
0
        public TemplateResult FillVariables(TemplateContext context)
        {
            var    expansion  = CodeTemplateService.GetExpansionObject(this);
            var    result     = new TemplateResult();
            var    sb         = StringBuilderCache.Allocate();
            int    lastOffset = 0;
            string code       = context.Editor.FormatString(context.InsertPosition, context.TemplateCode);

            result.TextLinks = new List <TextLink> ();
            foreach (System.Text.RegularExpressions.Match match in variableRegEx.Matches(code))
            {
                string name = match.Groups [1].Value;
                sb.Append(code, lastOffset, match.Index - lastOffset);
                lastOffset = match.Index + match.Length;
                if (string.IsNullOrEmpty(name))                    // $$ is interpreted as $
                {
                    sb.Append("$");
                }
                else
                {
                    switch (name)
                    {
                    case "end":
                        result.CaretEndOffset = sb.Length;
                        break;

                    case "selected":
                        if (!string.IsNullOrEmpty(context.SelectedText))
                        {
                            string indent    = GetIndent(sb);
                            string selection = Reindent(context.SelectedText, indent);
                            sb.Append(selection);
                        }
                        break;

                    case "TM_CURRENT_LINE":
                        sb.Append(context.Editor.CaretLine);
                        break;

                    case "TM_CURRENT_WORD":
                        sb.Append("");
                        break;

                    case "TM_FILENAME":
                        sb.Append(context.Editor.FileName);
                        break;

                    case "TM_FILEPATH":
                        sb.Append(Path.GetDirectoryName(context.Editor.FileName));
                        break;

                    case "TM_FULLNAME":
                        sb.Append(AuthorInformation.Default.Name);
                        break;

                    case "TM_LINE_INDEX":
                        sb.Append(context.Editor.CaretColumn - 1);
                        break;

                    case "TM_LINE_NUMBER":
                        sb.Append(context.Editor.CaretLine);
                        break;

                    case "TM_SOFT_TABS":
                        sb.Append(context.Editor.Options.TabsToSpaces ? "YES" : "NO");                          // Note: these strings need no translation.
                        break;

                    case "TM_TAB_SIZE":
                        sb.Append(context.Editor.Options.TabSize);
                        break;
                    }
                }
                if (!variableDecarations.ContainsKey(name))
                {
                    continue;
                }
                var  link  = result.TextLinks.Find(l => l.Name == name);
                bool isNew = link == null;
                if (isNew)
                {
                    link = new TextLink(name);
                    if (!string.IsNullOrEmpty(variableDecarations [name].ToolTip))
                    {
                        link.Tooltip = GettextCatalog.GetString(variableDecarations [name].ToolTip);
                    }
                    link.Values = new CodeTemplateListDataProvider(variableDecarations [name].Values);
                    if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                    {
                        link.Values = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    }
                    result.TextLinks.Add(link);
                }
                link.IsEditable   = variableDecarations [name].IsEditable;
                link.IsIdentifier = variableDecarations [name].IsIdentifier;
                if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                {
                    var functionResult = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    if (functionResult != null && functionResult.Count > 0)
                    {
                        string s = (string)functionResult [functionResult.Count - 1];
                        if (s == null)
                        {
                            if (variableDecarations.ContainsKey(name))
                            {
                                s = variableDecarations [name].Default;
                            }
                        }
                        if (s != null)
                        {
                            link.AddLink(new TextSegment(sb.Length, s.Length));
                            if (isNew)
                            {
                                link.GetStringFunc = delegate(Func <string, string> callback) {
                                    return(expansion.RunFunction(context, callback, variableDecarations [name].Function));
                                };
                            }
                            sb.Append(s);
                        }
                    }
                    else
                    {
                        AddDefaultValue(sb, link, name);
                    }
                }
                else
                {
                    AddDefaultValue(sb, link, name);
                }
            }
            sb.Append(code, lastOffset, code.Length - lastOffset);

            // format & indent template code
            var data = TextEditorFactory.CreateNewDocument();

            data.Text         = StringBuilderCache.ReturnAndFree(sb);
            data.TextChanged += delegate(object sender, MonoDevelop.Core.Text.TextChangeEventArgs e) {
                for (int i = 0; i < e.TextChanges.Count; ++i)
                {
                    var change = e.TextChanges[i];
                    int delta  = change.InsertionLength - change.RemovalLength;

                    foreach (var link in result.TextLinks)
                    {
                        link.Links = link.Links.AdjustSegments(e).ToList();
                    }
                    if (result.CaretEndOffset > change.Offset)
                    {
                        result.CaretEndOffset += delta;
                    }
                }
            };

            IndentCode(data, context.LineIndent);
            result.Code = data.Text;
            return(result);
        }
Beispiel #26
0
        public Task <Projection> CreateProjection(DocumentInfo info, IReadonlyTextDocument data, bool buildExpressions)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            var document = new StringBuilder();

            WriteUsings(info.Imports, document);
            var segBuilder = System.Collections.Immutable.ImmutableList <ProjectedSegment> .Empty.ToBuilder();

            foreach (var node in info.XScriptBlocks)
            {
                var start = data.LocationToOffset(node.Region.Begin.Line, node.Region.Begin.Column) + 2;
                var end   = data.LocationToOffset(node.Region.End.Line, node.Region.End.Column) - 2;

                segBuilder.Add(new ProjectedSegment(start, document.Length, end - start));

                document.AppendLine(data.GetTextBetween(start, end));
            }
            if (buildExpressions)
            {
                WriteClassDeclaration(info, document);
                document.AppendLine("{");
                document.AppendLine("void Generated ()");
                document.AppendLine("{");
                //Console.WriteLine ("start:" + location.BeginLine  +"/" +location.BeginColumn);

                foreach (var node in info.XExpressions)
                {
                    bool isBlock = node is WebFormsRenderBlock;

                    var start = data.LocationToOffset(node.Region.Begin.Line, node.Region.Begin.Column) + 2;
                    var end   = data.LocationToOffset(node.Region.End.Line, node.Region.End.Column) - 2;

                    if (!isBlock)
                    {
                        document.Append("WriteLine (");
                        start += 1;
                    }

                    string expr = data.GetTextBetween(start, end);
                    segBuilder.Add(new ProjectedSegment(start, document.Length, expr.Length));
                    document.Append(expr);
                    if (!isBlock)
                    {
                        document.Append(");");
                    }
                }
                document.AppendLine("}");
                document.AppendLine("}");
            }
            return(Task.FromResult(new Projection(
                                       TextEditorFactory.CreateNewDocument(new StringTextSource(document.ToString()), info.AspNetDocument.FileName + ".g.cs", "text/x-csharp"),
                                       segBuilder.ToImmutable()
                                       )));
        }
        internal SignatureChangeDialog() : base(GettextCatalog.GetString("Change Signature"), IdeApp.Workbench.RootWindow, DialogFlags.Modal)
        {
            this.Build();

            previewEditor            = TextEditorFactory.CreateNewEditor(TextEditorFactory.CreateNewDocument());
            previewEditor.IsReadOnly = true;
            previewEditor.MimeType   = "text/x-csharp";
            var options = new CustomEditorOptions {
                ShowLineNumberMargin = false,
                ShowFoldMargin       = false,
                ShowIconMargin       = false,
                ShowRuler            = false,
                EditorTheme          = DefaultSourceEditorOptions.Instance.EditorTheme,
                FontName             = DefaultSourceEditorOptions.Instance.FontName
            };

            previewEditor.Options = options;
            vbox4.PackStart(previewEditor, true, true, 0);
            vbox4.ShowAll();

            var tr  = new CellRendererText();
            var col = this.treeviewParameterList.AppendColumn(GettextCatalog.GetString("Modifier"), tr);

            col.SetCellDataFunc(tr, new TreeCellDataFunc((column, cell, model, iter) => {
                var param = model.GetValue(iter, 0) as IParameterSymbol;
                if (param == parameters.ThisParameter)
                {
                    ((CellRendererText)cell).Text = "this";
                    return;
                }
                if (param == parameters.ParamsParameter)
                {
                    ((CellRendererText)cell).Text = "params";
                    return;
                }
                switch (param.RefKind)
                {
                case RefKind.Out:
                    ((CellRendererText)cell).Text = "out";
                    break;

                case RefKind.Ref:
                    ((CellRendererText)cell).Text = "ref";
                    break;

                default:
                    ((CellRendererText)cell).Text = "";
                    break;
                }
            }));

            col = this.treeviewParameterList.AppendColumn(GettextCatalog.GetString("Type"), tr);
            col.SetCellDataFunc(tr, new TreeCellDataFunc((column, cell, model, iter) => {
                var param = model.GetValue(iter, 0) as IParameterSymbol;
                ((CellRendererText)cell).Text = param.Type.ToDisplayString();
            }));

            col = this.treeviewParameterList.AppendColumn(GettextCatalog.GetString("Parameter"), tr);
            col.SetCellDataFunc(tr, new TreeCellDataFunc((column, cell, model, iter) => {
                var param = model.GetValue(iter, 0) as IParameterSymbol;
                ((CellRendererText)cell).Text = param.Name;
            }));

            col = this.treeviewParameterList.AppendColumn(GettextCatalog.GetString("Standard"), tr);
            col.SetCellDataFunc(tr, new TreeCellDataFunc((column, cell, model, iter) => {
                var param = model.GetValue(iter, 0) as IParameterSymbol;
                ((CellRendererText)cell).Text = param.HasExplicitDefaultValue ? param.ExplicitDefaultValue.ToString() : "";
            }));
            this.treeviewParameterList.Model              = store;
            this.treeviewParameterList.Selection.Changed += delegate {
                UpdateSensitivity();
            };

            this.buttonUp.Clicked += delegate {
                Gtk.TreeIter iter, iter2;
                if (!treeviewParameterList.Selection.GetSelected(out iter))
                {
                    return;
                }
                var path = store.GetPath(iter);
                if (!path.Prev())
                {
                    return;
                }
                if (!store.GetIter(out iter2, path))
                {
                    return;
                }
                store.MoveBefore(iter, iter2);
                UpdatePreview();
            };

            this.buttonDown.Clicked += delegate {
                Gtk.TreeIter iter, iter2;
                if (!treeviewParameterList.Selection.GetSelected(out iter))
                {
                    return;
                }
                var path = store.GetPath(iter);
                path.Next();
                if (!store.GetIter(out iter2, path))
                {
                    return;
                }
                store.MoveAfter(iter, iter2);
                UpdatePreview();
            };

            this.buttonRemove.Clicked += delegate {
                Gtk.TreeIter iter;
                if (!treeviewParameterList.Selection.GetSelected(out iter))
                {
                    return;
                }
                store.Remove(ref iter);
                UpdatePreview();
            };

            this.buttonRefresh.Clicked += delegate {
                Refresh();
            };
        }