Generate code with user's formatting in VS extension - visual-studio

I have a Visual Studio extension that generates some code. How do I respect the user's formatting settings (like Tab vs Spaces, this. qualifier, etc) when generating it?
I know you can make a syntax tree in Roslyn but you still need to specify what exactly is in all of the whitespace. Is there a global way to apply this formatting or do we need to try and read all the individual settings?
If so, how would I read the tab vs space and this. prefix settings, respecting .EditorConfig files?
Currently my extension just builds a string assuming default settings, writes it to a file and adds it to the solution.

You need the VisualStudioWorkspace object (which I assume you already have, otherwise take a look at Josh Varity's blog post here)
Generate your text and add it to the project using AddDocument
Call GetOptionsAsync to get the set of options (.editorconfig, user settings, etc) that apply to this document
Call Formatter.FormatAsync passing in the optionset that was given to you by GetOptionsAsync
Update the formatted document by calling WithDocumentText on the solution.

Related

Visual Studio -> wrap every parameter

Using Visual Studio 2019, I found a really useful refactoring option in 'Quick actions and refactoring':
(might come from PowerTools, whatever)
I just wondered how:
I can make this wrapping settings a default formatting settings
Or apply this formatting on my whole solution at once (without resharper)
For the later, a solution with Visual Studio Code would be perfect as well !
Thanks for your help
You can try using Rewrap extension which formats code, comments, and other text to a given line length (80 by default).
The main Rewrap command is: Rewrap Code / Comment, by default bound to
Alt+Q. Put the text cursor inside a comment line, block or plain text
paragraph and invoke the command to wrap. You can also select just a few lines, or multiple comments in one selection.
There is currently an Open request for this in the VS Code Issue tracker on GitHub

Visual studio SDK - Get current line seperator

I'm working on a visual studio extension that requires me inserting lines of text into the current user document. Since line separators are not a universal thing, and every operating system, text editor or end user uses a different style, I would like to make sure I am using the correct style for the current environment when I am inserting text.
I tried looking for some VS SDK global that stores this value but I couldn't find it. All I found was VSConstants.VSStd97CmdID.LineBreak which is supposed to be the command number for inserting a line break. Unfortunately I need this as a string and not a command.
So, does there exist such a global somewhere ? The editor itself defiantly stores this since there is a menu option for it

Automatic Tab / Insert spaces as tab setting switch

It happens sometimes to switch between codebases using different strategy for indentantion, in term of using pure tabs or spaces instead of tab. Since each codebase reasonably want to preserve the coding style, the developer has to remember to switch to the proper setting each time he change the project he's working on. Is there some way to do this automatically, or having the setting saved as a property on the project/solution ?
VS, out-of-the-box, only supports per-user-per-machine settings, including code formatting.
There are third-party add-ins that enable per-project settings. This example add-in provides support for VS2008.
Another option is to perform the formatting externally, one option is "Uncrustify", which is blogged about here.

How to use Setup variables in Descriptions?

I have a setup project in VS 2005.
In the UI section I put some textboxes with some variables, that the user should fill-in when installing the application.
How can I use properties like [VARIABLES] in the fields like the shortcut descriptions?
Your question came up when I was Googling for a list of properties. Seems like the property stuff on MSDN is a bit hidden in the search engines. Of course it helps if you or I found the right name ("property") rather than "variable".
For future reference, the list can be found here:
http://msdn.microsoft.com/en-us/library/aa370905%28v=vs.85%29.aspx
This should also get you into the "how to use properties in your installer" help.
Unfortunately the shortcut description field is not formatted, so it doesn't support installer properties: http://msdn.microsoft.com/en-us/library/aa371847(VS.85).aspx
A solution is to use a custom action (write your own EXE or DLL) which modifies the shortcut description after installation.

How can I sort Fields, Properties and Methods in Visual Studio?

I know that for clarity in codes, I have to write first fields then constructor and then methods etc. But how can I automate it in Visual Studio?
I think CodeMaid is the best free option for code formatting in Visual Studio.
To sort your file, open the file via solution explorer:
Right click the open file
Code Maid menu (likely near the top of the right click menu)
Click Reorganize Active Document
Alternatively, using the default CodeMaid hotkeys CTRL+M,Z to sort your active file.
ReSharper can sort your class members (fields, constructors, methods, delegates) by name, accessibility, type, readonly, etc... You can also surround specific members with regions. What I like the most is the ability to group interface members (e.g., #region IDisposable with void Dispose() method in it) and methods that handle an event.
ReSharper provides both - an easy way to configure and trigger the sorting of class members.
Configuration
Create a XML file within Visual Studio and copy-paste the default type member layout (ReSharper Options > Languages > C# > Type Members Layout) into that file. Download the latest XSD schema. Add the schema file to Visual Studio's schema files (Menu > XML > Schemas... > Add). You should be able now, to edit the XML file with the help of IntelliSense.
Triggering
If you use the Visual Studio keyboard scheme (ReSharper Options > Visual Studio Integration) and press Ctrl+E,F for Silent Code Cleanup. A dialog will pop up, where you can select a Code Cleanup setting. For this setting you should check Reorder type members. The second time you press the shortcut, ReSharper will automatically reorder your class members.
1: ReSharper Type Members XSD Schema
Visual Studio has no feature that allows re-ordering already written code. That's the domain of add-ons. Resharper has a "Reordering type members" feature but that's only supported for C#, not for VB.NET code. NArrange seems to be able to do this. No idea, never used it myself.
Limited sorting of lines is included with Visual Studio 2022.
To use: select the lines you want to sort and in the top menu click:
Edit > Advanced > Sort Lines
Another option I found is XArrange. It is free and can be installed from the Extension Manager.
Issues I took with it...
It puts methods before constructors.
It removes any comments between members,properties,methods, etc.
It's configuration is very limited. No way to change sorting order.
If Code Sorting is your only concern, you can try the Visual Studio Extension CodeSorter
CodeSorter is highly customizable extension that allows its users to
sort C# code itby various conditions such as names, types (method,
class, struct, ...), visibility modifiers (private, public, ...),
constness modifiers (const, static, readonly) and virtuality modifiers
(virtual, override, new, ...).
It is possible to assign multiple search criteria to have the same
priority, for example place protected and private members first, and
then publics and internals.
Names are compared in a way that leading "m_" and "_" is stripped.
This allows fields and properties (eg. _foo and Foo) to be right next
to each other.
One-lined declarations are placed without delimiting blank line, while
multi-lined declarations are separated by a blank line. The exception
is that one-lined field followed by a multi-lined property without
comment of the same name will be placed without the delimiting blank
line.

Resources