public InsertCtorDialog(InsertionContext context, ITextEditor editor, ITextAnchor anchor) : base(context, editor, anchor) { InitializeComponent(); Visibility = System.Windows.Visibility.Collapsed; }
internal static CreatePropertiesDialog CreateDialog(InsertionContext context) { ITextEditor textEditor = context.TextArea.GetService(typeof(ITextEditor)) as ITextEditor; if (textEditor == null) { return(null); } using (textEditor.Document.OpenUndoGroup()) { IEditorUIService uiService = textEditor.GetService(typeof(IEditorUIService)) as IEditorUIService; if (uiService == null) { return(null); } ITextAnchor anchor = textEditor.Document.CreateAnchor(context.InsertionPosition); anchor.MovementType = AnchorMovementType.BeforeInsertion; CreatePropertiesDialog dialog = new CreatePropertiesDialog(context, textEditor, anchor); dialog.Element = uiService.CreateInlineUIElement(anchor, dialog); // Add creation of this inline dialog as undoable operation TextDocument document = textEditor.Document as TextDocument; if (document != null) { document.UndoStack.Push(dialog.UndoableCreationOperation); } return(dialog); } }
InsertCtorDialog CreateDialog(InsertionContext context) { ITextEditor textEditor = context.TextArea.GetService(typeof(ITextEditor)) as ITextEditor; if (textEditor == null) { return(null); } IEditorUIService uiService = textEditor.GetService(typeof(IEditorUIService)) as IEditorUIService; if (uiService == null) { return(null); } ITextAnchor anchor = textEditor.Document.CreateAnchor(context.InsertionPosition); anchor.MovementType = AnchorMovementType.BeforeInsertion; InsertCtorDialog dialog = new InsertCtorDialog(context, textEditor, anchor); dialog.Element = uiService.CreateInlineUIElement(anchor, dialog); return(dialog); }
/// <inheritdoc/> public override void Insert(InsertionContext context) { if (Text != null) { context.InsertText(Text); } }
TextAnchor SetUpAnchorAtInsertion(InsertionContext context) { var anchor = context.Document.CreateAnchor(context.InsertionPosition); anchor.MovementType = ICSharpCode.AvalonEdit.Document.AnchorMovementType.BeforeInsertion; return(anchor); }
/// <summary> /// Called when this switch body element is inserted to the editor. /// </summary> public override void Insert(InsertionContext context) { this.context = context; this.context.Deactivated += new EventHandler <SnippetEventArgs>(InteractiveModeCompleted); this.anchor = SetUpAnchorAtInsertion(context); this.classFinderContext = new ClassFinder(ParserService.ParseCurrentViewContent(), Editor.Document.Text, Editor.Caret.Offset); }
public override Task Link(params AstNode[] nodes) { var segs = nodes.Select(node => GetSegment(node)).ToArray(); InsertionContext c = new InsertionContext(editor.GetRequiredService <TextArea>(), segs.Min(seg => seg.Offset)); c.InsertionPosition = segs.Max(seg => seg.EndOffset); var tcs = new TaskCompletionSource <bool>(); c.Deactivated += (sender, e) => tcs.SetResult(true); if (segs.Length > 0) { // try to use node in identifier context to avoid the code completion popup. var identifier = nodes.OfType <Identifier>().FirstOrDefault(); ISegment first; if (identifier == null) { first = segs[0]; } else { first = GetSegment(identifier); } c.Link(first, segs.Except(new[] { first }).ToArray()); c.RaiseInsertionCompleted(EventArgs.Empty); } else { c.RaiseInsertionCompleted(EventArgs.Empty); c.Deactivate(new SnippetEventArgs(DeactivateReason.NoActiveElements)); } return(tcs.Task); }
public override void Insert(InsertionContext context) { AbstractInlineRefactorDialog dialog = createDialog(context); if (dialog != null) { context.RegisterActiveElement(this, dialog); } }
public OverrideToStringMethodDialog(InsertionContext context, ITextEditor editor, ITextAnchor startAnchor, ITextAnchor anchor, IList <PropertyOrFieldWrapper> fields, string baseCall) : base(context, editor, anchor) { InitializeComponent(); this.baseCall = baseCall; this.listBox.ItemsSource = fields; listBox.SelectAll(); }
public OverrideToStringMethodDialog(InsertionContext context, ITextEditor editor, ITextAnchor anchor, IList <PropertyOrFieldWrapper> fields, AstNode baseCallNode) : base(context, editor, anchor) { InitializeComponent(); this.baseCallNode = baseCallNode; parameterList = fields; this.listBox.ItemsSource = fields; SelectAllChecked(); }
InsertCtorDialog CreateDialog(InsertionContext context) { ITextEditor textEditor = context.TextArea.GetService(typeof(ITextEditor)) as ITextEditor; if (textEditor == null) { return(null); } IEditorUIService uiService = textEditor.GetService(typeof(IEditorUIService)) as IEditorUIService; if (uiService == null) { return(null); } ParseInformation parseInfo = ParserService.GetParseInformation(textEditor.FileName); if (parseInfo == null) { return(null); } CodeGenerator generator = parseInfo.CompilationUnit.Language.CodeGenerator; // cannot use insertion position at this point, because it might not be // valid, because we are still generating the elements. // DOM is not updated ICSharpCode.AvalonEdit.Document.TextLocation loc = context.Document.GetLocation(context.StartPosition); IClass current = parseInfo.CompilationUnit.GetInnermostClass(loc.Line, loc.Column); if (current == null) { return(null); } List <PropertyOrFieldWrapper> parameters = CreateCtorParams(current).ToList(); if (!parameters.Any()) { return(null); } ITextAnchor anchor = textEditor.Document.CreateAnchor(context.InsertionPosition); anchor.MovementType = AnchorMovementType.BeforeInsertion; InsertCtorDialog dialog = new InsertCtorDialog(context, textEditor, anchor, current, parameters); dialog.Element = uiService.CreateInlineUIElement(anchor, dialog); return(dialog); }
public OverrideToStringMethodDialog(InsertionContext context, ITextEditor editor, ITextAnchor startAnchor, ITextAnchor anchor, IList <IField> fields, string baseCall) : base(context, editor, anchor) { InitializeComponent(); this.baseCall = baseCall; this.fields = fields.Select(f => new PropertyOrFieldWrapper(f) { IsSelected = true }).ToList(); this.listBox.ItemsSource = this.fields; }
public InsertCtorDialog(InsertionContext context, ITextEditor editor, ITextAnchor anchor, IClass current, IList <PropertyOrFieldWrapper> possibleParameters) : base(context, editor, anchor) { InitializeComponent(); this.varList.ItemsSource = parameterList = possibleParameters; if (!parameterList.Any()) { Visibility = System.Windows.Visibility.Collapsed; } }
protected AbstractInlineRefactorDialog(InsertionContext context, ITextEditor editor, ITextAnchor anchor) { if (context == null) { throw new ArgumentNullException("context"); } this.anchor = insertionEndAnchor = anchor; this.editor = editor; this.context = context; this.classFinderContext = new ClassFinder(ParserService.ParseCurrentViewContent(), editor.Document.Text, anchor.Offset); this.Background = SystemColors.ControlBrush; }
protected AbstractInlineRefactorDialog(InsertionContext context, ITextEditor editor, ITextAnchor anchor) { if (context == null) { throw new ArgumentNullException("context"); } this.anchor = insertionEndAnchor = anchor; this.editor = editor; this.insertionContext = context; this.Background = SystemColors.ControlBrush; undoableCreationOperation = new UndoableInlineDialogCreation(this); }
public CreatePropertiesDialog(InsertionContext context, ITextEditor editor, ITextAnchor anchor, IClass current, IList <FieldWrapper> availableFields) : base(context, editor, anchor) { InitializeComponent(); this.listBox.ItemsSource = fields = availableFields; if (!fields.Any()) { Visibility = System.Windows.Visibility.Collapsed; } implementInterface.IsChecked = !current.IsStatic && HasOnPropertyChanged(current); if (current.IsStatic) { implementInterface.Visibility = System.Windows.Visibility.Collapsed; } listBox.UnselectAll(); }
/// <summary> /// Assuming that interactive mode of 'switch' snippet has currently finished in context, /// returns the switch condition that user entered. /// </summary> string GetSwitchConditionText(InsertionContext context, out int conditionEndOffset) { var snippetActiveElements = context.ActiveElements.ToList(); if (snippetActiveElements.Count == 0) { throw new InvalidOperationException("Switch snippet should have at least one active element"); } var switchConditionElement = snippetActiveElements[0] as IReplaceableActiveElement; if (switchConditionElement == null) { throw new InvalidOperationException("Switch snippet condition should be " + typeof(IReplaceableActiveElement).Name); } if (switchConditionElement.Segment == null) { throw new InvalidOperationException("Swith condition should have a start offset"); } conditionEndOffset = switchConditionElement.Segment.EndOffset - 1; return(switchConditionElement.Text); }
public OverrideEqualsGetHashCodeMethodsDialog(InsertionContext context, ITextEditor editor, ITextAnchor startAnchor, ITextAnchor endAnchor, ITextAnchor insertionPosition, IClass selectedClass, IMethod selectedMethod, string baseCall) : base(context, editor, insertionPosition) { if (selectedClass == null) { throw new ArgumentNullException("selectedClass"); } InitializeComponent(); this.selectedClass = selectedClass; this.startAnchor = startAnchor; this.insertionEndAnchor = endAnchor; this.selectedMethod = selectedMethod; this.baseCall = baseCall; addIEquatable.Content = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddInterface}"), "IEquatable<" + selectedClass.Name + ">"); string otherMethod = selectedMethod.Name == "Equals" ? "GetHashCode" : "Equals"; addOtherMethod.Content = StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddOtherMethod}", new StringTagPair("otherMethod", otherMethod)); addIEquatable.IsEnabled = !selectedClass.BaseTypes.Any( type => { if (!type.IsGenericReturnType) { return(false); } var genericType = type.CastToGenericReturnType(); var boundTo = genericType.TypeParameter.BoundTo; if (boundTo == null) { return(false); } return(boundTo.Name == selectedClass.Name); } ); }
public OverrideEqualsGetHashCodeMethodsDialog(InsertionContext context, ITextEditor editor, ITextAnchor endAnchor, ITextAnchor insertionPosition, ITypeDefinition selectedClass, IMethod selectedMethod, AstNode baseCallNode) : base(context, editor, insertionPosition) { if (selectedClass == null) { throw new ArgumentNullException("selectedClass"); } InitializeComponent(); this.selectedClass = selectedClass; this.insertionEndAnchor = endAnchor; this.selectedMethod = selectedMethod; this.baseCallNode = baseCallNode; addIEquatable.Content = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddInterface}"), "IEquatable<" + selectedClass.Name + ">"); string otherMethod = selectedMethod.Name == "Equals" ? "GetHashCode" : "Equals"; addOtherMethod.Content = StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddOtherMethod}", new StringTagPair("otherMethod", otherMethod)); addIEquatable.IsEnabled = !selectedClass.GetAllBaseTypes().Any( type => { if (!type.IsParameterized || (type.TypeParameterCount != 1)) { return(false); } if (type.FullName != "System.IEquatable") { return(false); } return(type.TypeArguments.First().FullName == selectedClass.FullName); } ); }
/// <summary> /// Performs insertion of the snippet. /// </summary> public abstract void Insert(InsertionContext context);
public void Insert(CompletionContext context, ICompletionItem item) { if (item == null) { throw new ArgumentNullException("item"); } if (!(item is OverrideCompletionItem)) { throw new ArgumentException("item is not an OverrideCompletionItem"); } OverrideCompletionItem completionItem = item as OverrideCompletionItem; ITextEditor textEditor = context.Editor; IEditorUIService uiService = textEditor.GetService(typeof(IEditorUIService)) as IEditorUIService; if (uiService == null) { return; } ParseInformation parseInfo = ParserService.GetParseInformation(textEditor.FileName); if (parseInfo == null) { return; } CodeGenerator generator = parseInfo.CompilationUnit.Language.CodeGenerator; IClass current = parseInfo.CompilationUnit.GetInnermostClass(textEditor.Caret.Line, textEditor.Caret.Column); ClassFinder finder = new ClassFinder(current, textEditor.Caret.Line, textEditor.Caret.Column); if (current == null) { return; } using (textEditor.Document.OpenUndoGroup()) { ITextAnchor startAnchor = textEditor.Document.CreateAnchor(textEditor.Caret.Offset); startAnchor.MovementType = AnchorMovementType.BeforeInsertion; ITextAnchor endAnchor = textEditor.Document.CreateAnchor(textEditor.Caret.Offset); endAnchor.MovementType = AnchorMovementType.AfterInsertion; MethodDeclaration member = (MethodDeclaration)generator.GetOverridingMethod(completionItem.Member, finder); string indent = DocumentUtilitites.GetWhitespaceBefore(textEditor.Document, textEditor.Caret.Offset); string codeForBaseCall = generator.GenerateCode(member.Body.Children.OfType <AbstractNode>().First(), ""); string code = generator.GenerateCode(member, indent); int marker = code.IndexOf(codeForBaseCall); textEditor.Document.Insert(startAnchor.Offset, code.Substring(0, marker).TrimStart()); ITextAnchor insertionPos = textEditor.Document.CreateAnchor(endAnchor.Offset); insertionPos.MovementType = AnchorMovementType.BeforeInsertion; InsertionContext insertionContext = new InsertionContext(textEditor.GetService(typeof(TextArea)) as TextArea, startAnchor.Offset); AbstractInlineRefactorDialog dialog = new OverrideEqualsGetHashCodeMethodsDialog(insertionContext, textEditor, startAnchor, endAnchor, insertionPos, current, completionItem.Member as IMethod, codeForBaseCall.Trim()); dialog.Element = uiService.CreateInlineUIElement(insertionPos, dialog); textEditor.Document.InsertNormalized(endAnchor.Offset, Environment.NewLine + code.Substring(marker + codeForBaseCall.Length)); insertionContext.RegisterActiveElement(new InlineRefactorSnippetElement(cxt => null, ""), dialog); insertionContext.RaiseInsertionCompleted(EventArgs.Empty); } }
public override void Complete(CompletionContext context) { if (declarationBegin > context.StartOffset) { base.Complete(context); return; } TypeSystemAstBuilder b = new TypeSystemAstBuilder(contextAtCaret); b.ShowTypeParameterConstraints = false; b.GenerateBody = true; var entityDeclaration = b.ConvertEntity(this.Entity); entityDeclaration.Modifiers &= ~(Modifiers.Virt | Modifiers.Abstract); entityDeclaration.Modifiers |= Modifiers.Override; var body = entityDeclaration.GetChildByRole(Roles.Body); Statement baseCallStatement = body.Children.OfType <Statement>().FirstOrDefault(); if (!this.Entity.IsAbstract) { // modify body to call the base method if (this.Entity.SymbolKind == SymbolKind.Method) { var baseCall = new BaseReferenceExpression().Invoke(this.Entity.Name, new Expression[] { }); if (((IMethod)this.Entity).ReturnType.IsKnownType(KnownTypeCode.Void)) { baseCallStatement = new ExpressionStatement(baseCall); } else { baseCallStatement = new ReturnStatement(baseCall); } // Clear body of inserted method entityDeclaration.GetChildByRole(Roles.Body).Statements.Clear(); } } var document = context.Editor.Document; StringWriter w = new StringWriter(); var formattingOptions = AlFormattingPolicies.Instance.GetProjectOptions(contextAtCaret.Compilation.GetProject()); var segmentDict = SegmentTrackingOutputFormatter.WriteNode( w, entityDeclaration, formattingOptions.OptionsContainer.GetEffectiveOptions(), context.Editor.Options); using (document.OpenUndoGroup()) { InsertionContext insertionContext = new InsertionContext(context.Editor.GetService(typeof(TextArea)) as TextArea, declarationBegin); insertionContext.InsertionPosition = context.Editor.Caret.Offset; string newText = w.ToString().TrimEnd(); document.Replace(declarationBegin, context.EndOffset - declarationBegin, newText); var throwStatement = entityDeclaration.Descendants.FirstOrDefault(n => n is ThrowStatement); if (throwStatement != null) { var segment = segmentDict[throwStatement]; context.Editor.Select(declarationBegin + segment.Offset, segment.Length); } AlFormatterHelper.Format(context.Editor, declarationBegin, newText.Length, formattingOptions.OptionsContainer); var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None); var typeResolveContext = refactoringContext.GetTypeResolveContext(); if (typeResolveContext == null) { return; } var resolvedCurrent = typeResolveContext.CurrentTypeDefinition; IEditorUIService uiService = context.Editor.GetService(typeof(IEditorUIService)) as IEditorUIService; ITextAnchor endAnchor = context.Editor.Document.CreateAnchor(context.Editor.Caret.Offset); endAnchor.MovementType = AnchorMovementType.AfterInsertion; ITextAnchor startAnchor = context.Editor.Document.CreateAnchor(context.Editor.Caret.Offset); startAnchor.MovementType = AnchorMovementType.BeforeInsertion; ITextAnchor insertionPos = context.Editor.Document.CreateAnchor(endAnchor.Offset); insertionPos.MovementType = AnchorMovementType.BeforeInsertion; var current = typeResolveContext.CurrentTypeDefinition; AbstractInlineRefactorDialog dialog = new OverrideEqualsGetHashCodeMethodsDialog(insertionContext, context.Editor, endAnchor, insertionPos, current, Entity as IMethod, baseCallStatement); dialog.Element = uiService.CreateInlineUIElement(insertionPos, dialog); insertionContext.RegisterActiveElement(new InlineRefactorSnippetElement(cxt => null, ""), dialog); insertionContext.RaiseInsertionCompleted(EventArgs.Empty); } }
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 CodeEditor() { _codeAnalysisRunner = new JobRunner(1); _shell = IoC.Get <IShell>(); _snippetManager = IoC.Get <SnippetManager>(); _renameManager = new RenameManager(this); _lineNumberMargin = new LineNumberMargin(this); _breakpointMargin = new BreakPointMargin(this, IoC.Get <IDebugManager2>()?.Breakpoints); _selectedLineBackgroundRenderer = new SelectedLineBackgroundRenderer(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.SelectionBrush = Brush.Parse("#AA569CD6"); TextArea.SelectionCornerRadius = 0; EventHandler <KeyEventArgs> tunneledKeyUpHandler = (send, ee) => { if (CaretOffset > 0) { _intellisenseManager?.OnKeyUp(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column); } }; EventHandler <KeyEventArgs> tunneledKeyDownHandler = (send, ee) => { if (CaretOffset > 0) { _intellisenseManager?.OnKeyDown(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column); if (ee.Key == Key.Tab && _currentSnippetContext == null && LanguageService != null) { var wordStart = Document.FindPrevWordStart(CaretOffset); if (wordStart > 0) { string word = Document.GetText(wordStart, CaretOffset - wordStart); var codeSnippet = _snippetManager.GetSnippet(LanguageService, SourceFile.Project?.Solution, SourceFile.Project, word); if (codeSnippet != null) { var snippet = SnippetParser.Parse(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.BackgroundAccent; if (_textColorizer != null) { _textColorizer.ColorScheme = colorScheme; } if (_diagnosticMarkersRenderer != null) { _diagnosticMarkersRenderer.ColorScheme = colorScheme; } TextArea.TextView.InvalidateLayer(KnownLayer.Background); TriggerCodeAnalysis(); } }), this.GetObservable(CaretOffsetProperty).Subscribe(s => { if (Document?.TextLength > s) { CaretOffset = s; } }), 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.Throttle(TimeSpan.FromMilliseconds(300)).ObserveOn(AvaloniaScheduler.Instance).Subscribe(async _ => { await DoCodeAnalysisAsync(); }), this.GetObservableWithHistory(SourceFileProperty).Subscribe((file) => { if (file.Item1 != file.Item2) { using (var fs = file.Item2.OpenText()) { using (var reader = new StreamReader(fs)) { Document = new TextDocument(reader.ReadToEnd()) { FileName = file.Item2.Location }; } } DocumentAccessor = new EditorAdaptor(this); _isLoaded = true; RegisterLanguageService(file.Item2); TextArea.TextView.Redraw(); SourceText = Text; } }), Observable.FromEventPattern(TextArea.Caret, nameof(TextArea.Caret.PositionChanged)).Subscribe(e => { if (TextArea.Caret.Line != _lastLine && LanguageService != null) { var line = Document.GetLineByNumber(TextArea.Caret.Line); if (line.Length == 0) { _suppressIsDirtyNotifications = true; LanguageService.IndentationStrategy?.IndentLine(Document, line); _suppressIsDirtyNotifications = false; } } _lastLine = TextArea.Caret.Line; }), Observable.FromEventPattern(TextArea.Caret, nameof(TextArea.Caret.PositionChanged)).Throttle(TimeSpan.FromMilliseconds(100)).ObserveOn(AvaloniaScheduler.Instance).Subscribe(e => { if (_intellisenseManager != null && !_textEntering) { if (TextArea.Selection.IsEmpty) { var location = Document.GetLocation(CaretOffset); _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()); } } if (CaretOffset > 0) { var prevLocation = new TextViewPosition(Document.GetLocation(CaretOffset - 1)); var visualLocation = TextArea.TextView.GetVisualPosition(prevLocation, VisualYPosition.LineBottom); var visualLocationTop = TextArea.TextView.GetVisualPosition(prevLocation, VisualYPosition.LineTop); var position = visualLocation - TextArea.TextView.ScrollOffset; position = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value); _intellisenseControl.SetLocation(position); _selectedWordBackgroundRenderer.SelectedWord = GetWordAtOffset(CaretOffset); Line = TextArea.Caret.Line; Column = TextArea.Caret.Column; EditorCaretOffset = TextArea.Caret.Offset; TextArea.TextView.InvalidateLayer(KnownLayer.Background); } }), 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); }
public CreatePropertiesDialog(InsertionContext context, ITextEditor editor, ITextAnchor anchor) : base(context, editor, anchor) { InitializeComponent(); }