public string GetRtf(DocumentEditor tb) { this.tb = tb; Range sel = new Range(tb); sel.SelectAll(); return GetRtf(sel); }
public FileTextSource(DocumentEditor currentTB) : base(currentTB) { timer.Interval = 10000; timer.Tick += new EventHandler(timer_Tick); timer.Enabled = true; SaveEOL = Environment.NewLine; }
public AutocompleteMenu(DocumentEditor tb) { // create a new popup and add the list view to it AutoClose = false; AutoSize = false; Margin = Padding.Empty; Padding = Padding.Empty; BackColor = Color.White; listView = new AutocompleteListView(tb); host = new ToolStripControlHost(listView); host.Margin = new Padding(2, 2, 2, 2); host.Padding = Padding.Empty; host.AutoSize = false; host.AutoToolTip = false; CalcSize(); base.Items.Add(host); listView.Parent = this; SearchPattern = @"[\w\.]"; MinFragmentLength = 2; }
private static async Task <Document> MakeConstructorProtected(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var ctorSyntax = (ConstructorDeclarationSyntax)nodeToFix; if (ctorSyntax == null) { return(document); } var modifiers = ctorSyntax.Modifiers; foreach (var modifier in modifiers.Where(m => m.IsKind(SyntaxKind.PublicKeyword) || m.IsKind(SyntaxKind.InternalKeyword))) { modifiers = modifiers.Remove(modifier); } modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); editor.ReplaceNode(ctorSyntax, ctorSyntax.WithModifiers(modifiers)); return(editor.GetChangedDocument()); }
private static void ConvertToLambda(DocumentEditor editor, SyntaxNode toReplace, IMethodSymbol method, MethodDeclarationSyntax declaration, CancellationToken cancellationToken) { if (method.Parameters.TrySingle(out var parameter)) { if (declaration.ExpressionBody is { } expressionBody) { editor.ReplaceNode( toReplace, SyntaxFactory.ParseExpression($"{parameter.Name} => {expressionBody.Expression}") .WithLeadingTriviaFrom(toReplace)); RemoveMethod(editor, method, declaration, cancellationToken); } else if (declaration.Body is { } body&& body.Statements.TrySingle(out var statement) && statement is ReturnStatementSyntax returnStatement) { editor.ReplaceNode( toReplace, SyntaxFactory.ParseExpression($"{parameter.Name} => {returnStatement.Expression}") .WithLeadingTriviaFrom(toReplace)); RemoveMethod(editor, method, declaration, cancellationToken); } }
private void ProccessNode(CSharpSyntaxNode node) { var modifiers = GetModifiers(Command.Modifiers, Command.Abstract, Command.Static, Command.Partial); var bodySyntax = Command.BlockBody; var method = SyntaxFactory.MethodDeclaration(Command.ReturnType ?? SyntaxFactory.ParseTypeName("void"), Command.Name) .WithAttributeLists(Command.Attributes) .WithBody(Command.BlockBody) .WithExpressionBody(Command.ExpressionBody) .WithParameterList(Command.Parameters ?? SyntaxFactory.ParameterList()) .WithTypeParameterList(Command.GenericParameters) .WithConstraintClauses(Command.GenericParametersConstraints) .WithModifiers(modifiers) .WithAdditionalAnnotations(new SyntaxAnnotation($"{Id}")); if (Command.ExpressionBody != null) { method = method.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } DocumentEditor.InsertMembers(node, 0, new[] { method }); }
private static async Task <Solution> GenerateRegisterChildModel(Document document, SemanticModel semanticModel, PropertyDeclarationSyntax propertyDeclaration, IPropertySymbol childProperty, IPropertySymbol foreignKey, CancellationToken ct) { var staticConstructor = await GetStaticConstructor(childProperty, ct); ClassDeclarationSyntax classDeclaration; if (staticConstructor != null) { document = document.Project.GetDocument(staticConstructor.SyntaxTree); classDeclaration = staticConstructor.FirstAncestor <ClassDeclarationSyntax>(); } else { classDeclaration = propertyDeclaration.FirstAncestor <ClassDeclarationSyntax>(); } var editor = await DocumentEditor.CreateAsync(document, ct); GenerateRegisterChildModel(editor, staticConstructor, classDeclaration, semanticModel, childProperty, foreignKey); return(editor.GetChangedDocument().Project.Solution); }
/// <summary> /// Add the backing field and figure out placement. /// StyleCop ordering is the default but it also checks for if field adjacent to property is used. /// The property is unchanged by this call. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/>.</param> /// <param name="propertyDeclaration">The <see cref="PropertyDeclarationSyntax"/>.</param> /// <returns>A <see cref="FieldDeclarationSyntax"/>.</returns> public static FieldDeclarationSyntax AddBackingField(this DocumentEditor editor, PropertyDeclarationSyntax propertyDeclaration) { if (editor is null) { throw new System.ArgumentNullException(nameof(editor)); } if (propertyDeclaration is null) { throw new System.ArgumentNullException(nameof(propertyDeclaration)); } if (propertyDeclaration.Parent is TypeDeclarationSyntax type) { var backingField = CreateBackingField(editor, propertyDeclaration); editor.ReplaceNode( type, (node, generator) => AddBackingField(editor, (TypeDeclarationSyntax)node, backingField, propertyDeclaration.Identifier.ValueText)); return(backingField); } throw new System.ArgumentNullException(nameof(propertyDeclaration), "Property.Parent is not a TypeDeclaration."); }
private async Task <Document> FixMethodAsync(Document document, SemanticModel semanticModel, MethodDeclarationSyntax methodDeclarationSyntax) { var editor = await DocumentEditor.CreateAsync(document); foreach (var conditionStatement in methodDeclarationSyntax.DescendantNodes().OfType <IfStatementSyntax>()) { if (RequiresFix(semanticModel, conditionStatement.Statement)) { editor.ReplaceNode(conditionStatement.Statement, GetFixedStatement(conditionStatement.Statement)); } if (RequiresFix(semanticModel, conditionStatement.Else.Statement)) { var fixedStatement = GetFixedStatement(conditionStatement.Else.Statement); editor.ReplaceNode(conditionStatement.Else.Statement, fixedStatement); } } return(editor.GetChangedDocument()); }
private static async Task <Document> ApplyObserveEventLamdaFixAsync( CancellationToken cancellationToken, CodeFixContext context, AssignmentExpressionSyntax assignment, bool usesArg) { var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken) .ConfigureAwait(false); var eventSymbol = (IEventSymbol)editor.SemanticModel.GetSymbolSafe(assignment.Left, cancellationToken); var observeSubscribe = GetObservableFromEventString(eventSymbol) .Replace("HANDLERTYPE", eventSymbol.Type.ToDisplayString()) .Replace("ARGTYPE", ArgType(eventSymbol)) .Replace("LEFT", assignment.Left.ToString()) .Replace("LAMBDA", Lambda((ParenthesizedLambdaExpressionSyntax)assignment.Right, usesArg)); editor.ReplaceNode( assignment, SyntaxFactory.ParseExpression(observeSubscribe) .WithLeadingTrivia(assignment.GetLeadingTrivia()) .WithAdditionalAnnotations(Simplifier.Annotation)); return(editor.GetChangedDocument()); }
private void block_2_MouseDown(object sender, MouseButtonEventArgs e) { if (UserLogIn.UserName == "") { MessageBox.Show("请先登录系统。若为新用户,请先注册。"); } else { if (e.LeftButton == MouseButtonState.Pressed) { if (DocumentEditor_Object == null) { DocumentEditor doc = new DocumentEditor(); DocumentEditor_Object = doc; doc.Show(); } else { DocumentEditor_Object.Activate(); } } } }
private static async Task <Document> FixMismatchedParameterOptionality(Diagnostic diagnostic, Document document, CancellationToken cancellationToken) { DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root == null) { return(document); } var param = root.FindNode(diagnostic.Location.SourceSpan); if (param is ParameterSyntax { Type : { } parameterType } parameterSyntax) { var newParam = parameterSyntax.WithType(SyntaxFactory.NullableType(parameterType)); editor.ReplaceNode(parameterSyntax, newParam); } return(editor.GetChangedDocument()); }
/// <summary> /// update the original document and remove the type that was moved. /// perform other fix ups as necessary. /// </summary> /// <returns>an updated solution with the original document fixed up as appropriate.</returns> private async Task <Solution> RemoveTypeFromSourceDocumentAsync(Document sourceDocument) { var documentEditor = await DocumentEditor .CreateAsync(sourceDocument, CancellationToken) .ConfigureAwait(false); // Make the type chain above the type we're moving 'partial'. // However, keep all the attributes on these types as theses are the // original attributes and we don't want to mess with them. AddPartialModifiersToTypeChain( documentEditor, removeAttributesAndComments: false, removeTypeInheritance: false ); documentEditor.RemoveNode( State.TypeNode, SyntaxRemoveOptions.KeepUnbalancedDirectives ); var updatedDocument = documentEditor.GetChangedDocument(); return(updatedDocument.Project.Solution); }
private static async Task <Document> MakeConstructorProtected(Document document, SyntaxNode nodeToFix, string comparerName, CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = editor.SemanticModel; var generator = editor.Generator; var syntax = (MemberAccessExpressionSyntax)nodeToFix; var stringComparer = semanticModel.Compilation.GetTypeByMetadataName("System.StringComparer"); if (stringComparer is null) { return(document); } var newSyntax = generator.MemberAccessExpression( generator.TypeExpression(stringComparer), comparerName); editor.ReplaceNode(syntax, newSyntax); return(editor.GetChangedDocument()); }
private static async Task <Solution> AddMissingUsingsIfNeeded( DocumentEditor documentEditor, Document newDocument, string namespaceName, CancellationToken cancellationToken) { if (documentEditor.OriginalRoot is CompilationUnitSyntax compilationUnitSyntax && compilationUnitSyntax.Usings.All(x => x.Name.ToString() != namespaceName)) { // Have to create new editor, since it overwrites/can't find node if do both changes in one editor var usingsDocumentEditor = await DocumentEditor.CreateAsync(newDocument, cancellationToken); var newCompilationUnitSyntax = usingsDocumentEditor.OriginalRoot as CompilationUnitSyntax; var newUsings = newCompilationUnitSyntax.Usings.Add(UsingDirective(IdentifierName(namespaceName))) .OrderBy(x => x.Name.ToString()); var newRoot = newCompilationUnitSyntax.WithUsings(new SyntaxList <UsingDirectiveSyntax>(newUsings)); usingsDocumentEditor.ReplaceNode(newCompilationUnitSyntax, newRoot); return(usingsDocumentEditor.GetChangedDocument().Project.Solution); } return(newDocument.Project.Solution); }
protected override async Task <Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var fromTypeSymbol = semanticModel.Compilation.GetTypeByMetadataName(fromTypeName); foreach (var attributeList in attributeLists) { foreach (var attribute in attributeList.Attributes) { cancellationToken.ThrowIfCancellationRequested(); var currentType = semanticModel.GetTypeInfo(attribute).Type; if (currentType == fromTypeSymbol) { editor.SetName(attribute, toTypeName); } } } return(editor.GetChangedDocument()); }
private static async Task <Document> IntroduceLocal(Document originalDocument, SyntaxNode diagnosticSyntaxNode) { ExpressionSyntax diagnosticExpression = diagnosticSyntaxNode as ExpressionSyntax; if (diagnosticExpression == null) { return(originalDocument); } SemanticModel model = await originalDocument.GetSemanticModelAsync(); IOperation diagnosticOperation = model.GetOperation(diagnosticSyntaxNode); ITypeSymbol type = diagnosticOperation.Type; string newVariableName = GetNewLocalName(model, diagnosticSyntaxNode); LocalDeclarationStatementSyntax newLocal = GetVariableDeclaration(type, newVariableName, diagnosticExpression); ExpressionSyntax identifier = IdentifierName(newVariableName); StatementSyntax methodInvocation = GetMethodInvocation(diagnosticSyntaxNode); var editor = await DocumentEditor.CreateAsync(originalDocument); editor.InsertBefore(methodInvocation, newLocal); editor.ReplaceNode(diagnosticExpression, identifier); return(editor.GetChangedDocument()); }
public static AttributeSyntax GetAttributeSyntax(DocumentEditor editor, ClassDeclarationSyntax ccClass, CancellationToken cancellationToken) { var classSymbol = editor.SemanticModel.GetDeclaredSymbol(ccClass, cancellationToken); if (classSymbol == null) { return(null); } var attrib = classSymbol.GetAttributes().FirstOrDefault(o => o.AttributeClass.Name == nameof(System.Diagnostics.Contracts.ContractClassForAttribute)); if (attrib == null) { return(null); } var argument = attrib.ConstructorArguments[0]; INamedTypeSymbol targetType = null; if (argument.Value is INamedTypeSymbol namedType && namedType.IsUnboundGenericType) { targetType = namedType.ConstructedFrom; }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { const string title = "Remove ModelState.IsValid check"; var rootNode = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); context.RegisterCodeFix( CodeAction.Create( title, createChangedDocument: CreateChangedDocumentAsync, equivalenceKey: title), context.Diagnostics); async Task <Document> CreateChangedDocumentAsync(CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken).ConfigureAwait(false); var node = rootNode.FindNode(context.Span); editor.RemoveNode(node); return(editor.GetChangedDocument()); } }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { Document doc = context.Document; SyntaxNode root = await doc.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); // Get the target syntax node from the incoming span. For a field like: // private string _value = null; // the node will be for the `= null;` portion. For a property like: // private string Value { get; } = "hello"; // the node will be for the `= "hello"`. if (root.FindNode(context.Span) is SyntaxNode node) { string title = MicrosoftCodeQualityAnalyzersResources.DoNotInitializeUnnecessarilyFix; context.RegisterCodeFix( new MyCodeAction(title, async ct => { // Simply delete the field or property initializer. DocumentEditor editor = await DocumentEditor.CreateAsync(doc, ct).ConfigureAwait(false); if (node.Parent is PropertyDeclarationSyntax prop) { // For a property, we also need to get rid of the semicolon that follows the initializer. editor.ReplaceNode(prop, prop.WithInitializer(default).WithSemicolonToken(default).WithTrailingTrivia(prop.SemicolonToken.TrailingTrivia));
public static async Task PartialClass(string before, string after) { var code = @" namespace N { partial class C { } }".AssertReplace("partial class C", before); var sln = CodeFactory.CreateSolution(code); var editor = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false); var expected = @" namespace N { sealed partial class C { } }".AssertReplace("sealed partial class C", after); _ = editor.Seal(editor.OriginalRoot.Find <ClassDeclarationSyntax>("class C")); CodeAssert.AreEqual(expected, editor.GetChangedDocument()); }
private static async Task <Document> AddStringComparison(Document document, SyntaxNode nodeToFix, string stringComparisonMode, CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = editor.SemanticModel; var generator = editor.Generator; var invocationExpression = (InvocationExpressionSyntax)nodeToFix; if (invocationExpression == null) { return(document); } var stringComparison = semanticModel.Compilation.GetTypeByMetadataName("System.StringComparison"); var newArgument = (ArgumentSyntax)generator.Argument( generator.MemberAccessExpression( generator.TypeExpression(stringComparison, addImport: true), stringComparisonMode)); editor.ReplaceNode(invocationExpression, invocationExpression.AddArgumentListArguments(newArgument)); return(editor.GetChangedDocument()); }
private static async Task <Solution> InlineAndRemoveMethodAsync( Document document, InvocationExpressionSyntax invocation, MethodDeclarationSyntax methodDeclaration, ExpressionSyntax expression, ParameterInfo[] parameterInfos, CancellationToken cancellationToken = default(CancellationToken)) { if (invocation.SyntaxTree.Equals(methodDeclaration.SyntaxTree)) { DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); Solution solution = document.Project.Solution; expression = await ReplaceParameterExpressionWithArgumentExpressionAsync(parameterInfos, expression, solution, cancellationToken).ConfigureAwait(false); editor.ReplaceNode(invocation, expression); editor.RemoveNode(methodDeclaration); document = editor.GetChangedDocument(); return(document.Project.Solution); } else { Solution solution = document.Project.Solution; document = await InlineMethodAsync(document, invocation, expression, parameterInfos, cancellationToken).ConfigureAwait(false); DocumentId documentId = solution.GetDocumentId(methodDeclaration.SyntaxTree); solution = document.Project.Solution; return(await RemoveMethodAsync(solution.GetDocument(documentId), methodDeclaration, cancellationToken).ConfigureAwait(false)); } }
private async Task <Solution> AddEmptyCases(SyntaxNode root, Document document, TextSpan diagnosticSpan, IEnumerable <string> caseNames, CancellationToken cancellationToken) { var switchToken = root.FindToken(diagnosticSpan.Start).Parent as SwitchStatementSyntax; if (switchToken == null) { return(document.Project.Solution); } var missingLabels = caseNames.Select(CreatEmptyNode).ToList(); var(section, created) = GetOrCreateStatement(switchToken); var newSectionLabels = section.Labels.InsertRange(0, missingLabels); var newSection = section.WithLabels(newSectionLabels); if (created) { var breakStatement = Block( SingletonList <StatementSyntax>( BreakStatement())); newSection = newSection.WithStatements(SingletonList <StatementSyntax>(breakStatement)); } var newSections = ApplySection(switchToken, section, created, newSection); var newSwitch = switchToken.WithSections(newSections); var documentEditor = await DocumentEditor.CreateAsync(document, cancellationToken); documentEditor.ReplaceNode(switchToken, newSwitch); var newDocument = documentEditor.GetChangedDocument(); return(newDocument.Project.Solution); }
protected override async Task <Document> FixAllAsync(FixAllContext fixAllContext, Document document, ImmutableArray <Diagnostic> diagnostics) { SyntaxNode?root = await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false); if (root == null) { return(document); } DocumentEditor editor = await DocumentEditor.CreateAsync(document, fixAllContext.CancellationToken).ConfigureAwait(false); switch (fixAllContext.CodeActionEquivalenceKey) { case AddMissingCustomTypeMarshallerMembersKey: foreach (IGrouping <TextSpan, Diagnostic> diagnosticsBySpan in diagnostics.GroupBy(d => d.Location.SourceSpan)) { SyntaxNode node = root.FindNode(diagnosticsBySpan.Key); AddMissingMembers(fixAllContext, editor, diagnosticsBySpan, node); } break; case AddMissingCustomTypeMarshallerFeaturesKey: foreach (IGrouping <TextSpan, Diagnostic> diagnosticsBySpan in diagnostics.GroupBy(d => d.Location.SourceSpan)) { SyntaxNode node = root.FindNode(diagnosticsBySpan.Key); await AddMissingFeatures(fixAllContext, editor, diagnosticsBySpan, node).ConfigureAwait(false); } break; default: break; } return(editor.GetChangedDocument()); }
private static async Task <Document> UseAny(Document document, Diagnostic diagnostic, SyntaxNode nodeToFix, bool constantValue, CancellationToken cancellationToken) { var countOperationStart = int.Parse(diagnostic.Properties.GetValueOrDefault("CountOperationStart"), NumberStyles.Integer, CultureInfo.InvariantCulture); var countOperationLength = int.Parse(diagnostic.Properties.GetValueOrDefault("CountOperationLength"), NumberStyles.Integer, CultureInfo.InvariantCulture); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var countNode = root?.FindNode(new TextSpan(countOperationStart, countOperationLength), getInnermostNodeForTie: true); if (countNode == null) { return(document); } var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = editor.SemanticModel; var countOperation = semanticModel.GetOperation(countNode, cancellationToken) as IInvocationOperation; if (countOperation == null) { return(document); } var generator = editor.Generator; var newExpression = generator.InvocationExpression( generator.MemberAccessExpression(countOperation.Arguments[0].Syntax, "Any"), countOperation.Arguments.Skip(1).Select(arg => arg.Syntax)); if (!constantValue) { newExpression = generator.LogicalNotExpression(newExpression); } editor.ReplaceNode(nodeToFix, newExpression); return(editor.GetChangedDocument()); }
static async Task <Document> UseEqualCheckAsync(Document document, InvocationExpressionSyntax invocation, string replacementMethodName, string isStaticMethodCall, string ignoreCase, CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; var equalsInvocation = (InvocationExpressionSyntax)invocation.ArgumentList.Arguments[0].Expression; var equalsMethodInvocation = (MemberAccessExpressionSyntax)equalsInvocation.Expression; var equalsTarget = equalsMethodInvocation.Expression; var arguments = isStaticMethodCall == bool.TrueString ? equalsInvocation.ArgumentList.Arguments : equalsInvocation.ArgumentList.Arguments.Insert(0, SyntaxFactory.Argument(equalsTarget)); if (ignoreCase == bool.TrueString) { arguments = arguments.Replace( arguments[arguments.Count - 1], SyntaxFactory.Argument( SyntaxFactory.NameColon(SyntaxFactory.IdentifierName("ignoreCase")), arguments[arguments.Count - 1].RefOrOutKeyword, SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression))); } else if (ignoreCase == bool.FalseString) { arguments = arguments.RemoveAt(arguments.Count - 1); } editor.ReplaceNode( invocation, invocation.WithArgumentList( SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList(arguments))) .WithExpression(memberAccess.WithName(SyntaxFactory.IdentifierName(replacementMethodName)))); return(editor.GetChangedDocument()); }
private static async Task <Document> RemoveDuplicatedOrderBy(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { // a."b()".c() // a.c() var firstOperationStart = int.Parse(diagnostic.Properties.GetValueOrDefault("FirstOperationStart"), NumberStyles.Integer, CultureInfo.InvariantCulture); var firstOperationLength = int.Parse(diagnostic.Properties.GetValueOrDefault("FirstOperationLength"), NumberStyles.Integer, CultureInfo.InvariantCulture); var lastOperationStart = int.Parse(diagnostic.Properties.GetValueOrDefault("LastOperationStart"), NumberStyles.Integer, CultureInfo.InvariantCulture); var lastOperationLength = int.Parse(diagnostic.Properties.GetValueOrDefault("LastOperationLength"), NumberStyles.Integer, CultureInfo.InvariantCulture); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var firstNode = root.FindNode(new TextSpan(firstOperationStart, firstOperationLength), getInnermostNodeForTie: true); var lastNode = root.FindNode(new TextSpan(lastOperationStart, lastOperationLength), getInnermostNodeForTie: true); if (firstNode == null || lastNode == null) { return(document); } var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var firstOperation = semanticModel.GetOperation(firstNode, cancellationToken) as IInvocationOperation; var lastOperation = semanticModel.GetOperation(lastNode, cancellationToken) as IInvocationOperation; if (firstOperation == null || lastOperation == null) { return(document); } var method = editor.Generator.MemberAccessExpression(firstOperation.Arguments[0].Syntax, lastOperation.TargetMethod.Name); var newExpression = editor.Generator.InvocationExpression(method, lastOperation.Arguments.Skip(1).Select(arg => arg.Syntax)); editor.ReplaceNode(lastOperation.Syntax, newExpression); return(editor.GetChangedDocument()); }
private static async Task <Document> ApplyFixAsync(CodeFixContext context, CancellationToken cancellationToken, ExpressionStatementSyntax statement, bool usesUnderscoreNames) { var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken) .ConfigureAwait(false); var containingType = statement.FirstAncestor <TypeDeclarationSyntax>(); var field = editor.AddField( containingType, usesUnderscoreNames ? "_disposable" : "disposable", Accessibility.Private, DeclarationModifiers.ReadOnly, CompositeDisposableType, cancellationToken); var fieldAccess = usesUnderscoreNames ? SyntaxFactory.IdentifierName(field.Name()) : SyntaxFactory.ParseExpression($"this.{field.Name()}"); editor.ReplaceNode( statement, SyntaxFactory.ExpressionStatement( (ExpressionSyntax)editor.Generator.AssignmentStatement( fieldAccess, ((ObjectCreationExpressionSyntax)editor.Generator.ObjectCreationExpression( CompositeDisposableType)) .WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SingletonSeparatedList( statement.Expression))))) .WithLeadingTrivia(SyntaxFactory.ElasticMarker) .WithTrailingTrivia(SyntaxFactory.ElasticMarker)); return(editor.GetChangedDocument()); }
/// <summary> /// update the original document and remove the type that was moved. /// perform other fix ups as necessary. /// </summary> /// <returns>an updated solution with the original document fixed up as appropriate.</returns> private async Task <Solution> RemoveTypeFromSourceDocumentAsync( Document sourceDocument, Document documentWithMovedType) { var documentEditor = await DocumentEditor.CreateAsync(sourceDocument, CancellationToken).ConfigureAwait(false); // Make the type chain above the type we're moving 'partial'. // However, keep all the attributes on these types as theses are the // original attributes and we don't want to mess with them. AddPartialModifiersToTypeChain(documentEditor, removeAttributesAndComments: false, removeTypeInheritance: false); documentEditor.RemoveNode(State.TypeNode, SyntaxRemoveOptions.KeepUnbalancedDirectives); var updatedDocument = documentEditor.GetChangedDocument(); // Now, remove any imports that we no longer need *if* they were used in the new // file with the moved type. Essentially, those imports were here just to serve // that new type and we should remove them. If we have *other* imports that // other file does not use *and* we do not use, we'll still keep those around. // Those may be important to the user for code they're about to write, and we // don't want to interfere with them by removing them. var service = sourceDocument.GetLanguageService <IRemoveUnnecessaryImportsService>(); var syntaxFacts = sourceDocument.GetLanguageService <ISyntaxFactsService>(); var rootWithMovedType = await documentWithMovedType.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false); var movedImports = rootWithMovedType.DescendantNodes() .Where(syntaxFacts.IsUsingOrExternOrImport) .ToImmutableArray(); Func <SyntaxNode, bool> predicate = n => movedImports.Contains(i => i.IsEquivalentTo(n)); updatedDocument = await service.RemoveUnnecessaryImportsAsync( updatedDocument, predicate, CancellationToken).ConfigureAwait(false); return(updatedDocument.Project.Solution); }
private static async Task <Document> FixContentDialogAPI(Document document, MemberAccessExpressionSyntax contentDialogMemberAccess, CancellationToken cancellationToken) { var newMethodDeclarationSibling = contentDialogMemberAccess.Ancestors().OfType <MethodDeclarationSyntax>().First(); var newMethodCall = SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression("SetContentDialogRoot"), SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(contentDialogMemberAccess.Expression), SyntaxFactory.Argument(SyntaxFactory.ParseExpression("this")) }))); var newMethodCallComment = SyntaxFactory.Comment(DialogSetterComment); var documentEditor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); documentEditor.ReplaceNode(contentDialogMemberAccess.Expression, newMethodCall.WithLeadingTrivia(newMethodCallComment)); if (!newMethodDeclarationSibling.Parent !.ChildNodes().OfType <MethodDeclarationSyntax>() .Any(sibling => sibling.Identifier.ValueText == "SetContentDialogRoot")) { var newMethodRoot = await CSharpSyntaxTree.ParseText(@" class A { private static ContentDialog SetContentDialogRoot(ContentDialog contentDialog, UserControl control) { if (Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent(""Windows.Foundation.UniversalApiContract"", 8)) { contentDialog.XamlRoot = control.Content.XamlRoot; } return contentDialog; } }", cancellationToken : cancellationToken).GetRootAsync(cancellationToken).ConfigureAwait(false); var newMethodDeclaration = newMethodRoot.DescendantNodes().OfType <MethodDeclarationSyntax>().First(); documentEditor.InsertAfter(newMethodDeclarationSibling, newMethodDeclaration); } return(document.WithSyntaxRoot(documentEditor.GetChangedRoot())); }
public static async Task Simplify() { var code = @" namespace N { using System; class C { /// <summary> /// <see cref=""System.EventHandler""/> /// </summary> public event System.EventHandler E; } }"; var sln = CodeFactory.CreateSolution(code); var editor = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false); var containingType = editor.OriginalRoot.SyntaxTree.FindClassDeclaration("C"); _ = editor.ReplaceNode(containingType, x => x.WithSimplifiedNames()); var expected = @" namespace N { using System; class C { /// <summary> /// <see cref=""EventHandler""/> /// </summary> public event EventHandler E; } }"; CodeAssert.AreEqual(expected, editor.GetChangedDocument()); }
/// <summary> /// Move <paramref name="toMove"></paramref> before <paramref name="member">.</paramref>. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/>.</param> /// <param name="toMove">The <see cref="MemberDeclarationSyntax"/> to move.</param> /// <param name="member">The <see cref="MemberDeclarationSyntax"/>.</param> /// <returns>The <see cref="DocumentEditor"/> that was passed in.</returns> public static DocumentEditor MoveBefore(this DocumentEditor editor, MemberDeclarationSyntax toMove, MemberDeclarationSyntax member) { if (editor is null) { throw new ArgumentNullException(nameof(editor)); } if (toMove is null) { throw new ArgumentNullException(nameof(toMove)); } if (member is null) { throw new ArgumentNullException(nameof(member)); } editor.RemoveNode(toMove); editor.InsertBefore(member, ToMove()); editor.ReplaceNode(member, Member()); return(editor); MemberDeclarationSyntax ToMove() { if (toMove.Parent is TypeDeclarationSyntax typeDeclaration) { return(toMove.AdjustLeadingNewLine(typeDeclaration.Members.ElementAtOrDefault(typeDeclaration.Members.IndexOf(member) - 1))); } return(toMove); } MemberDeclarationSyntax Member() { return(member.AdjustLeadingNewLine(toMove)); } }
protected void RestoreBrackets(DocumentEditor tb, char[] oldBrackets) { tb.LeftBracket = oldBrackets[0]; tb.RightBracket = oldBrackets[1]; tb.LeftBracket2 = oldBrackets[2]; tb.RightBracket2 = oldBrackets[3]; }
internal MacrosManager(DocumentEditor ctrl) { UnderlayingControl = ctrl; AllowMacroRecordingByUser = true; }
protected virtual void Subscribe(DocumentEditor target) { target.Scroll += new ScrollEventHandler(target_Scroll); target.SelectionChanged += new EventHandler(target_SelectionChanged); target.VisibleRangeChanged += new EventHandler(target_VisibleRangeChanged); }
/// <summary> /// Shows VisualMarker /// Call this method in Draw method, when you need to show VisualMarker for your style /// </summary> protected virtual void AddVisualMarker(DocumentEditor tb, StyleVisualMarker marker) { tb.AddVisualMarker(marker); }
/// <summary> /// Occurs when user click on StyleVisualMarker joined to this style /// </summary> public virtual void OnVisualMarkerClick(DocumentEditor tb, VisualMarkerEventArgs args) { if (VisualMarkerClick != null) VisualMarkerClick(tb, args); }
public ReplaceForm(DocumentEditor tb) { InitializeComponent(); this.tb = tb; }
public FindForm(DocumentEditor tb) { InitializeComponent(); this.tb = tb; }
public string GetHtml(Range r) { this.tb = r.tb; Dictionary<StyleIndex, object> styles = new Dictionary<StyleIndex, object>(); StringBuilder sb = new StringBuilder(); StringBuilder tempSB = new StringBuilder(); StyleIndex currentStyleId = StyleIndex.None; r.Normalize(); int currentLine = r.Start.iLine; styles[currentStyleId] = null; // if (UseOriginalFont) sb.AppendFormat("<font style=\"font-family: {0}, monospace; font-size: {1}pt; line-height: {2}px;\">", r.tb.Font.Name, r.tb.Font.SizeInPoints, r.tb.CharHeight); // if (IncludeLineNumbers) tempSB.AppendFormat("<span class=lineNumber>{0}</span> ", currentLine + 1); // bool hasNonSpace = false; foreach (Place p in r) { Char c = r.tb[p.iLine][p.iChar]; if (c.style != currentStyleId) { Flush(sb, tempSB, currentStyleId); currentStyleId = c.style; styles[currentStyleId] = null; } if (p.iLine != currentLine) { for (int i = currentLine; i < p.iLine; i++) { tempSB.Append(UseBr ? "<br>" : "\r\n"); if (IncludeLineNumbers) tempSB.AppendFormat("<span class=lineNumber>{0}</span> ", i + 2); } currentLine = p.iLine; hasNonSpace = false; } switch (c.c) { case ' ': if ((hasNonSpace || !UseForwardNbsp) && !UseNbsp) goto default; tempSB.Append(" "); break; case '<': tempSB.Append("<"); break; case '>': tempSB.Append(">"); break; case '&': tempSB.Append("&"); break; default: hasNonSpace = true; tempSB.Append(c.c); break; } } Flush(sb, tempSB, currentStyleId); if (UseOriginalFont) sb.Append("</font>"); //build styles if (UseStyleTag) { tempSB.Length = 0; tempSB.Append("<style type=\"text/css\">"); foreach (var styleId in styles.Keys) tempSB.AppendFormat(".fctb{0}{{ {1} }}\r\n", GetStyleName(styleId), GetCss(styleId)); tempSB.Append("</style>"); sb.Insert(0, tempSB.ToString()); } if (IncludeLineNumbers) sb.Insert(0, LineNumbersCSS); return sb.ToString(); }
public string GetRtf(Range r) { this.tb = r.tb; var styles = new Dictionary<StyleIndex, object>(); var sb = new StringBuilder(); var tempSB = new StringBuilder(); var currentStyleId = StyleIndex.None; r.Normalize(); int currentLine = r.Start.iLine; styles[currentStyleId] = null; colorTable.Clear(); // var lineNumberColor = GetColorTableNumber(r.tb.LineNumberColor); if (IncludeLineNumbers) tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", currentLine + 1, lineNumberColor); // foreach (Place p in r) { Char c = r.tb[p.iLine][p.iChar]; if (c.style != currentStyleId) { Flush(sb, tempSB, currentStyleId); currentStyleId = c.style; styles[currentStyleId] = null; } if (p.iLine != currentLine) { for (int i = currentLine; i < p.iLine; i++) { tempSB.AppendLine(@"\line"); if (IncludeLineNumbers) tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", i + 2, lineNumberColor); } currentLine = p.iLine; } switch (c.c) { case '\\': tempSB.Append(@"\\"); break; case '{': tempSB.Append(@"\{"); break; case '}': tempSB.Append(@"\}"); break; default: var ch = c.c; var code = (int)ch; if(code < 128) tempSB.Append(c.c); else tempSB.AppendFormat(@"{{\u{0}}}", code); break; } } Flush(sb, tempSB, currentStyleId); //build color table var list = new SortedList<int, Color>(); foreach (var pair in colorTable) list.Add(pair.Value, pair.Key); tempSB.Length = 0; tempSB.AppendFormat(@"{{\colortbl;"); foreach (var pair in list) tempSB.Append(GetColorAsString(pair.Value)+";"); tempSB.AppendLine("}"); // if (UseOriginalFont) { sb.Insert(0, string.Format(@"{{\fonttbl{{\f0\fmodern {0};}}}}{{\fs{1} ", tb.Font.Name, (int)(2 * tb.Font.SizeInPoints), tb.CharHeight)); sb.AppendLine(@"}"); } sb.Insert(0, tempSB.ToString()); sb.Insert(0, @"{\rtf1\ud\deff0"); sb.AppendLine(@"}"); return sb.ToString(); }
protected char[] RememberBrackets(DocumentEditor tb) { return new[] { tb.LeftBracket, tb.RightBracket, tb.LeftBracket2, tb.RightBracket2 }; }
internal AutocompleteListView(DocumentEditor tb) { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true); base.Font = new Font(FontFamily.GenericSansSerif, 9); visibleItems = new List<AutocompleteItem>(); VerticalScroll.SmallChange = ItemHeight; MaximumSize = new Size(Size.Width, 180); toolTip.ShowAlways = false; AppearInterval = 500; timer.Tick += new EventHandler(timer_Tick); SelectedColor = Color.Orange; HoveredColor = Color.Red; ToolTipDuration = 3000; this.tb = tb; tb.KeyDown += new KeyEventHandler(tb_KeyDown); tb.SelectionChanged += new EventHandler(tb_SelectionChanged); tb.KeyPressed += new KeyPressEventHandler(tb_KeyPressed); Form form = tb.FindForm(); if (form != null) { form.LocationChanged += (o, e) => Menu.Close(); form.ResizeBegin += (o, e) => Menu.Close(); form.FormClosing += (o, e) => Menu.Close(); form.LostFocus += (o, e) => Menu.Close(); } tb.LostFocus += (o, e) => { if (!Menu.Focused) Menu.Close(); }; tb.Scroll += (o, e) => Menu.Close(); this.VisibleChanged += (o, e) => { if (this.Visible) DoSelectedVisible(); }; }