How can NRefactory keep the original formatting

699 Views Asked by At

Hi I use NRefactory to extract String constant and remplace it by static variable for i18n, I can successfully do it but when I output my code with GetText() it doesn't keep the original formatting. I want to be do that with the minimum formatting change.

Thanks.

2

There are 2 best solutions below

2
On

Take a look at the "Modifying C# code" portion (last section) of the NRefactory CodeProject article.

0
On

If you want to keep current formatting you can use DocumentScript to apply modifications on AST. It works based in TextLocation property stored in syntax tree.

To create a script you need to do this :

IDocument document = new StringBuilderDocument("source code");
CSharpFormattingOptions policy = FormattingOptionsFactory.CreateAllman();
var options = new TextEditorOptions();

var script = new DocumentScript(document, policy, options);

Now you can use methods like Replace, Remove, InsertAfter and etc. on you AST. It works with both ast nodes as well as offsets.

It also keeps track of modifications, so you don't have to be worry about conflicts on multiple changes.
For more examples on NRefactory you may wanna also check my blog.