Skip to main content

comment_indentation_after

Function comment_indentation_after 

Source
pub fn comment_indentation_after(
    preceding: AnyNodeRef<'_>,
    comment_range: TextRange,
    source: &str,
) -> TextSize
Expand description

Determine the indentation level of an own-line comment, defined as the minimum indentation of all comments between the preceding node and the comment, including the comment itself. In other words, we don’t allow successive comments to ident further than any preceding comments.

For example, given:

if True:
    pass
    # comment

The indentation would be 4, as the comment is indented by 4 spaces.

Given:

if True:
    pass
# comment
else:
    pass

The indentation would be 0, as the comment is not indented at all.

Given:

if True:
    pass
    # comment
        # comment

Both comments would be marked as indented at 4 spaces, as the indentation of the first comment is used for the second comment.

This logic avoids pathological cases like:

try:
    if True:
        if True:
            pass

        # a
            # b
        # c
except Exception:
    pass

If we don’t use the minimum indentation of any preceding comments, we would mark # b as indented to the same depth as pass, which could in turn lead to us treating it as a trailing comment of pass, despite there being a comment between them that “resets” the indentation.