Stop Visual Studio text editor from auto moving comment lines

ccommentstext-editorsvisual studio 2015visual studio 2017

Is there a way to stop Visual Studio text editor (2015 or 2017) from auto moving the comment lines when pressing Ctrl+K,D or relevant key stroke (Ctrl+E,D – format entire document) ?

I would like my comments to stay at the position placed, regardless of the code position above or below.

For example, when writing a comment on a new line starting say at col 60 as below:

code line  
|-------- white space ----------| //... comment ..  <-- comment is auto shifted left  
code line

so that it doesn't interfere with the code below or above, when pressing Ctrl+K,D the comment is shifted left, to align with the surrounding code.

On the other hand, when a comment is placed following a code line, as below:

|--code line --|- white space -| //..1st comment line..  
|------white space ------------| //..2nd comment line.. <-- comment is properly auto aligned

an eventual 2nd comment on a new line, remains aligned with the one above, which indicates that the editor can adjust the position of comment lines based on certain criteria.

I should clarify that I would like to preserve the rest of the functionality of Ctrl+K,D.

Edit: I'm afraid that all the guidelines mentioned in Managing Code Formatting provided below by Seth, simply force the application of the instructions already set in text editor for every specific language (and in particular c#)
about intending text.

So, even if some tabs or spaces are inserted in front of the comment, they are automatically wiped out if Ctrl+K,D is applied, simply because there is
no relevant instruction about the handling of spaces in certain constructs, and so the general rule is applied.

I believe that a simple instruction added to text editor, such as "preserve spaces or tabs in front of comments", would solve the problem (as is indeed the case but only when a comment follows code).
It would be just an improvement to an already existing, albeit undocumented, behavior (as far as I have searched).

Best Answer

If you have ReSharper (a great tool to have for lots of reasons) its formatting engine does not have this issue. Go to VS > Tools > Customize > Keyboard... > Show Commands Containing "FormatDocument", and remove all key mappings. Now Show Commands Containing "Reformat", add shortcut Ctrl-KD to the ReSharper command.

Voila, unrelated comments don't get lined up just because they are on consecutive lines. You can also just use the R# command Ctrl-Alt-Enter instead of Ctrl-KD but the latter is what my fingers automatically do after years of practice so overriding this key combination is my preferred solution.

If you want a comment to have extra indentation, you can use "// // Comment..." which might not be exactly what you want but isn't too bad.

Related Question