Copy with proper indentation
You want to share some code you’ve written with a colleague, so you select it in the editor and hit Ctrl+C to copy it. As you paste it in Outlook/Slack/Teams, you realize that the indentation levels are inconsistent due to your original selection. You must now either go back to Visual Studio and do a box selection and copy that, or manually fix the indentation issue in Outlook. You know this, yet you make this mistake almost every time. Sounds familiar?
It usually happens because you start your selection without the leading indentation. But every subsequent line has it. The result looks something like this when you paste it into Outlook:
If this has happened to you, you’re not alone. In fact, multiple developers have reported this and requested a feature to fix it, so remember to vote for it if you agree.
Let’s do an experiment to see if we can fix this problem once and for all.
We’ve created an extension called Copy Nice for this experiment. It removes unwanted indentation when you copy text from the editor. The question is, how does it determine if indentation is unwanted or not?
Consider this selection:
Notice how the first line of the selection doesn’t have its leading indentation selected. Also, all other lines in the selection contain only whitespace in the same span. This pattern is very common when copying code to share it with others in email or IM or elsewhere. In this case, Visual Studio recognizes the pattern and strips the leading indentation from the selection to end up with a well-formatted code snippet.
For Visual Studio to correctly identify when to strip indentation, these conditions must all be true:
- Selection mode is not Box Selection
- Selection is not multi-caret selection
- Selection spans multiple lines
- Selection must start on an empty indentation
This makes sure that what you copy is always what you expect. But in case you want to disable this feature, you can of course do that from the Edit -> Advanced -> Strip Leading Whitespace on Copy command.
If this feature is interesting to you, please install the Copy Nice extension and take it for a ride. Make sure to share any ideas and bugs on the GitHub issue tracker, and feel free to send pull requests too. The feature request ticket is a suitable place to share your comments and thoughts, so make sure to vote and comment there as well.
Do you like the idea of community experiments like this one? Let us know in the comments below.