analyzeEnforcingContext

Analyzes the indentation enforcement context at a given position in the node text.

Context and Purpose:

This method is primarily used by the Difference class during AST modification to determine if excess whitespace should be removed after deleting elements. When a node is removed from the AST, surrounding whitespace may need to be adjusted to maintain proper formatting.

Algorithm Overview:

The algorithm performs a two-phase scan to identify excess whitespace:
  1. Backward Scan: Looks backward from the given index to find contiguous whitespace characters, stopping at either a newline or a non-whitespace element.
  2. Forward Scan: If the current position contains whitespace, scans forward to count additional contiguous whitespace characters.

Examples:

Example 1 - Whitespace between elements after deletion:
  Before: "public class A { int foo; }"
  After deletion of "int foo;": "public class A { [space][space] }"
  analyzeEnforcingContext(nodeText, firstSpaceIndex) returns:
    - startIndex: index of first space
    - extraCharacters: 2 (both spaces should be considered for removal)

Example 2 - Indentation after newline:
  Structure: "[newline][space][space][space][space]public"
  analyzeEnforcingContext(nodeText, middleSpaceIndex) returns:
    - startIndex: index of first space after newline
    - extraCharacters: 4 (all indentation spaces)

Example 3 - Non-whitespace interrupts sequence:
  Structure: "public[space][space]"
  analyzeEnforcingContext(nodeText, firstSpaceIndex) returns:
    - startIndex: index of first space (reset due to "public")
    - extraCharacters: 2 (spaces after "public")

Important Behavior:

When a non-whitespace element is encountered during the backward scan, the context is reset (start becomes the current index, extraCharacters becomes 0), but the forward scan still executes if the current position is whitespace. This allows the method to identify and count trailing spaces after non-whitespace elements.

Return

context containing the start index and count of excess whitespace characters

Parameters

nodeText

the node text being modified

index

position to analyze (typically points to a position after a deletion)