Exemple #1
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);
        }
        public DisassemblyView()
        {
            DocumentTitle = GettextCatalog.GetString("Disassembly");

            sw                = new Gtk.ScrolledWindow();
            editor            = TextEditorFactory.CreateNewEditor();
            editor.IsReadOnly = true;
            asmMarker         = TextMarkerFactory.CreateAsmLineMarker(editor);

            editor.Options = DefaultSourceEditorOptions.PlainEditor;

            sw.AddWithViewport(editor);
            sw.HscrollbarPolicy = Gtk.PolicyType.Automatic;
            sw.VscrollbarPolicy = Gtk.PolicyType.Automatic;
            sw.ShowAll();
            sw.Vadjustment.ValueChanged      += OnScrollEditor;
            sw.VScrollbar.ButtonPressEvent   += OnPress;
            sw.VScrollbar.ButtonReleaseEvent += OnRelease;
            sw.VScrollbar.Events             |= Gdk.EventMask.ButtonPressMask | Gdk.EventMask.ButtonReleaseMask;
            sw.ShadowType = Gtk.ShadowType.In;

            sw.Sensitive = false;

            DebuggingService.StoppedEvent += OnStop;
        }
        void TestGuessSemicolonInsertionOffset(string fooBar, bool expected = true)
        {
            StringBuilder sb = new StringBuilder();
            int           semicolonOffset = 0;
            int           guessedOffset   = 0;

            for (int i = 0; i < fooBar.Length; i++)
            {
                char ch = fooBar [i];
                if (ch == '$')
                {
                    semicolonOffset = sb.Length - 1;
                }
                else if (ch == '~')
                {
                    guessedOffset = sb.Length - 1;
                }
                else
                {
                    sb.Append(ch);
                }
            }
            var data = TextEditorFactory.CreateNewEditor();

            data.Text = sb.ToString();
            int guessed;

            Assert.AreEqual(expected, CSharpTextEditorIndentation.GuessSemicolonInsertionOffset(data, data.GetLineByOffset(semicolonOffset), semicolonOffset, out guessed));
            if (expected)
            {
                Assert.AreEqual(guessedOffset, guessed);
            }
        }
Exemple #4
0
        public IWpfTextView CreateTextView(IEnumerable <SnapshotSpan> lines)
        {
            var parentView = TextViewConnectionListener.GetTextViewDataForBuffer(lines.First().Snapshot.TextBuffer).LastActiveView;

            var buffer = ProjectionFactory.CreateProjectionBuffer(
                null,
                lines.SelectMany(s => new object[] { Environment.NewLine }.Concat(
                                     // Use the text from the outer ProjectionBuffer, which can
                                     // include language services from other projected buffers.
                                     // This makes the tooltip include syntax highlighting that
                                     // does not exist in the innermost Markdown buffer.
                                     parentView.BufferGraph
                                     .MapUpToBuffer(s, SpanTrackingMode.EdgeExclusive, parentView.TextBuffer)
                                     .Select(s2 => s2.Snapshot.CreateTrackingSpan(s, SpanTrackingMode.EdgeExclusive))
                                     ))
                .Skip(1)        // Skip first newline
                .ToList(),
                ProjectionBufferOptions.None
                );
            var view = TextEditorFactory.CreateTextView(buffer, TextEditorFactory.NoRoles);

            view.Background = Brushes.Transparent;
            SizeToFit(view);
            return(view);
        }
Exemple #5
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);
        }
Exemple #6
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 => {
Exemple #7
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);
            }
        }
Exemple #8
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>";
            }
        }
Exemple #9
0
        /// <summary>
        /// Constructor</summary>
        /// <param name="uri">URI of document</param>
        public CodeDocument(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            m_uri = uri;

            string filePath = uri.LocalPath;
            string fileName = Path.GetFileName(filePath);

            m_type = GetDocumentType(fileName);

            m_editor = TextEditorFactory.CreateSyntaxHighlightingEditor();

            Languages lang = GetDocumentLanguage(fileName);

            m_editor.SetLanguage(lang);
            Control ctrl = (Control)m_editor;

            ctrl.Tag = this;

            m_editor.EditorTextChanged += editor_EditorTextChanged;

            m_controlInfo = new ControlInfo(fileName, filePath, StandardControlGroup.Center);
            // tell ControlHostService this control should be considered a document in the menu,
            // and using the full path of the document for menu text to avoid adding a number in the end
            // in control header,  which is not desirable for documents that have the same name
            // but located at different directories.
            m_controlInfo.IsDocument = true;
        }
Exemple #10
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);
        }
        public void Run(XElement element, MSBuildLanguageElement resolvedElement, string filename, ITextSource textDocument, MSBuildDocument document, int offset = 0, int length = 0)
        {
            Filename  = filename;
            Document  = document;
            Extension = System.IO.Path.GetExtension(filename);

            //HACK: we should really use the ITextSource directly, but since the XML parser positions are
            //currently line/col, we need a TextDocument to convert to offsets
            TextDocument = textDocument as IReadonlyTextDocument
                           ?? TextEditorFactory.CreateNewReadonlyDocument(
                textDocument, filename, MSBuildTextEditorExtension.MSBuildMimeType
                );

            range = new DocumentRegion(
                TextDocument.OffsetToLocation(offset),
                length > 0
                                        ? TextDocument.OffsetToLocation(length + offset)
                                        : new DocumentLocation(int.MaxValue, int.MaxValue));

            if (resolvedElement != null)
            {
                VisitResolvedElement(element, resolvedElement);
            }
            else if (element != null)
            {
                ResolveAndVisit(element, null);
            }
        }
Exemple #12
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);
        }
Exemple #13
0
        public IronPythonRepl()
        {
            InitializeComponent();
            textEditorControl.CreateControl();

            textEditorControl.ShowLineNumbers = false;
            textEditorControl.ShowVRuler      = false;
            textEditorControl.ShowHRuler      = false;

            //Our ICSharpCode.TextEditor has been modified to include the Python syntax file
            //allowing us to do this
            textEditorControl.SetHighlighting("Python"); //NOXLATE

            this.Title     = this.Description = Strings.Title_IronPython_Console;
            this.Disposed += OnDisposed;

            textEditor = TextEditorFactory.CreateEditor(textEditorControl);

            if (PropertyService.Get(ScriptingConfigProperties.ShowIronPythonConsole, ScriptingConfigProperties.DefaultShowIronPythonConsole))
            {
                Console.WriteLine("Run python host");
                host = new PythonConsoleHost(textEditor);
                host.Run();
            }
        }
Exemple #14
0
        /// <summary>
        /// Constructor
        /// </summary>
        public SledBreakpointConditionForm()
        {
            InitializeComponent();

            // Add items to combo box
            m_cmbEnvironment.Items.Add(new ComboBoxItem("Global", false));
            m_cmbEnvironment.Items.Add(new ComboBoxItem("Environment", true));
            m_cmbEnvironment.SelectedIndex = 0;

            // Create SyntaxEditorControl
            m_txtCondition = TextEditorFactory.CreateSyntaxHighlightingEditor();

            // These values were what the previous TextBox used
            m_txtCondition.Control.Location = new System.Drawing.Point(12, 35);
            m_txtCondition.Control.Size     = new System.Drawing.Size(383, 20);
            m_txtCondition.Control.TabIndex = 2;
            m_txtCondition.Control.Anchor   = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;

            // Set some special stuff to make it single line
            m_txtCondition.Multiline = false;
            m_txtCondition.LineNumberMarginVisible = false;
            m_txtCondition.IndicatorMarginVisible  = false;

            Controls.Add(m_txtCondition.Control);

            m_txtCondition.Control.Focus();
        }
Exemple #15
0
        private static void InitTextEditor()
        {
            // Syntax definitions are loaded globally for all TextEditor instances,
            // so we only need to call this method once on startup.
            var editor = TextEditorFactory.CreateMultiLineTextEditor();

            editor.LoadSyntaxDefinitions(new BDHeroT4SyntaxModeProvider());
        }
        public void TestBug294858()          // [Feedback] Do NOT go to definition if Ctrl/Cmd is pressed AFTER mouse down.
        {
            var editor = TextEditorFactory.CreateNewEditor();

            editor.Text = "Hello World";
            Assert.IsTrue(AbstractNavigationExtension.IsHoverNavigationValid(editor));
            editor.SetSelection(0, editor.Length);
            Assert.IsFalse(AbstractNavigationExtension.IsHoverNavigationValid(editor));
        }
 public void SetUp()
 {
     originalGetActiveDocument = RazorWorkbenchService.GetActiveDocument;
     editor          = TextEditorFactory.CreateNewEditor();
     editor.MimeType = "text/x-cshtml";
     RazorWorkbenchService.GetActiveDocument = () => {
         return(editor);
     };
 }
 protected AbstractOptionPreviewViewModel(OptionSet options, IServiceProvider serviceProvider, string language)
 {
     this.Options          = options;
     _originalOptions      = options;
     this.Items            = new List <object> ();
     this.CodeStyleItems   = new ObservableCollection <AbstractCodeStyleOptionViewModel> ();
     this.Language         = language;
     _textViewHost         = TextEditorFactory.CreateNewEditor();
     _textViewHost.Options = DefaultSourceEditorOptions.PlainEditor;
 }
Exemple #19
0
 TextEditor GetDocument()
 {
     if (cachedEditor == null || cachedEditor.FileName != FileName)
     {
         var content = FileProvider.ReadString();
         cachedEditor?.Dispose();
         cachedEditor = TextEditorFactory.CreateNewEditor(TextEditorFactory.CreateNewReadonlyDocument(new Core.Text.StringTextSource(content.ReadToEnd()), FileName, DesktopService.GetMimeTypeForUri(FileName)));
     }
     return(cachedEditor);
 }
Exemple #20
0
        public static MSBuildNavigationResult GetNavigation(
            MSBuildRootDocument doc, DocumentLocation location, MSBuildResolveResult rr)
        {
            if (rr == null)
            {
                return(null);
            }

            //HACK: we should really use the ITextSource directly, but since the XML parser positions are
            //currently line/col, we need a TextDocument to convert to offsets
            var textDocument = doc.Text as IReadonlyTextDocument
                               ?? TextEditorFactory.CreateNewReadonlyDocument(
                doc.Text, doc.Filename, MSBuildTextEditorExtension.MSBuildMimeType
                );

            var annotations     = GetAnnotationsAtLocation <NavigationAnnotation> (doc, location);
            var firstAnnotation = annotations.FirstOrDefault();

            if (firstAnnotation != null)
            {
                var beginOffset = textDocument.LocationToOffset(firstAnnotation.Region.Begin);
                var endOffset   = textDocument.LocationToOffset(firstAnnotation.Region.End);
                return(new MSBuildNavigationResult(
                           annotations.Select(a => a.Path).ToArray(), beginOffset, endOffset - beginOffset + 1
                           ));
            }

            if (rr.ReferenceKind == MSBuildReferenceKind.Target)
            {
                return(new MSBuildNavigationResult(
                           MSBuildReferenceKind.Target, (string)rr.Reference, rr.ReferenceOffset, rr.ReferenceLength
                           ));
            }

            if (rr.ReferenceKind == MSBuildReferenceKind.FileOrFolder)
            {
                return(new MSBuildNavigationResult(
                           (string[])rr.Reference, rr.ReferenceOffset, rr.ReferenceLength
                           ));
            }

            if (rr.ReferenceKind == MSBuildReferenceKind.Task)
            {
                var task = doc.GetTask((string)rr.Reference);
                if (task.DeclaredInFile != null)
                {
                    return(new MSBuildNavigationResult(
                               MSBuildReferenceKind.Task, (string)rr.Reference, rr.ReferenceOffset, rr.ReferenceLength,
                               task.DeclaredInFile, task.DeclaredAtLocation
                               ));
                }
            }

            return(null);
        }
Exemple #21
0
        void ToggleCodeCommentWithBlockComments()
        {
            var blockStarts = TextEditorFactory.GetSyntaxProperties(Editor.MimeType, "BlockCommentStart");
            var blockEnds   = TextEditorFactory.GetSyntaxProperties(Editor.MimeType, "BlockCommentEnd");

            if (blockStarts == null || blockEnds == null || blockStarts.Length == 0 || blockEnds.Length == 0)
            {
                return;
            }

            string blockStart = blockStarts[0];
            string blockEnd   = blockEnds[0];

            using (var undo = Editor.OpenUndoGroup()) {
                IDocumentLine startLine;
                IDocumentLine endLine;

                if (Editor.IsSomethingSelected)
                {
                    startLine = Editor.GetLineByOffset(Editor.SelectionRange.Offset);
                    endLine   = Editor.GetLineByOffset(Editor.SelectionRange.EndOffset);

                    // If selection ends at begining of line... This is visible as previous line
                    // is selected, hence we want to select previous line Bug 26287
                    if (endLine.Offset == Editor.SelectionRange.EndOffset)
                    {
                        endLine = endLine.PreviousLine;
                    }
                }
                else
                {
                    startLine = endLine = Editor.GetLine(Editor.CaretLine);
                }
                string startLineText = Editor.GetTextAt(startLine.Offset, startLine.Length);
                string endLineText   = Editor.GetTextAt(endLine.Offset, endLine.Length);
                if (startLineText.StartsWith(blockStart, StringComparison.Ordinal) && endLineText.EndsWith(blockEnd, StringComparison.Ordinal))
                {
                    Editor.RemoveText(endLine.Offset + endLine.Length - blockEnd.Length, blockEnd.Length);
                    Editor.RemoveText(startLine.Offset, blockStart.Length);
                    if (Editor.IsSomethingSelected)
                    {
                        Editor.SelectionAnchorOffset -= blockEnd.Length;
                    }
                }
                else
                {
                    Editor.InsertText(endLine.Offset + endLine.Length, blockEnd);
                    Editor.InsertText(startLine.Offset, blockStart);
                    if (Editor.IsSomethingSelected)
                    {
                        Editor.SelectionAnchorOffset += blockEnd.Length;
                    }
                }
            }
        }
        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);
            }
        }
Exemple #23
0
 public TextEditor CreateProjectedEditor(DocumentContext originalContext)
 {
     if (projectedEditor == null)
     {
         projectedEditor          = TextEditorFactory.CreateNewEditor(Document, TextEditorType.Projection);
         projectedDocumentContext = new ProjectedDocumentContext(projectedEditor, originalContext);
         projectedEditor.InitializeExtensionChain(projectedDocumentContext);
         projectedProjections.InstallListener(projectedEditor);
     }
     return(projectedEditor);
 }
        static string AddIndent(string text, string indent)
        {
            var doc    = TextEditorFactory.CreateNewReadonlyDocument(new StringTextSource(text), "");
            var result = StringBuilderCache.Allocate();

            foreach (var line in doc.GetLines())
            {
                result.Append(indent);
                result.Append(doc.GetTextAt(line.SegmentIncludingDelimiter));
            }
            return(StringBuilderCache.ReturnAndFree(result));
        }
Exemple #25
0
        bool TryGetLineCommentTag(out string commentTag)
        {
            var lineComments = TextEditorFactory.GetSyntaxProperties(Editor.MimeType, "LineComment");

            if (lineComments == null || lineComments.Length == 0)
            {
                commentTag = null;
                return(false);
            }
            commentTag = lineComments [0];
            return(true);
        }
Exemple #26
0
 public CodeRulePanelWidget()
 {
     TextEditor          = TextEditorFactory.CreateNewEditor();
     TextEditor.MimeType = "application/xml";
     TextEditor.Options  = DefaultSourceEditorOptions.PlainEditor;
     try {
         TextEditor.Text = TextFileUtility.GetText(TypeSystemService.RuleSetManager.GlobalRulesetFileName, out encoding);
     } catch (Exception e) {
         LoggingService.LogError("Error while loading global rule set file " + TypeSystemService.RuleSetManager, e);
         loadingError = true;
     }
 }
Exemple #27
0
        void OnUpdateToggleComment(CommandInfo info)
        {
            var lineComments = TextEditorFactory.GetSyntaxProperties(Editor.MimeType, "LineComment");

            if (lineComments != null && lineComments.Length > 0)
            {
                info.Visible = true;
                return;
            }
            var blockStarts = TextEditorFactory.GetSyntaxProperties(Editor.MimeType, "BlockCommentStart");
            var blockEnds   = TextEditorFactory.GetSyntaxProperties(Editor.MimeType, "BlockCommentEnd");

            info.Visible = blockStarts != null && blockStarts.Length > 0 && blockEnds != null && blockEnds.Length > 0;
        }
Exemple #28
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());
        }
Exemple #29
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);
        }
Exemple #30
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());
        }