Saturday, March 30, 2013

Code formatting with NRefactory

NRefactory is a library for parsing and analyzing C# source code hosted at GitHub. It is a bit like Roslyn from Microsoft, but fully open source and free to use (MIT X11). It's possible to parse and analyze individual C# files or whole projects. Mainly it was developed for IDEs therefore it has many high level features suited for development environments like type semantic highlighting, refactorings or code completion.
It provides almost everything needed for working with C# code.

NRefactory get's used in SharpDevelop 5, MonoDevelop and Xamarin Studio for providing high level C# features. Even VIM got a C# plugin providing high level C# features: Omnisharp. I've seen many uses of the library in various non IDE releated projects like the Saltarelle C#->JavaScript compiler.

But I've never seen anyone using the C# formatter from nrefactory. The formatter provides rich formatting features and is very easy to use. Let's take an example.
Today I wrote a piece of code using a text editor:

As you see there is a space after the 'null' that shouldn't be there. I could've just removed the space and continue my work - but what would happen if I do it again ? Wouldn't it be nice if it could be auto formatted like in a IDE. Just make the code format itself!

First step - make the program print itself. For that I added some code around the if that repeats the program and prints it:


Now running the program on the console gives:

The first step is done. Now we need to call the formatter. The project needs to reference NRefactory + NRefactory.CSharp and a using to the ICSharpCode.NRefactory.CSharp namespace needs to be added. The WriteLine call should use the CSharpFormatter to print a formatted version of itself:

Now running this will correctly format the if statement:

The self formatting source code - easy and without any external IDE.
The wrong space is finally gone. But the formatter has done something with the brackets. That's because of the options I gave to the formatter.
The C# formatter needs an options object that specifies how the C# code should be formatted. The CSharpFormattingOptions class provides a large set of very fine grained formatting options. The factory gives easy access to the most common indenting styles (see wikipedia). The Allman style is used in Visual Studio .NET which puts all braces on it's own line. That's why the formatter has altered the if brackets.
That's just one way to call the formatter. It was built for in IDE use.
The formatter can generate the minimum change set of replace operations required to do the formatting. Furthermore it's possible to format only a portion of the text inside a document. In monodevelop the on the fly formatter uses this functionality to provide formatting.
The formatting engine in NRefactory is mighty and easy to use - let me know if you find uses for it or have improvements.

73 comments:

  1. I would recommend using roslyn now - NRefactory has been discontinued :/

    ReplyDelete
  2. I really like the dear information you offer in your articles. I’m able to bookmark your site and show the kids check out up here generally. Im fairly positive theyre likely to be informed a great deal of new stuff here than anyone

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

    ReplyDelete
  3. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.

    Java training in Bangalore | Java training in Btm layout

    Java training in Bangalore |Java training in Rajaji nagar

    Java training in Bangalore | Java training in Kalyan nagar

    ReplyDelete
  4. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information.

    rpa training in chennai
    rpa training in bangalore
    rpa course in bangalore
    best rpa training in bangalore
    rpa online training

    ReplyDelete
  5. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    python interview questions and answers
    python tutorials
    python course institute in electronic city

    ReplyDelete
  6. In the beginning, I would like to thank you much about this great post. Its very useful and helpful for anyone looking for tips. I like your writing style and I hope you will keep doing this good working.
    Angularjs Training Institute in Bangalore
    Angularjs Classes in Bangalore
    Angularjs Coaching in Bangalore
    Best Institute For ccna Course in Bangalore
    Best ccna Training Institute in Bangalore
    ccna Coaching in Bangalore

    ReplyDelete
  7. Great blog!!! It was very impressed to me. I like so much and keep sharing. Thank you.

    list-your-blog
    Technology

    ReplyDelete
  8. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    rpa training in bangalore
    best rpa training in bangalore
    RPA training in bangalore
    rpa course in bangalore
    rpa training in chennai
    rpa online training

    ReplyDelete
  9. Well done! Pleasant post! This truly helps me to discover the solutions for my inquiry. Trusting, that you will keep posting articles having heaps of valuable data. You're the best! 
    python interview questions and answers
    python tutorials
    python course institute in electronic city

    ReplyDelete
  10. Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    AWS Training in Bangalore
    AWS training in sholinganallur
    AWS training in Tambaram
    AWS training in Velachery

    ReplyDelete
  11. If you have Natural Curls or Curly Hair, you are just blessed. You can experiment with many Hairstyles which will Look Stylish here we tell about top best and easy Curly Hairstyles

    ReplyDelete
  12. I Got Job in my dream company with decent 12 Lacks Per Annum salary, I have learned this world most demanding course out there in the current IT Market from the instant approval blog commenting sites

    ReplyDelete
  13. amazing post written ... It shows your effort and dedication. Thanks for share such a nice post. Please check whatsapp status in hindi and best wifi names

    ReplyDelete
  14. Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man, Keep it up.
    Veteran Mode, MLive Mod APK, Layon Shop, Multitas Pinjaman, Brasil Tv New, Project IGI, Enlight Pixaloop Pro, Gimy TV, Sakura Live Show China, TR Vibes HotStar

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. I think this is the best article today about the future technology. Thanks for taking your own time to discuss this topic, I feel happy about that curiosity has increased to learn more about this topic. Artificial Intelligence Training in Bangalore. Keep sharing your information regularly for my future reference 우리카지노.

    ReplyDelete
  17. Really i found this article more informative, thanks for sharing this article! Also Check here
    ccc question answer online

    ReplyDelete
  18. Thank you for sharing valuable information. Thanks for providing a great informatic blog, really nice required information & the things I never imagined. Thanks you once again Marvel Future Fight Mod Apk

    ReplyDelete
  19. Download Latest Android Mod Apk from Modkiller. This is the Best Modded APK site of 2019, We share Modded Games and other android apps for Free.

    Mod Killer
    Jntuk Fast Updates
    fast vpn mod apk
    tinder gold mod apk
    unblock website vpn mod apk
    vpn lighter mod apk
    avg cleaner pro mod apk
    videoshop pro mod apk

    ReplyDelete
  20. Greetings! Very useful advice in this particular article data! It's the little changes that make the biggest changes. Thanks for sharing!

    ReplyDelete
  21. Begin by doing ample keyword research. The keywords should be referenced throughout your website and in the titles of your articles. By doing this keyword research, you are able understand what people are looking for related to you. You should highlight these keywords so you can become higher in rankings 토토사이트.

    ReplyDelete
  22. Your Website is very good, Your Website impressed us a lot, We have liked your website very much.
    We have also created a website of Android App that you can see it.
    http://damodapk.com/
    http://infotodaypk.com/

    ReplyDelete
  23. very useful blog and it build a lot ...thanks for sharing this
    BEST ANGULAR JS TRAINING IN CHENNAI WITH PLACEMENT

    https://www.acte.in/angular-js-training-in-chennai
    https://www.acte.in/angular-js-training-in-annanagar
    https://www.acte.in/angular-js-training-in-omr
    https://www.acte.in/angular-js-training-in-porur
    https://www.acte.in/angular-js-training-in-tambaram
    https://www.acte.in/angular-js-training-in-velachery

    ReplyDelete
  24. Thanks for posting such a blog it is really very informative. And useful for the freshers Keep posting the
    updates.

    BCA Notes

    ReplyDelete
  25. This blog is very interesting. I learned so much and want to thank you for sharing it in the first place. It is really helpful for my future endeavors. Thanks for your efforts and making it available to public
    Java course in chennai

    python course in chennai

    web designing and development course in chennai

    selenium course in chennai

    digital-marketing seo course in chennai

    ReplyDelete
  26. Excellent post, it will be definitely helpful for many people. Keep posting more like this.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  27. Shop for the latest Redmi mobiles from Helmet Don at the best prices in India. Xiaomi smartphones include Mi Series, Mi Note Series, Redmi Series, Pocophone, Mi Max Series, Mi Mix Series, and the Blackshark.
    HelmetDon
    MI
    redmi-phones


    ReplyDelete
  28. this is the one i am searching in google to read, if you wish to buy oud perfumes in dubai check our website. we are the best perfumes seller and manufacturer in UAE.

    ReplyDelete
  29. There Are Many Complaints About XM REVIEW Broker In The Internet But You Should Read This Review Before Investing Your Money With Them. We Have Personally Tested XM Fx And Found It To Be A Scam, Avoid Them At All Costs!

    ReplyDelete
  30. یتبلیغات گسترده تلگرام یکی از بهترین روش های برندینگ است.

    ReplyDelete
  31. Nice work here. Are you planning to send money from the USA to Nigeria? If so, I think you should check out the dollar to naira today black market rate in 2022/2023.
    Check out the Uscd acceptance rate for 2022-2026.
    Want to share airtime with your loved ones? see how to transfer airtime on Glo
    Want to share airtime with your loved ones? see how to transfer airtime on MTN
    See OAU Cut Off Mark
    See all you need to know about POLAC Form

    ReplyDelete
  32. Impressive post I've been looking for! I'm very happy to finally read this post.
    best jewellery software jewellery accounting software swarnapp software
    Girvi Software

    ReplyDelete
  33. Impressive post I've been looking for! I'm very happy to finally read this post.
    Jewellery ERP Software Dubai
    Jewellery ERP Software Dubai

    ReplyDelete