0

I'm trying to replicate a feature from PyCharm in Visual Studio Code and running into trouble.

In PyCharm, when I copy a block of Python code and paste it inside a function, class, or loop, the IDE automatically adjusts the indentation to match the surrounding context. This behavior—often referred to as context-aware indentation—makes it easy to maintain clean code structure without manually fixing tabs or spaces.

In VSCode, however, when I paste the same block of code into a similar context, the indentation remains exactly as it was copied. This often results in broken indentation that I have to fix manually.


Example:

Copied code:

for item in collection:
    process(item)

Pasted inside a function:

def my_function():
    do_something()
    # cursor is here

Result in VSCode:

def my_function():
    do_something()
    for item in collection:
    process(item)

Expected (like in PyCharm):

def my_function():
    do_something()
    for item in collection:
        process(item)

What I’ve tried:

  • Installing the Black Formatter extension
  • Enabling "editor.formatOnPaste": true
  • Enabling "editor.formatOnSave": true
  • Enabling "editor.autoIndentOnPaste": true
  • Using "[python]": { "editor.defaultFormatter": "ms-python.black-formatter" }
  • Running Format Document and Format Selection
  • Installing the Python Indent extension

None of these worked. The pasted code still doesn’t align with the surrounding block structure.

2
  • “This often results in broken indentation that I have to fix manually.” What’s wrong with fixing the indentation manually? Commented Sep 27 at 21:20
  • It's just an extra step—manual indentation is inconvenient and annoying when you're doing it repeatedly throughout the day. Commented Sep 27 at 21:22

1 Answer 1

0

Simply turn on "editor.autoIndentOnPaste" setting, and it should automatically indent when you paste your Python (or any other programming language) code.

{
    "editor.autoIndentOnPaste": true
}

enter image description here

It's a native VS Code setting.

Sign up to request clarification or add additional context in comments.

2 Comments

I have turned it on now, but unfortunately it still does not work. Same behavior as before when pasting
Maybe the Python, or other formatter extension, may be intercepting the paste and not allowing VS Code to format. Try doing it on other file type or even disabling other extensions, to see if it works. If yes, you could look for some formatter setting for those extensions and disable it. Or even open an issue in the extension's repo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.