Copy with proper indentation

Mads Kristensen

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?

Image selection

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:

Code with improper indentation pasted 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.

The experiment

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:

A common code selection pattern when copying code snippets

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.

A well-formatted code snippet pasted into Outlook

For Visual Studio to correctly identify when to strip indentation, these conditions must all be true:

  1. Selection mode is not Box Selection
  2. Selection is not multi-caret selection
  3. Selection spans multiple lines
  4. 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.

Toggle the feature on/off in Edit -> Advanced -> Copy Without Indentation

Next steps

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.