# Configuration and Modes

Black's configuration system controls all formatting behavior through the Mode class and associated enums for target versions, language features, and preview options.

## Capabilities

### Mode Configuration

The central configuration class that controls all aspects of Black's formatting behavior.

```python { .api }
@dataclass
class Mode:
    """
    Configuration for Black formatting behavior.
    """
    target_versions: set[TargetVersion] = field(default_factory=set)
    line_length: int = 88
    string_normalization: bool = True
    is_pyi: bool = False
    is_ipynb: bool = False
    skip_source_first_line: bool = False
    magic_trailing_comma: bool = True
    python_cell_magics: set[str] = field(default_factory=set)
    preview: bool = False
    unstable: bool = False
    enabled_features: set[Preview] = field(default_factory=set)
    
    def __contains__(self, feature: Preview) -> bool:
        """Check if a preview feature is enabled."""
        
    def get_cache_key(self) -> str:
        """Generate cache key for this configuration."""
```

#### Mode Parameters

- **target_versions**: Set of Python versions to support (default: auto-detect)
- **line_length**: Maximum line length in characters (default: 88)
- **string_normalization**: Normalize string quotes to double quotes (default: True)
- **is_pyi**: Format as .pyi stub file with relaxed rules (default: False)
- **is_ipynb**: Format as Jupyter notebook with special handling (default: False)
- **skip_source_first_line**: Skip shebang lines when formatting (default: False)
- **magic_trailing_comma**: Use trailing commas to force line splits (default: True)
- **python_cell_magics**: Set of IPython cell magics to recognize (default: empty)
- **preview**: Enable all preview features (default: False)
- **unstable**: Enable unstable features (default: False)
- **enabled_features**: Specific preview features to enable (default: empty)

### Target Version System

Enumeration of supported Python versions with automatic feature compatibility checking.

```python { .api }
class TargetVersion(Enum):
    """Python version enumeration for compatibility targeting."""
    PY33 = 3, 3
    PY34 = 3, 4
    PY35 = 3, 5
    PY36 = 3, 6
    PY37 = 3, 7
    PY38 = 3, 8
    PY39 = 3, 9
    PY310 = 3, 10
    PY311 = 3, 11
    PY312 = 3, 12
    PY313 = 3, 13
    
    def pretty(self) -> str:
        """Return human-readable version string (e.g., 'Python 3.9')."""
```

### Language Features

Enumeration of Python language features used for version compatibility analysis.

```python { .api }
class Feature(Enum):
    """Python language features for compatibility checking."""
    F_STRINGS = 1
    NUMERIC_UNDERSCORES = 2
    TRAILING_COMMA_IN_CALL = 3
    TRAILING_COMMA_IN_DEF = 4
    ASYNC_IDENTIFIERS = 5
    ASYNC_KEYWORDS = 6
    ASSIGNMENT_EXPRESSIONS = 7
    POS_ONLY_ARGUMENTS = 8
    RELAXED_DECORATORS = 9
    PATTERN_MATCHING = 10
    UNPACKING_ON_FLOW = 11
    ANN_ASSIGN_EXTENDED_RHS = 12
    EXCEPT_STAR = 13
    VARIADIC_GENERICS = 14
    DEBUG_F_STRINGS = 15
    PARENTHESIZED_CONTEXT_MANAGERS = 16
    TYPE_PARAMS = 17
    FSTRING_PARSING = 18
    TYPE_PARAM_DEFAULTS = 19
    FORCE_OPTIONAL_PARENTHESES = 20
    FUTURE_ANNOTATIONS = 21
```

### Preview Features

Individual preview features that can be enabled independently for experimental formatting behaviors.

```python { .api }
class Preview(Enum):
    """Individual preview features for experimental formatting."""
    string_processing = 1
    hug_parens_with_braces_and_square_brackets = 2
    wrap_long_dict_values_in_parens = 3
    multiline_string_handling = 4
    always_one_newline_after_import = 5
```

### Write-Back Modes

Configuration for output behavior when formatting files.

```python { .api }
class WriteBack(Enum):
    """Output modes for file formatting."""
    NO = 0      # No output, just return status
    YES = 1     # Write formatted content to file
    DIFF = 2    # Output unified diff
    CHECK = 3   # Check only, exit with error if changes needed
    COLOR_DIFF = 4  # Output colored diff
    
    @classmethod
    def from_configuration(cls, *, check: bool, diff: bool, color: bool = False) -> WriteBack:
        """Create WriteBack mode from boolean flags."""
```

### Feature Support Functions

Utility functions for checking feature compatibility across Python versions.

```python { .api }
def supports_feature(target_versions: set[TargetVersion], feature: Feature) -> bool:
    """
    Check if a feature is supported by all target versions.
    
    Parameters:
    - target_versions: Set of Python versions to check
    - feature: Language feature to validate
    
    Returns:
    True if feature is supported by all target versions
    """
```

### Configuration Loading

Functions for loading Black configuration from pyproject.toml files.

```python { .api }
def read_pyproject_toml(ctx: click.Context, param: click.Parameter, value: Optional[str]) -> Optional[str]:
    """
    Parse Black configuration from pyproject.toml.
    
    Parameters:
    - ctx: Click context
    - param: Click parameter
    - value: Optional path to configuration file
    
    Returns:
    Path to configuration file if found
    """

def validate_regex(ctx: click.Context, param: click.Parameter, value: Optional[str]) -> Optional[Pattern[str]]:
    """
    Validate regex patterns for CLI options.
    
    Parameters:
    - ctx: Click context  
    - param: Click parameter
    - value: Regex pattern string
    
    Returns:
    Compiled regex pattern or None
    
    Raises:
    - click.BadParameter: If regex is invalid
    """
```

## Constants

### Version Feature Mapping

```python { .api }
# Maps Python versions to supported language features
VERSION_TO_FEATURES: dict[TargetVersion, set[Feature]]

# Maps __future__ imports to Feature enums  
FUTURE_FLAG_TO_FEATURE: dict[str, Feature]

# Set of unstable preview features
UNSTABLE_FEATURES: set[Preview]
```

## Usage Examples

### Basic Mode Configuration

```python
import black

# Default configuration
mode = black.Mode()

# Custom line length
mode = black.Mode(line_length=79)

# Target specific Python versions
mode = black.Mode(
    target_versions={black.TargetVersion.PY39, black.TargetVersion.PY310}
)

# Disable string normalization
mode = black.Mode(string_normalization=False)

# Format as stub file (.pyi)
mode = black.Mode(is_pyi=True)
```

### Preview Features

```python
# Enable all preview features
mode = black.Mode(preview=True)

# Enable specific preview features
mode = black.Mode(
    preview=True,
    enabled_features={
        black.Preview.string_processing,
        black.Preview.wrap_long_dict_values_in_parens
    }
)

# Check if feature is enabled
if black.Preview.string_processing in mode:
    print("String processing enabled")

# Enable unstable features
mode = black.Mode(unstable=True)
```

### Jupyter Notebook Configuration

```python
# Configure for Jupyter notebooks
mode = black.Mode(
    is_ipynb=True,
    python_cell_magics={'%%time', '%%timeit', '%%capture'}
)

# Format with custom cell magics
code = """
%%time
def slow_function():
    time.sleep(1)
    return "done"
"""

formatted = black.format_cell(code, fast=False, mode=mode)
```

### Version Compatibility

```python
# Check feature support
versions = {black.TargetVersion.PY38, black.TargetVersion.PY39}
supports_walrus = black.supports_feature(versions, black.Feature.ASSIGNMENT_EXPRESSIONS)
print(f"Assignment expressions supported: {supports_walrus}")

# Auto-detect compatible versions
import ast
code = "x := 1"  # Assignment expression (Python 3.8+)
tree = ast.parse(code)
node = black.lib2to3_parse(code)
compatible = black.detect_target_versions(node)
print(f"Compatible versions: {compatible}")
```

### File Processing Modes

```python
from pathlib import Path

# Different write-back modes
modes = [
    black.WriteBack.NO,        # Just check, don't modify
    black.WriteBack.YES,       # Write changes to file  
    black.WriteBack.DIFF,      # Show diff
    black.WriteBack.CHECK,     # Exit with error if changes needed
    black.WriteBack.COLOR_DIFF # Show colored diff
]

for write_mode in modes:
    changed = black.format_file_in_place(
        Path("example.py"),
        fast=False,
        mode=black.Mode(),
        write_back=write_mode
    )
```

## Types

```python { .api }
# Legacy alias for backwards compatibility
FileMode = Mode

# Set types for configuration
TargetVersionSet = set[TargetVersion]
FeatureSet = set[Feature]
PreviewSet = set[Preview]
```