Skip to content

LanguageFormatter

Sub classes

Name Children Inherits
ElixirFormatter
anyenv.language_formatters._elixir
Elixir formatter using mix format.
    KtlintFormatter
    anyenv.language_formatters._jvm
    Kotlin formatter using ktlint.
      PythonRuffFormatter
      anyenv.language_formatters._python
      Python formatter using ruff directly.
        PythonUvFormatter
        anyenv.language_formatters._python
        Python formatter using uv to run ruff.
          AirFormatter
          anyenv.language_formatters._r
          R formatter using air.
            RubocopFormatter
            anyenv.language_formatters._ruby
            Ruby formatter using rubocop.
              StandardRBFormatter
              anyenv.language_formatters._ruby
              Ruby formatter using standardrb.
                GoFormatter
                anyenv.language_formatters._systems
                Go formatter using gofmt.
                  RustFormatter
                  anyenv.language_formatters._systems
                  Rust formatter using rustfmt and clippy.
                    ZigFormatter
                    anyenv.language_formatters._systems
                    Zig formatter using zig fmt.
                      ClangFormatFormatter
                      anyenv.language_formatters._systems
                      C/C++ formatter using clang-format.
                        TOMLFormatter
                        anyenv.language_formatters._toml
                        TOML formatter using tombi.
                          BiomeFormatter
                          anyenv.language_formatters._web
                          TypeScript/JavaScript/JSON formatter using biome.
                            PrettierFormatter
                            anyenv.language_formatters._web
                            Multi-language formatter using prettier.
                              HtmlBeautifierFormatter
                              anyenv.language_formatters._web
                              ERB formatter using htmlbeautifier.

                                Base classes

                                Name Children Inherits
                                ABC
                                abc
                                Helper class that provides a standard way to create an ABC using

                                â‹” Inheritance diagram

                                graph TD
                                  3820931366["_base.LanguageFormatter"]
                                  925645236["abc.ABC"]
                                  2751680898["builtins.object"]
                                  925645236 --> 3820931366
                                  2751680898 --> 925645236

                                🛈 DocStrings

                                Bases: ABC

                                Abstract base class for language-specific formatters.

                                Source code in src/anyenv/language_formatters/_base.py
                                class LanguageFormatter(ABC):
                                    """Abstract base class for language-specific formatters."""
                                
                                    def __init__(
                                        self,
                                        execution_env: ExecutionEnvironment | ExecutionEnvironmentStr = "local",
                                    ) -> None:
                                        """Initialize formatter with execution environment.
                                
                                        Args:
                                            execution_env: Execution environment - either a string provider name
                                                or a direct ExecutionEnvironment instance
                                        """
                                        from exxec import ExecutionEnvironment, get_environment
                                
                                        self._execution_env: ExecutionEnvironment = (
                                            execution_env
                                            if isinstance(execution_env, ExecutionEnvironment)
                                            else get_environment(execution_env)
                                        )
                                
                                    async def _execute_command(self, cmd: list[str]) -> tuple[bool, str, str, float, str | None]:
                                        """Execute command and return rich result information."""
                                        async with self._execution_env as env:
                                            result = await env.execute_command(shlex.join(cmd))
                                            return (
                                                result.success,
                                                result.stdout or str(result.result) if result.result else "",
                                                result.stderr or result.error or "",
                                                result.duration,
                                                result.error_type,
                                            )
                                
                                    @property
                                    @abstractmethod
                                    def name(self) -> str:
                                        """Language name (e.g., 'Python', 'TOML')."""
                                
                                    @property
                                    @abstractmethod
                                    def command(self) -> str:
                                        """Primary CLI command required (e.g., 'ruff', 'biome', 'gofmt')."""
                                
                                    @property
                                    @abstractmethod
                                    def extensions(self) -> list[str]:
                                        """File extensions this formatter handles (e.g., ['.py', '.pyi'])."""
                                
                                    @property
                                    @abstractmethod
                                    def pygments_lexers(self) -> list[str]:
                                        """Pygments lexer names for this language (e.g., ['python', 'python3'])."""
                                
                                    @abstractmethod
                                    async def format(self, path: Path) -> FormatResult:
                                        """Format a file."""
                                
                                    @abstractmethod
                                    async def lint(self, path: Path, fix: bool = False) -> LintResult:
                                        """Lint a file, optionally fixing issues."""
                                
                                    def is_available(self) -> bool:
                                        """Check if the formatter command is available on the system."""
                                        return shutil.which(self.command) is not None
                                
                                    async def format_and_lint(self, path: Path, fix: bool = False) -> FormatAndLintResult:
                                        """Format and then lint a file."""
                                        format_result = await self.format(path)
                                        lint_result = await self.lint(path, fix=fix)
                                        return FormatAndLintResult(format_result, lint_result)
                                
                                    def can_handle(self, path: Path) -> bool:
                                        """Check if this formatter can handle the given file."""
                                        return path.suffix.lower() in self.extensions
                                
                                    def can_handle_language(self, language: str) -> bool:
                                        """Check if this formatter can handle the given language name."""
                                        return language.lower() in [lexer.lower() for lexer in self.pygments_lexers]
                                
                                    async def format_string(self, content: str, language: str | None = None) -> FormatResult:
                                        """Format a string by creating a temporary file.
                                
                                        Args:
                                            content: String content to format
                                            language: Language name (pygments lexer name) if extension can't be determined
                                
                                        Returns:
                                            FormatResult with formatted content in output field
                                        """
                                        extension = self.extensions[0] if self.extensions else ".txt"
                                
                                        with tempfile.NamedTemporaryFile(mode="w", suffix=extension, delete=False) as temp_file:
                                            temp_file.write(content)
                                            temp_path = Path(temp_file.name)
                                
                                        try:
                                            result = await self.format(temp_path)
                                            if result.success:
                                                formatted_content = temp_path.read_text("utf-8")
                                                result.output = formatted_content
                                            return result
                                        finally:
                                            temp_path.unlink(missing_ok=True)
                                
                                    async def lint_string(
                                        self, content: str, language: str | None = None, fix: bool = False
                                    ) -> LintResult:
                                        """Lint a string by creating a temporary file.
                                
                                        Args:
                                            content: String content to lint
                                            language: Language name (pygments lexer name) if extension can't be determined
                                            fix: Whether to apply fixes
                                
                                        Returns:
                                            LintResult with any fixes applied to output field
                                        """
                                        extension = self.extensions[0] if self.extensions else ".txt"
                                
                                        with tempfile.NamedTemporaryFile(mode="w", suffix=extension, delete=False) as temp_file:
                                            temp_file.write(content)
                                            temp_path = Path(temp_file.name)
                                
                                        try:
                                            result = await self.lint(temp_path, fix=fix)
                                            if result.success and fix:
                                                modified_content = temp_path.read_text("utf-8")
                                                result.output = modified_content
                                            return result
                                        finally:
                                            temp_path.unlink(missing_ok=True)
                                
                                    async def format_and_lint_string(
                                        self, content: str, language: str | None = None, fix: bool = False
                                    ) -> FormatAndLintResult:
                                        """Format and lint a string."""
                                        format_result = await self.format_string(content, language)
                                        content_to_lint = format_result.output if format_result.success else content
                                        lint_result = await self.lint_string(content_to_lint, language, fix)
                                        return FormatAndLintResult(format_result, lint_result)
                                

                                command abstractmethod property

                                command: str
                                

                                Primary CLI command required (e.g., 'ruff', 'biome', 'gofmt').

                                extensions abstractmethod property

                                extensions: list[str]
                                

                                File extensions this formatter handles (e.g., ['.py', '.pyi']).

                                name abstractmethod property

                                name: str
                                

                                Language name (e.g., 'Python', 'TOML').

                                pygments_lexers abstractmethod property

                                pygments_lexers: list[str]
                                

                                Pygments lexer names for this language (e.g., ['python', 'python3']).

                                __init__

                                __init__(execution_env: ExecutionEnvironment | ExecutionEnvironmentStr = 'local') -> None
                                

                                Initialize formatter with execution environment.

                                Parameters:

                                Name Type Description Default
                                execution_env ExecutionEnvironment | ExecutionEnvironmentStr

                                Execution environment - either a string provider name or a direct ExecutionEnvironment instance

                                'local'
                                Source code in src/anyenv/language_formatters/_base.py
                                def __init__(
                                    self,
                                    execution_env: ExecutionEnvironment | ExecutionEnvironmentStr = "local",
                                ) -> None:
                                    """Initialize formatter with execution environment.
                                
                                    Args:
                                        execution_env: Execution environment - either a string provider name
                                            or a direct ExecutionEnvironment instance
                                    """
                                    from exxec import ExecutionEnvironment, get_environment
                                
                                    self._execution_env: ExecutionEnvironment = (
                                        execution_env
                                        if isinstance(execution_env, ExecutionEnvironment)
                                        else get_environment(execution_env)
                                    )
                                

                                can_handle

                                can_handle(path: Path) -> bool
                                

                                Check if this formatter can handle the given file.

                                Source code in src/anyenv/language_formatters/_base.py
                                def can_handle(self, path: Path) -> bool:
                                    """Check if this formatter can handle the given file."""
                                    return path.suffix.lower() in self.extensions
                                

                                can_handle_language

                                can_handle_language(language: str) -> bool
                                

                                Check if this formatter can handle the given language name.

                                Source code in src/anyenv/language_formatters/_base.py
                                def can_handle_language(self, language: str) -> bool:
                                    """Check if this formatter can handle the given language name."""
                                    return language.lower() in [lexer.lower() for lexer in self.pygments_lexers]
                                

                                format abstractmethod async

                                format(path: Path) -> FormatResult
                                

                                Format a file.

                                Source code in src/anyenv/language_formatters/_base.py
                                @abstractmethod
                                async def format(self, path: Path) -> FormatResult:
                                    """Format a file."""
                                

                                format_and_lint async

                                format_and_lint(path: Path, fix: bool = False) -> FormatAndLintResult
                                

                                Format and then lint a file.

                                Source code in src/anyenv/language_formatters/_base.py
                                async def format_and_lint(self, path: Path, fix: bool = False) -> FormatAndLintResult:
                                    """Format and then lint a file."""
                                    format_result = await self.format(path)
                                    lint_result = await self.lint(path, fix=fix)
                                    return FormatAndLintResult(format_result, lint_result)
                                

                                format_and_lint_string async

                                format_and_lint_string(
                                    content: str, language: str | None = None, fix: bool = False
                                ) -> FormatAndLintResult
                                

                                Format and lint a string.

                                Source code in src/anyenv/language_formatters/_base.py
                                async def format_and_lint_string(
                                    self, content: str, language: str | None = None, fix: bool = False
                                ) -> FormatAndLintResult:
                                    """Format and lint a string."""
                                    format_result = await self.format_string(content, language)
                                    content_to_lint = format_result.output if format_result.success else content
                                    lint_result = await self.lint_string(content_to_lint, language, fix)
                                    return FormatAndLintResult(format_result, lint_result)
                                

                                format_string async

                                format_string(content: str, language: str | None = None) -> FormatResult
                                

                                Format a string by creating a temporary file.

                                Parameters:

                                Name Type Description Default
                                content str

                                String content to format

                                required
                                language str | None

                                Language name (pygments lexer name) if extension can't be determined

                                None

                                Returns:

                                Type Description
                                FormatResult

                                FormatResult with formatted content in output field

                                Source code in src/anyenv/language_formatters/_base.py
                                async def format_string(self, content: str, language: str | None = None) -> FormatResult:
                                    """Format a string by creating a temporary file.
                                
                                    Args:
                                        content: String content to format
                                        language: Language name (pygments lexer name) if extension can't be determined
                                
                                    Returns:
                                        FormatResult with formatted content in output field
                                    """
                                    extension = self.extensions[0] if self.extensions else ".txt"
                                
                                    with tempfile.NamedTemporaryFile(mode="w", suffix=extension, delete=False) as temp_file:
                                        temp_file.write(content)
                                        temp_path = Path(temp_file.name)
                                
                                    try:
                                        result = await self.format(temp_path)
                                        if result.success:
                                            formatted_content = temp_path.read_text("utf-8")
                                            result.output = formatted_content
                                        return result
                                    finally:
                                        temp_path.unlink(missing_ok=True)
                                

                                is_available

                                is_available() -> bool
                                

                                Check if the formatter command is available on the system.

                                Source code in src/anyenv/language_formatters/_base.py
                                def is_available(self) -> bool:
                                    """Check if the formatter command is available on the system."""
                                    return shutil.which(self.command) is not None
                                

                                lint abstractmethod async

                                lint(path: Path, fix: bool = False) -> LintResult
                                

                                Lint a file, optionally fixing issues.

                                Source code in src/anyenv/language_formatters/_base.py
                                @abstractmethod
                                async def lint(self, path: Path, fix: bool = False) -> LintResult:
                                    """Lint a file, optionally fixing issues."""
                                

                                lint_string async

                                lint_string(content: str, language: str | None = None, fix: bool = False) -> LintResult
                                

                                Lint a string by creating a temporary file.

                                Parameters:

                                Name Type Description Default
                                content str

                                String content to lint

                                required
                                language str | None

                                Language name (pygments lexer name) if extension can't be determined

                                None
                                fix bool

                                Whether to apply fixes

                                False

                                Returns:

                                Type Description
                                LintResult

                                LintResult with any fixes applied to output field

                                Source code in src/anyenv/language_formatters/_base.py
                                async def lint_string(
                                    self, content: str, language: str | None = None, fix: bool = False
                                ) -> LintResult:
                                    """Lint a string by creating a temporary file.
                                
                                    Args:
                                        content: String content to lint
                                        language: Language name (pygments lexer name) if extension can't be determined
                                        fix: Whether to apply fixes
                                
                                    Returns:
                                        LintResult with any fixes applied to output field
                                    """
                                    extension = self.extensions[0] if self.extensions else ".txt"
                                
                                    with tempfile.NamedTemporaryFile(mode="w", suffix=extension, delete=False) as temp_file:
                                        temp_file.write(content)
                                        temp_path = Path(temp_file.name)
                                
                                    try:
                                        result = await self.lint(temp_path, fix=fix)
                                        if result.success and fix:
                                            modified_content = temp_path.read_text("utf-8")
                                            result.output = modified_content
                                        return result
                                    finally:
                                        temp_path.unlink(missing_ok=True)
                                

                                :fa-brands-github: Show source on GitHub