Skip to content

Python: Fix auto_format adding extra indentation on sub-trees#6842

Merged
knutwannheden merged 1 commit intomainfrom
fix/auto-format-subtree-indentation
Feb 27, 2026
Merged

Python: Fix auto_format adding extra indentation on sub-trees#6842
knutwannheden merged 1 commit intomainfrom
fix/auto-format-subtree-indentation

Conversation

@knutwannheden
Copy link
Copy Markdown
Contributor

Summary

  • Fix TabsAndIndentsVisitor.visit() adding an extra indentation level when auto_format is called on a sub-tree with a cursor
  • The setup pre_visit() call incorrectly set indent_type=INDENT on the root element's cursor, causing visit_space() to double the indentation (e.g., 4-space indent became 8-space)
  • Add 3 regression tests covering auto_format on an If node inside a method, a nested class method, and at top level

Context

Discovered while developing Python cleanup recipes that call auto_format(result, p, cursor=self.cursor) after restructuring if/else chains. The SwapIfElseBranches recipe's auto_format call shifted a 4-space-indented if to 8-space indentation inside a method body.

Test plan

  • 1042 framework tests pass (1039 existing + 3 new), 0 regressions
  • 3 new tests in auto_format_subtree_test.py verify the fix at different nesting levels

When auto_format is called on a sub-tree (e.g., an If node inside a
method body) with a cursor, TabsAndIndentsVisitor.visit() called
pre_visit() on the root element during setup. This set
indent_type=INDENT on the cursor, causing visit_space() to add an
extra indent_size to the node's own prefix — doubling the indentation.

The pre_visit setup was intended to establish context for children,
but it incorrectly affected the root element itself. In normal
full-tree traversal, pre_visit is called as the visitor descends,
so the node's own prefix uses the parent's indent_type (not its own).

Remove the setup pre_visit call. The normal traversal pre_visit calls
handle child indentation correctly without it.
@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite Feb 27, 2026
@knutwannheden knutwannheden changed the title Python: Fix auto_format adding extra indentation on sub-trees Python: Fix auto_format adding extra indentation on sub-trees Feb 27, 2026
@knutwannheden knutwannheden merged commit 82d6e55 into main Feb 27, 2026
1 check passed
@knutwannheden knutwannheden deleted the fix/auto-format-subtree-indentation branch February 27, 2026 11:45
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Feb 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

1 participant