Skip to content

brycewang-stanford/Auto-Empirical-Research-Skills / skills/35-bahayonghang-academic-writing-skills/skills/typst-paper

typst-paper

Verified

Typst academic paper assistant for existing `.typ` paper projects in English or Chinese. Use this skill whenever the user wants to compile, audit, or improve a Typst paper, including format checks, bibliography validation for BibTeX or Hayagriva, grammar/sentence/logic review, expression polishing, translation, title optimization, pseudocode review, algorithm block cleanup, de-AI editing, experiment-section review, table structure validation, three-line table generation, abstract structure diagnosis, or journal adaptation. Trigger even when the user only mentions one Typst file, one bibliography issue, one pseudocode block, one section rewrite, "three-line table", "check abstract", or "reformat for another journal". Also trigger when the user mentions ".typ files", "typst compile error", "typst export", "typst bibliography", `algorithm-figure`, `lovelace`, or `algorithmic` even without saying the word "Typst" explicitly.

FileKindSize
SKILL.mdskill md7.5 KB
agents/openai.yamlconfig330 B
evals/evals.jsonconfig7.3 KB
examples/bibliography-and-title.mdmarkdown509 B
examples/compile-and-format.mdmarkdown495 B
examples/expression-and-translation.mdmarkdown554 B
references/ABSTRACT_STRUCTURE.mdmarkdown4.9 KB
references/BEST_PRACTICES.mdmarkdown391 B
references/CITATION_STYLES.mdmarkdown4.2 KB
references/CITATION_VERIFICATION.mdmarkdown4.9 KB
references/COMMON_ERRORS.mdmarkdown5.3 KB
references/DEAI_GUIDE.mdmarkdown14.9 KB
references/JOURNAL_ABBREVIATIONS.mdmarkdown3.5 KB
references/JOURNAL_ADAPTATION_WORKFLOW.mdmarkdown3.6 KB
references/NUMBER_UNIT_GUIDE.mdmarkdown2.3 KB
references/REVIEWER_PERSPECTIVE.mdmarkdown4.9 KB
references/STYLE_GUIDE.mdmarkdown7.9 KB
references/TABLE_GUIDE.mdmarkdown2.6 KB
references/TEMPLATES.mdmarkdown2.5 KB
references/TERMINOLOGY.mdmarkdown9.9 KB
references/TRANSLATION_GUIDE.mdmarkdown11.4 KB
references/TYPST_SYNTAX.mdmarkdown9.8 KB
references/VENUES.mdmarkdown13.0 KB
references/WRITING_PHILOSOPHY.mdmarkdown6.7 KB
references/modules/ABSTRACT.mdmarkdown1.2 KB
references/modules/ADAPT.mdmarkdown1.3 KB
references/modules/BIBLIOGRAPHY.mdmarkdown1.3 KB
references/modules/CAPTION.mdmarkdown2.1 KB
references/modules/COMPILE.mdmarkdown1.2 KB
references/modules/DEAI.mdmarkdown2.8 KB
references/modules/EXPERIMENT.mdmarkdown3.8 KB
references/modules/EXPRESSION.mdmarkdown1.6 KB
references/modules/FORMAT.mdmarkdown1.1 KB
references/modules/GRAMMAR.mdmarkdown1.1 KB
references/modules/LOGIC.mdmarkdown5.4 KB
references/modules/PSEUDOCODE.mdmarkdown1.4 KB
references/modules/SENTENCES.mdmarkdown726 B
references/modules/TABLES.mdmarkdown1.3 KB
references/modules/TITLE.mdmarkdown7.3 KB
references/modules/TRANSLATION.mdmarkdown1.5 KB
references/modules/WORKFLOW.mdmarkdown706 B
scripts/analyze_abstract.pyscript17.3 KB
scripts/analyze_experiment.pyscript11.1 KB
scripts/analyze_grammar.pyscript3.6 KB
scripts/analyze_logic.pyscript18.8 KB
scripts/analyze_sentences.pyscript3.6 KB
scripts/check_format.pyscript11.3 KB
scripts/check_pseudocode.pyscript8.6 KB
scripts/check_references.pyscript14.1 KB
scripts/check_tables.pyscript9.8 KB
scripts/compile.pyscript8.1 KB
scripts/deai_batch.pyscript10.2 KB
scripts/deai_check.pyscript19.2 KB
scripts/generate_table.pyscript6.7 KB
scripts/improve_expression.pyscript3.2 KB
scripts/online_bib_verify.pyscript11.9 KB
scripts/optimize_title.pyscript16.9 KB
scripts/parsers.pyscript8.0 KB
scripts/translate_academic.pyscript4.2 KB
scripts/verify_bib.pyscript15.1 KB

scripts/compile.py

View on GitHub
#!/usr/bin/env python3
"""
Typst Compilation Script - Fast compilation for Typst documents

Usage:
    uv run python compile.py main.typ                    # Compile once
    uv run python compile.py main.typ --watch            # Watch mode (auto-recompile)
    uv run python compile.py main.typ --format png       # Export as PNG
    uv run python compile.py main.typ --output out.pdf   # Custom output name
    uv run python compile.py main.typ --font-path ./fonts # Custom font directory

Features:
    - Fast compilation (milliseconds)
    - Watch mode for live preview
    - Multiple output formats (PDF, PNG, SVG)
    - Custom font support
    - Automatic error reporting
"""

import argparse
import shutil
import subprocess
import sys
import time
from pathlib import Path
from typing import Optional


class TypstCompiler:
    """Unified Typst compilation with multiple output formats."""

    SUPPORTED_FORMATS = ["pdf", "png", "svg"]

    def __init__(self, typ_file: str):
        self.typ_file = Path(typ_file).resolve()
        self.work_dir = self.typ_file.parent

    def _check_typst(self) -> tuple[bool, str]:
        """Check if Typst is installed."""
        if not shutil.which("typst"):
            return False, (
                "Typst not found. Install it using:\n"
                "  - Cargo: cargo install typst-cli\n"
                "  - Homebrew (macOS): brew install typst\n"
                "  - Package manager (Linux): check your distro's package manager\n"
                "  - Download: https://github.com/typst/typst/releases"
            )
        return True, "Typst is available"

    def compile(
        self,
        output: Optional[str] = None,
        format: str = "pdf",
        font_path: Optional[str] = None,
        watch: bool = False,
    ) -> int:
        """
        Compile the Typst document.

        Args:
            output: Output file path (optional)
            format: Output format (pdf, png, svg)
            font_path: Custom font directory
            watch: Enable watch mode for live preview

        Returns:
            Exit code (0 for success)
        """
        # Check if Typst is installed
        ok, msg = self._check_typst()
        if not ok:
            print(f"[ERROR] {msg}")
            return 1

        # Validate format
        if format not in self.SUPPORTED_FORMATS:
            print(f"[ERROR] Unsupported format: {format}")
            print(f"[INFO] Supported formats: {', '.join(self.SUPPORTED_FORMATS)}")
            return 1

        # Build command
        if watch:
            cmd = ["typst", "watch"]
            print(f"[INFO] Watch mode enabled for {self.typ_file.name}")
            print("[INFO] File will be recompiled automatically on changes")
            print("[INFO] Press Ctrl+C to stop")
        else:
            cmd = ["typst", "compile"]
            print(f"[INFO] Compiling {self.typ_file.name}")

        # Add input file
        cmd.append(str(self.typ_file))

        # Add output file if specified
        if output:
            cmd.append(output)
        elif not watch:
            # Default output name
            default_output = self.typ_file.with_suffix(f".{format}")
            cmd.append(str(default_output))

        # Add format option (only for compile, not watch)
        if not watch and format != "pdf":
            cmd.insert(2, "--format")
            cmd.insert(3, format)

        # Add font path if specified
        if font_path:
            cmd.extend(["--font-path", font_path])

        print(f"[INFO] Working directory: {self.work_dir}")
        print(f"[INFO] Command: {' '.join(cmd)}")

        # Run compilation
        try:
            start_time = time.time()
            result = subprocess.run(
                cmd,
                cwd=self.work_dir,
                capture_output=False,
            )
            elapsed = time.time() - start_time

            if result.returncode == 0:
                if not watch:
                    output_file = output or self.typ_file.with_suffix(f".{format}")
                    print(f"\n[SUCCESS] Output generated: {output_file}")
                    print(f"[INFO] Compilation time: {elapsed:.3f}s")
            else:
                print(f"\n[ERROR] Compilation failed with exit code {result.returncode}")

            return result.returncode

        except KeyboardInterrupt:
            print("\n[INFO] Compilation stopped by user")
            return 0
        except Exception as e:
            print(f"[ERROR] {e}")
            return 1

    def list_fonts(self) -> int:
        """List available fonts in the system."""
        ok, msg = self._check_typst()
        if not ok:
            print(f"[ERROR] {msg}")
            return 1

        print("[INFO] Listing available fonts...")
        try:
            result = subprocess.run(
                ["typst", "fonts"],
                cwd=self.work_dir,
                capture_output=False,
            )
            return result.returncode
        except Exception as e:
            print(f"[ERROR] {e}")
            return 1

    def query(self, selector: str) -> int:
        """Query document metadata."""
        ok, msg = self._check_typst()
        if not ok:
            print(f"[ERROR] {msg}")
            return 1

        print(f"[INFO] Querying: {selector}")
        try:
            result = subprocess.run(
                ["typst", "query", str(self.typ_file), selector],
                cwd=self.work_dir,
                capture_output=False,
            )
            return result.returncode
        except Exception as e:
            print(f"[ERROR] {e}")
            return 1


def main():
    parser = argparse.ArgumentParser(
        description="Typst Compilation Script - Fast compilation for Typst documents",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  uv run python compile.py main.typ                        # Compile to PDF
  uv run python compile.py main.typ --watch                # Watch mode
  uv run python compile.py main.typ --format png           # Export as PNG
  uv run python compile.py main.typ --output paper.pdf     # Custom output name
  uv run python compile.py main.typ --font-path ./fonts    # Custom fonts
  uv run python compile.py main.typ --list-fonts           # List available fonts

Output Formats:
  pdf    Portable Document Format (default)
  png    Portable Network Graphics (raster image)
  svg    Scalable Vector Graphics (vector image)

Installation:
  - Cargo: cargo install typst-cli
  - Homebrew (macOS): brew install typst
  - Package manager (Linux): check your distro
  - Download: https://github.com/typst/typst/releases
        """,
    )
    parser.add_argument("typ_file", help="Main .typ file to compile")
    parser.add_argument(
        "--output",
        "-o",
        help="Output file path (default: same name as input with appropriate extension)",
    )
    parser.add_argument(
        "--format",
        "-f",
        choices=["pdf", "png", "svg"],
        default="pdf",
        help="Output format (default: pdf)",
    )
    parser.add_argument("--font-path", help="Custom font directory")
    parser.add_argument(
        "--watch",
        "-w",
        action="store_true",
        help="Enable watch mode (auto-recompile on file changes)",
    )
    parser.add_argument(
        "--list-fonts", action="store_true", help="List available fonts in the system"
    )
    parser.add_argument("--query", "-q", help='Query document metadata (e.g., "<heading>")')

    args = parser.parse_args()

    # Validate input file
    typ_path = Path(args.typ_file)
    if not typ_path.exists():
        print(f"[ERROR] File not found: {args.typ_file}")
        sys.exit(1)

    if typ_path.suffix != ".typ":
        print(f"[WARNING] File does not have .typ extension: {args.typ_file}")

    # Create compiler instance
    compiler = TypstCompiler(args.typ_file)

    # Execute requested action
    if args.list_fonts:
        sys.exit(compiler.list_fonts())
    elif args.query:
        sys.exit(compiler.query(args.query))
    else:
        sys.exit(
            compiler.compile(
                output=args.output, format=args.format, font_path=args.font_path, watch=args.watch
            )
        )


if __name__ == "__main__":
    main()
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall