Example #1
0
        protected override void ExecuteCodeCompletion(Suffix suffix,
                                                      ITextControl textControl,
                                                      IntellisenseManager intellisenseManager,
                                                      bool automatic,
                                                      IContextBoundSettingsStore settingsStore)
        {
            ResultProposalCollection = new ProposalCollection();

            var parameters = CodeCompletionParameters.CreateSingle(CodeCompletionType.BasicCompletion);

            parameters.EvaluationMode = EvaluationMode.LightAndFull;
            FilteredLookupItems filteredItems;
            var result = GetCompletionResult(
                textControl,
                intellisenseManager,
                parameters,
                LookupListSorting.ByRelevance,
                out filteredItems,
                settingsStore);

            if (result != null)
            {
                ResultProposalCollection = result.LookupItems.ToProposalCollection();
            }
        }
Example #2
0
 public ContextGenerator(TextControlManager textControlManager,
                         IntellisenseManager intellisenseManager,
                         ILogger logger)
 {
     _textControlManager = textControlManager;
     _logger             = logger;
     _solution           = intellisenseManager.Solution;
 }
 protected override void AddItemsGroups(
     NTriplesCodeCompletionContext context, GroupedItemsCollector collector, IntellisenseManager intellisenseManager)
 {
     collector.AddRanges(
         new TextLookupRanges(
             context.BasicContext.SelectedRange.TextRange,
             context.BasicContext.SelectedRange.TextRange));
     collector.AddFilter(new ReferencesBetterFilter());
 }
Example #4
0
        public T4TypingAssist([NotNull] Lifetime lifetime, [NotNull] ISolution solution, [NotNull] ISettingsStore settingsStore,
                              [NotNull] CachingLexerService cachingLexerService, [NotNull] ICommandProcessor commandProcessor, [NotNull] IPsiServices psiServices,
                              [NotNull] ITypingAssistManager typingAssistManager, [NotNull] SkippingTypingAssist skippingTypingAssist, [NotNull] IntellisenseManager intellisenseManager)
            : base(solution, settingsStore, cachingLexerService, commandProcessor, psiServices)
        {
            _skippingTypingAssist = skippingTypingAssist;
            _intellisenseManager  = intellisenseManager;

            typingAssistManager.AddTypingHandler(lifetime, '=', this, OnEqualTyped, IsTypingSmartParenthesisHandlerAvailable);
            typingAssistManager.AddTypingHandler(lifetime, '"', this, OnQuoteTyped, IsTypingSmartParenthesisHandlerAvailable);
        }
Example #5
0
        public ContextGenerator(TextControlManager textControlManager,
                                IntellisenseManager intellisenseManager,
                                ILogger logger)
        {
            _textControlManager = textControlManager;
            _documentManager    = intellisenseManager.DocumentManager;
            _logger             = logger;
            _solution           = intellisenseManager.Solution;

            ContextGeneratorCreated(this);
        }
Example #6
0
        private void RegisterLanguageService(ISourceFile sourceFile)
        {
            UnRegisterLanguageService();

            if (sourceFile.Project?.Solution != null)
            {
                _snippetManager.InitialiseSnippetsForSolution(sourceFile.Project.Solution);
            }

            if (sourceFile.Project != null)
            {
                _snippetManager.InitialiseSnippetsForProject(sourceFile.Project);
            }

            LanguageService = _shell.LanguageServices.FirstOrDefault(o => o.CanHandle(sourceFile));

            if (LanguageService != null)
            {
                LanguageServiceName = LanguageService.Title;

                LanguageService.RegisterSourceFile(this, sourceFile, Document);

                _languageServiceBackgroundRenderers.AddRange(LanguageService.GetBackgroundRenderers(sourceFile));

                foreach (var backgroundRenderer in _languageServiceBackgroundRenderers)
                {
                    TextArea.TextView.BackgroundRenderers.Add(backgroundRenderer);
                }

                _languageServiceDocumentLineTransformers.AddRange(LanguageService.GetDocumentLineTransformers(sourceFile));

                foreach (var transformer in _languageServiceDocumentLineTransformers)
                {
                    TextArea.TextView.LineTransformers.Insert(0, transformer);
                }

                _intellisenseManager = new IntellisenseManager(this, _intellisense, _completionAssistant, LanguageService, sourceFile);

                TextArea.IndentationStrategy = LanguageService.IndentationStrategy;
            }
            else
            {
                LanguageService     = null;
                LanguageServiceName = "Plain Text";
            }

            StartBackgroundWorkers();

            Document.TextChanged += TextDocument_TextChanged;

            DoCodeAnalysisAsync().GetAwaiter();
        }
Example #7
0
        private void UnRegisterLanguageService()
        {
            _languageServiceDisposables?.Dispose();

            if (_scopeLineBackgroundRenderer != null)
            {
                TextArea.TextView.BackgroundRenderers.Remove(_scopeLineBackgroundRenderer);
            }

            if (_textColorizer != null)
            {
                TextArea.TextView.LineTransformers.Remove(_textColorizer);
                _textColorizer = null;
            }

            if (_diagnosticMarkersRenderer != null)
            {
                TextArea.TextView.BackgroundRenderers.Remove(_diagnosticMarkersRenderer);
                _diagnosticMarkersRenderer = null;
            }

            ShutdownBackgroundWorkers();

            UnsavedFile unsavedFile = null;

            lock (UnsavedFiles)
            {
                unsavedFile = UnsavedFiles.BinarySearch(SourceFile.Location);
            }

            if (unsavedFile != null)
            {
                lock (UnsavedFiles)
                {
                    UnsavedFiles.Remove(unsavedFile);
                }
            }

            if (LanguageService != null)
            {
                LanguageService.UnregisterSourceFile(DocumentAccessor);
            }

            Document.TextChanged -= TextDocument_TextChanged;

            TextArea.TextEntering -= TextArea_TextEntering;
            TextArea.TextEntered  -= TextArea_TextEntered;

            _intellisenseManager = null;
        }
        protected override void ExecuteCodeCompletion(Suffix suffix,
                                                      ITextControl textControl,
                                                      IntellisenseManager intellisenseManager,
                                                      bool automatic,
                                                      IContextBoundSettingsStore settingsStore)
        {
            base.ExecuteCodeCompletion(suffix, textControl, intellisenseManager, automatic, settingsStore);

            if (TestAnalysisComponent.HasFailed)
            {
                throw new Exception(
                          TestAnalysisComponent.LastException.Item2,
                          TestAnalysisComponent.LastException.Item1);
            }
        }
Example #9
0
        public CodeTextBox()
        {
            InitializeComponent();

            //Set some defaults...
            this.AcceptsTab = true;
            this.Font       = new Font(FontFamily.GenericMonospace, 8f);

            // TODO
            //
            //Do not enable drag and dropping text
            //The same problem, as paste - the onDragDrop event fires, BEFORE the text is written into the textbox
            //Need to be handled in WndPrc
            this.EnableAutoDragDrop = false;

            this.DetectUrls        = false;
            this.WordWrap          = false;
            this.AutoWordSelection = true;

            #region Instantiate Syntax highlightning and Intellisense members
            //Instantiate word lists
            mp_CodeWords_Keywords       = new List <string>();
            mp_CodeWords_Types          = new List <string>();
            mp_CodeWords_Functions      = new List <string>();
            mp_CodeWords_Comments       = new List <string>();
            mp_CodeWords_ScopeOperators = new List <string>();
            mp_CodeWords_Chaines        = new List <string>();

            //Instantiate intellisense manager
            m_IntellisenseManager = new IntellisenseManager(this);

            //Instantiate the intellisense box
            mp_IntellisenseBox = new ImageListBox();

            //Instantiate intellisense tree
            mp_IntellisenseTree = new TreeView();
            #endregion

            #region Setup intellisense box
            //Setup intellisense box
            this.Controls.Add(mp_IntellisenseBox);
            mp_IntellisenseBox.Size         = new Size(250, 150);
            mp_IntellisenseBox.Visible      = false;
            mp_IntellisenseBox.KeyDown     += new KeyEventHandler(mp_IntellisenseBox_KeyDown);
            mp_IntellisenseBox.DoubleClick += new EventHandler(mp_IntellisenseBox_DoubleClick);
            #endregion
        }
 protected override void AddItemsGroups(PsiCodeCompletionContext context, GroupedItemsCollector collector, IntellisenseManager intellisenseManager)
 {
     collector.AddRanges(EvaluateRanges(context));
     collector.AddFilter(new KeywordsBetterFilter());
 }
Example #11
0
        private void RegisterLanguageService(ISourceFile sourceFile)
        {
            UnRegisterLanguageService();

            if (sourceFile.Project?.Solution != null)
            {
                _snippetManager.InitialiseSnippetsForSolution(sourceFile.Project.Solution);
            }

            if (sourceFile.Project != null)
            {
                _snippetManager.InitialiseSnippetsForProject(sourceFile.Project);
            }

            var contentTypeService = ContentTypeServiceInstance.Instance;

            LanguageService = _shell.LanguageServices.FirstOrDefault(
                o => o.Metadata.TargetCapabilities.Any(
                    c => contentTypeService.CapabilityAppliesToContentType(c, sourceFile.ContentType)))?.Value;

            if (LanguageService != null)
            {
                SyntaxHighlighting = CustomHighlightingManager.Instance.GetDefinition(LanguageService.LanguageId.ToUpper());

                LanguageServiceName = LanguageService.Title;

                LanguageService.RegisterSourceFile(DocumentAccessor);

                _diagnosticMarkersRenderer   = new TextMarkerService(Document);
                _textColorizer               = new TextColoringTransformer(Document);
                _scopeLineBackgroundRenderer = new ScopeLineBackgroundRenderer(Document);

                _contextActionsRenderer = new ContextActionsRenderer(this, _diagnosticMarkersRenderer);
                TextArea.LeftMargins.Add(_contextActionsRenderer);

                foreach (var contextActionProvider in LanguageService.GetContextActionProviders(DocumentAccessor))
                {
                    _contextActionsRenderer.Providers.Add(contextActionProvider);
                }

                TextArea.TextView.BackgroundRenderers.Add(_scopeLineBackgroundRenderer);
                TextArea.TextView.BackgroundRenderers.Add(_diagnosticMarkersRenderer);
                TextArea.TextView.LineTransformers.Insert(0, _textColorizer);

                _intellisenseManager = new IntellisenseManager(DocumentAccessor, _intellisense, _completionAssistant, LanguageService, sourceFile, offset =>
                {
                    var location = new TextViewPosition(Document.GetLocation(offset));

                    var visualLocation    = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom);
                    var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop);

                    var position = visualLocation - TextArea.TextView.ScrollOffset;
                    position     = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value);

                    _completionAssistantControl.SetLocation(position);
                });

                _disposables.Add(_intellisenseManager);

                TextArea.IndentationStrategy = LanguageService.IndentationStrategy;

                if (TextArea.IndentationStrategy == null)
                {
                    TextArea.IndentationStrategy = new DefaultIndentationStrategy();
                }

                _languageServiceDisposables = new CompositeDisposable
                {
                    Observable.FromEventPattern <DiagnosticsUpdatedEventArgs>(LanguageService, nameof(LanguageService.DiagnosticsUpdated)).ObserveOn(AvaloniaScheduler.Instance).Subscribe(args =>
                                                                                                                                                                                           LanguageService_DiagnosticsUpdated(args.Sender, args.EventArgs))
                };
            }
            else
            {
                LanguageService     = null;
                LanguageServiceName = "Plain Text";
            }

            StartBackgroundWorkers();

            Document.TextChanged += TextDocument_TextChanged;

            TextArea.TextEntering += TextArea_TextEntering;

            TextArea.TextEntered += TextArea_TextEntered;

            DoCodeAnalysisAsync().GetAwaiter();
        }
Example #12
0
        private void RegisterLanguageService(ISourceFile sourceFile)
        {
            UnRegisterLanguageService();

            if (sourceFile.Project?.Solution != null)
            {
                _snippetManager.InitialiseSnippetsForSolution(sourceFile.Project.Solution);
            }

            if (sourceFile.Project != null)
            {
                _snippetManager.InitialiseSnippetsForProject(sourceFile.Project);
            }

            LanguageService = _shell.LanguageServices.FirstOrDefault(o => o.CanHandle(DocumentAccessor));

            if (LanguageService != null)
            {
                SyntaxHighlighting = CustomHighlightingManager.Instance.GetDefinition(LanguageService.LanguageId.ToUpper());

                LanguageServiceName = LanguageService.Title;

                LanguageService.RegisterSourceFile(DocumentAccessor);

                _diagnosticMarkersRenderer   = new TextMarkerService(Document);
                _textColorizer               = new TextColoringTransformer(Document);
                _scopeLineBackgroundRenderer = new ScopeLineBackgroundRenderer(Document);

                TextArea.TextView.BackgroundRenderers.Add(_scopeLineBackgroundRenderer);
                TextArea.TextView.BackgroundRenderers.Add(_diagnosticMarkersRenderer);
                TextArea.TextView.LineTransformers.Insert(0, _textColorizer);

                _intellisenseManager = new IntellisenseManager(DocumentAccessor, _intellisense, _completionAssistant, LanguageService, sourceFile, offset =>
                {
                    var location = new TextViewPosition(Document.GetLocation(offset));

                    var visualLocation    = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom);
                    var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop);

                    var position = visualLocation - TextArea.TextView.ScrollOffset;
                    position     = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value);

                    _completionAssistantControl.SetLocation(position);
                });

                _disposables.Add(_intellisenseManager);

                TextArea.IndentationStrategy = LanguageService.IndentationStrategy;

                if (TextArea.IndentationStrategy == null)
                {
                    TextArea.IndentationStrategy = new DefaultIndentationStrategy();
                }

                //LanguageService.Diagnostics?.ObserveOn(AvaloniaScheduler.Instance).Subscribe(d =>
                //{
                //    _diagnosticMarkersRenderer?.SetDiagnostics(d);

                //    Diagnostics = d;

                //    _shell.InvalidateErrors();

                //    TextArea.TextView.Redraw();
                //});
            }
            else
            {
                LanguageService     = null;
                LanguageServiceName = "Plain Text";
            }

            StartBackgroundWorkers();

            Document.TextChanged += TextDocument_TextChanged;

            TextArea.TextEntering += TextArea_TextEntering;

            TextArea.TextEntered += TextArea_TextEntered;

            DoCodeAnalysisAsync().GetAwaiter();
        }
Example #13
0
        public MainForm()
        {
            var items = new List <AutocompleteItem>
            {
                new SnippetAutocompleteItem(
                    "if ^[expression]\r\n\r\t#do something\nend if"),
                new SnippetAutocompleteItem(
                    "try \r\n\r^#do something\n\rcatch ex\r\n#do something\n\nfinally\n#do something\nend try"),
                new SnippetAutocompleteItem(
                    "switch ^parent \r\n\r#do something\ncase condition:\r\n#do something\nbreak;\ndefault:\n#do something\nend switch")
            };

            //items.Add(new MethodAutocompleteItem2("Console.WriteLine"));

            foreach (ExtensionNode node in AddinManager.GetExtensionObjects("/EcIDE/Intellisense/Snippets"))
            {
                var cmd = node.CreateInstances <ISnippet>();

                cmd.ForEach(c => c.Init(new ServiceContainer()));
                cmd.ForEach(c => items.Add(new SnippetAutocompleteItem(c.GetSnippet())));
            }

            IntellisenseManager.PopulateClass(items, typeof(Console));
            IntellisenseManager.PopulateClass(items, typeof(MessageBox));

            foreach (ExtensionNode node in AddinManager.GetExtensionObjects("/EcIDE/Intellisense/Commands"))
            {
                var cmd = node.CreateInstances <IIntellisenseCommand>();

                cmd.ForEach(c => c.Init(new ServiceContainer()));

                foreach (IIntellisenseCommand intellisenseCommand in cmd)
                {
                    StyleManager.Add(
                        intellisenseCommand.GetPattern(),
                        intellisenseCommand.GetColor(),
                        intellisenseCommand.GetStyle());
                    InfoManager.Add(intellisenseCommand.GetPattern(), intellisenseCommand.GetDescription());

                    items.Add(new AutocompleteItem(intellisenseCommand.GetPattern(), 0));
                }
            }

            this.InitializeComponent();

            var menu = new AutocompleteMenu(this.fastColoredTextBox1)
            {
                SearchPattern = @"[\w\.]", AllowTabKey = true
            };

            menu.Items.SetAutocompleteItems(items);

            Console.SetOut(new ControlWriter(this.console));
            Console.SetIn(this.rdtxt);
            engine = new Engine {
                Flag = Engine.ExecutanFlags.RamOptimized
            };

            OptionsManager.Load();

            ServiceProviderContainer.AddService(new EditorService(this.fastColoredTextBox1));
            ServiceProviderContainer.AddService(new MenuService(this.MainMenu));
            ServiceProviderContainer.AddService(new AddinService(AddinManager.Registry));
            ServiceProviderContainer.AddService(new NotificationService(this.RadDesktopAlert));
            ServiceProviderContainer.AddService(new WindowService(this.dock));
            ServiceProviderContainer.AddService(new OptionsService());

            foreach (ExtensionNode node in AddinManager.GetExtensionObjects("/EcIDE/StartupCommands"))
            {
                var cmd = node.CreateInstances <ICommand>();

                cmd.ForEach(c => c.Init(new ServiceContainer()));
                cmd.ForEach(c => c.Run());

                var ecommand = node.GetCommand();

                foreach (var ec in ecommand)
                {
                    var ep = ec as window;
                    if (ep != null)
                    {
                        if (ep.title != "")
                        {
                            this.Text = ep.title;
                        }
                        if (ep.close != "")
                        {
                            cmd.ForEach(
                                c =>
                            {
                                this.FormClosing += (sender, args) => c.GetType().GetMethod(ep.close).Invoke(c, null);
                            });
                        }
                    }
                }
            }

            foreach (ExtensionNode node in AddinManager.GetExtensionObjects("/EcIDE/Menu"))
            {
                foreach (var ec in node.GetCommand())
                {
                    var ep = ec as menuitem;
                    if (ep != null)
                    {
                        var target = node.CreateInstances <IMenu>()[0];
                        target.Init(new ServiceContainer());

                        MainMenu.Items.Add(
                            new ToolStripMenuItem(ep.text, null, (sender, args) => target.GetType().GetMethod(ep.click).Invoke(target, new[] { sender, args })));
                    }
                }
            }

            MenuBinder.Bind(MainMenu);

            explorerTree.ExpandAll();

            projectProperties1.AddCurrentTabPage(new GeneralPage());
            this.AddPropertyTabPage("General", new GeneralPage());

            dock.CloseWindow(propertiesWindow);

            fastColoredTextBox1.Refresh();
        }
Example #14
0
        public CodeTextBox()
        {
            InitializeComponent();

            //Set some defaults...
            this.AcceptsTab = true;
            this.Font = new Font(FontFamily.GenericMonospace, 8f);

            // TODO
            //
            //Do not enable drag and dropping text
            //The same problem, as paste - the onDragDrop event fires, BEFORE the text is written into the textbox
            //Need to be handled in WndPrc
            this.EnableAutoDragDrop = false;

            this.DetectUrls = false;
            this.WordWrap = false;
            this.AutoWordSelection = true;

            #region Instantiate Syntax highlightning and Intellisense members
            //Instantiate word lists
            mp_CodeWords_Keywords        = new List<string>();
            mp_CodeWords_Types           = new List<string>();
            mp_CodeWords_Functions       = new List<string>();
            mp_CodeWords_Comments        = new List<string>();
            mp_CodeWords_ScopeOperators  = new List<string>();

            //Instantiate intellisense manager
            m_IntellisenseManager        = new IntellisenseManager(this);

            //Instantiate the intellisense box
            mp_IntellisenseBox           = new ImageListBox();

            //Instantiate intellisense tree
            mp_IntellisenseTree          = new TreeView();
            #endregion

            #region Setup intellisense box
            //Setup intellisense box
            this.Controls.Add(mp_IntellisenseBox);
            mp_IntellisenseBox.Size = new Size(250, 150);
            mp_IntellisenseBox.Visible = false;
            mp_IntellisenseBox.KeyDown += new KeyEventHandler(mp_IntellisenseBox_KeyDown);
            mp_IntellisenseBox.DoubleClick += new EventHandler(mp_IntellisenseBox_DoubleClick);
            #endregion
        }
Example #15
0
        public CodeEditor() : base(new TextArea(), null)
        {
            TextArea.IndentationStrategy = null;

            _shell = IoC.Get <IShell>();

            _snippetManager = IoC.Get <SnippetManager>();

            _lineNumberMargin = new LineNumberMargin(this);

            _breakpointMargin = new BreakPointMargin(this, IoC.Get <IDebugManager2>()?.Breakpoints);

            _selectedLineBackgroundRenderer    = new SelectedLineBackgroundRenderer(this);
            _bracketMatchingBackgroundRenderer = new BracketMatchingBackgroundRenderer(this);

            _selectedWordBackgroundRenderer = new SelectedWordBackgroundRenderer();

            _columnLimitBackgroundRenderer = new ColumnLimitBackgroundRenderer();

            _selectedDebugLineBackgroundRenderer = new SelectedDebugLineBackgroundRenderer();

            TextArea.TextView.Margin = new Thickness(10, 0, 0, 0);

            TextArea.TextView.BackgroundRenderers.Add(_selectedDebugLineBackgroundRenderer);
            TextArea.TextView.LineTransformers.Add(_selectedDebugLineBackgroundRenderer);
            TextArea.TextView.BackgroundRenderers.Add(_bracketMatchingBackgroundRenderer);

            TextArea.SelectionBrush        = Brush.Parse("#AA569CD6");
            TextArea.SelectionCornerRadius = 0;

            void tunneledKeyUpHandler(object send, KeyEventArgs ee)
            {
                if (CaretOffset > 0)
                {
                    _intellisenseManager?.OnKeyUp(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column);
                }
            }

            void tunneledKeyDownHandler(object send, KeyEventArgs ee)
            {
                if (CaretOffset > 0)
                {
                    _intellisenseManager?.OnKeyDown(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column);

                    if (ee.Key == Key.Tab && _currentSnippetContext == null && Editor is ICodeEditor codeEditor && codeEditor.LanguageService != null)
                    {
                        var wordStart = Document.FindPrevWordStart(CaretOffset);

                        if (wordStart > 0)
                        {
                            string word = Document.GetText(wordStart, CaretOffset - wordStart);

                            var codeSnippet = _snippetManager.GetSnippet(codeEditor.LanguageService, Editor.SourceFile.Project?.Solution, Editor.SourceFile.Project, word);

                            if (codeSnippet != null)
                            {
                                var snippet = SnippetParser.Parse(codeEditor.LanguageService, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column, codeSnippet.Snippet);

                                _intellisenseManager.CloseIntellisense();

                                using (Document.RunUpdate())
                                {
                                    Document.Remove(wordStart, CaretOffset - wordStart);

                                    _intellisenseManager.IncludeSnippets = false;
                                    _currentSnippetContext = snippet.Insert(TextArea);
                                }

                                if (_currentSnippetContext.ActiveElements.Count() > 0)
                                {
                                    IDisposable disposable = null;

                                    disposable = Observable.FromEventPattern <SnippetEventArgs>(_currentSnippetContext, nameof(_currentSnippetContext.Deactivated)).Take(1).Subscribe(o =>
                                    {
                                        _currentSnippetContext = null;
                                        _intellisenseManager.IncludeSnippets = true;

                                        disposable.Dispose();
                                    });
                                }
                                else
                                {
                                    _currentSnippetContext = null;
                                    _intellisenseManager.IncludeSnippets = true;
                                }
                            }
                        }
                    }
                }
            }

            _disposables = new CompositeDisposable {
                this.GetObservable(LineNumbersVisibleProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.LeftMargins.Add(_lineNumberMargin);
                    }
                    else
                    {
                        TextArea.LeftMargins.Remove(_lineNumberMargin);
                    }
                }),

                this.GetObservable(ShowBreakpointsProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.LeftMargins.Insert(0, _breakpointMargin);
                    }
                    else
                    {
                        TextArea.LeftMargins.Remove(_breakpointMargin);
                    }
                }),

                this.GetObservable(HighlightSelectedWordProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.TextView.BackgroundRenderers.Add(_selectedWordBackgroundRenderer);
                    }
                    else
                    {
                        TextArea.TextView.BackgroundRenderers.Remove(_selectedWordBackgroundRenderer);
                    }
                }),

                this.GetObservable(HighlightSelectedLineProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.TextView.BackgroundRenderers.Insert(0, _selectedLineBackgroundRenderer);
                    }
                    else
                    {
                        TextArea.TextView.BackgroundRenderers.Remove(_selectedLineBackgroundRenderer);
                    }
                }),

                this.GetObservable(ShowColumnLimitProperty).Subscribe(s =>
                {
                    if (s)
                    {
                        TextArea.TextView.BackgroundRenderers.Add(_columnLimitBackgroundRenderer);
                    }
                    else
                    {
                        TextArea.TextView.BackgroundRenderers.Remove(_columnLimitBackgroundRenderer);
                    }
                }),

                this.GetObservable(ColumnLimitProperty).Subscribe(limit =>
                {
                    _columnLimitBackgroundRenderer.Column = limit;
                    this.TextArea.TextView.InvalidateLayer(KnownLayer.Background);
                }),

                this.GetObservable(ContextActionsIconProperty).Subscribe(icon =>
                {
                    if (_contextActionsRenderer != null)
                    {
                        _contextActionsRenderer.IconImage = icon;
                    }
                }),

                this.GetObservable(ColorSchemeProperty).Subscribe(colorScheme =>
                {
                    if (colorScheme != null)
                    {
                        Background = colorScheme.Background;
                        Foreground = colorScheme.Text;

                        _lineNumberMargin.Background = colorScheme.Background;

                        if (_diagnosticMarkersRenderer != null)
                        {
                            _diagnosticMarkersRenderer.ColorScheme = colorScheme;
                        }

                        _textColorizer?.RecalculateBrushes();
                        TextArea.TextView.InvalidateLayer(KnownLayer.Background);
                        TextArea.TextView.Redraw();
                    }
                }),

                this.GetObservable(EditorCaretOffsetProperty).Subscribe(s =>
                {
                    if (Document?.TextLength >= s)
                    {
                        CaretOffset = s;
                        TextArea.Caret.BringCaretToView();
                    }
                }),

                BackgroundRenderersProperty.Changed.Subscribe(s =>
                {
                    if (s.Sender == this)
                    {
                        if (s.OldValue != null)
                        {
                            foreach (var renderer in (ObservableCollection <IBackgroundRenderer>)s.OldValue)
                            {
                                TextArea.TextView.BackgroundRenderers.Remove(renderer);
                            }
                        }

                        if (s.NewValue != null)
                        {
                            foreach (var renderer in (ObservableCollection <IBackgroundRenderer>)s.NewValue)
                            {
                                TextArea.TextView.BackgroundRenderers.Add(renderer);
                            }
                        }
                    }
                }),

                DocumentLineTransformersProperty.Changed.Subscribe(s =>
                {
                    if (s.Sender == this)
                    {
                        if (s.OldValue != null)
                        {
                            foreach (var renderer in (ObservableCollection <IVisualLineTransformer>)s.OldValue)
                            {
                                TextArea.TextView.LineTransformers.Remove(renderer);
                            }
                        }

                        if (s.NewValue != null)
                        {
                            foreach (var renderer in (ObservableCollection <IVisualLineTransformer>)s.NewValue)
                            {
                                TextArea.TextView.LineTransformers.Add(renderer);
                            }
                        }
                    }
                }),

                Observable.FromEventPattern(TextArea.Caret, nameof(TextArea.Caret.PositionChanged)).Subscribe(e =>
                {
                    if (_isLoaded && Document != null)
                    {
                        _lastLine = TextArea.Caret.Line;

                        Line              = TextArea.Caret.Line;
                        Column            = TextArea.Caret.Column;
                        EditorCaretOffset = TextArea.Caret.Offset;

                        var location = new TextViewPosition(Document.GetLocation(CaretOffset));

                        var visualLocation    = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom);
                        var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop);

                        var position = visualLocation - TextArea.TextView.ScrollOffset;
                        position     = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value);

                        _intellisenseControl.SetLocation(position);
                    }
                }),

                Observable.FromEventPattern(TextArea.Caret, nameof(TextArea.Caret.PositionChanged)).Throttle(TimeSpan.FromMilliseconds(100)).ObserveOn(AvaloniaScheduler.Instance).Subscribe(e =>
                {
                    if (Document != null)
                    {
                        var location = new TextViewPosition(Document.GetLocation(CaretOffset));

                        if (_intellisenseManager != null && !_textEntering)
                        {
                            if (TextArea.Selection.IsEmpty)
                            {
                                _intellisenseManager.SetCursor(CaretOffset, location.Line, location.Column, UnsavedFiles.ToList());
                            }
                            else if (_currentSnippetContext != null)
                            {
                                var offset = Document.GetOffset(TextArea.Selection.StartPosition.Location);
                                _intellisenseManager.SetCursor(offset, TextArea.Selection.StartPosition.Line, TextArea.Selection.StartPosition.Column, UnsavedFiles.ToList());
                            }
                        }

                        _selectedWordBackgroundRenderer.SelectedWord = GetWordAtOffset(CaretOffset);

                        TextArea.TextView.InvalidateLayer(KnownLayer.Background);
                    }
                }),

                this.WhenAnyValue(x => x.DebugHighlight).Where(loc => loc != null).Subscribe(location =>
                {
                    if (location.Line != -1)
                    {
                        SetDebugHighlight(location.Line, location.StartColumn, location.EndColumn);
                    }
                    else
                    {
                        ClearDebugHighlight();
                    }
                }),
                this.GetObservable(EditorProperty).Subscribe(editor =>
                {
                    if (editor != null)
                    {
                        if (editor.SourceFile.Project?.Solution != null)
                        {
                            _snippetManager.InitialiseSnippetsForSolution(editor.SourceFile.Project.Solution);
                        }

                        if (editor.SourceFile.Project != null)
                        {
                            _snippetManager.InitialiseSnippetsForProject(editor.SourceFile.Project);
                        }

                        SyntaxHighlighting = CustomHighlightingManager.Instance.GetDefinition(editor.SourceFile.ContentType);

                        if (editor.Document is AvalonStudioTextDocument td && Document != td.Document)
                        {
                            Document = td.Document;

                            if (editor.Offset <= Document.TextLength)
                            {
                                CaretOffset = editor.Offset;
                            }

                            _textColorizer = new TextColoringTransformer(Document);
                            _scopeLineBackgroundRenderer = new ScopeLineBackgroundRenderer(Document);


                            TextArea.TextView.BackgroundRenderers.Add(_scopeLineBackgroundRenderer);
                            TextArea.TextView.LineTransformers.Insert(0, _textColorizer);

                            _diagnosticMarkersRenderer = new TextMarkerService(Document);
                            _contextActionsRenderer    = new ContextActionsRenderer(this, _diagnosticMarkersRenderer);
                            TextArea.LeftMargins.Add(_contextActionsRenderer);
                            TextArea.TextView.BackgroundRenderers.Add(_diagnosticMarkersRenderer);
                        }

                        if (editor is ICodeEditor codeEditor)
                        {
                            if (codeEditor.Highlights != null)
                            {
                                _disposables.Add(
                                    Observable.FromEventPattern <NotifyCollectionChangedEventArgs>(codeEditor.Highlights, nameof(codeEditor.Highlights.CollectionChanged))
                                    .Subscribe(observer =>
                                {
                                    var e = observer.EventArgs;

                                    switch (e.Action)
                                    {
                                    case NotifyCollectionChangedAction.Add:
                                        foreach (var(tag, highlightList) in  e.NewItems.Cast <(object tag, SyntaxHighlightDataList highlightList)>())
                                        {
                                            _textColorizer.SetTransformations(tag, highlightList);
                                        }
                                        break;

                                    case NotifyCollectionChangedAction.Remove:
                                        foreach (var(tag, highlightList) in  e.OldItems.Cast <(object tag, SyntaxHighlightDataList highlightList)>())
                                        {
                                            _textColorizer.RemoveAll(i => i.Tag == tag);
                                        }
                                        break;

                                    case NotifyCollectionChangedAction.Reset:
                                        foreach (var(tag, highlightList) in  e.OldItems.Cast <(object tag, SyntaxHighlightDataList highlightList)>())
                                        {
                                            _textColorizer.RemoveAll(i => true);
                                        }
                                        break;

                                    default:
                                        throw new NotSupportedException();
                                    }

                                    TextArea.TextView.Redraw();
                                }));

                                _disposables.Add(
                                    Observable.FromEventPattern <NotifyCollectionChangedEventArgs>(codeEditor.Diagnostics, nameof(codeEditor.Diagnostics.CollectionChanged))
                                    .Subscribe(observer =>
                                {
                                    var e = observer.EventArgs;

                                    switch (e.Action)
                                    {
                                    case NotifyCollectionChangedAction.Add:
                                        foreach (var(tag, diagnostics) in  e.NewItems.Cast <(object tag, IEnumerable <Diagnostic> diagnostics)>())
                                        {
                                            _diagnosticMarkersRenderer.SetDiagnostics(tag, diagnostics);
                                        }
                                        break;

                                    case NotifyCollectionChangedAction.Remove:
                                        foreach (var(tag, diagnostics) in  e.OldItems.Cast <(object tag, IEnumerable <Diagnostic> diagnostics)>())
                                        {
                                            _diagnosticMarkersRenderer.RemoveAll(x => x.Tag == tag);
                                        }
                                        break;

                                    case NotifyCollectionChangedAction.Reset:
                                        foreach (var(tag, diagnostics) in  e.OldItems.Cast <(object tag, IEnumerable <Diagnostic> diagnostics)>())
                                        {
                                            _diagnosticMarkersRenderer.RemoveAll(i => true);
                                        }
                                        break;

                                    default:
                                        throw new NotSupportedException();
                                    }

                                    TextArea.TextView.Redraw();
                                    _contextActionsRenderer.OnDiagnosticsUpdated();
                                }));

                                _disposables.Add(codeEditor.WhenAnyValue(x => x.CodeIndex).Subscribe(codeIndex =>
                                {
                                    _scopeLineBackgroundRenderer.ApplyIndex(codeIndex);
                                }));

                                _scopeLineBackgroundRenderer.ApplyIndex(codeEditor.CodeIndex);

                                foreach (var(tag, diagnostics) in codeEditor.Diagnostics)
                                {
                                    _diagnosticMarkersRenderer.SetDiagnostics(tag, diagnostics);
                                }

                                foreach (var(tag, highlights) in codeEditor.Highlights)
                                {
                                    _textColorizer.SetTransformations(tag, highlights);
                                }

                                TextArea.TextView.Redraw();
                            }

                            _intellisenseManager = new IntellisenseManager(editor, Intellisense, _completionAssistant, codeEditor.LanguageService, editor.SourceFile, offset =>
                            {
                                var location = new TextViewPosition(Document.GetLocation(offset));

                                var visualLocation    = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom);
                                var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop);

                                var position = visualLocation - TextArea.TextView.ScrollOffset;
                                position     = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value);

                                _completionAssistantControl.SetLocation(position);
                            });

                            _disposables.Add(_intellisenseManager);

                            foreach (var contextActionProvider in codeEditor.LanguageService.GetContextActionProviders())
                            {
                                _contextActionsRenderer.Providers.Add(contextActionProvider);
                            }
                        }

                        Dispatcher.UIThread.Post(() =>
                        {
                            TextArea.ScrollToLine(Line);
                            Focus();
                        });
                    }
                    else
                    {
                        if (Document != null)
                        {
                            Document = null;
                        }
                    }
                }),
                this.GetObservable(RenameOpenProperty).Subscribe(open =>
                {
                    if (_isLoaded && Editor != null)
                    {
                        var token    = Editor.Document.GetToken(CaretOffset);
                        var location = new TextViewPosition(Document.GetLocation(token.Offset));

                        var visualLocation    = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom);
                        var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop);

                        var position = visualLocation - TextArea.TextView.ScrollOffset;
                        position     = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value);

                        _renameControl.SetLocation(position);
                        _renameControl.Open(this, Editor.Document.GetText(token));
                    }
                }),

                AddHandler(KeyDownEvent, tunneledKeyDownHandler, RoutingStrategies.Tunnel),
                AddHandler(KeyUpEvent, tunneledKeyUpHandler, RoutingStrategies.Tunnel)
            };

            Options = new AvaloniaEdit.TextEditorOptions
            {
                ConvertTabsToSpaces   = true,
                IndentationSize       = 4,
                EnableHyperlinks      = false,
                EnableEmailHyperlinks = false,
            };

            //BackgroundRenderersProperty.Changed.Subscribe(s =>
            //{
            //    if (s.Sender == this)
            //    {
            //        if (s.OldValue != null)
            //        {
            //            foreach (var renderer in (ObservableCollection<IBackgroundRenderer>)s.OldValue)
            //            {
            //                TextArea.TextView.BackgroundRenderers.Remove(renderer);
            //            }
            //        }

            //        if (s.NewValue != null)
            //        {
            //            foreach (var renderer in (ObservableCollection<IBackgroundRenderer>)s.NewValue)
            //            {
            //                TextArea.TextView.BackgroundRenderers.Add(renderer);
            //            }
            //        }
            //    }
            //});

            //DocumentLineTransformersProperty.Changed.Subscribe(s =>
            //{
            //    if (s.Sender == this)
            //    {
            //        if (s.OldValue != null)
            //        {
            //            foreach (var renderer in (ObservableCollection<IVisualLineTransformer>)s.OldValue)
            //            {
            //                TextArea.TextView.LineTransformers.Remove(renderer);
            //            }
            //        }

            //        if (s.NewValue != null)
            //        {
            //            foreach (var renderer in (ObservableCollection<IVisualLineTransformer>)s.NewValue)
            //            {
            //                TextArea.TextView.LineTransformers.Add(renderer);
            //            }
            //        }
            //    }
            //});


            /*_analysisTriggerEvents.Select(_ => Observable.Timer(TimeSpan.FromMilliseconds(300)).ObserveOn(AvaloniaScheduler.Instance)
             * .SelectMany(o => DoCodeAnalysisAsync())).Switch().Subscribe(_ => { });*/

            Intellisense = new IntellisenseViewModel();

            _completionAssistant = new CompletionAssistantViewModel(Intellisense);

            TextArea.TextEntering += TextArea_TextEntering;

            TextArea.TextEntered += TextArea_TextEntered;
        }

        ~CodeEditor()
        {
        }