Skip to content

Option to apply on an indented fragment of Python code (e.g. a single method) #1352

@tartley

Description

@tartley

My problem is that sometimes I'm editing some code in a project that doesn't use Black (heresy, I know). Sometimes I'll type some code, or paste into the source something like a generated dict literal, and I want to run Black on just the edited section of code.

I set up a Vim binding to do that, passing just the code from the visual selection to Black, and using the output to update the code in Vim. The result is:

  1. If I select lines of module-level code, this works really well! Hooray!
  2. If I select a few lines in the middle of a function, or select a whole class method, this fails, because Black (understandably) does not like that the initial line of code is indented.
  3. Trivially, it also fails if the selected code is not an entire valid expression or statement. That's fine and I don't propose trying to "fix" that.

What I'd like to see:

  • Black invoked normally should continue to produce an error if the initial line has indents.
  • Black should gain something like a "--fragment" (or perhaps "--indented") command line flag, for working on potentially indented code fragments. When given, this causes Black to:
    • un-indent the given source sufficiently to make the first line have no indents
    • reformat as normal
    • re-indent the reformatted source by the same amount.

The alternative I'm currently considering is writing my own wrapper script to do the un-indenting and re-indenting. Not a biggie, but I thought other people might appreciate this mode of operation being supported out of the box.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C: integrationsEditor plugins and other integrationsT: enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions