public HighlightingOptions() { // ensure all definitions from AddIns are registered so that they are available for the example view AvalonEditDisplayBinding.RegisterAddInHighlightingDefinitions(); InitializeComponent(); textEditor.Document.UndoStack.SizeLimit = 0; CodeEditorOptions.Instance.BindToTextEditor(textEditor); textEditor.Options = new TextEditorOptions(CodeEditorOptions.Instance); bracketHighlighter = new BracketHighlightRenderer(textEditor.TextArea.TextView); foldingManager = FoldingManager.Install(textEditor.TextArea); textMarkerService = new TextMarkerService(textEditor.Document); textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); textEditor.Document.GetRequiredService<IServiceContainer>().AddService(typeof(ITextMarkerService), textMarkerService); }
public static DebugStackFrameMarker Create(TextMarkerService svc, DebugEngineWrapper.StackFrame frm) { string fn; uint ln; ulong off = frm.InstructionOffset; if (Engine.Symbols.GetLineByOffset(off, out fn, out ln)) { var text_off = svc.Editor.Document.GetOffset((int)ln, 0); var m = new DebugStackFrameMarker(svc, frm, text_off); m.Redraw(); return(m); } return(null); }
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); _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.Add(_textColorizer); _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(); }
public DecompilerTextView() { HighlightingManager.Instance.RegisterHighlighting( "ILAsm", new string[] { ".il" }, delegate { using (Stream s = typeof(DecompilerTextView).Assembly.GetManifestResourceStream(typeof(DecompilerTextView), "ILAsm-Mode.xshd")) { using (XmlTextReader reader = new XmlTextReader(s)) { return(HighlightingLoader.Load(reader, HighlightingManager.Instance)); } } }); this.Loaded += new RoutedEventHandler(DecompilerTextView_Loaded); InitializeComponent(); this.referenceElementGenerator = new ReferenceElementGenerator(this.JumpToReference, this.IsLink); textEditor.TextArea.TextView.ElementGenerators.Add(referenceElementGenerator); this.uiElementGenerator = new UIElementGenerator(); textEditor.TextArea.TextView.ElementGenerators.Add(uiElementGenerator); textEditor.Options.RequireControlModifierForHyperlinkClick = false; textEditor.TextArea.TextView.MouseHover += TextViewMouseHover; textEditor.TextArea.TextView.MouseHoverStopped += TextViewMouseHoverStopped; textEditor.SetBinding(TextEditor.FontFamilyProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFont") }); textEditor.SetBinding(TextEditor.FontSizeProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFontSize") }); // add marker service & margin iconMargin = new IconBarMargin((manager = new IconBarManager())); textMarkerService = new TextMarkerService(); textMarkerService.CodeEditor = textEditor; textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); textEditor.ShowLineNumbers = true; DisplaySettingsPanel.CurrentDisplaySettings.PropertyChanged += CurrentDisplaySettings_PropertyChanged; textEditor.TextArea.LeftMargins.Insert(0, iconMargin); textEditor.TextArea.TextView.VisualLinesChanged += delegate { iconMargin.InvalidateVisual(); }; // Bookmarks context menu IconMarginActionsProvider.Add(iconMargin); this.Loaded += new RoutedEventHandler(DecompilerTextView_Loaded); }
public DocumentView() { InitializeComponent(); _textMarkerService = new TextMarkerService(Editor); _errorMargin = new ErrorMargin { Visibility = Visibility.Collapsed, MarkerBrush = TryFindResource("ExceptionMarker") as Brush, Width = 10 }; Editor.TextArea.TextView.BackgroundRenderers.Add(_textMarkerService); Editor.TextArea.TextView.LineTransformers.Add(_textMarkerService); Editor.TextArea.LeftMargins.Insert(0, _errorMargin); Editor.PreviewMouseWheel += EditorOnPreviewMouseWheel; Editor.TextArea.Caret.PositionChanged += CaretOnPositionChanged; _syncContext = SynchronizationContext.Current; DataContextChanged += OnDataContextChanged; }
/// <summary> /// Constructor. Initialize all components and sets basic fields. /// </summary> /// <param name="currentLesson">Specyfic <see cref="Lesson"/> object for current lesson</param> public SourceCode(Lesson currentLesson) { InitializeComponent(); // Initialize with defaults CurrentLesson = currentLesson; TitleTextBox.Text = CurrentLesson.Title; LessonInfoTextBlock.Text = CurrentLesson.Info; SourceCodeTextBox.Text = CurrentLesson.DefaultCode; DiagnosticListView.ItemsSource = lastDiagnostics_; CurrentResultTextBlock.Text = CurrentLesson.CurrentResultsStars; // Create marker service textMarkerService_ = new TextMarkerService(SourceCodeTextBox.Document); SourceCodeTextBox.TextArea.TextView.BackgroundRenderers.Add(textMarkerService_); SourceCodeTextBox.TextArea.TextView.LineTransformers.Add(textMarkerService_); // Add service to document ((IServiceContainer)SourceCodeTextBox.Document .ServiceProvider .GetService(typeof(IServiceContainer))) ?.AddService(typeof(ITextMarkerService), textMarkerService_); SourceCodeTextBox.TextArea.TextEntered += SourceCodeTextBox_TextArea_TextEntered; SourceCodeTextBox.TextArea.SelectionChanged += SourceCodeTextBox_TextArea_SelectionChanged; SourceCodeTextBox.Focus(); // Handle real-time diagnostic updation dispacherTimer_.Tick += (sender, args) => { if (timer_.Elapsed >= TimeSpan.FromSeconds(1)) { UpdateDiagnostic(); timer_.Reset(); } }; dispacherTimer_.Interval = TimeSpan.FromSeconds(2); dispacherTimer_.Start(); UpdateDiagnostic(); EnbleAllButtons(); }
public MainWindow() { this.InitializeComponent(); this.Model = new Model(); this.DataContext = new ViewModel(this, this.Model); // Set up handlers to manage the cursor position in the status bar: this.SourceEditor.TextArea.Caret.PositionChanged += EditorPositionChanged; this.ResultsEditor.TextArea.Caret.PositionChanged += EditorPositionChanged; this.QueryEditor.TextArea.Caret.PositionChanged += EditorPositionChanged; this.QueryResultsEditor.TextArea.Caret.PositionChanged += EditorPositionChanged; // Install a find facility in the text editors ICSharpCode.AvalonEdit.Search.SearchPanel.Install(this.SourceEditor.TextArea); ICSharpCode.AvalonEdit.Search.SearchPanel.Install(this.ResultsEditor.TextArea); ICSharpCode.AvalonEdit.Search.SearchPanel.Install(this.QueryEditor.TextArea); ICSharpCode.AvalonEdit.Search.SearchPanel.Install(this.QueryResultsEditor.TextArea); // Initialize the text marker services for the editors, so squiggley lines can be added this.SourceEditorTextMarkerService = CreateTextMarkerService(this.SourceEditor); this.ResultsEditorTextMarkerService = CreateTextMarkerService(this.ResultsEditor); this.QueryEditorTextMarkerService = CreateTextMarkerService(this.QueryEditor); this.QueryResultsEditorTextMarkerService = CreateTextMarkerService(this.QueryResultsEditor); DispatcherTimer sourceEditorTimer = new DispatcherTimer() { IsEnabled = false }; sourceEditorTimer.Interval = TimeSpan.FromSeconds(2); sourceEditorTimer.Stop(); //sourceEditorTimer.Tick += (object s, EventArgs ea) => //{ // ViewModel.ExecuteExtractionCommand.Execute(null); // (s as DispatcherTimer).Stop(); //}; this.SourceEditor.TextChanged += (object sender, EventArgs e) => { sourceEditorTimer.Stop(); sourceEditorTimer.Start(); }; }
public DecompilerTextView() { InitializeComponent(); this.referenceElementGenerator = new ReferenceElementGenerator(this.JumpToReference, this.IsLink); textEditor.TextArea.TextView.ElementGenerators.Add(referenceElementGenerator); this.uiElementGenerator = new UIElementGenerator(); this.bracketHighlightRenderer = new BracketHighlightRenderer(textEditor.TextArea.TextView); textEditor.TextArea.TextView.ElementGenerators.Add(uiElementGenerator); textEditor.Options.RequireControlModifierForHyperlinkClick = false; textEditor.TextArea.TextView.PointerHover += TextViewMouseHover; textEditor.TextArea.TextView.PointerHoverStopped += TextViewMouseHoverStopped; textEditor.TextArea.AddHandler(PointerPressedEvent, TextAreaMouseDown, RoutingStrategies.Tunnel); textEditor.TextArea.AddHandler(PointerReleasedEvent, TextAreaMouseUp, RoutingStrategies.Tunnel); textEditor.TextArea.Caret.PositionChanged += HighlightBrackets; textEditor.Bind(TextEditor.FontFamilyProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = "SelectedFont" }); textEditor.Bind(TextEditor.FontSizeProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = "SelectedFontSize" }); textEditor.Bind(TextEditor.WordWrapProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = "EnableWordWrap" }); // disable Tab editing command (useless for read-only editor); allow using tab for focus navigation instead RemoveEditCommand(EditingCommands.TabForward); RemoveEditCommand(EditingCommands.TabBackward); textMarkerService = new TextMarkerService(textEditor.TextArea.TextView); textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); textEditor.ShowLineNumbers = true; DisplaySettingsPanel.CurrentDisplaySettings.PropertyChanged += CurrentDisplaySettings_PropertyChanged; // TODO: SearchPanel is automatically installed, but have to disable replace mode // TemplateApplied += (s,e) => ShowLineMargin(); // add marker service & margin textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); }
public void UnRegisterLanguageService() { 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(this, SourceFile); } Document.TextChanged -= TextDocument_TextChanged; }
public DecompilerTextView() { HighlightingManager.Instance.RegisterHighlighting( "ILAsm", new string[] { ".il" }, delegate { using (Stream s = typeof(DecompilerTextView).Assembly.GetManifestResourceStream(typeof(DecompilerTextView), "ILAsm-Mode.xshd")) { using (XmlTextReader reader = new XmlTextReader(s)) { return(HighlightingLoader.Load(reader, HighlightingManager.Instance)); } } }); InitializeComponent(); this.referenceElementGenerator = new ReferenceElementGenerator(this.JumpToReference, this.IsLink); textEditor.TextArea.TextView.ElementGenerators.Add(referenceElementGenerator); this.uiElementGenerator = new UIElementGenerator(); textEditor.TextArea.TextView.ElementGenerators.Add(uiElementGenerator); textEditor.Options.RequireControlModifierForHyperlinkClick = false; textEditor.TextArea.TextView.MouseHover += TextViewMouseHover; textEditor.TextArea.TextView.MouseHoverStopped += TextViewMouseHoverStopped; textEditor.SetBinding(Control.FontFamilyProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFont") }); textEditor.SetBinding(Control.FontSizeProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFontSize") }); textMarkerService = new TextMarkerService(textEditor.Document); textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); textEditor.ShowLineNumbers = true; DisplaySettingsPanel.CurrentDisplaySettings.PropertyChanged += CurrentDisplaySettings_PropertyChanged; // Bookmarks context menu textEditor.TextArea.DefaultInputHandler.NestedInputHandlers.Add(new SearchInputHandler(textEditor.TextArea)); ShowLineMargin(); // add marker service & margin textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); }
public DocumentView() { InitializeComponent(); _textMarkerService = new TextMarkerService(Editor); Editor.TextArea.TextView.BackgroundRenderers.Add(_textMarkerService); Editor.TextArea.TextView.LineTransformers.Add(_textMarkerService); Editor.Options = new TextEditorOptions { ConvertTabsToSpaces = true, AllowScrollBelowDocument = true, IndentationSize = 4 }; Editor.PreviewMouseWheel += EditorOnPreviewMouseWheel; Editor.TextArea.Caret.PositionChanged += CaretOnPositionChanged; _syncContext = SynchronizationContext.Current; DataContextChanged += OnDataContextChanged; }
public DAXEditor() { //DefaultStyleKeyProperty.OverrideMetadata(typeof(DAXEditor), new FrameworkPropertyMetadata(typeof(DAXEditor))); //SearchPanel.Install(this.TextArea); var brush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#C8FFA55F")); //orange // grey FFE6E6E6 HighlightBackgroundBrush = brush; this.TextArea.SelectionChanged += TextEditor_TextArea_SelectionChanged; TextView textView = this.TextArea.TextView; // Add Bracket Highlighter _bracketRenderer = new BracketHighlightRenderer(textView); textView.BackgroundRenderers.Add(_bracketRenderer); //textView.LineTransformers.Add(_bracketRenderer); textView.Services.AddService(typeof(BracketHighlightRenderer), _bracketRenderer); // Add Syntax Error marker _textMarkerService = new TextMarkerService(this); textView.BackgroundRenderers.Add(_textMarkerService); textView.LineTransformers.Add(_textMarkerService); textView.Services.AddService(typeof(TextMarkerService), _textMarkerService); // add handlers for tooltip error display textView.MouseHover += TextEditorMouseHover; textView.MouseHoverStopped += TextEditorMouseHoverStopped; textView.VisualLinesChanged += VisualLinesChanged; //textView.PreviewKeyUp += TextArea_PreviewKeyUp; // add the stub Intellisense provider IntellisenseProvider = new IntellisenseProviderStub(); this.DocumentChanged += DaxEditor_DocumentChanged; DataObject.AddPastingHandler(this, OnDataObjectPasting); RegiserKeyBindings(); }
/// <summary> /// Init service /// </summary> private void InitializeTextMarkerService() { var textMarkerService = new TextMarkerService(editor.Document); editor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); editor.TextArea.TextView.LineTransformers.Add(textMarkerService); IServiceContainer services = (IServiceContainer)editor.Document.ServiceProvider.GetService(typeof(IServiceContainer)); if (services != null) { services.AddService(typeof(ITextMarkerService), textMarkerService); } this.textMarkerService = textMarkerService; // Syntax highlight using (Stream s = this.GetType().Assembly.GetManifestResourceStream("Simplic.EPLEditor.AvalonEditor.EPL.xshd")) { using (XmlTextReader reader = new XmlTextReader(s)) { editor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance); } } }
private void TemplateServiceProviderOnTemplateCreated(object sender, GeneratedTemplateInfos e) { BeginThreadSaveAction(() => { TextMarkerService.RemoveAll(f => true); foreach (var morestachioError in e.Errors ?? new IMorestachioError[0]) { //var column = Math.Max( // morestachioError.Location.Snipped.Snipped.Length - morestachioError.Location.Character - 1, // morestachioError.Location.Character - 1); var charOffset = Template.GetOffset(morestachioError.Location.Line, morestachioError.Location.Character - 1); var textMarker = TextMarkerService.Create(charOffset, 1); textMarker.MarkerColor = Colors.Red; textMarker.MarkerTypes = TextMarkerTypes.SquigglyUnderline; } if (e.InferredTemplateModel != null) { MorestachioFoldingStrategy.UpdateFolding(FoldingManager, Template, e.InferredTemplateModel); } }); }
void CreateTextEditor() { if (textEditorHost != null) { return; } textEditor = AvalonEditTextEditorAdapter.CreateAvalonEditInstance(); textEditor.IsReadOnly = true; textEditor.MouseDoubleClick += TextEditorDoubleClick; var adapter = new AvalonEditTextEditorAdapter(textEditor); var textMarkerService = new TextMarkerService(adapter.TextEditor.Document); adapter.TextEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); adapter.TextEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); adapter.TextEditor.TextArea.TextView.Services.AddService(typeof(ITextMarkerService), textMarkerService); textEditorHost = new ElementHost(); textEditorHost.Dock = DockStyle.Fill; textEditorHost.Child = textEditor; }
public MainWindow() { _viewModel = new MainViewModel(); _viewModel.NuGet.PackageInstalled += NuGetOnPackageInstalled; DataContext = _viewModel; InitializeComponent(); _textMarkerService = new TextMarkerService(Editor); Editor.TextArea.TextView.BackgroundRenderers.Add(_textMarkerService); Editor.TextArea.TextView.LineTransformers.Add(_textMarkerService); ConfigureEditor(); _lock = new object(); _objects = new ObservableCollection <ResultObject>(); BindingOperations.EnableCollectionSynchronization(_objects, _lock); Results.ItemsSource = _objects; ObjectExtensions.Dumped += OnDumped; var syncContext = SynchronizationContext.Current; _viewModel.RoslynHost.GetService <IDiagnosticService>().DiagnosticsUpdated += (sender, args) => syncContext.Post(o => ProcessDiagnostics(args), null); var avalonEditTextContainer = new AvalonEditTextContainer(Editor); _viewModel.RoslynHost.SetDocument(avalonEditTextContainer); _viewModel.RoslynHost.ApplyingTextChange += (id, text) => avalonEditTextContainer.UpdateText(text); Editor.TextArea.TextView.LineTransformers.Insert(0, new RoslynHighlightingColorizer(_viewModel.RoslynHost)); _contextActionsRenderer = new ContextActionsRenderer(Editor, _textMarkerService); _contextActionsRenderer.Providers.Add(new RoslynContextActionProvider(_viewModel.RoslynHost)); Editor.CompletionProvider = new RoslynCodeEditorCompletionProvider(_viewModel.RoslynHost); }
public DAXEditor() { //SearchPanel.Install(this.TextArea); var brush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#C8FFA55F")); //orange // grey FFE6E6E6 HighlightBackgroundBrush = brush; this.TextArea.SelectionChanged += textEditor_TextArea_SelectionChanged; TextView textView = this.TextArea.TextView; // Add Bracket Highlighter _bracketRenderer = new BracketHighlightRenderer(textView); textView.BackgroundRenderers.Add(_bracketRenderer); //textView.LineTransformers.Add(_bracketRenderer); textView.Services.AddService(typeof(BracketHighlightRenderer), _bracketRenderer); // Add Syntax Error marker textMarkerService = new TextMarkerService(this); textView.BackgroundRenderers.Add(textMarkerService); textView.LineTransformers.Add(textMarkerService); textView.Services.AddService(typeof(TextMarkerService), textMarkerService); // add handlers for tooltip error display textView.MouseHover += TextEditorMouseHover; textView.MouseHoverStopped += TextEditorMouseHoverStopped; textView.VisualLinesChanged += VisualLinesChanged; //textView.PreviewKeyUp += TextArea_PreviewKeyUp; // add the stub Intellisense provider IntellisenseProvider = new IntellisenseProviderStub(); this.DocumentChanged += DaxEditor_DocumentChanged; }
public MainWindow() { InitializeComponent(); TextEdit.TextArea.TextView.LineTransformers.Add(new ColorizeAvalonEdit()); string[] commands = { "call", "ret", "add", "sub", "div", "mul", "xor", "and", "or", "not", "inc", "dec", "ret", "mov", "push", "pop", "jmp", "cmp", "jt", "jnt", "lstart", "lend", "nop" }; string[] registers = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "ax", "bx", "cx", "dx" }; /* * */ foreach (var str in commands) { ColorizedCommands.Instance.Add(new ColorizedCommands.HighlightCommand() { command = str, size = 21, forecolor = System.Windows.Media.Brushes.Yellow, bold = true }); } foreach (var str in registers) { ColorizedCommands.Instance.Add(new ColorizedCommands.HighlightCommand() { command = str, size = 21, forecolor = System.Windows.Media.Brushes.LightGreen, bold = true }); } ColorizedCommands.Instance.Add(new ColorizedCommands.HighlightCommand() { command = "break", size = 25, background = System.Windows.Media.Brushes.Red, bold = true }); ColorizedCommands.Instance.Add(new ColorizedCommands.HighlightCommand() { command = "//", size = 25, background = System.Windows.Media.Brushes.Green, }); var textMarkerService = new TextMarkerService(TextEdit.Document); TextEdit.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); TextEdit.TextArea.TextView.LineTransformers.Add(textMarkerService); IServiceContainer services = (IServiceContainer)TextEdit.Document.ServiceProvider.GetService(typeof(IServiceContainer)); if (services != null) { services.AddService(typeof(ITextMarkerService), textMarkerService); } this.textMarkerService = textMarkerService; TextEdit.TextArea.TextEntering += textEditor_TextArea_TextEntering; TextEdit.TextArea.TextEntered += textEditor_TextArea_TextEntered; AppendText("Output:\n", "White"); }
void Init() { // Apply common editor settings to this instance CommonEditorSettings.Instance.AssignToEditor(Editor); // If Ctrl+MouseWheel was pressed/turned, increase/decrease font size Editor.PreviewMouseWheel += new MouseWheelEventHandler((object sender, MouseWheelEventArgs e)=> { if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { CommonEditorSettings.Instance.FontSize = CommonEditorSettings.Instance.FontSize+( e.Delta > 0 ? 1 : -1); CommonEditorSettings.Instance.AssignAllOpenEditors(); e.Handled = true; } }); /* * HACK: To re-focus the editor when this document is activated (the user chose this document tab page) * , it's simply needed to catch the Loaded-Event which calls Focus on the editor instance then! */ Editor.Loaded += new RoutedEventHandler((object sender, RoutedEventArgs e) => { DoOutsideModificationCheck(); Editor.Focus(); }); #region UI Command registration /* * UI Command hack - delete the DeleteLine command (which is bound statically to Ctrl-D) * and override it with our line duplication event */ var commandBindings=Editor.TextArea.CommandBindings; foreach(CommandBinding cb in commandBindings) if (cb.Command == AvalonEditCommands.DeleteLine) { // Note: We have to break the for-loop because we change the commandBinding's contents! commandBindings.Remove(cb); break; } CommandBindings.Add(new CommandBinding(IDEUICommands.DoubleLine,DoubleLine)); CommandBindings.Add(new CommandBinding(ApplicationCommands.Save,Save_event)); CommandBindings.Add(new CommandBinding(IDEUICommands.ToggleBreakpoint,ToggleBreakpoint_event)); #endregion // Setup editor overlay // Let a grid own the entire control // - this enables us in EditorDocument derivates to insert additional controls var gr = new Grid(); MainEditorContainer = gr; AddChild(gr); gr.Children.Add(Editor); // Let there be no border Editor.Margin = new System.Windows.Thickness(0); Editor.BorderBrush = null; // Init bracket hightlighter bracketHightlighter = new BracketHighlightRenderer(Editor.TextArea.TextView); //TODO: More editor settings Editor.ShowLineNumbers = true; Editor.TextChanged += new EventHandler(Editor_TextChanged); Editor.Document.PropertyChanged+=new System.ComponentModel.PropertyChangedEventHandler(Document_PropertyChanged); // Register Marker strategy MarkerStrategy = new TextMarkerService(Editor); Editor.TextArea.MouseRightButtonDown += new System.Windows.Input.MouseButtonEventHandler(TextArea_MouseRightButtonDown); // Make UTF-8 encoding default Editor.Encoding = Encoding.UTF8; // Enhance text rendering TextOptions.SetTextFormattingMode(Editor.TextArea.TextView, TextFormattingMode.Display); TextOptions.SetTextRenderingMode(Editor.TextArea.TextView, TextRenderingMode.ClearType); // Load file contents if file path given Reload(); // Initially draw all probably required text markers RefreshErrorHighlightings(); RefreshBreakpointHighlightings(); RefreshDebugHighlightings(); }
private void GenerateDiagnostics(IEnumerable <ClangDiagnostic> clangDiagnostics, ClangTranslationUnit translationUnit, IProject project, TextSegmentCollection <Diagnostic> result, TextMarkerService service) { foreach (var diagnostic in clangDiagnostics) { if (diagnostic.Location.IsFromMainFile) { var diag = new Diagnostic { Project = project, StartOffset = diagnostic.Location.FileLocation.Offset, Line = diagnostic.Location.FileLocation.Line, Spelling = diagnostic.Spelling, File = diagnostic.Location.FileLocation.File.FileName, Level = (DiagnosticLevel)diagnostic.Severity }; var cursor = translationUnit.GetCursor(diagnostic.Location); var tokens = translationUnit.Tokenize(cursor.CursorExtent); foreach (var token in tokens.Tokens) { if (token.Location == diagnostic.Location) { diag.EndOffset = diag.StartOffset + token.Spelling.Length; } } result.Add(diag); tokens.Dispose(); Color markerColor; switch (diag.Level) { case DiagnosticLevel.Error: case DiagnosticLevel.Fatal: markerColor = Color.FromRgb(253, 45, 45); break; case DiagnosticLevel.Warning: markerColor = Color.FromRgb(255, 207, 40); break; default: markerColor = Color.FromRgb(0, 42, 74); break; } service.Create(diag.StartOffset, diag.Length, diag.Spelling, markerColor); } } }
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(); }
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(); }
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() { }
public CSharpDataAssociation(TextDocument textDocument) { BackgroundRenderers = new List<IBackgroundRenderer>(); DocumentLineTransformers = new List<IDocumentLineTransformer>(); TextColorizer = new TextColoringTransformer(textDocument); TextMarkerService = new TextMarkerService(textDocument); BackgroundRenderers.Add(new BracketMatchingBackgroundRenderer()); BackgroundRenderers.Add(TextMarkerService); DocumentLineTransformers.Add(TextColorizer); }
public SourceEditor() { this.TextArea.Caret.PositionChanged += (object sender, EventArgs a) => { var caret = sender as ICSharpCode.AvalonEdit.Editing.Caret; this.Model.CaretPositionString = string.Format(CultureInfo.CurrentCulture, "Line: {0} Column: {1}", caret.Line, caret.Column); }; // Install the search panel that appears in the upper left corner. ICSharpCode.AvalonEdit.Search.SearchPanel.Install(this.TextArea); this.PreviewMouseWheel += MouseWheelHandler; this.IsReadOnly = true; var fontFamilyBinding = new Binding("SourceFont") { Source = Properties.Settings.Default }; this.SetBinding(FontFamilyProperty, fontFamilyBinding); var fontSizeBinding = new Binding("SourceFontSize") { Source = Properties.Settings.Default }; this.SetBinding(FontSizeProperty, fontSizeBinding); var showLineNumbersBinding = new Binding("ShowLineNumbers") { Source = Properties.Settings.Default }; this.SetBinding(ShowLineNumbersProperty, showLineNumbersBinding); this.Options = new TextEditorOptions { ConvertTabsToSpaces = true, IndentationSize = 4, }; var textMarkerService = new TextMarkerService(this.Document); this.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); this.TextArea.TextView.LineTransformers.Add(textMarkerService); IServiceContainer services = (IServiceContainer)this.Document.ServiceProvider.GetService(typeof(IServiceContainer)); if (services != null) { services.AddService(typeof(ITextMarkerService), textMarkerService); } this.TextMarkerService = textMarkerService; this.ContextMenu = new ContextMenu { ItemsSource = new[] { new MenuItem { Command = ApplicationCommands.Cut, Icon = new Image { Source = new BitmapImage(new Uri("images/Cut_16x.png", UriKind.Relative)) } }, new MenuItem { Command = ApplicationCommands.Copy, Icon = new Image { Source = new BitmapImage(new Uri("images/Copy_16x.png", UriKind.Relative)) } }, new MenuItem { Command = ApplicationCommands.Paste, Icon = new Image { Source = new BitmapImage(new Uri("images/Paste_16x.png", UriKind.Relative)) } }, new MenuItem { Command = ApplicationCommands.Delete, Icon = new Image { Source = new BitmapImage(new Uri("images/Cancel_16x.png", UriKind.Relative)) } }, new MenuItem() { Header = "Undo", ToolTip = "Undo", Icon = new Image { Source = new BitmapImage(new Uri("images/undo_16x.png", UriKind.Relative)) }, InputGestureText = "Ctrl+Z", Command = new RelayCommand( p => { this.Undo(); }, p => { return(this.CanUndo); }) }, new MenuItem() { Header = "Redo", ToolTip = "Redo", Icon = new Image { Source = new BitmapImage(new Uri("images/redo_16x.png", UriKind.Relative)) }, InputGestureText = "Ctrl+Y", Command = new RelayCommand( p => { this.Redo(); }, p => { return(this.CanRedo); }) }, new MenuItem { Command = ApplicationCommands.SelectAll, Icon = new Image { Source = new BitmapImage(new Uri("images/SelectAll_16x.png", UriKind.Relative)) } } } }; }
private void InitializeTextEditor() { #region AssemblyLoader assemblyLoader = new AssemblyLoader(); assemblyLoader.AssembliesLoading += (sender, args) => OnAssembliesLoading(args.Value); assemblyLoader.InternalAssembliesLoaded += (sender, args) => OnInternalAssembliesLoaded(args.Value); assemblyLoader.AssembliesLoaded += (sender, args) => OnAssembliesLoaded(args.Value); assemblyLoader.AssembliesUnloading += (sender, args) => OnAssembliesUnloading(args.Value); assemblyLoader.InternalAssembliesUnloaded += (sender, args) => OnInternalAssembliesUnloaded(args.Value); assemblyLoader.AssembliesUnloaded += (sender, args) => OnAssembliesUnloaded(args.Value); #endregion #region TextMarkerService textMarkerService = new TextMarkerService(TextEditor.Document); TextEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); TextEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); TextEditor.TextArea.TextView.Services.AddService(typeof(ITextMarkerService), textMarkerService); #endregion #region ReadOnlySectionProvider TextEditor.TextArea.ReadOnlySectionProvider = new MethodDefinitionReadOnlySectionProvider(this); #endregion #region SearchPanel SearchPanel.Install(TextEditor); #endregion #region CompletionCommand CompletionCommand = new Input.RoutedCommand(); CompletionCommand.InputGestures.Add(new Input.KeyGesture(Input.Key.Space, Input.ModifierKeys.Control)); #endregion #region MoveLinesUpCommand var moveLinesUpCommand = new Input.RoutedCommand(); moveLinesUpCommand.InputGestures.Add(new Input.KeyGesture(Input.Key.Up, Input.ModifierKeys.Alt)); var moveLinesUpCommandBinding = new Input.CommandBinding(moveLinesUpCommand, (sender, args) => ExecuteMoveLinesCommand(MovementDirection.Up)); TextEditor.CommandBindings.Add(moveLinesUpCommandBinding); #endregion #region MoveLinesDownCommand var moveLinesDownCommand = new Input.RoutedCommand(); moveLinesDownCommand.InputGestures.Add(new Input.KeyGesture(Input.Key.Down, Input.ModifierKeys.Alt)); var moveLinesDownCommandBinding = new Input.CommandBinding(moveLinesDownCommand, (sender, args) => ExecuteMoveLinesCommand(MovementDirection.Down)); TextEditor.CommandBindings.Add(moveLinesDownCommandBinding); #endregion #region GoToLineCommand var goToLineCommand = new Input.RoutedCommand(); goToLineCommand.InputGestures.Add(new Input.KeyGesture(Input.Key.G, Input.ModifierKeys.Control)); var goToLineCommandBinding = new Input.CommandBinding(goToLineCommand, (sender, args) => ExecuteGoToLineCommand()); TextEditor.CommandBindings.Add(goToLineCommandBinding); #endregion TextEditorSyntaxHighlighting = DefaultTextEditorSyntaxHighlighting; TextEditorShowLineNumbers = DefaultTextEditorShowLineNumbers; TextEditorShowSpaces = DefaultTextEditorShowSpaces; TextEditorShowTabs = DefaultTextEditorShowTabs; TextEditorConvertTabsToSpaces = DefaultTextEditorConvertTabsToSpaces; TextEditorHighlightCurrentLine = DefaultTextEditorHighlightCurrentLine; TextEditorIndentationSize = DefaultTextEditorIndentationSize; Doc.FileName = DefaultDocumentFileName; TextEditor.FontFamily = new Media.FontFamily(DefaultTextEditorFontFamily); TextEditor.FontSize = DefaultTextEditorFontSize; TextEditor.Options.EnableVirtualSpace = true; TextEditor.TextArea.IndentationStrategy = new CSharpIndentationStrategy(TextEditor.Options); TextEditor.TextChanged += (sender, args) => { foreach (var marker in textMarkerService.TextMarkers) { if (marker == prefixMarker || marker == suffixMarker) { continue; } if (marker.Length != (int)marker.Tag) { marker.Delete(); } else { int caretOffset = TextEditor.CaretOffset; var line = Doc.GetLineByOffset(marker.StartOffset); int lineEndOffset = line.EndOffset; if (caretOffset == lineEndOffset) // special case for markers beyond line length { marker.Delete(); } } } OnTextEditorTextChanged(); }; }
void Init() { // Apply common editor settings to this instance CommonEditorSettings.Instance.AssignToEditor(Editor); // If Ctrl+MouseWheel was pressed/turned, increase/decrease font size Editor.PreviewMouseWheel += new MouseWheelEventHandler((object sender, MouseWheelEventArgs e) => { if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { CommonEditorSettings.Instance.FontSize = CommonEditorSettings.Instance.FontSize + (e.Delta > 0 ? 1 : -1); CommonEditorSettings.Instance.AssignAllOpenEditors(); e.Handled = true; } }); /* * HACK: To re-focus the editor when this document is activated (the user chose this document tab page) * , it's simply needed to catch the Loaded-Event which calls Focus on the editor instance then! */ Editor.Loaded += new RoutedEventHandler((object sender, RoutedEventArgs e) => { DoOutsideModificationCheck(); Editor.Focus(); }); #region UI Command registration /* * UI Command hack - delete the DeleteLine command (which is bound statically to Ctrl-D) * and override it with our line duplication event */ var commandBindings = Editor.TextArea.CommandBindings; foreach (CommandBinding cb in commandBindings) { if (cb.Command == AvalonEditCommands.DeleteLine) { // Note: We have to break the for-loop because we change the commandBinding's contents! commandBindings.Remove(cb); break; } } CommandBindings.Add(new CommandBinding(IDEUICommands.DoubleLine, DoubleLine)); CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, Save_event)); CommandBindings.Add(new CommandBinding(IDEUICommands.ToggleBreakpoint, ToggleBreakpoint_event)); #endregion // Setup editor overlay // Let a grid own the entire control // - this enables us in EditorDocument derivates to insert additional controls var gr = new Grid(); MainEditorContainer = gr; AddChild(gr); gr.Children.Add(Editor); // Let there be no border Editor.Margin = new System.Windows.Thickness(0); Editor.BorderBrush = null; // Init bracket hightlighter bracketHightlighter = new BracketHighlightRenderer(Editor.TextArea.TextView); //TODO: More editor settings Editor.ShowLineNumbers = true; Editor.TextChanged += new EventHandler(Editor_TextChanged); Editor.Document.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Document_PropertyChanged); // Register Marker strategy MarkerStrategy = new TextMarkerService(Editor); Editor.TextArea.MouseRightButtonDown += new System.Windows.Input.MouseButtonEventHandler(TextArea_MouseRightButtonDown); // Make UTF-8 encoding default Editor.Encoding = Encoding.UTF8; // Enhance text rendering TextOptions.SetTextFormattingMode(Editor.TextArea.TextView, TextFormattingMode.Display); TextOptions.SetTextRenderingMode(Editor.TextArea.TextView, TextRenderingMode.ClearType); // Load file contents if file path given Reload(); // Initially draw all probably required text markers RefreshErrorHighlightings(); RefreshBreakpointHighlightings(); RefreshDebugHighlightings(); }
/// <summary> /// Cria uma nova instância de TankProperties /// </summary> public TankProperties() { this.InitializeComponent(); #if DEBUG this.AttachDevTools(); #endif _editor = this.FindControl <TextEditor>("Editor"); _editor.Background = Brushes.Transparent; _editor.Options.ConvertTabsToSpaces = true; _editor.Options.IndentationSize = 4; _editor.ShowLineNumbers = true; _editor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#"); _editor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _editor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _editor.TextArea.TextInput += TextArea_TextInput; _editor.TextArea.Initialized += (s, a) => AnalyzeCodeSyntax(); _editor.KeyUp += TextArea_KeyUp; _editor.TextArea.IndentationStrategy = new AvaloniaEdit.Indentation.CSharp.CSharpIndentationStrategy(); _insightWindow = new OverloadInsightWindow(_editor.TextArea); _editor.FontFamily = GetPlatformFontFamily(); _editor.TextArea.PointerMoved += TextArea_PointerMoved; foldingManager = FoldingManager.Install(_editor.TextArea); foldingStretegy = new BraceFoldingStrategy(); var textMarkerService = new TextMarkerService(_editor.Document); _editor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); _editor.TextArea.TextView.LineTransformers.Add(textMarkerService); IServiceContainer services = _editor.Document.GetService <IServiceContainer>(); if (services != null) { services.AddService(typeof(ITextMarkerService), textMarkerService); } this.textMarkerService = textMarkerService; this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) { return; } if (i.Delta.Y > 0) { _editor.FontSize++; } else { _editor.FontSize = _editor.FontSize > 1 ? _editor.FontSize - 1 : 1; } }, RoutingStrategies.Bubble, true); codeService = CodeAnalysisService.LoadDocument(_editor.Document.Text); UndoCommand = new CommandAdapter(true) { Action = (p) => _editor.Undo() }; RedoCommand = new CommandAdapter(true) { Action = (p) => _editor.Redo() }; }
public DecompilerTextView() { HighlightingManager.Instance.RegisterHighlighting( "ILAsm", new string[] { ".il" }, delegate { using (Stream s = typeof(DecompilerTextView).Assembly.GetManifestResourceStream(typeof(DecompilerTextView), "ILAsm-Mode.xshd")) { using (XmlTextReader reader = new XmlTextReader(s)) { return(HighlightingLoader.Load(reader, HighlightingManager.Instance)); } } }); HighlightingManager.Instance.RegisterHighlighting( "C#", new string[] { ".cs" }, delegate { using (Stream s = typeof(DecompilerTextView).Assembly.GetManifestResourceStream(typeof(DecompilerTextView), "CSharp-Mode.xshd")) { using (XmlTextReader reader = new XmlTextReader(s)) { return(HighlightingLoader.Load(reader, HighlightingManager.Instance)); } } }); InitializeComponent(); this.referenceElementGenerator = new ReferenceElementGenerator(this.JumpToReference, this.IsLink); textEditor.TextArea.TextView.ElementGenerators.Add(referenceElementGenerator); this.uiElementGenerator = new UIElementGenerator(); textEditor.TextArea.TextView.ElementGenerators.Add(uiElementGenerator); textEditor.Options.RequireControlModifierForHyperlinkClick = false; textEditor.TextArea.TextView.PointerHover += TextViewMouseHover; textEditor.TextArea.TextView.PointerHoverStopped += TextViewMouseHoverStopped; textEditor.TextArea.AddHandler(PointerPressedEvent, TextAreaMouseDown, RoutingStrategies.Tunnel); textEditor.TextArea.AddHandler(PointerReleasedEvent, TextAreaMouseUp, RoutingStrategies.Tunnel); textEditor.Bind(TextEditor.FontFamilyProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = "SelectedFont" }); textEditor.Bind(TextEditor.FontSizeProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = "SelectedFontSize" }); textEditor.Bind(TextEditor.WordWrapProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = "EnableWordWrap" }); // disable Tab editing command (useless for read-only editor); allow using tab for focus navigation instead RemoveEditCommand(EditingCommands.TabForward); RemoveEditCommand(EditingCommands.TabBackward); textMarkerService = new TextMarkerService(textEditor.TextArea.TextView); textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); textEditor.ShowLineNumbers = true; DisplaySettingsPanel.CurrentDisplaySettings.PropertyChanged += CurrentDisplaySettings_PropertyChanged; // TODO: SearchPanel is automatically installed, but have to disable replace mode // TemplateApplied += (s,e) => ShowLineMargin(); // add marker service & margin textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); }
public DecompilerTextView() { HighlightingManager.Instance.RegisterHighlighting( "ILAsm", new string[] { ".il" }, delegate { using (Stream s = typeof(DecompilerTextView).Assembly.GetManifestResourceStream(typeof(DecompilerTextView), "ILAsm-Mode.xshd")) { using (XmlTextReader reader = new XmlTextReader(s)) { return(HighlightingLoader.Load(reader, HighlightingManager.Instance)); } } }); HighlightingManager.Instance.RegisterHighlighting( "C#", new string[] { ".cs" }, delegate { using (Stream s = typeof(DecompilerTextView).Assembly.GetManifestResourceStream(typeof(DecompilerTextView), "CSharp-Mode.xshd")) { using (XmlTextReader reader = new XmlTextReader(s)) { return(HighlightingLoader.Load(reader, HighlightingManager.Instance)); } } }); InitializeComponent(); this.referenceElementGenerator = new ReferenceElementGenerator(this.JumpToReference, this.IsLink); textEditor.TextArea.TextView.ElementGenerators.Add(referenceElementGenerator); this.uiElementGenerator = new UIElementGenerator(); textEditor.TextArea.TextView.ElementGenerators.Add(uiElementGenerator); textEditor.Options.RequireControlModifierForHyperlinkClick = false; textEditor.TextArea.TextView.MouseHover += TextViewMouseHover; textEditor.TextArea.TextView.MouseHoverStopped += TextViewMouseHoverStopped; textEditor.TextArea.TextView.MouseDown += TextViewMouseDown; textEditor.SetBinding(Control.FontFamilyProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFont") }); textEditor.SetBinding(Control.FontSizeProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFontSize") }); textEditor.SetBinding(TextEditor.WordWrapProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("EnableWordWrap") }); // disable Tab editing command (useless for read-only editor); allow using tab for focus navigation instead RemoveEditCommand(EditingCommands.TabForward); RemoveEditCommand(EditingCommands.TabBackward); textMarkerService = new TextMarkerService(textEditor.TextArea.TextView); textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); textEditor.ShowLineNumbers = true; DisplaySettingsPanel.CurrentDisplaySettings.PropertyChanged += CurrentDisplaySettings_PropertyChanged; // SearchPanel SearchPanel.Install(textEditor.TextArea) .RegisterCommands(Application.Current.MainWindow.CommandBindings); ShowLineMargin(); // add marker service & margin textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); }
public MainWindow() { _settings = Settings.Default; ToolTipService.ShowDurationProperty.OverrideMetadata( typeof(DependencyObject), new FrameworkPropertyMetadata(Int32.MaxValue)); InitializeComponent(); this.Top = _settings.WindowTop; this.Left = _settings.WindowLeft; this.Height = _settings.WindowHeight; this.Width = _settings.WindowLWidth; this.WindowState = (WindowState)_settings.WindowState; _mainRow.Height = new GridLength(_settings.TabControlHeight); _configComboBox.ItemsSource = new[] { "Debug", "Release" }; var config = _settings.Config; _configComboBox.SelectedItem = config == "Release" ? "Release" : "Debug"; _tabControl.SelectedIndex = _settings.ActiveTabIndex; _foldingStrategy = new NitraFoldingStrategy(); _textBox1Tooltip = new ToolTip { PlacementTarget = _text }; _parseTimer = new Timer { AutoReset = false, Enabled = false, Interval = 300 }; _parseTimer.Elapsed += _parseTimer_Elapsed; _text.TextArea.Caret.PositionChanged += Caret_PositionChanged; _highlightingStyles = new Dictionary <string, HighlightingColor> { { "Keyword", new HighlightingColor { Foreground = new SimpleHighlightingBrush(Colors.Blue) } }, { "Comment", new HighlightingColor { Foreground = new SimpleHighlightingBrush(Colors.Green) } }, { "Number", new HighlightingColor { Foreground = new SimpleHighlightingBrush(Colors.Magenta) } }, { "Operator", new HighlightingColor { Foreground = new SimpleHighlightingBrush(Colors.Navy) } }, { "String", new HighlightingColor { Foreground = new SimpleHighlightingBrush(Colors.Maroon) } }, }; _foldingManager = FoldingManager.Install(_text.TextArea); _textMarkerService = new TextMarkerService(_text.Document); _text.TextArea.TextView.BackgroundRenderers.Add(_textMarkerService); _text.TextArea.TextView.LineTransformers.Add(_textMarkerService); _text.Options.ConvertTabsToSpaces = true; _text.Options.EnableRectangularSelection = true; _text.Options.IndentationSize = 2; _testsTreeView.SelectedValuePath = "FullPath"; if (string.IsNullOrWhiteSpace(_settings.CurrentSolution)) { _solution = null; } else { LoadTests(); } }