+def normalize_fmt_off(node: Node) -> None:
+ """Allow `# fmt: off`/`# fmt: on` within bracket pairs.
+
+ Ignores `# fmt: off` and `# fmt: on` outside of brackets.
+
+ Raises :exc:`SyntaxError` if no matching `# fmt: on` is found for a `# fmt: off`
+ given inside brackets.
+ """
+ try_again = True
+ while try_again:
+ try_again = hide_fmt_off(node)
+
+
+def hide_fmt_off(node: Node) -> bool:
+ bt = BracketTracker()
+ for leaf in node.leaves():
+ bt.mark(leaf)
+ if bt.depth == 0:
+ continue
+
+ previous_consumed = 0
+ for comment in list_comments(leaf.prefix, is_endmarker=False):
+ if comment.value in FMT_OFF:
+ ignored_nodes = list(generate_ignored_nodes(leaf))
+ first = ignored_nodes[0] # Can be a container node with the `leaf`.
+ parent = first.parent
+ prefix = first.prefix
+ first.prefix = prefix[comment.consumed :]
+ hidden_value = (
+ comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
+ )
+ first_idx = None
+ for ignored in ignored_nodes:
+ index = ignored.remove()
+ if first_idx is None:
+ first_idx = index
+ assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (1)"
+ assert first_idx is not None, "INTERNAL ERROR: fmt: on/off handling (2)"
+ parent.insert_child(
+ first_idx,
+ Leaf(
+ STANDALONE_COMMENT,
+ hidden_value,
+ prefix=prefix[:previous_consumed] + "\n" * comment.newlines,
+ ),
+ )
+ return True
+
+ previous_consumed += comment.consumed
+
+ return False
+
+
+def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
+ container: Optional[LN] = container_of(leaf)
+ while container is not None:
+ for comment in list_comments(container.prefix, is_endmarker=False):
+ if comment.value in FMT_ON:
+ return
+
+ yield container
+
+ container = container.next_sibling
+
+