ReSharper formatting: align equal operands - c#

Note to Googlers, this question is somewhat out of date as the requested feature is now supported in the current version of ReSharper 2017.3.1
I like to formatting my code to align right side of equal operands.
Like here:
bool canRead = false;
bool canReadClass = true;
string className = boType.Name;
I've switch to ReSharper recently and found it very useful but cannot find option allowing me format code in described way.
Do you know if there is such option / plugin?
Maybe you know other than ReSharp solution allowing that?
EDIT:
How to decide what part of code shall be aligned?
My convention is aligning all variables in same block.
By "block" I meant part of code not divided by empty lines.
eg
// First block
int count = 10;
string name = "abc";
bool calculate = true;
.....
.....
// Second block
MyOwnType myType = new MyOwntype();
int count = 10;
EDIT -2
I've opened R# ticket for this. If anyone interested please vote!

There is (currently) no way to do this out of the box in ReSharper. Fortunately, ReSharper has a very rich extensibility API (albeit poorly documented). I've spent a lot of time with Reflector trying to figure things out.
We use a similar alignment guideline for class members in a company I work for (to the extreme, we also align method parameters). I wrote a plugin for ReSharper to help me do just that. It's a "Code Cleanup" module, which runs sometime during the code cleanup (Ctrl-E, Ctrl-F) and aligns the code for you. It also makes the class sealed, if possible.
Some examples:
Method parameters:
public void DoSomething(string name,
int age,
IEnumerable coll)
(you will need to change Wrap formal parameters to Chop always in Options->Formatting Style->Line Breaks and Wrapping for this to work properly)
Constants:
private const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
private const int CONNECT_COMMANDLINE = 0x00000800;
private const int CONNECT_INTERACTIVE = 0x00000008;
private const string RESOURCE_NAME = "Unknown";
You can download the source code from my SkyDrive.
Edit I seem to have lost access to that SkyDrive, and lost the files too. This was before github :(
Please note that you'll need several things to compile/debug it:
Update the Command Line Arguments
in Debug tab in Project
Properties with the correct path of
the output DLL:
/ReSharper.Plugin
"X:\<projects>\MyCompany.CodeFormatter\MyCompany.CodeFormatter\bin\Debug\MyCompany.CodeFormatter.dll"
This allows debugging the plugin via
F5, and it will be
automatically installed in
ReSharper's Plugins in the new
Visual Studio instance which will
open.
The plugin is for ReSharper 4.5 and it references the DLLs of this version. If you installed ReSharper anywhere else except C:\Program Files\JetBrains\ReSharper, you will have to fix the references.
This does not align variables inside methods, but it shouldn't be hard to add :)
After you install this, just run Code Cleanup to fix your alignment (I never got a reply from JetBrains about how to do this during brace/semicolon formatting, unfortunately).
Assembly was renamed to protect the innocent :)
Good luck!

I think it is worth noting that the Visual Studio Productivity Power Tools have an Align Assignments feature.
Here's a link to the Visual Studio 2013 Productivity Power Tools.

You can try this: Code Alignment
It supports
Align by... (Dialog)
Align by position... (Dialog)
Align by Equals
Align by m_
Align by "
Align by .
Align by Space

Productivity Power Tools 2012 also has a command for this: ctrl-alt-]
Other goodies are obviously there as well.

As far as I know, this is unfortunately not possible using Resharper.

Years late, but further to the comment from #MickyD, Resharper can do this for you, see Resharper blog. Go to Resharper/ Options/ Code Editing/ C#/ Tabs, Indents, Alignment. Scroll to the bottom of the options in the right hand window pane to find "Align Similar Code in Columns", click things, enjoy.

Related

C#->Python SVN Pre-Commit Hook: How to access svn:keywords?

I've been asked to re-add an extra check to our pre-commit hook to ensure svn:keywords are set on certain paths in our repos (e.g. scripts that need the Revision and URL values injecting). We had a clunky pre-commit hook written in C# using SharpSvn doing this originally, but we've migrated our SVN server to Linux, so I rewrote the hook in Python. It has most of the functionality, but I missed out the keyword checking.
In C#, the code used is like so:
SvnPropertyCollection propCollection;
svnLookClient.GetPropertyList(svnHookArgs.LookOrigin, item.Path, out propCollection);
....
if (item.Path.Contains("some path") && !propCollection.Contains("svn:keywords"))
{ /*Fail the commit here*/ }
I've found out the hard way that the transaction properties do not contain svn:keywords, even when I make a commit where all I have done is set them; calling svn.fs.svn_fs_txn_proplist on the transaction gives me the following properties:
svn:log
svn:txn-client-compat-version
svn:txn-user-agent
svn:author
svn:date
My Python code looks like this:
def check_keywords_are_set(transaction, repos_name):
commit_has_source_files = False
source_extensions = ('.sql', '.hlr') #Only care about source files
transaction_root = svn.fs.svn_fs_txn_root(transaction)
changed_paths = svn.fs.paths_changed(transaction_root)
for path, change in changed_paths.iteritems():
if repos_name == 'repo1' or (repos_name == 'repo2' and ('some path' in path): #These are the paths I want to enforce keywords being set on
if path.endswith(source_extensions):
commit_has_source_files = True
if not commit_has_source_files:
return True
#debugging code here:
transaction_props = svn.fs.svn_fs_txn_proplist(transaction)
sys.stdout.write('Transaction prop list:\n{0}\n'.format(transaction_props))
#end debugging
keywords = svn.fs.svn_fs_txn_prop(transaction, 'svn:keywords')
#keywords is always None
Looking back at the C# code, I can see references to svnlook, so I guess I'll have to use this. However, I'm getting confused between 'revision properties' and all other 'properties'. I'm also not sure how to write this so that if a developer is adding the missing keywords to files within a folder that should have them, or we're creating a new folder where this will later be enforced, it won't throw a false negative. The documentation for doing this in Python is quite poor and generally requires reading the C API source, which unfortunately I cannot get my head around (I am not a C developer), let alone translate into Python. Any assistance would be greatly appreciated.

How to disable all whitespace autoformatting in Visual Studio 2015?

I really like the new Visual Studio 2015, but the auto formatting is a bit too much extensive for my liking. Especially I like to have control over whitespace:
public class TipStats
{
public int Points { get; set; }
public int Position { get; set; }
public decimal Percentage { get; set; }
}
I only see three autoformat settings in my settings, and I have ticked them all off - still Visual Studio is autoformatting my whitespace.
Are there any other hidden settings that I need to know for disabling all whitespace autoformatting?
Update
As #Saragis notes Ignore spaces in declaration statements works sometimes for this specific example, but still there all kind of autoformat forces working against what I want.
Most options seem to only define how you want your autoformatting. I'm looking for the setting that defines if you want autoformatting.
PS: I'm having only problems with autoformatting I still use CTRL+K, F to manual format parts of my code now and then.
Update - Added feature request on UserVoice
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/9795837-add-an-ignore-space-for-all-format-options
I realised I misunderstood the question in my original answer, so have added a partial answer disabling autoformatting for white space.
If you select ignore white space on all options where it is offered, it will not reformat the white space of those areas of code.
These screen shots are taken from VS2015 Enterprise.
I'm starting from the beginning to help anyone who lands here.
Go to Tools -> Options.
Scroll down to Text Editor. It's worth clicking through the all the general tabs. And the All languages tabs. There are some shared formatting settings that can be set, like line wraps.
Then go to the languages you wish to customise (I'm showing C#) and click on formatting. There you will find options, I have expanded the spacing one, as per the title of your question.
Then you can explore each of these tabs to customise your format for each language.
edit- since question has actually changed
To reduce the incidents of autoformatting, uncheck options like these:
The only way you can manage the autoformatting is to play with these settings.
You can also use regex with find and replace to remove space from files, but do so carefully.
Beyond these tips to customise your autoformatting, to reduce VS process of autoformatting and to manually autoformat, that's all I can think of.
There is also this:
Under Edit -> Advanced -> Delete Horizontal White Space
The answer from Yvette Colomb is fine, but it does neither work on declarations inside functions, nor on enums (where in my opinion it is needed most).
Thus I had the idea to just add a comment between the variable and the operator, which simply breaks the obvious rule "set exactly one space character between variable (or enum name) and operator (=)", because there is no operator following the variable any longer! Not very nice, but also not too bad and IMHO it has definitely more advantages than disadvantages. :-)
Disable virtual space
Virtual space is a headache, please disable it int Tool>Options>Text Editor>C#>General. Life is better.
For the last version of Visual Studio :
Go Preferences :
Go Source code > C# :
Set Policy to custom :
Go C# format and tap on edit :
Set like me the New Lines :
And voila.

How to customize formatting of code that is generated by "Encapsulate Field"?

Previously I am fairly certain that the "Encapsulate Field" command would turn something like the following:
public int SomeNumber;
into the following (what I want from VS 2015):
private int someNumber;
public int SomeNumber {
get { return someNumber; }
set { someNumber = value; }
}
but in Visual Studio 2015 I am seeing the following:
private int someNumber;
public int SomeNumber {
get {
return someNumber;
}
set {
someNumber = value;
}
}
Is there a way to fix this?
This was a design change in VS2015. In previous versions, the refactoring command paid attention to the Tools > Options > Text Editor > C# > Wrapping > "Leave block on single line" option. With it turned on, you'll get the property getter and setter body the way it encoded in the snippet, braces on the same line. The way you like it.
Different in VS2015, it now pays attention to the Tools > Options > Text Editor > C# > Formatting > New Lines > "Place open brace on new line for methods" setting. You get to choose between "egyptian" braces or having the opening brace separate. Neither of which you like.
Accidents happen when Microsoft creates new VS versions, this was not an accident. Whether this was done by "popular demand" is hard to reverse-engineer, I consider it pretty likely since this refactoring is usually done to write a non-trivial getter or setter, the kind that won't fit a single line. Providing us with a choice between all three possible formatting preferences looks like a problem to me, the existing formatting options are not a good match.
Only real option is to let Microsoft know that you are not happy with the change. There is an existing UserVoice article that proposes a change. You can vote for it or write your own. Post a link to it in your question so other SO users can vote.
Will that help you:
-Encapsulate Field Refactoring (C#):
https://msdn.microsoft.com/en-us/library/a5adyhe9.aspx
This website seems to offer a solution a the end of the topic.
Check also this post :
-Different Refactoring style for field encapsulation: how to make Visual Studio change it?
Different Refactoring style for field encapsulation: how to make Visual Studio change it?
This one is corresponding to your question in a certain manner: the question is really related to yours :)
I myself have tried changing the snippet file to suite my file but VS doesn't take effect. What I end up doing is
Encapsulate the fields as usual.
Copy and paste the code into notepad++ and do a Find and Replace.
Find:
(\{)*(\s*)*(get|set)\r\n\s+{\r\n\s+(.*)\r\n\s+\}\s+
Replace with:
$1$3\{$4\}
Paste the result back into VS. VS will format it follow the "Leave block on single line".

it is possible have different editor styles in visual studio 2010?

Well in short i am a big fan of writing nice looking code, there is a great article here
the beauty of doom 3 source code I have been using different code editors before visual studio.
And i liked a compact writing style.
I dont like almost empty white lines like
public void my function(string s)
{ //almost empty line
string n = domystuff();
if (n=="blanc")
{ //almost empty
mycode("should start a row earlier on { line");
} //..
else
{
ohno.notagain("another two blanc lines above and below else");
Altough.it.compiles("equaly");
myscreen.used = not.optimal;
}
}
If code is better written, then its nice to read, if something is nice to read with much white lines then the white lines spoil it. So i wonder can this auto-formatting be changed in VS2010 ?
C# as a language has a set of coding conventions which C# programmers expect to be fairly consistent from project to project. If you want to use the One True Brace style, switch to Java.
If you insist on being the odd man out, you can configure the Visual Studio auto-formatter in Tools → Options... → Text Editor → C# → Formatting.

What's VS2010 shortcut for surrounding the line in a if block

Let's assume I have a following line
myObject.SomeStatement();
My cursor is at the end of the line.
What's the keboard shortcut to put an if statement around it and obtain:
if ()
{
myObject.SomeStatement();
}
What's the keboard shortcut to put a for loop around it and obtain:
for (int i = 0; i<length; ++i)
{
myObject.SomeStatement();
}
I use Edit.SurroundWith (CTRL+K, CTRL+S) and then select if from the popup list
You can surround with a for in a similar manner.
There are actually many surround templates available - I also use the try and tryf templates quite often (perhaps a sign that I'm doing it wrong ☺).
In addition, please check also this reference page Visual Studio 2010 Keybinding Posters, with details on shortcuts for all VS2010 languages.
As far as i know the behaviour you want isn't quite there, but something close, i think. Take your statement:
myObject.SomeStatement();
and select the line, e.g. by double clicking, and press CTRL+K, CTRL+S, then select the "snippet" you want to apply.

Categories