# -*- coding: utf-8 -*-
# :-
# SPDX-FileCopyrightText: © 2026 Franz Glasner
# SPDX-License-Identifier: MIT
# :-
r"Sub-package for filters."""

__all__ = [
    "TokenReplaceFilter",
    "ErrorToGenericErrorTokenFilter",
]


from pygments.filter import Filter
from pygments.token import (Error, Generic, Token,
                            is_token_subtype, string_to_tokentype)


class TokenReplaceFilter(Filter):

    """Replace a given fixed token type with another token."""

    def __init__(self, **options):
        """Specifiy the replacement options:

        :param token_from:
        :type token_from: str or pygments.token.Token

        :param token_to:
        :type token_to: str or pygments.token.Token

        Both these arguments are *required*!

        """
        Filter.__init__(self, **options)
        # The option "token_from" is required!
        self.token_from = options["token_from"]
        if not is_token_subtype(self.token_from, Token):
            self.token_from = string_to_tokentype(self.token_from)
        # The option "token_to" is required!
        self.token_to = options["token_to"]
        if not is_token_subtype(self.token_to, Token):
            self.token_to = string_to_tokentype(self.token_to)

    def filter(self, lexer, stream):
        for ttype, value in stream:
            if ttype is self.token_from:
                yield self.token_to, value
            else:
                yield ttype, value


class ErrorToGenericErrorTokenFilter(TokenReplaceFilter):

    """Convert all :py:class:`pygments.token.Token.Error` tokens to
    :py:class:`pygments.token.Token.Generic.Error` tokens.

    """

    def __init__(self, **options):
        options["token_from"] = Error
        options["token_to"] = Generic.Error
        TokenReplaceFilter.__init__(self, **options)
