ConvertEntity() public method

public ConvertEntity ( IEntity entity ) : EntityDeclaration
entity IEntity
return EntityDeclaration
コード例 #1
0
		static string GeneratePartialClassContextStub(DebuggerCompletionContext context)
		{
			var compilation = SD.ParserService.GetCompilationForFile(context.FileName);
			var file = SD.ParserService.GetExistingUnresolvedFile(context.FileName);
			if (compilation == null || file == null)
				return "";
			var unresolvedMember = file.GetMember(context.Location);
			if (unresolvedMember == null)
				return "";
			var member = unresolvedMember.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly));
			if (member == null)
				return "";
			var builder = new TypeSystemAstBuilder();
			MethodDeclaration decl;
			if (unresolvedMember is IMethod) {
				// If it's a method, convert it directly (including parameters + type parameters)
				decl = (MethodDeclaration)builder.ConvertEntity(member);
			} else {
				// Otherwise, create a method anyways, and copy the parameters
				decl = new MethodDeclaration();
				if (member is IParameterizedMember) {
					foreach (var p in ((IParameterizedMember)member).Parameters) {
						decl.Parameters.Add(builder.ConvertParameter(p));
					}
				}
			}
			decl.Name = "__DebuggerStub__";
			decl.ReturnType = builder.ConvertType(member.ReturnType);
			decl.Modifiers = unresolvedMember.IsStatic ? Modifiers.Static : Modifiers.None;
			// Make the method look like an explicit interface implementation so that it doesn't appear in CC
			decl.PrivateImplementationType = new SimpleType("__DummyType__");
			decl.Body = GenerateBodyFromContext(builder, context);
			return WrapInType(unresolvedMember.DeclaringTypeDefinition, decl).ToString();
		}
コード例 #2
0
		static string GeneratePartialClassContextStub(ICodeContext context)
		{
			var member = context.CurrentMember;
			if (member == null)
				return "";
			var builder = new TypeSystemAstBuilder();
			MethodDeclaration decl;
			if (member is IMethod) {
				// If it's a method, convert it directly (including parameters + type parameters)
				decl = (MethodDeclaration)builder.ConvertEntity(member);
			} else {
				// Otherwise, create a method anyways, and copy the parameters
				decl = new MethodDeclaration();
				if (member is IParameterizedMember) {
					foreach (var p in ((IParameterizedMember)member).Parameters) {
						decl.Parameters.Add(builder.ConvertParameter(p));
					}
				}
			}
			decl.Name = "__DebuggerStub__";
			decl.ReturnType = builder.ConvertType(member.ReturnType);
			decl.Modifiers = member.IsStatic ? Modifiers.Static : Modifiers.None;
			// Make the method look like an explicit interface implementation so that it doesn't appear in CC
			decl.PrivateImplementationType = new SimpleType("__DummyType__");
			decl.Body = GenerateBodyFromContext(builder, context.LocalVariables.ToArray());
			return WrapInType(context.CurrentTypeDefinition, decl).ToString();
		}
コード例 #3
0
		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.Virtual | Modifiers.Abstract);
			entityDeclaration.Modifiers |= Modifiers.Override;
			
			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, ParametersToExpressions(this.Entity));
					var body = entityDeclaration.GetChildByRole(Roles.Body);
					body.Statements.Clear();
					if (((IMethod)this.Entity).ReturnType.IsKnownType(KnownTypeCode.Void))
						body.Statements.Add(new ExpressionStatement(baseCall));
					else
						body.Statements.Add(new ReturnStatement(baseCall));
				} else if (this.Entity.SymbolKind == SymbolKind.Indexer || this.Entity.SymbolKind == SymbolKind.Property) {
					Expression baseCall;
					if (this.Entity.SymbolKind == SymbolKind.Indexer)
						baseCall = new BaseReferenceExpression().Indexer(ParametersToExpressions(this.Entity));
					else
						baseCall = new BaseReferenceExpression().Member(this.Entity.Name);
					var getterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.GetterRole).Body;
					if (!getterBody.IsNull) {
						getterBody.Statements.Clear();
						getterBody.Add(new ReturnStatement(baseCall.Clone()));
					}
					var setterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.SetterRole).Body;
					if (!setterBody.IsNull) {
						setterBody.Statements.Clear();
						setterBody.Add(new AssignmentExpression(baseCall.Clone(), new IdentifierExpression("value")));
					}
				}
			}
			
			var document = context.Editor.Document;
			StringWriter w = new StringWriter();
			var formattingOptions = FormattingOptionsFactory.CreateSharpDevelop();
			var segmentDict = SegmentTrackingOutputFormatter.WriteNode(w, entityDeclaration, formattingOptions, context.Editor.Options);
			
			using (document.OpenUndoGroup()) {
				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);
				}
				CSharpFormatterHelper.Format(context.Editor, declarationBegin, newText.Length, formattingOptions);
			}
		}
コード例 #4
0
		public override void Complete(CompletionContext context)
		{
			if (declarationBegin > context.StartOffset) {
				base.Complete(context);
				return;
			}
			
			TypeSystemAstBuilder b = new TypeSystemAstBuilder(contextAtCaret);
			b.GenerateBody = true;
			
			var entityDeclaration = b.ConvertEntity(this.Entity);
			entityDeclaration.Modifiers &= ~Modifiers.VisibilityMask; // remove visiblity
			entityDeclaration.Modifiers |= Modifiers.Partial;
			
			var document = context.Editor.Document;
			StringWriter w = new StringWriter();
			var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(contextAtCaret.Compilation.GetProject());
			var segmentDict = SegmentTrackingOutputFormatter.WriteNode(
				w, entityDeclaration, formattingOptions.OptionsContainer.GetEffectiveOptions(), context.Editor.Options);
			
			using (document.OpenUndoGroup()) {
				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);
				}
				CSharpFormatterHelper.Format(context.Editor, declarationBegin, newText.Length, formattingOptions.OptionsContainer);
			}
		}
コード例 #5
0
        public static string GetOverrideTargetName
            (IMember m, CSharpTypeResolveContext resolveContext) {
            var builder = new TypeSystemAstBuilder
                (new CSharpResolver(resolveContext));

			return builder.ConvertEntity(m).ToString()
                // Builder automatically adds a trailing newline
                .TrimEnd(Environment.NewLine.ToCharArray());
        }
コード例 #6
0
		public override void InsertEventHandler(ITypeDefinition target, string name, IEvent eventDefinition, bool jumpTo)
		{
			IUnresolvedTypeDefinition match = null;
			
			foreach (var part in target.Parts) {
				if (match == null || EntityModelContextUtils.IsBetterPart(part, match, ".cs"))
					match = part;
			}
			
			if (match == null) return;
			
			var view = SD.FileService.OpenFile(new FileName(match.Region.FileName), jumpTo);
			var editor = view.GetRequiredService<ITextEditor>();
			var last = match.Members.LastOrDefault() ?? (IUnresolvedEntity)match;
			editor.Caret.Location = last.BodyRegion.End;
			var context = SDRefactoringContext.Create(editor, CancellationToken.None);
			
			var node = context.RootNode.GetNodeAt<EntityDeclaration>(last.Region.Begin);
			var resolver = context.GetResolverStateAfter(node);
			var builder = new TypeSystemAstBuilder(resolver);
			var delegateDecl = builder.ConvertEntity(eventDefinition.ReturnType.GetDefinition()) as DelegateDeclaration;
			if (delegateDecl == null) return;
			var throwStmt = new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")));
			var decl = new MethodDeclaration() {
				ReturnType = delegateDecl.ReturnType.Clone(),
				Name = name,
				Body = new BlockStatement() {
					throwStmt
				}
			};
			var param = delegateDecl.Parameters.Select(p => p.Clone()).OfType<ParameterDeclaration>().ToArray();
			decl.Parameters.AddRange(param);
			
			using (Script script = context.StartScript()) {
				// FIXME : will not work properly if there are no members.
				if (last == match) {
					throw new NotImplementedException();
					// TODO InsertWithCursor not implemented!
					//script.InsertWithCursor("Insert event handler", Script.InsertPosition.End, decl).RunSynchronously();
				} else {
					// TODO does not jump correctly...
					script.InsertAfter(node, decl);
					editor.JumpTo(throwStmt.StartLocation.Line, throwStmt.StartLocation.Column);
				}
			}
		}
コード例 #7
0
		static string GeneratePartialClassContextStub(FileName fileName, TextLocation currentLocation, StackFrame context)
		{
			var compilation = SD.ParserService.GetCompilationForFile(fileName);
			var file = SD.ParserService.GetExistingUnresolvedFile(fileName);
			if (compilation == null || file == null)
				return "";
			var member = file.GetMember(currentLocation);
			if (member == null)
				return "";
			var builder = new TypeSystemAstBuilder();
			EntityDeclaration decl = builder.ConvertEntity(member.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly)));
			decl.Name = "__DebuggerStub_" + decl.Name;
			decl.Modifiers &= (Modifiers.Static);
			switch (member.SymbolKind) {
				case SymbolKind.Property:
					break;
				case SymbolKind.Indexer:
					break;
				case SymbolKind.Event:
					break;
				case SymbolKind.Method:
					GenerateBodyFromContext(builder, context, (MethodDeclaration)decl);
					break;
				case SymbolKind.Operator:
					break;
				case SymbolKind.Constructor:
					break;
				case SymbolKind.Destructor:
					break;
				case SymbolKind.Accessor:
					break;
				default:
					throw new ArgumentOutOfRangeException();
			}
			return WrapInType(member.DeclaringTypeDefinition, decl.ToString());
		}
コード例 #8
0
ファイル: OverrideHandler.cs プロジェクト: gamwang/vimrc
        /// <summary>
        ///   Takes an editing context. Inserts an override
        ///   declaration of the chosen member in the context. Returns
        ///   the new context.
        /// </summary>
        /// <remarks>
        ///   The text editor cursor stays in the same line and column
        ///   it originally was.
        /// </remarks>
        public RunOverrideTargetResponse RunOverrideTarget
            (RunOverrideTargetRequest request) {
            var overrideContext = new OverrideContext(request, _parser);
            var refactoringContext = OmniSharpRefactoringContext.GetContext
                (overrideContext.BufferParser, request);

            var memberToOverride = overrideContext.GetOverridableMembers()
                .First(ot => {
                    var memberSignature =
                     GetOverrideTargetsResponse.GetOverrideTargetName
                      (ot, overrideContext.CompletionContext.ResolveContext);

                    return memberSignature == request.OverrideTargetName;});

            var builder = new TypeSystemAstBuilder
                (new CSharpResolver
                 (overrideContext.CompletionContext.ResolveContext))
                 // Will generate a "throw new
                 // NotImplementedException();" statement in the
                 // bodies
                 {GenerateBody = true};

            var newEditorContents = runOverrideTargetWorker
                ( request
                , refactoringContext
                , overrideContext.CompletionContext.ParsedContent
                , script: new OmniSharpScript(refactoringContext, _config)
                , memberDeclaration:
                    builder.ConvertEntity(memberToOverride));

            return new RunOverrideTargetResponse
                ( fileName : request.FileName
                , buffer   : newEditorContents.Text
                , line     : request.Line
                , column   : request.Column);
        }
コード例 #9
0
 void WriteTypeDeclarationName(ITypeDefinition typeDef, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
 {
     var astBuilder = new TypeSystemAstBuilder();
     EntityDeclaration node = astBuilder.ConvertEntity(typeDef);
     if (typeDef.DeclaringTypeDefinition != null)
     {
         WriteTypeDeclarationName(typeDef.DeclaringTypeDefinition, writer, formattingPolicy);
         writer.WriteToken(Roles.Dot, ".");
     }
     writer.WriteIdentifier(node.NameToken);
     WriteTypeParameters(writer, node.GetChildrenByRole(Roles.TypeParameter));
 }
コード例 #10
0
		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.Virtual | 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 = FormattingOptionsFactory.CreateSharpDevelop();
			var segmentDict = SegmentTrackingOutputFormatter.WriteNode(w, entityDeclaration, formattingOptions, 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);
				}
				CSharpFormatterHelper.Format(context.Editor, declarationBegin, newText.Length, formattingOptions);
				
				var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
				var typeResolveContext = refactoringContext.GetTypeResolveContext();
				if (typeResolveContext == null) {
					return;
				}
				var resolvedCurrent = typeResolveContext.CurrentTypeDefinition;
				var entities = FindFieldsAndProperties(resolvedCurrent).ToList();
				if (entities.Any()) {
					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;

					AbstractInlineRefactorDialog dialog = new OverrideToStringMethodDialog(insertionContext, context.Editor, insertionPos, entities, baseCallStatement);
					dialog.Element = uiService.CreateInlineUIElement(insertionPos, dialog);
					
					insertionContext.RegisterActiveElement(new InlineRefactorSnippetElement(cxt => null, ""), dialog);
				} else {
					if (baseCallStatement != null) {
						// Add default base call
						MethodDeclaration insertedOverrideMethod = refactoringContext.GetNode().PrevSibling as MethodDeclaration;
						if (insertedOverrideMethod == null)
						{
							// We are not inside of a method declaration
							return;
						}
						using (Script script = refactoringContext.StartScript()) {
							script.AddTo(insertedOverrideMethod.Body, baseCallStatement);
						}
					}
				}
				
				insertionContext.RaiseInsertionCompleted(EventArgs.Empty);
			}
		}
コード例 #11
0
		internal static string GenerateMemberCode (MDRefactoringContext ctx, TypeSystemAstBuilder builder, IMember member)
		{
			var method = builder.ConvertEntity (member) as MethodDeclaration;
			if (method != null) {
				method.Body = new BlockStatement {
					new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException")))
				};
				method.Modifiers &= ~Modifiers.Virtual;
				method.Modifiers &= ~Modifiers.Abstract;
				method.Attributes.Add (new AttributeSection {
					Attributes =  {
						GenerateExportAttribute (ctx, member)
					}
				});
				return method.ToString (ctx.FormattingOptions);
			}
			var property = builder.ConvertEntity (member) as PropertyDeclaration;
			if (property == null)
				return null;
			var p = (IProperty)member;
			property.Modifiers &= ~Modifiers.Virtual;
			property.Modifiers &= ~Modifiers.Abstract;
			if (p.CanGet) {
				property.Getter.Body = new BlockStatement {
					new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException")))
				};
				property.Getter.Attributes.Add (new AttributeSection {
					Attributes =  {
						GenerateExportAttribute (ctx, p.Getter)
					}
				});
			}
			if (p.CanSet) {
				property.Setter.Body = new BlockStatement {
					new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException")))
				};
				property.Setter.Attributes.Add (new AttributeSection {
					Attributes =  {
						GenerateExportAttribute (ctx, p.Setter)
					}
				});
			}
			return property.ToString (ctx.FormattingOptions);
		}
コード例 #12
0
		public override void InsertEventHandler(ITypeDefinition target, string name, IEvent eventDefinition, bool jumpTo, InsertEventHandlerBodyKind bodyKind = InsertEventHandlerBodyKind.ThrowNotImplementedException)
		{
			IUnresolvedTypeDefinition match = null;
			
			foreach (var part in target.Parts) {
				if (match == null || EntityModelContextUtils.IsBetterPart(part, match, ".cs"))
					match = part;
			}
			
			if (match == null) return;
			
			var view = SD.FileService.OpenFile(new FileName(match.Region.FileName), jumpTo);
			var editor = view.GetRequiredService<ITextEditor>();
			var last = match.Members.LastOrDefault() ?? (IUnresolvedEntity)match;
			editor.Caret.Location = last.BodyRegion.End;
			var context = SDRefactoringContext.Create(editor, CancellationToken.None);
			
			var node = context.RootNode.GetNodeAt<EntityDeclaration>(last.Region.Begin);
			var resolver = context.GetResolverStateAfter(node);
			var builder = new TypeSystemAstBuilder(resolver);
			var invokeMethod = eventDefinition.ReturnType.GetDelegateInvokeMethod();
			if (invokeMethod == null) return;
			var importedMethod = resolver.Compilation.Import(invokeMethod);
			var delegateDecl = builder.ConvertEntity(importedMethod) as MethodDeclaration;
			if (delegateDecl == null) return;
			var throwStmt = new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")));
			var decl = new MethodDeclaration() {
				ReturnType = delegateDecl.ReturnType.Clone(),
				Name = name,
				Body = new BlockStatement() {
					throwStmt
				}
			};
			var param = delegateDecl.Parameters.Select(p => p.Clone()).ToArray();
			decl.Parameters.AddRange(param);
			
			using (Script script = context.StartScript()) {
				int eolLen = 0;
				if (last == match) {
					eolLen = 2;
					script.AddTo((TypeDeclaration)node, decl);
				} else {
					script.InsertAfter(node, decl);
				}
				switch (bodyKind) {
					case InsertEventHandlerBodyKind.TodoComment:
						Comment comment = new Comment(" TODO: Implement " + name);
						script.Replace(throwStmt, comment);
						script.Select(comment);
						break;
					case InsertEventHandlerBodyKind.Nothing:
						var segment = script.GetSegment(throwStmt);
						if (script is DocumentScript && eolLen > 0) {
							eolLen = ((DocumentScript)script).CurrentDocument.GetLineByOffset(segment.Offset).DelimiterLength;
						}
						script.RemoveText(segment.Offset, segment.Length - eolLen);
						script.Select(segment.Offset, segment.Offset);
						break;
					case InsertEventHandlerBodyKind.ThrowNotImplementedException:
						script.Select(throwStmt);
						break;
				}
			}
		}
コード例 #13
0
        public override void Complete(ICSharpCode.AvalonEdit.Editing.TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
        {
            if (declarationBegin > completionSegment.Offset)
            {
                base.Complete(textArea, completionSegment, insertionRequestEventArgs);
                return;
            }
            TypeSystemAstBuilder b = new TypeSystemAstBuilder(new CSharpResolver(contextAtCaret));
            b.ShowTypeParameterConstraints = false;
            b.GenerateBody = true;

            var entityDeclaration = b.ConvertEntity(this.Entity);
            entityDeclaration.Modifiers &= ~(Modifiers.Virtual | Modifiers.Abstract);
            entityDeclaration.Modifiers |= Modifiers.Override;

            if (!this.Entity.IsAbstract)
            {
                // modify body to call the base method
                if (this.Entity.EntityType == EntityType.Method)
                {
                    var baseCall = new BaseReferenceExpression().Invoke(this.Entity.Name, ParametersToExpressions(this.Entity));
                    var body = entityDeclaration.GetChildByRole(Roles.Body);
                    body.Statements.Clear();
                    if (((IMethod)this.Entity).ReturnType.IsKnownType(KnownTypeCode.Void))
                        body.Statements.Add(new ExpressionStatement(baseCall));
                    else
                        body.Statements.Add(new ReturnStatement(baseCall));
                }
                else if (this.Entity.EntityType == EntityType.Indexer || this.Entity.EntityType == EntityType.Property)
                {
                    Expression baseCall;
                    if (this.Entity.EntityType == EntityType.Indexer)
                        baseCall = new BaseReferenceExpression().Indexer(ParametersToExpressions(this.Entity));
                    else
                        baseCall = new BaseReferenceExpression().Member(this.Entity.Name);
                    var getterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.GetterRole).Body;
                    if (!getterBody.IsNull)
                    {
                        getterBody.Statements.Clear();
                        getterBody.Add(new ReturnStatement(baseCall.Clone()));
                    }
                    var setterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.SetterRole).Body;
                    if (!setterBody.IsNull)
                    {
                        setterBody.Statements.Clear();
                        setterBody.Add(new AssignmentExpression(baseCall.Clone(), new IdentifierExpression("value")));
                    }
                }
            }

            var document = textArea.Document;
            StringWriter w = new StringWriter();
            var formattingOptions = FormattingOptionsFactory.CreateSharpDevelop();
            var segmentDict = SegmentTrackingOutputFormatter.WriteNode(w, entityDeclaration, formattingOptions, textArea.Options);

            string newText = w.ToString().TrimEnd();
            document.Replace(declarationBegin, completionSegment.EndOffset - declarationBegin, newText);
            var throwStatement = entityDeclaration.Descendants.FirstOrDefault(n => n is ThrowStatement);
            if (throwStatement != null)
            {
                var segment = segmentDict[throwStatement];
                textArea.Selection = new RectangleSelection(textArea, new TextViewPosition(textArea.Document.GetLocation(declarationBegin + segment.Offset)), new TextViewPosition(textArea.Document.GetLocation(declarationBegin + segment.Offset + segment.Length)));
            }

            //format the inserted code nicely
            var formatter = new CSharpFormatter(formattingOptions);
            formatter.AddFormattingRegion(new DomRegion(document.GetLocation(declarationBegin), document.GetLocation(declarationBegin + newText.Length)));
            var syntaxTree = new CSharpParser().Parse(document);
            formatter.AnalyzeFormatting(document, syntaxTree).ApplyChanges();
        }