feat: initial commit
This commit is contained in:
commit
a83e1a806e
454 files changed
+52429
No files matched your search
@@ -0,0 +1 @@
|
||||
result
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
name: c4-model
|
||||
description: Generate C4 architecture documentation at any level using specialized agents (Code, Component, Container, Context). Use this skill whenever the user wants to document system architecture with the C4 model, create architecture diagrams, document code structure, define component boundaries, map deployment containers, or create system context diagrams. Trigger for prompts like "document architecture", "create C4 diagram", "generate architecture docs", "map system components", "create context diagram", "document this codebase architecture", or "analyze code structure with C4". Always use this skill for C4 documentation requests, even partial ones like a single level.
|
||||
---
|
||||
|
||||
# C4 Model Documentation Orchestrator
|
||||
|
||||
Orchestrates four specialized agents to generate C4 model architecture documentation. Each agent targets one hierarchical level, producing documentation files that feed into the next level.
|
||||
|
||||
## C4 Levels Overview
|
||||
|
||||
| Level | Agent subagent_type | Input | Output files |
|
||||
| ------------- | ------------------- | --------------------------------------- | --------------------------------- |
|
||||
| **Code** | `c4-code` | Source directories | `c4-code-<name>.md` per directory |
|
||||
| **Component** | `c4-component` | `c4-code-*.md` files | `c4-component-<name>.md` + index |
|
||||
| **Container** | `c4-container` | Component docs + deployment configs | `c4-container.md` + OpenAPI specs |
|
||||
| **Context** | `c4-context` | Container/component docs + README/tests | `c4-context.md` |
|
||||
|
||||
## Workflow: Bottom-Up (Standard)
|
||||
|
||||
When the user requests full C4 documentation:
|
||||
|
||||
```
|
||||
1. Code level → Analyze all source directories (run in parallel per directory)
|
||||
2. Component → Synthesize code docs into logical components
|
||||
3. Container → Map components to deployment units + document APIs
|
||||
4. Context → Create high-level stakeholder view
|
||||
```
|
||||
|
||||
Run agents in sequence (each level depends on the previous). Within the Code level, multiple directories can be processed in parallel.
|
||||
|
||||
## Selective Documentation
|
||||
|
||||
Ask the user which level(s) they need if not clear from context:
|
||||
|
||||
- Single level: invoke just that agent
|
||||
- Partial chain: e.g., only Code + Component
|
||||
- Full chain: all four in order
|
||||
|
||||
## Agent Reference Files
|
||||
|
||||
When working on a specific level, read the corresponding reference file for full agent instructions, templates, and diagram syntax:
|
||||
|
||||
- **Code level** → `references/c4-code.md`
|
||||
- **Component level** → `references/c4-component.md`
|
||||
- **Container level** → `references/c4-container.md`
|
||||
- **Context level** → `references/c4-context.md`
|
||||
|
||||
## Output Organization
|
||||
|
||||
Suggest placing all documentation in a consistent location:
|
||||
|
||||
```
|
||||
docs/architecture/
|
||||
├── c4-code-handlers.md # Code level (one per directory)
|
||||
├── c4-code-services.md
|
||||
├── c4-component-api.md # Component level
|
||||
├── c4-component-domain.md
|
||||
├── c4-component.md # Component index
|
||||
├── c4-container.md # Container level
|
||||
├── api-spec.yaml # OpenAPI specs (if generated)
|
||||
└── c4-context.md # Context level
|
||||
```
|
||||
|
||||
## Invoking the Agents
|
||||
|
||||
Use the `Agent` tool with the appropriate `subagent_type`. Example for Code level:
|
||||
|
||||
```
|
||||
Agent(
|
||||
subagent_type="c4-code",
|
||||
prompt="Analyze the directory src/handlers and create C4 Code-level documentation. Save to docs/architecture/c4-code-handlers.md"
|
||||
)
|
||||
```
|
||||
|
||||
For the Context level agent, note it lives at `./references/c4-context.md` — use `subagent_type="c4-context"`.
|
||||
|
||||
## Key Principles
|
||||
|
||||
- **Bottom-up**: Code → Component → Container → Context (each level builds on the previous)
|
||||
- **Parallel Code runs**: Multiple directories can be documented simultaneously
|
||||
- **Sequential synthesis**: Component, Container, and Context must run after their inputs exist
|
||||
- **Self-contained**: Each output file should be understandable independently
|
||||
- **Mermaid diagrams**: Each level has specific diagram types (see reference files)
|
||||
@@ -0,0 +1,153 @@
|
||||
# C4 Code Level — Agent Reference
|
||||
|
||||
Agent: `c4-code` | Model: haiku | Output: `c4-code-<name>.md`
|
||||
|
||||
## Purpose
|
||||
|
||||
Documents individual source code directories at the most granular C4 level. Captures every function, class, module, and dependency. Creates documentation that feeds into the Component level.
|
||||
|
||||
## Capabilities
|
||||
|
||||
- Directory structure analysis and file relationships
|
||||
- Function/method signature extraction (parameters, return types, type hints)
|
||||
- Class hierarchy and module export documentation
|
||||
- Internal and external dependency mapping
|
||||
- Design pattern and architectural pattern recognition
|
||||
- Language-agnostic (Python, TypeScript, Java, Go, Rust, C#, Ruby, etc.)
|
||||
- Mermaid diagram generation (classDiagram for OOP, flowchart for FP/procedural)
|
||||
|
||||
## Programming Paradigm → Diagram Type
|
||||
|
||||
| Code Style | Diagram | When |
|
||||
| -------------------------------- | -------------------------------- | -------------------------------------------------- |
|
||||
| OOP (classes, interfaces) | `classDiagram` | Inheritance, composition, interface implementation |
|
||||
| FP (pure functions, pipelines) | `flowchart` | Data transformations, function composition |
|
||||
| FP (modules with exports) | `classDiagram` with `<<module>>` | Module structure and dependencies |
|
||||
| Procedural (structs + functions) | `classDiagram` | Data structures and associated functions |
|
||||
| Mixed | Combination | Use multiple diagrams if needed |
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Analyze directory structure (file relationships, module boundaries)
|
||||
2. Extract all functions/classes/modules with complete signatures
|
||||
3. Map all dependencies (internal and external)
|
||||
4. Generate structured documentation following the template below
|
||||
5. Add Mermaid diagrams for complex relationships
|
||||
|
||||
## Documentation Template
|
||||
|
||||
```markdown
|
||||
# C4 Code Level: [Directory Name]
|
||||
|
||||
## Overview
|
||||
|
||||
- **Name**: [Descriptive name for this code directory]
|
||||
- **Description**: [Short description of what this code does]
|
||||
- **Location**: [Link to actual directory path]
|
||||
- **Language**: [Primary programming language(s)]
|
||||
- **Purpose**: [What this code accomplishes]
|
||||
|
||||
## Code Elements
|
||||
|
||||
### Functions/Methods
|
||||
|
||||
- `functionName(param1: Type, param2: Type): ReturnType`
|
||||
- Description: [What this function does]
|
||||
- Location: [file path:line number]
|
||||
- Dependencies: [what this function depends on]
|
||||
|
||||
### Classes/Modules
|
||||
|
||||
- `ClassName`
|
||||
- Description: [What this class does]
|
||||
- Location: [file path]
|
||||
- Methods: [list of methods]
|
||||
- Dependencies: [what this class depends on]
|
||||
|
||||
## Dependencies
|
||||
|
||||
### Internal Dependencies
|
||||
|
||||
- [List of internal code dependencies]
|
||||
|
||||
### External Dependencies
|
||||
|
||||
- [List of external libraries, frameworks, services]
|
||||
|
||||
## Relationships
|
||||
|
||||
[Optional Mermaid diagram — see paradigm table above]
|
||||
```
|
||||
|
||||
## OOP Diagram Example
|
||||
|
||||
```mermaid
|
||||
---
|
||||
title: Code Diagram for [Component Name]
|
||||
---
|
||||
classDiagram
|
||||
namespace ComponentName {
|
||||
class Class1 {
|
||||
+attribute1 Type
|
||||
+method1() ReturnType
|
||||
}
|
||||
class Interface1 {
|
||||
<<interface>>
|
||||
+requiredMethod() ReturnType
|
||||
}
|
||||
}
|
||||
Class1 ..|> Interface1 : implements
|
||||
```
|
||||
|
||||
## FP Module Structure Example
|
||||
|
||||
```mermaid
|
||||
---
|
||||
title: Module Structure for [Component Name]
|
||||
---
|
||||
classDiagram
|
||||
namespace DataProcessing {
|
||||
class validators {
|
||||
<<module>>
|
||||
+validateInput(data) Result~Data, Error~
|
||||
+sanitize(input) string
|
||||
}
|
||||
class transformers {
|
||||
<<module>>
|
||||
+parseJSON(raw) Record
|
||||
+normalize(data) NormalizedData
|
||||
}
|
||||
}
|
||||
transformers --> validators : uses
|
||||
```
|
||||
|
||||
## FP Data Flow Example
|
||||
|
||||
```mermaid
|
||||
---
|
||||
title: Data Pipeline for [Component Name]
|
||||
---
|
||||
flowchart LR
|
||||
subgraph Input
|
||||
A[readFile]
|
||||
end
|
||||
subgraph Transform
|
||||
B[parseJSON]
|
||||
C[validateInput]
|
||||
D[normalize]
|
||||
end
|
||||
subgraph Output
|
||||
E[writeFile]
|
||||
end
|
||||
A -->|raw string| B
|
||||
B -->|parsed data| C
|
||||
C -->|valid data| D
|
||||
D -->|normalized| E
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Analyze starting from the deepest directories upward
|
||||
- Document every significant code element, not just public APIs
|
||||
- Create one `c4-code-<directory-name>.md` file per analyzed directory
|
||||
- This output feeds directly into the Component level agent
|
||||
@@ -0,0 +1,121 @@
|
||||
# C4 Component Level — Agent Reference
|
||||
|
||||
Agent: `c4-component` | Model: sonnet | Input: `c4-code-*.md` | Output: `c4-component-<name>.md` + index
|
||||
|
||||
## Purpose
|
||||
|
||||
Synthesizes C4 Code-level documentation into logical, well-bounded components. Defines component interfaces, maps relationships, and creates Component-level diagrams. Bridges code detail with deployment concerns (handled at Container level).
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
Components represent logical groupings of code that work together to provide cohesive functionality. Boundaries should align with domain, technical, or organizational boundaries. Each component must have clear responsibilities and well-defined interfaces.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Review all `c4-code-*.md` files to understand code structure
|
||||
2. Identify logical component boundaries (domain, technical, or organizational)
|
||||
3. Define component names, descriptions, and responsibilities
|
||||
4. List software features provided by each component
|
||||
5. Link `c4-code-*.md` files to their containing components
|
||||
6. Document component interfaces (APIs, protocols, data contracts)
|
||||
7. Map dependencies and relationships between components
|
||||
8. Generate Mermaid C4Component diagrams
|
||||
9. Create master `c4-component.md` index with all components
|
||||
|
||||
## Documentation Template
|
||||
|
||||
```markdown
|
||||
# C4 Component Level: [Component Name]
|
||||
|
||||
## Overview
|
||||
|
||||
- **Name**: [Component name]
|
||||
- **Description**: [Short description of component purpose]
|
||||
- **Type**: [Application, Service, Library, etc.]
|
||||
- **Technology**: [Primary technologies used]
|
||||
|
||||
## Purpose
|
||||
|
||||
[Detailed description of what this component does and what problems it solves]
|
||||
|
||||
## Software Features
|
||||
|
||||
- [Feature 1]: [Description]
|
||||
- [Feature 2]: [Description]
|
||||
|
||||
## Code Elements
|
||||
|
||||
This component contains the following code-level elements:
|
||||
|
||||
- [c4-code-file-1.md](./c4-code-file-1.md) - [Description]
|
||||
- [c4-code-file-2.md](./c4-code-file-2.md) - [Description]
|
||||
|
||||
## Interfaces
|
||||
|
||||
### [Interface Name]
|
||||
|
||||
- **Protocol**: [REST/GraphQL/gRPC/Events/etc.]
|
||||
- **Description**: [What this interface provides]
|
||||
- **Operations**:
|
||||
- `operationName(params): ReturnType` - [Description]
|
||||
|
||||
## Dependencies
|
||||
|
||||
### Components Used
|
||||
|
||||
- [Component Name]: [How it's used]
|
||||
|
||||
### External Systems
|
||||
|
||||
- [External System]: [How it's used]
|
||||
|
||||
## Component Diagram
|
||||
|
||||
[See diagram syntax below]
|
||||
```
|
||||
|
||||
## Component Diagram Syntax
|
||||
|
||||
Use `C4Component` Mermaid syntax. Shows components **within a single container**:
|
||||
|
||||
```mermaid
|
||||
C4Component
|
||||
title Component Diagram for [Container Name]
|
||||
|
||||
Container_Boundary(container, "Container Name") {
|
||||
Component(component1, "Component 1", "Type", "Description")
|
||||
Component(component2, "Component 2", "Type", "Description")
|
||||
ComponentDb(component3, "Component 3", "Database", "Description")
|
||||
}
|
||||
Container_Ext(externalContainer, "External Container", "Description")
|
||||
System_Ext(externalSystem, "External System", "Description")
|
||||
|
||||
Rel(component1, component2, "Uses")
|
||||
Rel(component2, component3, "Reads from and writes to")
|
||||
Rel(component1, externalContainer, "Uses", "API")
|
||||
```
|
||||
|
||||
## Master Index Template
|
||||
|
||||
```markdown
|
||||
# C4 Component Level: System Overview
|
||||
|
||||
## System Components
|
||||
|
||||
### [Component 1]
|
||||
|
||||
- **Name**: [Component name]
|
||||
- **Description**: [Short description]
|
||||
- **Documentation**: [c4-component-name-1.md](./c4-component-name-1.md)
|
||||
|
||||
## Component Relationships
|
||||
|
||||
[Mermaid diagram showing all components and their relationships]
|
||||
```
|
||||
|
||||
## Key Principles
|
||||
|
||||
- Focus on **logical grouping**, not deployment concerns (deferred to Container level)
|
||||
- Component boundaries should reflect domain or technical cohesion
|
||||
- Every component needs clear responsibilities and at least one defined interface
|
||||
- This output feeds directly into the Container level agent
|
||||
@@ -0,0 +1,275 @@
|
||||
# C4 Container Level — Agent Reference
|
||||
|
||||
Agent: `c4-container` | Model: sonnet | Input: Component docs + deployment configs | Output: `c4-container.md` + OpenAPI specs
|
||||
|
||||
## Purpose
|
||||
|
||||
Maps logical components to deployment containers (processes, applications, services, databases). Documents container interfaces as OpenAPI/Swagger specs. Shows high-level technology choices and deployment architecture.
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
Containers are deployable units that must be running for the system to work. Container diagrams show **high-level technology choices** and how responsibilities are distributed. Technology details belong here, not at Component or Context level.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Review all `c4-component-*.md` files to understand component structure
|
||||
2. Review deployment definitions (Dockerfiles, K8s manifests, Terraform, cloud configs)
|
||||
3. Map components to containers based on deployment reality
|
||||
4. Identify container names, descriptions, and deployment characteristics
|
||||
5. Create OpenAPI/Swagger specs for all container interfaces
|
||||
6. Map inter-container communication (HTTP, gRPC, queues, events)
|
||||
7. Generate Mermaid C4Container diagrams
|
||||
8. Link container docs to API specs and deployment configs
|
||||
|
||||
## Documentation Template
|
||||
|
||||
```markdown
|
||||
# C4 Container Level: System Deployment
|
||||
|
||||
## Containers
|
||||
|
||||
### [Container Name]
|
||||
|
||||
- **Name**: [Container name]
|
||||
- **Description**: [Short description of container purpose and deployment]
|
||||
- **Type**: [Web Application, API, Database, Message Queue, etc.]
|
||||
- **Technology**: [Node.js, Python, PostgreSQL, Redis, etc.]
|
||||
- **Deployment**: [Docker, Kubernetes, Cloud Service, etc.]
|
||||
|
||||
## Purpose
|
||||
|
||||
[Detailed description of what this container does and how it's deployed]
|
||||
|
||||
## Components
|
||||
|
||||
This container deploys the following components:
|
||||
|
||||
- [Component Name]: [Description]
|
||||
- Documentation: [c4-component-name.md](./c4-component-name.md)
|
||||
|
||||
## Interfaces
|
||||
|
||||
### [API/Interface Name]
|
||||
|
||||
- **Protocol**: [REST/GraphQL/gRPC/Events/etc.]
|
||||
- **Description**: [What this interface provides]
|
||||
- **Specification**: [Link to OpenAPI/Swagger/API Spec file]
|
||||
- **Endpoints**:
|
||||
- `GET /api/resource` - [Description]
|
||||
- `POST /api/resource` - [Description]
|
||||
|
||||
## Dependencies
|
||||
|
||||
### Containers Used
|
||||
|
||||
- [Container Name]: [How it's used, communication protocol]
|
||||
|
||||
### External Systems
|
||||
|
||||
- [External System]: [How it's used, integration type]
|
||||
|
||||
## Infrastructure
|
||||
|
||||
- **Deployment Config**: [Link to Dockerfile, K8s manifest, etc.]
|
||||
- **Scaling**: [Horizontal/vertical scaling strategy]
|
||||
- **Resources**: [CPU, memory, storage requirements]
|
||||
|
||||
## Container Diagram
|
||||
|
||||
[See diagram syntax below]
|
||||
```
|
||||
|
||||
## Container Diagram Syntax
|
||||
|
||||
```mermaid
|
||||
C4Container
|
||||
title Container Diagram for [System Name]
|
||||
|
||||
Person(user, "User", "Uses the system")
|
||||
System_Boundary(system, "System Name") {
|
||||
Container(webApp, "Web Application", "Spring Boot, Java", "Provides web interface")
|
||||
Container(api, "API Application", "Node.js, Express", "Provides REST API")
|
||||
ContainerDb(database, "Database", "PostgreSQL", "Stores data")
|
||||
Container_Queue(messageQueue, "Message Queue", "RabbitMQ", "Handles async messaging")
|
||||
}
|
||||
System_Ext(external, "External System", "Third-party service")
|
||||
|
||||
Rel(user, webApp, "Uses", "HTTPS")
|
||||
Rel(webApp, api, "Makes API calls to", "JSON/HTTPS")
|
||||
Rel(api, database, "Reads from and writes to", "SQL")
|
||||
Rel(api, messageQueue, "Publishes messages to")
|
||||
Rel(api, external, "Uses", "API")
|
||||
```
|
||||
|
||||
## OpenAPI Spec Template
|
||||
|
||||
For each container API, create a specification file (e.g., `api-spec.yaml`):
|
||||
|
||||
```yaml
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: [Container Name] API
|
||||
description: [API description]
|
||||
version: 1.0.0
|
||||
servers:
|
||||
- url: https://api.example.com
|
||||
description: Production server
|
||||
paths:
|
||||
/api/resource:
|
||||
get:
|
||||
summary: [Operation summary]
|
||||
description: [Operation description]
|
||||
responses:
|
||||
'200':
|
||||
description: [Response description]
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
```
|
||||
|
||||
## Key Principles
|
||||
|
||||
- This is where **technology details belong** in the C4 model
|
||||
- Map based on deployment reality, not just logical grouping
|
||||
- Every container interface should have an OpenAPI/Swagger spec
|
||||
- Show communication protocols between containers
|
||||
- Link to deployment configs (Dockerfiles, K8s manifests, etc.)
|
||||
- This output feeds into the Context level agen# C4 Container Level — Agent Reference
|
||||
|
||||
Agent: `c4-container` | Model: sonnet | Input: Component docs + deployment configs | Output: `c4-container.md` + OpenAPI specs
|
||||
|
||||
## Purpose
|
||||
|
||||
Maps logical components to deployment containers (processes, applications, services, databases). Documents container interfaces as OpenAPI/Swagger specs. Shows high-level technology choices and deployment architecture.
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
Containers are deployable units that must be running for the system to work. Container diagrams show **high-level technology choices** and how responsibilities are distributed. Technology details belong here, not at Component or Context level.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Review all `c4-component-*.md` files to understand component structure
|
||||
2. Review deployment definitions (Dockerfiles, K8s manifests, Terraform, cloud configs)
|
||||
3. Map components to containers based on deployment reality
|
||||
4. Identify container names, descriptions, and deployment characteristics
|
||||
5. Create OpenAPI/Swagger specs for all container interfaces
|
||||
6. Map inter-container communication (HTTP, gRPC, queues, events)
|
||||
7. Generate Mermaid C4Container diagrams
|
||||
8. Link container docs to API specs and deployment configs
|
||||
|
||||
## Documentation Template
|
||||
|
||||
```markdown
|
||||
# C4 Container Level: System Deployment
|
||||
|
||||
## Containers
|
||||
|
||||
### [Container Name]
|
||||
|
||||
- **Name**: [Container name]
|
||||
- **Description**: [Short description of container purpose and deployment]
|
||||
- **Type**: [Web Application, API, Database, Message Queue, etc.]
|
||||
- **Technology**: [Node.js, Python, PostgreSQL, Redis, etc.]
|
||||
- **Deployment**: [Docker, Kubernetes, Cloud Service, etc.]
|
||||
|
||||
## Purpose
|
||||
|
||||
[Detailed description of what this container does and how it's deployed]
|
||||
|
||||
## Components
|
||||
|
||||
This container deploys the following components:
|
||||
|
||||
- [Component Name]: [Description]
|
||||
- Documentation: [c4-component-name.md](./c4-component-name.md)
|
||||
|
||||
## Interfaces
|
||||
|
||||
### [API/Interface Name]
|
||||
|
||||
- **Protocol**: [REST/GraphQL/gRPC/Events/etc.]
|
||||
- **Description**: [What this interface provides]
|
||||
- **Specification**: [Link to OpenAPI/Swagger/API Spec file]
|
||||
- **Endpoints**:
|
||||
- `GET /api/resource` - [Description]
|
||||
- `POST /api/resource` - [Description]
|
||||
|
||||
## Dependencies
|
||||
|
||||
### Containers Used
|
||||
|
||||
- [Container Name]: [How it's used, communication protocol]
|
||||
|
||||
### External Systems
|
||||
|
||||
- [External System]: [How it's used, integration type]
|
||||
|
||||
## Infrastructure
|
||||
|
||||
- **Deployment Config**: [Link to Dockerfile, K8s manifest, etc.]
|
||||
- **Scaling**: [Horizontal/vertical scaling strategy]
|
||||
- **Resources**: [CPU, memory, storage requirements]
|
||||
|
||||
## Container Diagram
|
||||
|
||||
[See diagram syntax below]
|
||||
```
|
||||
|
||||
## Container Diagram Syntax
|
||||
|
||||
```mermaid
|
||||
C4Container
|
||||
title Container Diagram for [System Name]
|
||||
|
||||
Person(user, "User", "Uses the system")
|
||||
System_Boundary(system, "System Name") {
|
||||
Container(webApp, "Web Application", "Spring Boot, Java", "Provides web interface")
|
||||
Container(api, "API Application", "Node.js, Express", "Provides REST API")
|
||||
ContainerDb(database, "Database", "PostgreSQL", "Stores data")
|
||||
Container_Queue(messageQueue, "Message Queue", "RabbitMQ", "Handles async messaging")
|
||||
}
|
||||
System_Ext(external, "External System", "Third-party service")
|
||||
|
||||
Rel(user, webApp, "Uses", "HTTPS")
|
||||
Rel(webApp, api, "Makes API calls to", "JSON/HTTPS")
|
||||
Rel(api, database, "Reads from and writes to", "SQL")
|
||||
Rel(api, messageQueue, "Publishes messages to")
|
||||
Rel(api, external, "Uses", "API")
|
||||
```
|
||||
|
||||
## OpenAPI Spec Template
|
||||
|
||||
For each container API, create a specification file (e.g., `api-spec.yaml`):
|
||||
|
||||
```yaml
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: [Container Name] API
|
||||
description: [API description]
|
||||
version: 1.0.0
|
||||
servers:
|
||||
- url: https://api.example.com
|
||||
description: Production server
|
||||
paths:
|
||||
/api/resource:
|
||||
get:
|
||||
summary: [Operation summary]
|
||||
description: [Operation description]
|
||||
responses:
|
||||
'200':
|
||||
description: [Response description]
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
```
|
||||
|
||||
## Key Principles
|
||||
|
||||
- This is where **technology details belong** in the C4 model
|
||||
- Map based on deployment reality, not just logical grouping
|
||||
- Every container interface should have an OpenAPI/Swagger spec
|
||||
- Show communication protocols between containers
|
||||
- Link to deployment configs (Dockerfiles, K8s manifests, etc.)
|
||||
- This output feeds into the Context level agent
|
||||
@@ -0,0 +1,117 @@
|
||||
# C4 Context Level — Agent Reference
|
||||
|
||||
Agent: `c4-context` | Model: sonnet | Input: Container/component docs + README + tests | Output: `c4-context.md`
|
||||
|
||||
## Purpose
|
||||
|
||||
Creates the highest-level C4 view: the system as a box surrounded by users and external systems. Focuses on **people and software systems**, not technologies. Produces stakeholder-friendly documentation understandable by non-technical audiences.
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
Context diagrams show the system boundary, all users (human and programmatic), and all external systems the system interacts with. Technology, protocols, and low-level details are deliberately excluded at this level.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Review `c4-container.md` to understand system deployment
|
||||
2. Review `c4-component.md` to understand system components
|
||||
3. Review system documentation (README, architecture docs, requirements)
|
||||
4. Review test files to understand system behavior and features
|
||||
5. Identify system purpose and boundaries
|
||||
6. Identify all personas (human users AND programmatic users / external systems)
|
||||
7. Identify all high-level features provided by the system
|
||||
8. Map user journeys for each key feature per persona
|
||||
9. Identify all external systems and dependencies
|
||||
10. Generate Mermaid C4Context diagram
|
||||
11. Create comprehensive context documentation
|
||||
|
||||
## Documentation Template
|
||||
|
||||
```markdown
|
||||
# C4 Context Level: System Context
|
||||
|
||||
## System Overview
|
||||
|
||||
### Short Description
|
||||
|
||||
[One-sentence description of what the system does]
|
||||
|
||||
### Long Description
|
||||
|
||||
[Detailed description of the system's purpose, capabilities, and the problems it solves]
|
||||
|
||||
## Personas
|
||||
|
||||
### [Persona Name]
|
||||
|
||||
- **Type**: [Human User / Programmatic User / External System]
|
||||
- **Description**: [Who this persona is and what they need]
|
||||
- **Goals**: [What this persona wants to achieve]
|
||||
- **Key Features Used**: [List of features this persona uses]
|
||||
|
||||
## System Features
|
||||
|
||||
### [Feature Name]
|
||||
|
||||
- **Description**: [What this feature does]
|
||||
- **Users**: [Which personas use this feature]
|
||||
- **User Journey**: [Link to user journey map]
|
||||
|
||||
## User Journeys
|
||||
|
||||
### [Feature Name] - [Persona Name] Journey
|
||||
|
||||
1. [Step 1]: [Description]
|
||||
2. [Step 2]: [Description]
|
||||
3. [Step 3]: [Description]
|
||||
|
||||
### [External System] Integration Journey
|
||||
|
||||
1. [Step 1]: [Description]
|
||||
2. [Step 2]: [Description]
|
||||
|
||||
## External Systems and Dependencies
|
||||
|
||||
### [External System Name]
|
||||
|
||||
- **Type**: [Database, API, Service, Message Queue, etc.]
|
||||
- **Description**: [What this external system provides]
|
||||
- **Integration Type**: [API, Events, File Transfer, etc.]
|
||||
- **Purpose**: [Why the system depends on this]
|
||||
|
||||
## System Context Diagram
|
||||
|
||||
[See diagram syntax below]
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Container Documentation](./c4-container.md)
|
||||
- [Component Documentation](./c4-component.md)
|
||||
```
|
||||
|
||||
## Context Diagram Syntax
|
||||
|
||||
```mermaid
|
||||
C4Context
|
||||
title System Context Diagram
|
||||
|
||||
Person(user, "User", "Uses the system to accomplish their goals")
|
||||
System(system, "System Name", "Provides features X, Y, and Z")
|
||||
System_Ext(external1, "External System 1", "Provides service A")
|
||||
System_Ext(external2, "External System 2", "Provides service B")
|
||||
SystemDb(externalDb, "External Database", "Stores data")
|
||||
|
||||
Rel(user, system, "Uses")
|
||||
Rel(system, external1, "Uses", "API")
|
||||
Rel(system, external2, "Sends events to")
|
||||
Rel(system, externalDb, "Reads from and writes to")
|
||||
```
|
||||
|
||||
## Key Principles
|
||||
|
||||
- Focus on **people and software systems**, not technologies or protocols
|
||||
- Show the **system boundary** clearly (what's inside vs. outside)
|
||||
- Include **all users**: human and programmatic (external systems that call the system are also "users")
|
||||
- Include all **external systems** the system interacts with
|
||||
- Keep it **stakeholder-friendly** — avoid implementation details
|
||||
- Document **user journeys** for each key feature and persona
|
||||
- This is the final step of the C4 documentation chain
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
name: cavecrew
|
||||
description: >
|
||||
Decision guide for delegating to caveman-style subagents. Tells the main
|
||||
thread WHEN to spawn `cavecrew-investigator` (locate code), `cavecrew-builder`
|
||||
(1-2 file edit), or `cavecrew-reviewer` (diff review) instead of doing the
|
||||
work inline or using vanilla `Explore`. Subagent output is caveman-compressed
|
||||
so the tool-result injected back into main context is ~60% smaller — main
|
||||
context lasts longer across long sessions.
|
||||
Trigger: "delegate to subagent", "use cavecrew", "spawn investigator/builder/reviewer",
|
||||
"save context", "compressed agent output".
|
||||
---
|
||||
|
||||
Cavecrew = three subagent presets that emit caveman output. Same job as Anthropic defaults (`Explore`, edit-style agents, reviewer); difference is the tool-result they return is compressed, so main context shrinks per delegation.
|
||||
|
||||
## When to use cavecrew vs alternatives
|
||||
|
||||
| Task | Use |
|
||||
|---|---|
|
||||
| "Where is X defined / what calls Y / list uses of Z" | `cavecrew-investigator` |
|
||||
| Same but you also want suggestions/architecture commentary | `Explore` (vanilla) |
|
||||
| Surgical edit, ≤2 files, scope obvious | `cavecrew-builder` |
|
||||
| New feature / 3+ files / cross-cutting refactor | Main thread or `feature-dev:code-architect` |
|
||||
| Review diff, branch, or file for bugs | `cavecrew-reviewer` |
|
||||
| Deep code review with rationale + alternatives | `Code Reviewer` (vanilla) |
|
||||
| One-line answer you already know | Main thread, no subagent |
|
||||
|
||||
Rule of thumb: **if you'd want the subagent's output in 1/3 the tokens, pick cavecrew. If you'd want prose, pick vanilla.**
|
||||
|
||||
## Why this exists (the real win)
|
||||
|
||||
Subagent tool results get injected into main context verbatim. A vanilla `Explore` that returns 2k tokens of prose costs 2k tokens of main-context budget every time. The same finding from `cavecrew-investigator` returns ~700 tokens. Across 20 delegations in one session that's the difference between context exhaustion and finishing the task.
|
||||
|
||||
## Output contracts
|
||||
|
||||
What main thread can rely on per agent:
|
||||
|
||||
**`cavecrew-investigator`**
|
||||
```
|
||||
<Header>:
|
||||
- path:line — `symbol` — short note
|
||||
totals: <counts>.
|
||||
```
|
||||
Or `No match.` Always file-path-first, line-number-attached, backticked symbols. Safe to grep with `path:\d+`.
|
||||
|
||||
**`cavecrew-builder`**
|
||||
```
|
||||
<path:line-range> — <change ≤10 words>.
|
||||
verified: <re-read OK | mismatch @ path:line>.
|
||||
```
|
||||
Or one of: `too-big.` / `needs-confirm.` / `ambiguous.` / `regressed.` (terminal first token).
|
||||
|
||||
**`cavecrew-reviewer`**
|
||||
```
|
||||
path:line: <emoji> <severity>: <problem>. <fix>.
|
||||
totals: N🔴 N🟡 N🔵 N❓
|
||||
```
|
||||
Or `No issues.` Findings sorted file → line ascending.
|
||||
|
||||
## Chaining patterns
|
||||
|
||||
**Locate → fix → verify** (most common):
|
||||
1. `cavecrew-investigator` returns site list.
|
||||
2. Main thread picks 1-2 sites, hands paths to `cavecrew-builder`.
|
||||
3. `cavecrew-reviewer` audits the diff.
|
||||
|
||||
**Parallel scout** (when investigation is broad):
|
||||
Spawn 2-3 `cavecrew-investigator` calls in one message (different angles: defs vs callers vs tests). Aggregate in main thread.
|
||||
|
||||
**Single-shot edit** (when site is already known):
|
||||
Skip investigator. Hand exact path:line to `cavecrew-builder` directly.
|
||||
|
||||
## What NOT to do
|
||||
|
||||
- Don't use `cavecrew-builder` when you don't already know the file. Spawn investigator first or main thread will eat tokens passing context.
|
||||
- Don't chain `cavecrew-investigator → cavecrew-builder` for a 5-file refactor. Builder will return `too-big.` and you'll have wasted a turn.
|
||||
- Don't ask `cavecrew-reviewer` for "general feedback" — it returns findings only, no architecture opinions. Use `Code Reviewer` for that.
|
||||
- Don't expect prose. Cavecrew output is structured, sometimes terse to the point of cryptic. If a human will read it directly, paraphrase.
|
||||
|
||||
## Auto-clarity (inherited)
|
||||
|
||||
Subagents drop caveman → normal English for security warnings, irreversible-action confirmations, and any output where fragment ambiguity could be misread. Resume caveman after.
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
name: caveman-commit
|
||||
description: >
|
||||
Ultra-compressed commit message generator. Cuts noise from commit messages while preserving
|
||||
intent and reasoning. Conventional Commits format. Subject ≤50 chars, body only when "why"
|
||||
isn't obvious. Use when user says "write a commit", "commit message", "generate commit",
|
||||
"/commit", or invokes /caveman-commit. Auto-triggers when staging changes.
|
||||
---
|
||||
|
||||
Write commit messages terse and exact. Conventional Commits format. No fluff. Why over what.
|
||||
|
||||
## Rules
|
||||
|
||||
**Subject line:**
|
||||
- `<type>(<scope>): <imperative summary>` — `<scope>` optional
|
||||
- Types: `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `chore`, `build`, `ci`, `style`, `revert`
|
||||
- Imperative mood: "add", "fix", "remove" — not "added", "adds", "adding"
|
||||
- ≤50 chars when possible, hard cap 72
|
||||
- No trailing period
|
||||
- Match project convention for capitalization after the colon
|
||||
|
||||
**Body (only if needed):**
|
||||
- Skip entirely when subject is self-explanatory
|
||||
- Add body only for: non-obvious *why*, breaking changes, migration notes, linked issues
|
||||
- Wrap at 72 chars
|
||||
- Bullets `-` not `*`
|
||||
- Reference issues/PRs at end: `Closes #42`, `Refs #17`
|
||||
|
||||
**What NEVER goes in:**
|
||||
- "This commit does X", "I", "we", "now", "currently" — the diff says what
|
||||
- "As requested by..." — use Co-authored-by trailer
|
||||
- "Generated with Claude Code" or any AI attribution
|
||||
- Emoji (unless project convention requires)
|
||||
- Restating the file name when scope already says it
|
||||
|
||||
## Examples
|
||||
|
||||
Diff: new endpoint for user profile with body explaining the why
|
||||
- ❌ "feat: add a new endpoint to get user profile information from the database"
|
||||
- ✅
|
||||
```
|
||||
feat(api): add GET /users/:id/profile
|
||||
|
||||
Mobile client needs profile data without the full user payload
|
||||
to reduce LTE bandwidth on cold-launch screens.
|
||||
|
||||
Closes #128
|
||||
```
|
||||
|
||||
Diff: breaking API change
|
||||
- ✅
|
||||
```
|
||||
feat(api)!: rename /v1/orders to /v1/checkout
|
||||
|
||||
BREAKING CHANGE: clients on /v1/orders must migrate to /v1/checkout
|
||||
before 2026-06-01. Old route returns 410 after that date.
|
||||
```
|
||||
|
||||
## Auto-Clarity
|
||||
|
||||
Always include body for: breaking changes, security fixes, data migrations, anything reverting a prior commit. Never compress these into subject-only — future debuggers need the context.
|
||||
|
||||
## Boundaries
|
||||
|
||||
Only generates the commit message. Does not run `git commit`, does not stage files, does not amend. Output the message as a code block ready to paste. "stop caveman-commit" or "normal mode": revert to verbose commit style.
|
||||
@@ -0,0 +1,163 @@
|
||||
<p align="center">
|
||||
<img src="https://em-content.zobj.net/source/apple/391/rock_1faa8.png" width="80" />
|
||||
</p>
|
||||
|
||||
<h1 align="center">caveman-compress</h1>
|
||||
|
||||
<p align="center">
|
||||
<strong>shrink memory file. save token every session.</strong>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
A Claude Code skill that compresses your project memory files (`CLAUDE.md`, todos, preferences) into caveman format — so every session loads fewer tokens automatically.
|
||||
|
||||
Claude read `CLAUDE.md` on every session start. If file big, cost big. Caveman make file small. Cost go down forever.
|
||||
|
||||
## What It Do
|
||||
|
||||
```
|
||||
/caveman:compress CLAUDE.md
|
||||
```
|
||||
|
||||
```
|
||||
CLAUDE.md ← compressed (Claude reads this — fewer tokens every session)
|
||||
CLAUDE.original.md ← human-readable backup (you edit this)
|
||||
```
|
||||
|
||||
Original never lost. You can read and edit `.original.md`. Run skill again to re-compress after edits.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Real results on real project files:
|
||||
|
||||
| File | Original | Compressed | Saved |
|
||||
|------|----------:|----------:|------:|
|
||||
| `claude-md-preferences.md` | 706 | 285 | **59.6%** |
|
||||
| `project-notes.md` | 1145 | 535 | **53.3%** |
|
||||
| `claude-md-project.md` | 1122 | 636 | **43.3%** |
|
||||
| `todo-list.md` | 627 | 388 | **38.1%** |
|
||||
| `mixed-with-code.md` | 888 | 560 | **36.9%** |
|
||||
| **Average** | **898** | **481** | **46%** |
|
||||
|
||||
All validations passed ✅ — headings, code blocks, URLs, file paths preserved exactly.
|
||||
|
||||
## Before / After
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 📄 Original (706 tokens)
|
||||
|
||||
> "I strongly prefer TypeScript with strict mode enabled for all new code. Please don't use `any` type unless there's genuinely no way around it, and if you do, leave a comment explaining the reasoning. I find that taking the time to properly type things catches a lot of bugs before they ever make it to runtime."
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### 🪨 Caveman (285 tokens)
|
||||
|
||||
> "Prefer TypeScript strict mode always. No `any` unless unavoidable — comment why if used. Proper types catch bugs early."
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
**Same instructions. 60% fewer tokens. Every. Single. Session.**
|
||||
|
||||
## Security
|
||||
|
||||
`caveman-compress` is flagged as Snyk High Risk due to subprocess and file I/O patterns detected by static analysis. This is a false positive — see [SECURITY.md](./SECURITY.md) for a full explanation of what the skill does and does not do.
|
||||
|
||||
## Install
|
||||
|
||||
Compress is built in with the `caveman` plugin. Install `caveman` once, then use `/caveman:compress`.
|
||||
|
||||
If you need local files, the compress skill lives at:
|
||||
|
||||
```bash
|
||||
caveman-compress/
|
||||
```
|
||||
|
||||
**Requires:** Python 3.10+
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/caveman:compress <filepath>
|
||||
```
|
||||
|
||||
Examples:
|
||||
```
|
||||
/caveman:compress CLAUDE.md
|
||||
/caveman:compress docs/preferences.md
|
||||
/caveman:compress todos.md
|
||||
```
|
||||
|
||||
### What files work
|
||||
|
||||
| Type | Compress? |
|
||||
|------|-----------|
|
||||
| `.md`, `.txt`, `.rst` | ✅ Yes |
|
||||
| Extensionless natural language | ✅ Yes |
|
||||
| `.py`, `.js`, `.ts`, `.json`, `.yaml` | ❌ Skip (code/config) |
|
||||
| `*.original.md` | ❌ Skip (backup files) |
|
||||
|
||||
## How It Work
|
||||
|
||||
```
|
||||
/caveman:compress CLAUDE.md
|
||||
↓
|
||||
detect file type (no tokens)
|
||||
↓
|
||||
Claude compresses (tokens — one call)
|
||||
↓
|
||||
validate output (no tokens)
|
||||
checks: headings, code blocks, URLs, file paths, bullets
|
||||
↓
|
||||
if errors: Claude fixes cherry-picked issues only (tokens — targeted fix)
|
||||
does NOT recompress — only patches broken parts
|
||||
↓
|
||||
retry up to 2 times
|
||||
↓
|
||||
write compressed → CLAUDE.md
|
||||
write original → CLAUDE.original.md
|
||||
```
|
||||
|
||||
Only two things use tokens: initial compression + targeted fix if validation fails. Everything else is local Python.
|
||||
|
||||
## What Is Preserved
|
||||
|
||||
Caveman compress natural language. It never touch:
|
||||
|
||||
- Code blocks (` ``` ` fenced or indented)
|
||||
- Inline code (`` `backtick content` ``)
|
||||
- URLs and links
|
||||
- File paths (`/src/components/...`)
|
||||
- Commands (`npm install`, `git commit`)
|
||||
- Technical terms, library names, API names
|
||||
- Headings (exact text preserved)
|
||||
- Tables (structure preserved, cell text compressed)
|
||||
- Dates, version numbers, numeric values
|
||||
|
||||
## Why This Matter
|
||||
|
||||
`CLAUDE.md` loads on **every session start**. A 1000-token project memory file costs tokens every single time you open a project. Over 100 sessions that's 100,000 tokens of overhead — just for context you already wrote.
|
||||
|
||||
Caveman cut that by ~46% on average. Same instructions. Same accuracy. Less waste.
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────┐
|
||||
│ TOKEN SAVINGS PER FILE █████ 46% │
|
||||
│ SESSIONS THAT BENEFIT ██████████ 100% │
|
||||
│ INFORMATION PRESERVED ██████████ 100% │
|
||||
│ SETUP TIME █ 1x │
|
||||
└────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Part of Caveman
|
||||
|
||||
This skill is part of the [caveman](https://github.com/JuliusBrussee/caveman) toolkit — making Claude use fewer tokens without losing accuracy.
|
||||
|
||||
- **caveman** — make Claude *speak* like caveman (cuts response tokens ~65%)
|
||||
- **caveman-compress** — make Claude *read* less (cuts context tokens ~46%)
|
||||
@@ -0,0 +1,31 @@
|
||||
# Security
|
||||
|
||||
## Snyk High Risk Rating
|
||||
|
||||
`caveman-compress` receives a Snyk High Risk rating due to static analysis heuristics. This document explains what the skill does and does not do.
|
||||
|
||||
### What triggers the rating
|
||||
|
||||
1. **subprocess usage**: The skill calls the `claude` CLI via `subprocess.run()` as a fallback when `ANTHROPIC_API_KEY` is not set. The subprocess call uses a fixed argument list — no shell interpolation occurs. User file content is passed via stdin, not as a shell argument.
|
||||
|
||||
2. **File read/write**: The skill reads the file the user explicitly points it at, compresses it, and writes the result back to the same path. A `.original.md` backup is saved alongside it. No files outside the user-specified path are read or written.
|
||||
|
||||
### What the skill does NOT do
|
||||
|
||||
- Does not execute user file content as code
|
||||
- Does not make network requests except to Anthropic's API (via SDK or CLI)
|
||||
- Does not access files outside the path the user provides
|
||||
- Does not use shell=True or string interpolation in subprocess calls
|
||||
- Does not collect or transmit any data beyond the file being compressed
|
||||
|
||||
### Auth behavior
|
||||
|
||||
If `ANTHROPIC_API_KEY` is set, the skill uses the Anthropic Python SDK directly (no subprocess). If not set, it falls back to the `claude` CLI, which uses the user's existing Claude desktop authentication.
|
||||
|
||||
### File size limit
|
||||
|
||||
Files larger than 500KB are rejected before any API call is made.
|
||||
|
||||
### Reporting a vulnerability
|
||||
|
||||
If you believe you've found a genuine security issue, please open a GitHub issue with the label `security`.
|
||||
@@ -0,0 +1,111 @@
|
||||
---
|
||||
name: caveman-compress
|
||||
description: >
|
||||
Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format
|
||||
to save input tokens. Preserves all technical substance, code, URLs, and structure.
|
||||
Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md.
|
||||
Trigger: /caveman:compress <filepath> or "compress memory file"
|
||||
---
|
||||
|
||||
# Caveman Compress
|
||||
|
||||
## Purpose
|
||||
|
||||
Compress natural language files (CLAUDE.md, todos, preferences) into caveman-speak to reduce input tokens. Compressed version overwrites original. Human-readable backup saved as `<filename>.original.md`.
|
||||
|
||||
## Trigger
|
||||
|
||||
`/caveman:compress <filepath>` or when user asks to compress a memory file.
|
||||
|
||||
## Process
|
||||
|
||||
1. The compression scripts live in `caveman-compress/scripts/` (adjacent to this SKILL.md). If the path is not immediately available, search for `caveman-compress/scripts/__main__.py`.
|
||||
|
||||
2. Run:
|
||||
|
||||
cd caveman-compress && python3 -m scripts <absolute_filepath>
|
||||
|
||||
3. The CLI will:
|
||||
- detect file type (no tokens)
|
||||
- call Claude to compress
|
||||
- validate output (no tokens)
|
||||
- if errors: cherry-pick fix with Claude (targeted fixes only, no recompression)
|
||||
- retry up to 2 times
|
||||
- if still failing after 2 retries: report error to user, leave original file untouched
|
||||
|
||||
4. Return result to user
|
||||
|
||||
## Compression Rules
|
||||
|
||||
### Remove
|
||||
- Articles: a, an, the
|
||||
- Filler: just, really, basically, actually, simply, essentially, generally
|
||||
- Pleasantries: "sure", "certainly", "of course", "happy to", "I'd recommend"
|
||||
- Hedging: "it might be worth", "you could consider", "it would be good to"
|
||||
- Redundant phrasing: "in order to" → "to", "make sure to" → "ensure", "the reason is because" → "because"
|
||||
- Connective fluff: "however", "furthermore", "additionally", "in addition"
|
||||
|
||||
### Preserve EXACTLY (never modify)
|
||||
- Code blocks (fenced ``` and indented)
|
||||
- Inline code (`backtick content`)
|
||||
- URLs and links (full URLs, markdown links)
|
||||
- File paths (`/src/components/...`, `./config.yaml`)
|
||||
- Commands (`npm install`, `git commit`, `docker build`)
|
||||
- Technical terms (library names, API names, protocols, algorithms)
|
||||
- Proper nouns (project names, people, companies)
|
||||
- Dates, version numbers, numeric values
|
||||
- Environment variables (`$HOME`, `NODE_ENV`)
|
||||
|
||||
### Preserve Structure
|
||||
- All markdown headings (keep exact heading text, compress body below)
|
||||
- Bullet point hierarchy (keep nesting level)
|
||||
- Numbered lists (keep numbering)
|
||||
- Tables (compress cell text, keep structure)
|
||||
- Frontmatter/YAML headers in markdown files
|
||||
|
||||
### Compress
|
||||
- Use short synonyms: "big" not "extensive", "fix" not "implement a solution for", "use" not "utilize"
|
||||
- Fragments OK: "Run tests before commit" not "You should always run tests before committing"
|
||||
- Drop "you should", "make sure to", "remember to" — just state the action
|
||||
- Merge redundant bullets that say the same thing differently
|
||||
- Keep one example where multiple examples show the same pattern
|
||||
|
||||
CRITICAL RULE:
|
||||
Anything inside ``` ... ``` must be copied EXACTLY.
|
||||
Do not:
|
||||
- remove comments
|
||||
- remove spacing
|
||||
- reorder lines
|
||||
- shorten commands
|
||||
- simplify anything
|
||||
|
||||
Inline code (`...`) must be preserved EXACTLY.
|
||||
Do not modify anything inside backticks.
|
||||
|
||||
If file contains code blocks:
|
||||
- Treat code blocks as read-only regions
|
||||
- Only compress text outside them
|
||||
- Do not merge sections around code
|
||||
|
||||
## Pattern
|
||||
|
||||
Original:
|
||||
> You should always make sure to run the test suite before pushing any changes to the main branch. This is important because it helps catch bugs early and prevents broken builds from being deployed to production.
|
||||
|
||||
Compressed:
|
||||
> Run tests before push to main. Catch bugs early, prevent broken prod deploys.
|
||||
|
||||
Original:
|
||||
> The application uses a microservices architecture with the following components. The API gateway handles all incoming requests and routes them to the appropriate service. The authentication service is responsible for managing user sessions and JWT tokens.
|
||||
|
||||
Compressed:
|
||||
> Microservices architecture. API gateway route all requests to services. Auth service manage user sessions + JWT tokens.
|
||||
|
||||
## Boundaries
|
||||
|
||||
- ONLY compress natural language files (.md, .txt, extensionless)
|
||||
- NEVER modify: .py, .js, .ts, .json, .yaml, .yml, .toml, .env, .lock, .css, .html, .xml, .sql, .sh
|
||||
- If file has mixed content (prose + code), compress ONLY the prose sections
|
||||
- If unsure whether something is code or prose, leave it unchanged
|
||||
- Original file is backed up as FILE.original.md before overwriting
|
||||
- Never compress FILE.original.md (skip it)
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Caveman compress scripts.
|
||||
|
||||
This package provides tools to compress natural language markdown files
|
||||
into caveman format to save input tokens.
|
||||
"""
|
||||
|
||||
__all__ = ["cli", "compress", "detect", "validate"]
|
||||
|
||||
__version__ = "1.0.0"
|
||||
@@ -0,0 +1,3 @@
|
||||
from .cli import main
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
# Support both direct execution and module import
|
||||
try:
|
||||
from .validate import validate
|
||||
except ImportError:
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from validate import validate
|
||||
|
||||
try:
|
||||
import tiktoken
|
||||
_enc = tiktoken.get_encoding("o200k_base")
|
||||
except ImportError:
|
||||
_enc = None
|
||||
|
||||
|
||||
def count_tokens(text):
|
||||
if _enc is None:
|
||||
return len(text.split()) # fallback: word count
|
||||
return len(_enc.encode(text))
|
||||
|
||||
|
||||
def benchmark_pair(orig_path: Path, comp_path: Path):
|
||||
orig_text = orig_path.read_text()
|
||||
comp_text = comp_path.read_text()
|
||||
|
||||
orig_tokens = count_tokens(orig_text)
|
||||
comp_tokens = count_tokens(comp_text)
|
||||
saved = 100 * (orig_tokens - comp_tokens) / orig_tokens if orig_tokens > 0 else 0.0
|
||||
result = validate(orig_path, comp_path)
|
||||
|
||||
return (comp_path.name, orig_tokens, comp_tokens, saved, result.is_valid)
|
||||
|
||||
|
||||
def print_table(rows):
|
||||
print("\n| File | Original | Compressed | Saved % | Valid |")
|
||||
print("|------|----------|------------|---------|-------|")
|
||||
for r in rows:
|
||||
print(f"| {r[0]} | {r[1]} | {r[2]} | {r[3]:.1f}% | {'✅' if r[4] else '❌'} |")
|
||||
|
||||
|
||||
def main():
|
||||
# Direct file pair: python3 benchmark.py original.md compressed.md
|
||||
if len(sys.argv) == 3:
|
||||
orig = Path(sys.argv[1]).resolve()
|
||||
comp = Path(sys.argv[2]).resolve()
|
||||
if not orig.exists():
|
||||
print(f"❌ Not found: {orig}")
|
||||
sys.exit(1)
|
||||
if not comp.exists():
|
||||
print(f"❌ Not found: {comp}")
|
||||
sys.exit(1)
|
||||
print_table([benchmark_pair(orig, comp)])
|
||||
return
|
||||
|
||||
# Glob mode: repo_root/tests/caveman-compress/
|
||||
tests_dir = Path(__file__).parent.parent.parent / "tests" / "caveman-compress"
|
||||
if not tests_dir.exists():
|
||||
print(f"❌ Tests dir not found: {tests_dir}")
|
||||
sys.exit(1)
|
||||
|
||||
rows = []
|
||||
for orig in sorted(tests_dir.glob("*.original.md")):
|
||||
comp = orig.with_name(orig.stem.removesuffix(".original") + ".md")
|
||||
if comp.exists():
|
||||
rows.append(benchmark_pair(orig, comp))
|
||||
|
||||
if not rows:
|
||||
print("No compressed file pairs found.")
|
||||
return
|
||||
|
||||
print_table(rows)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Caveman Compress CLI
|
||||
|
||||
Usage:
|
||||
caveman <filepath>
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from .compress import compress_file
|
||||
from .detect import detect_file_type, should_compress
|
||||
|
||||
|
||||
def print_usage():
|
||||
print("Usage: caveman <filepath>")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print_usage()
|
||||
sys.exit(1)
|
||||
|
||||
filepath = Path(sys.argv[1])
|
||||
|
||||
# Check file exists
|
||||
if not filepath.exists():
|
||||
print(f"❌ File not found: {filepath}")
|
||||
sys.exit(1)
|
||||
|
||||
if not filepath.is_file():
|
||||
print(f"❌ Not a file: {filepath}")
|
||||
sys.exit(1)
|
||||
|
||||
filepath = filepath.resolve()
|
||||
|
||||
# Detect file type
|
||||
file_type = detect_file_type(filepath)
|
||||
|
||||
print(f"Detected: {file_type}")
|
||||
|
||||
# Check if compressible
|
||||
if not should_compress(filepath):
|
||||
print("Skipping: file is not natural language (code/config)")
|
||||
sys.exit(0)
|
||||
|
||||
print("Starting caveman compression...\n")
|
||||
|
||||
try:
|
||||
success = compress_file(filepath)
|
||||
|
||||
if success:
|
||||
print("\nCompression completed successfully")
|
||||
backup_path = filepath.with_name(filepath.stem + ".original.md")
|
||||
print(f"Compressed: {filepath}")
|
||||
print(f"Original: {backup_path}")
|
||||
sys.exit(0)
|
||||
else:
|
||||
print("\n❌ Compression failed after retries")
|
||||
sys.exit(2)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\nInterrupted by user")
|
||||
sys.exit(130)
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ Error: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Caveman Memory Compression Orchestrator
|
||||
|
||||
Usage:
|
||||
python scripts/compress.py <filepath>
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
OUTER_FENCE_REGEX = re.compile(
|
||||
r"\A\s*(`{3,}|~{3,})[^\n]*\n(.*)\n\1\s*\Z", re.DOTALL
|
||||
)
|
||||
|
||||
|
||||
def strip_llm_wrapper(text: str) -> str:
|
||||
"""Strip outer ```markdown ... ``` fence when it wraps the entire output."""
|
||||
m = OUTER_FENCE_REGEX.match(text)
|
||||
if m:
|
||||
return m.group(2)
|
||||
return text
|
||||
|
||||
from .detect import should_compress
|
||||
from .validate import validate
|
||||
|
||||
MAX_RETRIES = 2
|
||||
|
||||
|
||||
# ---------- Claude Calls ----------
|
||||
|
||||
|
||||
def call_claude(prompt: str) -> str:
|
||||
api_key = os.environ.get("ANTHROPIC_API_KEY")
|
||||
if api_key:
|
||||
try:
|
||||
import anthropic
|
||||
|
||||
client = anthropic.Anthropic(api_key=api_key)
|
||||
msg = client.messages.create(
|
||||
model=os.environ.get("CAVEMAN_MODEL", "claude-sonnet-4-5"),
|
||||
max_tokens=8192,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
)
|
||||
return strip_llm_wrapper(msg.content[0].text.strip())
|
||||
except ImportError:
|
||||
pass # anthropic not installed, fall back to CLI
|
||||
# Fallback: use claude CLI (handles desktop auth)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["claude", "--print"],
|
||||
input=prompt,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
return strip_llm_wrapper(result.stdout.strip())
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError(f"Claude call failed:\n{e.stderr}")
|
||||
|
||||
|
||||
def build_compress_prompt(original: str) -> str:
|
||||
return f"""
|
||||
Compress this markdown into caveman format.
|
||||
|
||||
STRICT RULES:
|
||||
- Do NOT modify anything inside ``` code blocks
|
||||
- Do NOT modify anything inside inline backticks
|
||||
- Preserve ALL URLs exactly
|
||||
- Preserve ALL headings exactly
|
||||
- Preserve file paths and commands
|
||||
- Return ONLY the compressed markdown body — do NOT wrap the entire output in a ```markdown fence or any other fence. Inner code blocks from the original stay as-is; do not add a new outer fence around the whole file.
|
||||
|
||||
Only compress natural language.
|
||||
|
||||
TEXT:
|
||||
{original}
|
||||
"""
|
||||
|
||||
|
||||
def build_fix_prompt(original: str, compressed: str, errors: List[str]) -> str:
|
||||
errors_str = "\n".join(f"- {e}" for e in errors)
|
||||
return f"""You are fixing a caveman-compressed markdown file. Specific validation errors were found.
|
||||
|
||||
CRITICAL RULES:
|
||||
- DO NOT recompress or rephrase the file
|
||||
- ONLY fix the listed errors — leave everything else exactly as-is
|
||||
- The ORIGINAL is provided as reference only (to restore missing content)
|
||||
- Preserve caveman style in all untouched sections
|
||||
|
||||
ERRORS TO FIX:
|
||||
{errors_str}
|
||||
|
||||
HOW TO FIX:
|
||||
- Missing URL: find it in ORIGINAL, restore it exactly where it belongs in COMPRESSED
|
||||
- Code block mismatch: find the exact code block in ORIGINAL, restore it in COMPRESSED
|
||||
- Heading mismatch: restore the exact heading text from ORIGINAL into COMPRESSED
|
||||
- Do not touch any section not mentioned in the errors
|
||||
|
||||
ORIGINAL (reference only):
|
||||
{original}
|
||||
|
||||
COMPRESSED (fix this):
|
||||
{compressed}
|
||||
|
||||
Return ONLY the fixed compressed file. No explanation.
|
||||
"""
|
||||
|
||||
|
||||
# ---------- Core Logic ----------
|
||||
|
||||
|
||||
def compress_file(filepath: Path) -> bool:
|
||||
# Resolve and validate path
|
||||
filepath = filepath.resolve()
|
||||
MAX_FILE_SIZE = 500_000 # 500KB
|
||||
if not filepath.exists():
|
||||
raise FileNotFoundError(f"File not found: {filepath}")
|
||||
if filepath.stat().st_size > MAX_FILE_SIZE:
|
||||
raise ValueError(f"File too large to compress safely (max 500KB): {filepath}")
|
||||
|
||||
print(f"Processing: {filepath}")
|
||||
|
||||
if not should_compress(filepath):
|
||||
print("Skipping (not natural language)")
|
||||
return False
|
||||
|
||||
original_text = filepath.read_text(errors="ignore")
|
||||
backup_path = filepath.with_name(filepath.stem + ".original.md")
|
||||
|
||||
# Check if backup already exists to prevent accidental overwriting
|
||||
if backup_path.exists():
|
||||
print(f"⚠️ Backup file already exists: {backup_path}")
|
||||
print("The original backup may contain important content.")
|
||||
print("Aborting to prevent data loss. Please remove or rename the backup file if you want to proceed.")
|
||||
return False
|
||||
|
||||
# Step 1: Compress
|
||||
print("Compressing with Claude...")
|
||||
compressed = call_claude(build_compress_prompt(original_text))
|
||||
|
||||
# Save original as backup, write compressed to original path
|
||||
backup_path.write_text(original_text)
|
||||
filepath.write_text(compressed)
|
||||
|
||||
# Step 2: Validate + Retry
|
||||
for attempt in range(MAX_RETRIES):
|
||||
print(f"\nValidation attempt {attempt + 1}")
|
||||
|
||||
result = validate(backup_path, filepath)
|
||||
|
||||
if result.is_valid:
|
||||
print("Validation passed")
|
||||
break
|
||||
|
||||
print("❌ Validation failed:")
|
||||
for err in result.errors:
|
||||
print(f" - {err}")
|
||||
|
||||
if attempt == MAX_RETRIES - 1:
|
||||
# Restore original on failure
|
||||
filepath.write_text(original_text)
|
||||
backup_path.unlink(missing_ok=True)
|
||||
print("❌ Failed after retries — original restored")
|
||||
return False
|
||||
|
||||
print("Fixing with Claude...")
|
||||
compressed = call_claude(
|
||||
build_fix_prompt(original_text, compressed, result.errors)
|
||||
)
|
||||
filepath.write_text(compressed)
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Detect whether a file is natural language (compressible) or code/config (skip)."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
# Extensions that are natural language and compressible
|
||||
COMPRESSIBLE_EXTENSIONS = {".md", ".txt", ".markdown", ".rst"}
|
||||
|
||||
# Extensions that are code/config and should be skipped
|
||||
SKIP_EXTENSIONS = {
|
||||
".py", ".js", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml",
|
||||
".toml", ".env", ".lock", ".css", ".scss", ".html", ".xml",
|
||||
".sql", ".sh", ".bash", ".zsh", ".go", ".rs", ".java", ".c",
|
||||
".cpp", ".h", ".hpp", ".rb", ".php", ".swift", ".kt", ".lua",
|
||||
".dockerfile", ".makefile", ".csv", ".ini", ".cfg",
|
||||
}
|
||||
|
||||
# Patterns that indicate a line is code
|
||||
CODE_PATTERNS = [
|
||||
re.compile(r"^\s*(import |from .+ import |require\(|const |let |var )"),
|
||||
re.compile(r"^\s*(def |class |function |async function |export )"),
|
||||
re.compile(r"^\s*(if\s*\(|for\s*\(|while\s*\(|switch\s*\(|try\s*\{)"),
|
||||
re.compile(r"^\s*[\}\]\);]+\s*$"), # closing braces/brackets
|
||||
re.compile(r"^\s*@\w+"), # decorators/annotations
|
||||
re.compile(r'^\s*"[^"]+"\s*:\s*'), # JSON-like key-value
|
||||
re.compile(r"^\s*\w+\s*=\s*[{\[\(\"']"), # assignment with literal
|
||||
]
|
||||
|
||||
|
||||
def _is_code_line(line: str) -> bool:
|
||||
"""Check if a line looks like code."""
|
||||
return any(p.match(line) for p in CODE_PATTERNS)
|
||||
|
||||
|
||||
def _is_json_content(text: str) -> bool:
|
||||
"""Check if content is valid JSON."""
|
||||
try:
|
||||
json.loads(text)
|
||||
return True
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def _is_yaml_content(lines: list[str]) -> bool:
|
||||
"""Heuristic: check if content looks like YAML."""
|
||||
yaml_indicators = 0
|
||||
for line in lines[:30]:
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("---"):
|
||||
yaml_indicators += 1
|
||||
elif re.match(r"^\w[\w\s]*:\s", stripped):
|
||||
yaml_indicators += 1
|
||||
elif stripped.startswith("- ") and ":" in stripped:
|
||||
yaml_indicators += 1
|
||||
# If most non-empty lines look like YAML
|
||||
non_empty = sum(1 for l in lines[:30] if l.strip())
|
||||
return non_empty > 0 and yaml_indicators / non_empty > 0.6
|
||||
|
||||
|
||||
def detect_file_type(filepath: Path) -> str:
|
||||
"""Classify a file as 'natural_language', 'code', 'config', or 'unknown'.
|
||||
|
||||
Returns:
|
||||
One of: 'natural_language', 'code', 'config', 'unknown'
|
||||
"""
|
||||
ext = filepath.suffix.lower()
|
||||
|
||||
# Extension-based classification
|
||||
if ext in COMPRESSIBLE_EXTENSIONS:
|
||||
return "natural_language"
|
||||
if ext in SKIP_EXTENSIONS:
|
||||
return "code" if ext not in {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".env"} else "config"
|
||||
|
||||
# Extensionless files (like CLAUDE.md, TODO) — check content
|
||||
if not ext:
|
||||
try:
|
||||
text = filepath.read_text(errors="ignore")
|
||||
except (OSError, PermissionError):
|
||||
return "unknown"
|
||||
|
||||
lines = text.splitlines()[:50]
|
||||
|
||||
if _is_json_content(text[:10000]):
|
||||
return "config"
|
||||
if _is_yaml_content(lines):
|
||||
return "config"
|
||||
|
||||
code_lines = sum(1 for l in lines if l.strip() and _is_code_line(l))
|
||||
non_empty = sum(1 for l in lines if l.strip())
|
||||
if non_empty > 0 and code_lines / non_empty > 0.4:
|
||||
return "code"
|
||||
|
||||
return "natural_language"
|
||||
|
||||
return "unknown"
|
||||
|
||||
|
||||
def should_compress(filepath: Path) -> bool:
|
||||
"""Return True if the file is natural language and should be compressed."""
|
||||
if not filepath.is_file():
|
||||
return False
|
||||
# Skip backup files
|
||||
if filepath.name.endswith(".original.md"):
|
||||
return False
|
||||
return detect_file_type(filepath) == "natural_language"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python detect.py <file1> [file2] ...")
|
||||
sys.exit(1)
|
||||
|
||||
for path_str in sys.argv[1:]:
|
||||
p = Path(path_str).resolve()
|
||||
file_type = detect_file_type(p)
|
||||
compress = should_compress(p)
|
||||
print(f" {p.name:30s} type={file_type:20s} compress={compress}")
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
URL_REGEX = re.compile(r"https?://[^\s)]+")
|
||||
FENCE_OPEN_REGEX = re.compile(r"^(\s{0,3})(`{3,}|~{3,})(.*)$")
|
||||
HEADING_REGEX = re.compile(r"^(#{1,6})\s+(.*)", re.MULTILINE)
|
||||
BULLET_REGEX = re.compile(r"^\s*[-*+]\s+", re.MULTILINE)
|
||||
|
||||
# crude but effective path detection
|
||||
# Requires either a path prefix (./ ../ / or drive letter) or a slash/backslash within the match
|
||||
PATH_REGEX = re.compile(r"(?:\./|\.\./|/|[A-Za-z]:\\)[\w\-/\\\.]+|[\w\-\.]+[/\\][\w\-/\\\.]+")
|
||||
|
||||
|
||||
class ValidationResult:
|
||||
def __init__(self):
|
||||
self.is_valid = True
|
||||
self.errors = []
|
||||
self.warnings = []
|
||||
|
||||
def add_error(self, msg):
|
||||
self.is_valid = False
|
||||
self.errors.append(msg)
|
||||
|
||||
def add_warning(self, msg):
|
||||
self.warnings.append(msg)
|
||||
|
||||
|
||||
def read_file(path: Path) -> str:
|
||||
return path.read_text(errors="ignore")
|
||||
|
||||
|
||||
# ---------- Extractors ----------
|
||||
|
||||
|
||||
def extract_headings(text):
|
||||
return [(level, title.strip()) for level, title in HEADING_REGEX.findall(text)]
|
||||
|
||||
|
||||
def extract_code_blocks(text):
|
||||
"""Line-based fenced code block extractor.
|
||||
|
||||
Handles ``` and ~~~ fences with variable length (CommonMark: closing
|
||||
fence must use same char and be at least as long as opening). Supports
|
||||
nested fences (e.g. an outer 4-backtick block wrapping inner 3-backtick
|
||||
content).
|
||||
"""
|
||||
blocks = []
|
||||
lines = text.split("\n")
|
||||
i = 0
|
||||
n = len(lines)
|
||||
while i < n:
|
||||
m = FENCE_OPEN_REGEX.match(lines[i])
|
||||
if not m:
|
||||
i += 1
|
||||
continue
|
||||
fence_char = m.group(2)[0]
|
||||
fence_len = len(m.group(2))
|
||||
open_line = lines[i]
|
||||
block_lines = [open_line]
|
||||
i += 1
|
||||
closed = False
|
||||
while i < n:
|
||||
close_m = FENCE_OPEN_REGEX.match(lines[i])
|
||||
if (
|
||||
close_m
|
||||
and close_m.group(2)[0] == fence_char
|
||||
and len(close_m.group(2)) >= fence_len
|
||||
and close_m.group(3).strip() == ""
|
||||
):
|
||||
block_lines.append(lines[i])
|
||||
closed = True
|
||||
i += 1
|
||||
break
|
||||
block_lines.append(lines[i])
|
||||
i += 1
|
||||
if closed:
|
||||
blocks.append("\n".join(block_lines))
|
||||
# Unclosed fences are silently skipped — they indicate malformed markdown
|
||||
# and including them would cause false-positive validation failures.
|
||||
return blocks
|
||||
|
||||
|
||||
def extract_urls(text):
|
||||
return set(URL_REGEX.findall(text))
|
||||
|
||||
|
||||
def extract_paths(text):
|
||||
return set(PATH_REGEX.findall(text))
|
||||
|
||||
|
||||
def count_bullets(text):
|
||||
return len(BULLET_REGEX.findall(text))
|
||||
|
||||
|
||||
# ---------- Validators ----------
|
||||
|
||||
|
||||
def validate_headings(orig, comp, result):
|
||||
h1 = extract_headings(orig)
|
||||
h2 = extract_headings(comp)
|
||||
|
||||
if len(h1) != len(h2):
|
||||
result.add_error(f"Heading count mismatch: {len(h1)} vs {len(h2)}")
|
||||
|
||||
if h1 != h2:
|
||||
result.add_warning("Heading text/order changed")
|
||||
|
||||
|
||||
def validate_code_blocks(orig, comp, result):
|
||||
c1 = extract_code_blocks(orig)
|
||||
c2 = extract_code_blocks(comp)
|
||||
|
||||
if c1 != c2:
|
||||
result.add_error("Code blocks not preserved exactly")
|
||||
|
||||
|
||||
def validate_urls(orig, comp, result):
|
||||
u1 = extract_urls(orig)
|
||||
u2 = extract_urls(comp)
|
||||
|
||||
if u1 != u2:
|
||||
result.add_error(f"URL mismatch: lost={u1 - u2}, added={u2 - u1}")
|
||||
|
||||
|
||||
def validate_paths(orig, comp, result):
|
||||
p1 = extract_paths(orig)
|
||||
p2 = extract_paths(comp)
|
||||
|
||||
if p1 != p2:
|
||||
result.add_warning(f"Path mismatch: lost={p1 - p2}, added={p2 - p1}")
|
||||
|
||||
|
||||
def validate_bullets(orig, comp, result):
|
||||
b1 = count_bullets(orig)
|
||||
b2 = count_bullets(comp)
|
||||
|
||||
if b1 == 0:
|
||||
return
|
||||
|
||||
diff = abs(b1 - b2) / b1
|
||||
|
||||
if diff > 0.15:
|
||||
result.add_warning(f"Bullet count changed too much: {b1} -> {b2}")
|
||||
|
||||
|
||||
# ---------- Main ----------
|
||||
|
||||
|
||||
def validate(original_path: Path, compressed_path: Path) -> ValidationResult:
|
||||
result = ValidationResult()
|
||||
|
||||
orig = read_file(original_path)
|
||||
comp = read_file(compressed_path)
|
||||
|
||||
validate_headings(orig, comp, result)
|
||||
validate_code_blocks(orig, comp, result)
|
||||
validate_urls(orig, comp, result)
|
||||
validate_paths(orig, comp, result)
|
||||
validate_bullets(orig, comp, result)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ---------- CLI ----------
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
if len(sys.argv) != 3:
|
||||
print("Usage: python validate.py <original> <compressed>")
|
||||
sys.exit(1)
|
||||
|
||||
orig = Path(sys.argv[1]).resolve()
|
||||
comp = Path(sys.argv[2]).resolve()
|
||||
|
||||
res = validate(orig, comp)
|
||||
|
||||
print(f"\nValid: {res.is_valid}")
|
||||
|
||||
if res.errors:
|
||||
print("\nErrors:")
|
||||
for e in res.errors:
|
||||
print(f" - {e}")
|
||||
|
||||
if res.warnings:
|
||||
print("\nWarnings:")
|
||||
for w in res.warnings:
|
||||
print(f" - {w}")
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: caveman-help
|
||||
description: >
|
||||
Quick-reference card for all caveman modes, skills, and commands.
|
||||
One-shot display, not a persistent mode. Trigger: /caveman-help,
|
||||
"caveman help", "what caveman commands", "how do I use caveman".
|
||||
---
|
||||
|
||||
# Caveman Help
|
||||
|
||||
Display this reference card when invoked. One-shot — do NOT change mode, write flag files, or persist anything. Output in caveman style.
|
||||
|
||||
## Modes
|
||||
|
||||
| Mode | Trigger | What change |
|
||||
|------|---------|-------------|
|
||||
| **Lite** | `/caveman lite` | Drop filler. Keep sentence structure. |
|
||||
| **Full** | `/caveman` | Drop articles, filler, pleasantries, hedging. Fragments OK. Default. |
|
||||
| **Ultra** | `/caveman ultra` | Extreme compression. Bare fragments. Tables over prose. |
|
||||
| **Wenyan-Lite** | `/caveman wenyan-lite` | Classical Chinese style, light compression. |
|
||||
| **Wenyan-Full** | `/caveman wenyan` | Full 文言文. Maximum classical terseness. |
|
||||
| **Wenyan-Ultra** | `/caveman wenyan-ultra` | Extreme. Ancient scholar on a budget. |
|
||||
|
||||
Mode stick until changed or session end.
|
||||
|
||||
## Skills
|
||||
|
||||
| Skill | Trigger | What it do |
|
||||
|-------|---------|-----------|
|
||||
| **caveman-commit** | `/caveman-commit` | Terse commit messages. Conventional Commits. ≤50 char subject. |
|
||||
| **caveman-review** | `/caveman-review` | One-line PR comments: `L42: bug: user null. Add guard.` |
|
||||
| **caveman-compress** | `/caveman:compress <file>` | Compress .md files to caveman prose. Saves ~46% input tokens. |
|
||||
| **caveman-help** | `/caveman-help` | This card. |
|
||||
|
||||
## Deactivate
|
||||
|
||||
Say "stop caveman" or "normal mode". Resume anytime with `/caveman`.
|
||||
|
||||
## Configure Default Mode
|
||||
|
||||
Default mode = `full`. Change it:
|
||||
|
||||
**Environment variable** (highest priority):
|
||||
```bash
|
||||
export CAVEMAN_DEFAULT_MODE=ultra
|
||||
```
|
||||
|
||||
**Config file** (`~/.config/caveman/config.json`):
|
||||
```json
|
||||
{ "defaultMode": "lite" }
|
||||
```
|
||||
|
||||
Set `"off"` to disable auto-activation on session start. User can still activate manually with `/caveman`.
|
||||
|
||||
Resolution: env var > config file > `full`.
|
||||
|
||||
## More
|
||||
|
||||
Full docs: https://github.com/JuliusBrussee/caveman
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
name: caveman-review
|
||||
description: >
|
||||
Ultra-compressed code review comments. Cuts noise from PR feedback while preserving
|
||||
the actionable signal. Each comment is one line: location, problem, fix. Use when user
|
||||
says "review this PR", "code review", "review the diff", "/review", or invokes
|
||||
/caveman-review. Auto-triggers when reviewing pull requests.
|
||||
---
|
||||
|
||||
Write code review comments terse and actionable. One line per finding. Location, problem, fix. No throat-clearing.
|
||||
|
||||
## Rules
|
||||
|
||||
**Format:** `L<line>: <problem>. <fix>.` — or `<file>:L<line>: ...` when reviewing multi-file diffs.
|
||||
|
||||
**Severity prefix (optional, when mixed):**
|
||||
- `🔴 bug:` — broken behavior, will cause incident
|
||||
- `🟡 risk:` — works but fragile (race, missing null check, swallowed error)
|
||||
- `🔵 nit:` — style, naming, micro-optim. Author can ignore
|
||||
- `❓ q:` — genuine question, not a suggestion
|
||||
|
||||
**Drop:**
|
||||
- "I noticed that...", "It seems like...", "You might want to consider..."
|
||||
- "This is just a suggestion but..." — use `nit:` instead
|
||||
- "Great work!", "Looks good overall but..." — say it once at the top, not per comment
|
||||
- Restating what the line does — the reviewer can read the diff
|
||||
- Hedging ("perhaps", "maybe", "I think") — if unsure use `q:`
|
||||
|
||||
**Keep:**
|
||||
- Exact line numbers
|
||||
- Exact symbol/function/variable names in backticks
|
||||
- Concrete fix, not "consider refactoring this"
|
||||
- The *why* if the fix isn't obvious from the problem statement
|
||||
|
||||
## Examples
|
||||
|
||||
❌ "I noticed that on line 42 you're not checking if the user object is null before accessing the email property. This could potentially cause a crash if the user is not found in the database. You might want to add a null check here."
|
||||
|
||||
✅ `L42: 🔴 bug: user can be null after .find(). Add guard before .email.`
|
||||
|
||||
❌ "It looks like this function is doing a lot of things and might benefit from being broken up into smaller functions for readability."
|
||||
|
||||
✅ `L88-140: 🔵 nit: 50-line fn does 4 things. Extract validate/normalize/persist.`
|
||||
|
||||
❌ "Have you considered what happens if the API returns a 429? I think we should probably handle that case."
|
||||
|
||||
✅ `L23: 🟡 risk: no retry on 429. Wrap in withBackoff(3).`
|
||||
|
||||
## Auto-Clarity
|
||||
|
||||
Drop terse mode for: security findings (CVE-class bugs need full explanation + reference), architectural disagreements (need rationale, not just a one-liner), and onboarding contexts where the author is new and needs the "why". In those cases write a normal paragraph, then resume terse for the rest.
|
||||
|
||||
## Boundaries
|
||||
|
||||
Reviews only — does not write the code fix, does not approve/request-changes, does not run linters. Output the comment(s) ready to paste into the PR. "stop caveman-review" or "normal mode": revert to verbose review style.
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: caveman-stats
|
||||
description: >
|
||||
Show real token usage and estimated savings for the current session.
|
||||
Reads directly from the Claude Code session log — no AI estimation.
|
||||
Triggers on /caveman-stats. Output is injected by the mode-tracker hook;
|
||||
the model itself does not compute the numbers.
|
||||
---
|
||||
|
||||
This skill is delivered by `hooks/caveman-stats.js` (read by `hooks/caveman-mode-tracker.js` on `/caveman-stats`). The model does not need to do anything when this skill fires — the hook returns `decision: "block"` with the formatted stats as the reason. The user sees the numbers immediately.
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: caveman
|
||||
description: >
|
||||
Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman
|
||||
while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra,
|
||||
wenyan-lite, wenyan-full, wenyan-ultra.
|
||||
Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens",
|
||||
"be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested.
|
||||
---
|
||||
|
||||
Respond terse like smart caveman. All technical substance stay. Only fluff die.
|
||||
|
||||
## Persistence
|
||||
|
||||
ACTIVE EVERY RESPONSE. No revert after many turns. No filler drift. Still active if unsure. Off only: "stop caveman" / "normal mode".
|
||||
|
||||
Default: **full**. Switch: `/caveman lite|full|ultra`.
|
||||
|
||||
## Rules
|
||||
|
||||
Drop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not "implement a solution for"). Technical terms exact. Code blocks unchanged. Errors quoted exact.
|
||||
|
||||
Pattern: `[thing] [action] [reason]. [next step].`
|
||||
|
||||
Not: "Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by..."
|
||||
Yes: "Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:"
|
||||
|
||||
## Intensity
|
||||
|
||||
| Level | What change |
|
||||
|-------|------------|
|
||||
| **lite** | No filler/hedging. Keep articles + full sentences. Professional but tight |
|
||||
| **full** | Drop articles, fragments OK, short synonyms. Classic caveman |
|
||||
| **ultra** | Abbreviate (DB/auth/config/req/res/fn/impl), strip conjunctions, arrows for causality (X → Y), one word when one word enough |
|
||||
| **wenyan-lite** | Semi-classical. Drop filler/hedging but keep grammar structure, classical register |
|
||||
| **wenyan-full** | Maximum classical terseness. Fully 文言文. 80-90% character reduction. Classical sentence patterns, verbs precede objects, subjects often omitted, classical particles (之/乃/為/其) |
|
||||
| **wenyan-ultra** | Extreme abbreviation while keeping classical Chinese feel. Maximum compression, ultra terse |
|
||||
|
||||
Example — "Why React component re-render?"
|
||||
- lite: "Your component re-renders because you create a new object reference each render. Wrap it in `useMemo`."
|
||||
- full: "New object ref each render. Inline object prop = new ref = re-render. Wrap in `useMemo`."
|
||||
- ultra: "Inline obj prop → new ref → re-render. `useMemo`."
|
||||
- wenyan-lite: "組件頻重繪,以每繪新生對象參照故。以 useMemo 包之。"
|
||||
- wenyan-full: "物出新參照,致重繪。useMemo .Wrap之。"
|
||||
- wenyan-ultra: "新參照→重繪。useMemo Wrap。"
|
||||
|
||||
Example — "Explain database connection pooling."
|
||||
- lite: "Connection pooling reuses open connections instead of creating new ones per request. Avoids repeated handshake overhead."
|
||||
- full: "Pool reuse open DB connections. No new connection per request. Skip handshake overhead."
|
||||
- ultra: "Pool = reuse DB conn. Skip handshake → fast under load."
|
||||
- wenyan-full: "池reuse open connection。不每req新開。skip handshake overhead。"
|
||||
- wenyan-ultra: "池reuse conn。skip handshake → fast。"
|
||||
|
||||
## Auto-Clarity
|
||||
|
||||
Drop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question. Resume caveman after clear part done.
|
||||
|
||||
Example — destructive op:
|
||||
> **Warning:** This will permanently delete all rows in the `users` table and cannot be undone.
|
||||
> ```sql
|
||||
> DROP TABLE users;
|
||||
> ```
|
||||
> Caveman resume. Verify backup exist first.
|
||||
|
||||
## Boundaries
|
||||
|
||||
Code/commits/PRs: write normal. "stop caveman" or "normal mode": revert. Level persist until changed or session end.
|
||||
@@ -0,0 +1,111 @@
|
||||
---
|
||||
name: compress
|
||||
description: >
|
||||
Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format
|
||||
to save input tokens. Preserves all technical substance, code, URLs, and structure.
|
||||
Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md.
|
||||
Trigger: /caveman:compress FILEPATH or "compress memory file"
|
||||
---
|
||||
|
||||
# Caveman Compress
|
||||
|
||||
## Purpose
|
||||
|
||||
Compress natural language files (CLAUDE.md, todos, preferences) into caveman-speak to reduce input tokens. Compressed version overwrites original. Human-readable backup saved as `<filename>.original.md`.
|
||||
|
||||
## Trigger
|
||||
|
||||
`/caveman:compress <filepath>` or when user asks to compress a memory file.
|
||||
|
||||
## Process
|
||||
|
||||
1. This SKILL.md lives alongside `scripts/` in the same directory. Find that directory.
|
||||
|
||||
2. Run:
|
||||
|
||||
cd <directory_containing_this_SKILL.md> && python3 -m scripts <absolute_filepath>
|
||||
|
||||
3. The CLI will:
|
||||
- detect file type (no tokens)
|
||||
- call Claude to compress
|
||||
- validate output (no tokens)
|
||||
- if errors: cherry-pick fix with Claude (targeted fixes only, no recompression)
|
||||
- retry up to 2 times
|
||||
- if still failing after 2 retries: report error to user, leave original file untouched
|
||||
|
||||
4. Return result to user
|
||||
|
||||
## Compression Rules
|
||||
|
||||
### Remove
|
||||
- Articles: a, an, the
|
||||
- Filler: just, really, basically, actually, simply, essentially, generally
|
||||
- Pleasantries: "sure", "certainly", "of course", "happy to", "I'd recommend"
|
||||
- Hedging: "it might be worth", "you could consider", "it would be good to"
|
||||
- Redundant phrasing: "in order to" → "to", "make sure to" → "ensure", "the reason is because" → "because"
|
||||
- Connective fluff: "however", "furthermore", "additionally", "in addition"
|
||||
|
||||
### Preserve EXACTLY (never modify)
|
||||
- Code blocks (fenced ``` and indented)
|
||||
- Inline code (`backtick content`)
|
||||
- URLs and links (full URLs, markdown links)
|
||||
- File paths (`/src/components/...`, `./config.yaml`)
|
||||
- Commands (`npm install`, `git commit`, `docker build`)
|
||||
- Technical terms (library names, API names, protocols, algorithms)
|
||||
- Proper nouns (project names, people, companies)
|
||||
- Dates, version numbers, numeric values
|
||||
- Environment variables (`$HOME`, `NODE_ENV`)
|
||||
|
||||
### Preserve Structure
|
||||
- All markdown headings (keep exact heading text, compress body below)
|
||||
- Bullet point hierarchy (keep nesting level)
|
||||
- Numbered lists (keep numbering)
|
||||
- Tables (compress cell text, keep structure)
|
||||
- Frontmatter/YAML headers in markdown files
|
||||
|
||||
### Compress
|
||||
- Use short synonyms: "big" not "extensive", "fix" not "implement a solution for", "use" not "utilize"
|
||||
- Fragments OK: "Run tests before commit" not "You should always run tests before committing"
|
||||
- Drop "you should", "make sure to", "remember to" — just state the action
|
||||
- Merge redundant bullets that say the same thing differently
|
||||
- Keep one example where multiple examples show the same pattern
|
||||
|
||||
CRITICAL RULE:
|
||||
Anything inside ``` ... ``` must be copied EXACTLY.
|
||||
Do not:
|
||||
- remove comments
|
||||
- remove spacing
|
||||
- reorder lines
|
||||
- shorten commands
|
||||
- simplify anything
|
||||
|
||||
Inline code (`...`) must be preserved EXACTLY.
|
||||
Do not modify anything inside backticks.
|
||||
|
||||
If file contains code blocks:
|
||||
- Treat code blocks as read-only regions
|
||||
- Only compress text outside them
|
||||
- Do not merge sections around code
|
||||
|
||||
## Pattern
|
||||
|
||||
Original:
|
||||
> You should always make sure to run the test suite before pushing any changes to the main branch. This is important because it helps catch bugs early and prevents broken builds from being deployed to production.
|
||||
|
||||
Compressed:
|
||||
> Run tests before push to main. Catch bugs early, prevent broken prod deploys.
|
||||
|
||||
Original:
|
||||
> The application uses a microservices architecture with the following components. The API gateway handles all incoming requests and routes them to the appropriate service. The authentication service is responsible for managing user sessions and JWT tokens.
|
||||
|
||||
Compressed:
|
||||
> Microservices architecture. API gateway route all requests to services. Auth service manage user sessions + JWT tokens.
|
||||
|
||||
## Boundaries
|
||||
|
||||
- ONLY compress natural language files (.md, .txt, .typ, .typst, .tex, extensionless)
|
||||
- NEVER modify: .py, .js, .ts, .json, .yaml, .yml, .toml, .env, .lock, .css, .html, .xml, .sql, .sh
|
||||
- If file has mixed content (prose + code), compress ONLY the prose sections
|
||||
- If unsure whether something is code or prose, leave it unchanged
|
||||
- Original file is backed up as FILE.original.md before overwriting
|
||||
- Never compress FILE.original.md (skip it)
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Caveman compress scripts.
|
||||
|
||||
This package provides tools to compress natural language markdown files
|
||||
into caveman format to save input tokens.
|
||||
"""
|
||||
|
||||
__all__ = ["cli", "compress", "detect", "validate"]
|
||||
|
||||
__version__ = "1.0.0"
|
||||
@@ -0,0 +1,3 @@
|
||||
from .cli import main
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
# Support both direct execution and module import
|
||||
try:
|
||||
from .validate import validate
|
||||
except ImportError:
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from validate import validate
|
||||
|
||||
try:
|
||||
import tiktoken
|
||||
_enc = tiktoken.get_encoding("o200k_base")
|
||||
except ImportError:
|
||||
_enc = None
|
||||
|
||||
|
||||
def count_tokens(text):
|
||||
if _enc is None:
|
||||
return len(text.split()) # fallback: word count
|
||||
return len(_enc.encode(text))
|
||||
|
||||
|
||||
def benchmark_pair(orig_path: Path, comp_path: Path):
|
||||
orig_text = orig_path.read_text()
|
||||
comp_text = comp_path.read_text()
|
||||
|
||||
orig_tokens = count_tokens(orig_text)
|
||||
comp_tokens = count_tokens(comp_text)
|
||||
saved = 100 * (orig_tokens - comp_tokens) / orig_tokens if orig_tokens > 0 else 0.0
|
||||
result = validate(orig_path, comp_path)
|
||||
|
||||
return (comp_path.name, orig_tokens, comp_tokens, saved, result.is_valid)
|
||||
|
||||
|
||||
def print_table(rows):
|
||||
print("\n| File | Original | Compressed | Saved % | Valid |")
|
||||
print("|------|----------|------------|---------|-------|")
|
||||
for r in rows:
|
||||
print(f"| {r[0]} | {r[1]} | {r[2]} | {r[3]:.1f}% | {'✅' if r[4] else '❌'} |")
|
||||
|
||||
|
||||
def main():
|
||||
# Direct file pair: python3 benchmark.py original.md compressed.md
|
||||
if len(sys.argv) == 3:
|
||||
orig = Path(sys.argv[1]).resolve()
|
||||
comp = Path(sys.argv[2]).resolve()
|
||||
if not orig.exists():
|
||||
print(f"❌ Not found: {orig}")
|
||||
sys.exit(1)
|
||||
if not comp.exists():
|
||||
print(f"❌ Not found: {comp}")
|
||||
sys.exit(1)
|
||||
print_table([benchmark_pair(orig, comp)])
|
||||
return
|
||||
|
||||
# Glob mode: repo_root/tests/caveman-compress/
|
||||
tests_dir = Path(__file__).parent.parent.parent / "tests" / "caveman-compress"
|
||||
if not tests_dir.exists():
|
||||
print(f"❌ Tests dir not found: {tests_dir}")
|
||||
sys.exit(1)
|
||||
|
||||
rows = []
|
||||
for orig in sorted(tests_dir.glob("*.original.md")):
|
||||
comp = orig.with_name(orig.stem.removesuffix(".original") + ".md")
|
||||
if comp.exists():
|
||||
rows.append(benchmark_pair(orig, comp))
|
||||
|
||||
if not rows:
|
||||
print("No compressed file pairs found.")
|
||||
return
|
||||
|
||||
print_table(rows)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Caveman Compress CLI
|
||||
|
||||
Usage:
|
||||
caveman <filepath>
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
# Force UTF-8 on stdout/stderr before any code can print. Windows consoles
|
||||
# default to cp1252 and crash on the ❌ glyphs in error/validation branches,
|
||||
# masking the real error and leaving the user with a half-compressed file.
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if callable(reconfigure):
|
||||
try:
|
||||
reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .compress import compress_file
|
||||
from .detect import detect_file_type, should_compress
|
||||
|
||||
|
||||
def print_usage():
|
||||
print("Usage: caveman <filepath>")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print_usage()
|
||||
sys.exit(1)
|
||||
|
||||
filepath = Path(sys.argv[1])
|
||||
|
||||
# Check file exists
|
||||
if not filepath.exists():
|
||||
print(f"❌ File not found: {filepath}")
|
||||
sys.exit(1)
|
||||
|
||||
if not filepath.is_file():
|
||||
print(f"❌ Not a file: {filepath}")
|
||||
sys.exit(1)
|
||||
|
||||
filepath = filepath.resolve()
|
||||
|
||||
# Detect file type
|
||||
file_type = detect_file_type(filepath)
|
||||
|
||||
print(f"Detected: {file_type}")
|
||||
|
||||
# Check if compressible
|
||||
if not should_compress(filepath):
|
||||
print("Skipping: file is not natural language (code/config)")
|
||||
sys.exit(0)
|
||||
|
||||
print("Starting caveman compression...\n")
|
||||
|
||||
try:
|
||||
success = compress_file(filepath)
|
||||
|
||||
if success:
|
||||
print("\nCompression completed successfully")
|
||||
backup_path = filepath.with_name(filepath.stem + ".original.md")
|
||||
print(f"Compressed: {filepath}")
|
||||
print(f"Original: {backup_path}")
|
||||
sys.exit(0)
|
||||
else:
|
||||
print("\n❌ Compression failed after retries")
|
||||
sys.exit(2)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\nInterrupted by user")
|
||||
sys.exit(130)
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ Error: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,254 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Caveman Memory Compression Orchestrator
|
||||
|
||||
Usage:
|
||||
python scripts/compress.py <filepath>
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
OUTER_FENCE_REGEX = re.compile(
|
||||
r"\A\s*(`{3,}|~{3,})[^\n]*\n(.*)\n\1\s*\Z", re.DOTALL
|
||||
)
|
||||
|
||||
# Filenames and paths that almost certainly hold secrets or PII. Compressing
|
||||
# them ships raw bytes to the Anthropic API — a third-party data boundary that
|
||||
# developers on sensitive codebases cannot cross. detect.py already skips .env
|
||||
# by extension, but credentials.md / secrets.txt / ~/.aws/credentials would
|
||||
# slip through the natural-language filter. This is a hard refuse before read.
|
||||
SENSITIVE_BASENAME_REGEX = re.compile(
|
||||
r"(?ix)^("
|
||||
r"\.env(\..+)?"
|
||||
r"|\.netrc"
|
||||
r"|credentials(\..+)?"
|
||||
r"|secrets?(\..+)?"
|
||||
r"|passwords?(\..+)?"
|
||||
r"|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?"
|
||||
r"|authorized_keys"
|
||||
r"|known_hosts"
|
||||
r"|.*\.(pem|key|p12|pfx|crt|cer|jks|keystore|asc|gpg)"
|
||||
r")$"
|
||||
)
|
||||
|
||||
SENSITIVE_PATH_COMPONENTS = frozenset({".ssh", ".aws", ".gnupg", ".kube", ".docker"})
|
||||
|
||||
SENSITIVE_NAME_TOKENS = (
|
||||
"secret", "credential", "password", "passwd",
|
||||
"apikey", "accesskey", "token", "privatekey",
|
||||
)
|
||||
|
||||
|
||||
def is_sensitive_path(filepath: Path) -> bool:
|
||||
"""Heuristic denylist for files that must never be shipped to a third-party API."""
|
||||
name = filepath.name
|
||||
if SENSITIVE_BASENAME_REGEX.match(name):
|
||||
return True
|
||||
lowered_parts = {p.lower() for p in filepath.parts}
|
||||
if lowered_parts & SENSITIVE_PATH_COMPONENTS:
|
||||
return True
|
||||
# Normalize separators so "api-key" and "api_key" both match "apikey".
|
||||
lower = re.sub(r"[_\-\s.]", "", name.lower())
|
||||
return any(tok in lower for tok in SENSITIVE_NAME_TOKENS)
|
||||
|
||||
|
||||
def strip_llm_wrapper(text: str) -> str:
|
||||
"""Strip outer ```markdown ... ``` fence when it wraps the entire output."""
|
||||
m = OUTER_FENCE_REGEX.match(text)
|
||||
if m:
|
||||
return m.group(2)
|
||||
return text
|
||||
|
||||
from .detect import should_compress
|
||||
from .validate import validate
|
||||
|
||||
MAX_RETRIES = 2
|
||||
|
||||
|
||||
# ---------- Claude Calls ----------
|
||||
|
||||
|
||||
def call_claude(prompt: str) -> str:
|
||||
api_key = os.environ.get("ANTHROPIC_API_KEY")
|
||||
if api_key:
|
||||
try:
|
||||
import anthropic
|
||||
|
||||
client = anthropic.Anthropic(api_key=api_key)
|
||||
msg = client.messages.create(
|
||||
model=os.environ.get("CAVEMAN_MODEL", "claude-sonnet-4-5"),
|
||||
max_tokens=8192,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
)
|
||||
return strip_llm_wrapper(msg.content[0].text.strip())
|
||||
except ImportError:
|
||||
pass # anthropic not installed, fall back to CLI
|
||||
# Fallback: use claude CLI (handles desktop auth)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["claude", "--print"],
|
||||
input=prompt,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
return strip_llm_wrapper(result.stdout.strip())
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError(f"Claude call failed:\n{e.stderr}")
|
||||
|
||||
|
||||
def build_compress_prompt(original: str) -> str:
|
||||
return f"""
|
||||
Compress this markdown into caveman format.
|
||||
|
||||
STRICT RULES:
|
||||
- Do NOT modify anything inside ``` code blocks
|
||||
- Do NOT modify anything inside inline backticks
|
||||
- Preserve ALL URLs exactly
|
||||
- Preserve ALL headings exactly
|
||||
- Preserve file paths and commands
|
||||
- Return ONLY the compressed markdown body — do NOT wrap the entire output in a ```markdown fence or any other fence. Inner code blocks from the original stay as-is; do not add a new outer fence around the whole file.
|
||||
|
||||
Only compress natural language.
|
||||
|
||||
TEXT:
|
||||
{original}
|
||||
"""
|
||||
|
||||
|
||||
def build_fix_prompt(original: str, compressed: str, errors: List[str]) -> str:
|
||||
errors_str = "\n".join(f"- {e}" for e in errors)
|
||||
return f"""You are fixing a caveman-compressed markdown file. Specific validation errors were found.
|
||||
|
||||
CRITICAL RULES:
|
||||
- DO NOT recompress or rephrase the file
|
||||
- ONLY fix the listed errors — leave everything else exactly as-is
|
||||
- The ORIGINAL is provided as reference only (to restore missing content)
|
||||
- Preserve caveman style in all untouched sections
|
||||
|
||||
ERRORS TO FIX:
|
||||
{errors_str}
|
||||
|
||||
HOW TO FIX:
|
||||
- Missing URL: find it in ORIGINAL, restore it exactly where it belongs in COMPRESSED
|
||||
- Code block mismatch: find the exact code block in ORIGINAL, restore it in COMPRESSED
|
||||
- Heading mismatch: restore the exact heading text from ORIGINAL into COMPRESSED
|
||||
- Do not touch any section not mentioned in the errors
|
||||
|
||||
ORIGINAL (reference only):
|
||||
{original}
|
||||
|
||||
COMPRESSED (fix this):
|
||||
{compressed}
|
||||
|
||||
Return ONLY the fixed compressed file. No explanation.
|
||||
"""
|
||||
|
||||
|
||||
# ---------- Core Logic ----------
|
||||
|
||||
|
||||
def compress_file(filepath: Path) -> bool:
|
||||
# Resolve and validate path
|
||||
filepath = filepath.resolve()
|
||||
MAX_FILE_SIZE = 500_000 # 500KB
|
||||
if not filepath.exists():
|
||||
raise FileNotFoundError(f"File not found: {filepath}")
|
||||
if filepath.stat().st_size > MAX_FILE_SIZE:
|
||||
raise ValueError(f"File too large to compress safely (max 500KB): {filepath}")
|
||||
|
||||
# Refuse files that look like they contain secrets or PII. Compressing ships
|
||||
# the raw bytes to the Anthropic API — a third-party boundary — so we fail
|
||||
# loudly rather than silently exfiltrate credentials or keys. Override is
|
||||
# intentional: the user must rename the file if the heuristic is wrong.
|
||||
if is_sensitive_path(filepath):
|
||||
raise ValueError(
|
||||
f"Refusing to compress {filepath}: filename looks sensitive "
|
||||
"(credentials, keys, secrets, or known private paths). "
|
||||
"Compression sends file contents to the Anthropic API. "
|
||||
"Rename the file if this is a false positive."
|
||||
)
|
||||
|
||||
print(f"Processing: {filepath}")
|
||||
|
||||
if not should_compress(filepath):
|
||||
print("Skipping (not natural language)")
|
||||
return False
|
||||
|
||||
original_text = filepath.read_text(errors="ignore")
|
||||
backup_path = filepath.with_name(filepath.stem + ".original.md")
|
||||
|
||||
if not original_text.strip():
|
||||
print("❌ Refusing to compress: file is empty or whitespace-only.")
|
||||
return False
|
||||
|
||||
# Check if backup already exists to prevent accidental overwriting
|
||||
if backup_path.exists():
|
||||
print(f"⚠️ Backup file already exists: {backup_path}")
|
||||
print("The original backup may contain important content.")
|
||||
print("Aborting to prevent data loss. Please remove or rename the backup file if you want to proceed.")
|
||||
return False
|
||||
|
||||
# Step 1: Compress
|
||||
print("Compressing with Claude...")
|
||||
compressed = call_claude(build_compress_prompt(original_text))
|
||||
|
||||
if compressed is None or not compressed.strip():
|
||||
print("❌ Compression aborted: Claude returned an empty response.")
|
||||
print(" Original file is untouched (no backup created).")
|
||||
return False
|
||||
|
||||
if compressed.strip() == original_text.strip():
|
||||
print("❌ Compression aborted: output is identical to input.")
|
||||
print(" Likely causes: Claude refused, returned the prompt verbatim, or the file is")
|
||||
print(" already in caveman form. Original file is untouched (no backup created).")
|
||||
return False
|
||||
|
||||
# Save original as backup, then verify the backup readback before
|
||||
# touching the input file. If the filesystem dropped bytes (encoding,
|
||||
# antivirus, disk full), unlink the bad backup and abort instead of
|
||||
# leaving the user with a corrupt backup + compressed primary.
|
||||
backup_path.write_text(original_text)
|
||||
backup_readback = backup_path.read_text(errors="ignore")
|
||||
if backup_readback != original_text:
|
||||
print(f"❌ Backup write verification failed: {backup_path}")
|
||||
print(" In-memory original differs from on-disk backup. Aborting before touching the input file.")
|
||||
try:
|
||||
backup_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return False
|
||||
filepath.write_text(compressed)
|
||||
|
||||
# Step 2: Validate + Retry
|
||||
for attempt in range(MAX_RETRIES):
|
||||
print(f"\nValidation attempt {attempt + 1}")
|
||||
|
||||
result = validate(backup_path, filepath)
|
||||
|
||||
if result.is_valid:
|
||||
print("Validation passed")
|
||||
break
|
||||
|
||||
print("❌ Validation failed:")
|
||||
for err in result.errors:
|
||||
print(f" - {err}")
|
||||
|
||||
if attempt == MAX_RETRIES - 1:
|
||||
# Restore original on failure
|
||||
filepath.write_text(original_text)
|
||||
backup_path.unlink(missing_ok=True)
|
||||
print("❌ Failed after retries — original restored")
|
||||
return False
|
||||
|
||||
print("Fixing with Claude...")
|
||||
compressed = call_claude(
|
||||
build_fix_prompt(original_text, compressed, result.errors)
|
||||
)
|
||||
filepath.write_text(compressed)
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Detect whether a file is natural language (compressible) or code/config (skip)."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
# Extensions that are natural language and compressible
|
||||
COMPRESSIBLE_EXTENSIONS = {".md", ".txt", ".markdown", ".rst", ".typ", ".typst", ".tex"}
|
||||
|
||||
# Extensions that are code/config and should be skipped
|
||||
SKIP_EXTENSIONS = {
|
||||
".py", ".js", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml",
|
||||
".toml", ".env", ".lock", ".css", ".scss", ".html", ".xml",
|
||||
".sql", ".sh", ".bash", ".zsh", ".go", ".rs", ".java", ".c",
|
||||
".cpp", ".h", ".hpp", ".rb", ".php", ".swift", ".kt", ".lua",
|
||||
".dockerfile", ".makefile", ".csv", ".ini", ".cfg",
|
||||
}
|
||||
|
||||
# Patterns that indicate a line is code
|
||||
CODE_PATTERNS = [
|
||||
re.compile(r"^\s*(import |from .+ import |require\(|const |let |var )"),
|
||||
re.compile(r"^\s*(def |class |function |async function |export )"),
|
||||
re.compile(r"^\s*(if\s*\(|for\s*\(|while\s*\(|switch\s*\(|try\s*\{)"),
|
||||
re.compile(r"^\s*[\}\]\);]+\s*$"), # closing braces/brackets
|
||||
re.compile(r"^\s*@\w+"), # decorators/annotations
|
||||
re.compile(r'^\s*"[^"]+"\s*:\s*'), # JSON-like key-value
|
||||
re.compile(r"^\s*\w+\s*=\s*[{\[\(\"']"), # assignment with literal
|
||||
]
|
||||
|
||||
|
||||
def _is_code_line(line: str) -> bool:
|
||||
"""Check if a line looks like code."""
|
||||
return any(p.match(line) for p in CODE_PATTERNS)
|
||||
|
||||
|
||||
def _is_json_content(text: str) -> bool:
|
||||
"""Check if content is valid JSON."""
|
||||
try:
|
||||
json.loads(text)
|
||||
return True
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def _is_yaml_content(lines: list[str]) -> bool:
|
||||
"""Heuristic: check if content looks like YAML."""
|
||||
yaml_indicators = 0
|
||||
for line in lines[:30]:
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("---"):
|
||||
yaml_indicators += 1
|
||||
elif re.match(r"^\w[\w\s]*:\s", stripped):
|
||||
yaml_indicators += 1
|
||||
elif stripped.startswith("- ") and ":" in stripped:
|
||||
yaml_indicators += 1
|
||||
# If most non-empty lines look like YAML
|
||||
non_empty = sum(1 for l in lines[:30] if l.strip())
|
||||
return non_empty > 0 and yaml_indicators / non_empty > 0.6
|
||||
|
||||
|
||||
def detect_file_type(filepath: Path) -> str:
|
||||
"""Classify a file as 'natural_language', 'code', 'config', or 'unknown'.
|
||||
|
||||
Returns:
|
||||
One of: 'natural_language', 'code', 'config', 'unknown'
|
||||
"""
|
||||
ext = filepath.suffix.lower()
|
||||
|
||||
# Extension-based classification
|
||||
if ext in COMPRESSIBLE_EXTENSIONS:
|
||||
return "natural_language"
|
||||
if ext in SKIP_EXTENSIONS:
|
||||
return "code" if ext not in {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".env"} else "config"
|
||||
|
||||
# Extensionless files (like CLAUDE.md, TODO) — check content
|
||||
if not ext:
|
||||
try:
|
||||
text = filepath.read_text(errors="ignore")
|
||||
except (OSError, PermissionError):
|
||||
return "unknown"
|
||||
|
||||
lines = text.splitlines()[:50]
|
||||
|
||||
if _is_json_content(text[:10000]):
|
||||
return "config"
|
||||
if _is_yaml_content(lines):
|
||||
return "config"
|
||||
|
||||
code_lines = sum(1 for l in lines if l.strip() and _is_code_line(l))
|
||||
non_empty = sum(1 for l in lines if l.strip())
|
||||
if non_empty > 0 and code_lines / non_empty > 0.4:
|
||||
return "code"
|
||||
|
||||
return "natural_language"
|
||||
|
||||
return "unknown"
|
||||
|
||||
|
||||
def should_compress(filepath: Path) -> bool:
|
||||
"""Return True if the file is natural language and should be compressed."""
|
||||
if not filepath.is_file():
|
||||
return False
|
||||
# Skip backup files
|
||||
if filepath.name.endswith(".original.md"):
|
||||
return False
|
||||
return detect_file_type(filepath) == "natural_language"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python detect.py <file1> [file2] ...")
|
||||
sys.exit(1)
|
||||
|
||||
for path_str in sys.argv[1:]:
|
||||
p = Path(path_str).resolve()
|
||||
file_type = detect_file_type(p)
|
||||
compress = should_compress(p)
|
||||
print(f" {p.name:30s} type={file_type:20s} compress={compress}")
|
||||
@@ -0,0 +1,213 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
URL_REGEX = re.compile(r"https?://[^\s)]+")
|
||||
FENCE_OPEN_REGEX = re.compile(r"^(\s{0,3})(`{3,}|~{3,})(.*)$")
|
||||
HEADING_REGEX = re.compile(r"^(#{1,6})\s+(.*)", re.MULTILINE)
|
||||
BULLET_REGEX = re.compile(r"^\s*[-*+]\s+", re.MULTILINE)
|
||||
|
||||
# crude but effective path detection
|
||||
# Requires either a path prefix (./ ../ / or drive letter) or a slash/backslash within the match
|
||||
PATH_REGEX = re.compile(r"(?:\./|\.\./|/|[A-Za-z]:\\)[\w\-/\\\.]+|[\w\-\.]+[/\\][\w\-/\\\.]+")
|
||||
|
||||
|
||||
class ValidationResult:
|
||||
def __init__(self):
|
||||
self.is_valid = True
|
||||
self.errors = []
|
||||
self.warnings = []
|
||||
|
||||
def add_error(self, msg):
|
||||
self.is_valid = False
|
||||
self.errors.append(msg)
|
||||
|
||||
def add_warning(self, msg):
|
||||
self.warnings.append(msg)
|
||||
|
||||
|
||||
def read_file(path: Path) -> str:
|
||||
return path.read_text(errors="ignore")
|
||||
|
||||
|
||||
# ---------- Extractors ----------
|
||||
|
||||
|
||||
def extract_headings(text):
|
||||
return [(level, title.strip()) for level, title in HEADING_REGEX.findall(text)]
|
||||
|
||||
|
||||
def extract_code_blocks(text):
|
||||
"""Line-based fenced code block extractor.
|
||||
|
||||
Handles ``` and ~~~ fences with variable length (CommonMark: closing
|
||||
fence must use same char and be at least as long as opening). Supports
|
||||
nested fences (e.g. an outer 4-backtick block wrapping inner 3-backtick
|
||||
content).
|
||||
"""
|
||||
blocks = []
|
||||
lines = text.split("\n")
|
||||
i = 0
|
||||
n = len(lines)
|
||||
while i < n:
|
||||
m = FENCE_OPEN_REGEX.match(lines[i])
|
||||
if not m:
|
||||
i += 1
|
||||
continue
|
||||
fence_char = m.group(2)[0]
|
||||
fence_len = len(m.group(2))
|
||||
open_line = lines[i]
|
||||
block_lines = [open_line]
|
||||
i += 1
|
||||
closed = False
|
||||
while i < n:
|
||||
close_m = FENCE_OPEN_REGEX.match(lines[i])
|
||||
if (
|
||||
close_m
|
||||
and close_m.group(2)[0] == fence_char
|
||||
and len(close_m.group(2)) >= fence_len
|
||||
and close_m.group(3).strip() == ""
|
||||
):
|
||||
block_lines.append(lines[i])
|
||||
closed = True
|
||||
i += 1
|
||||
break
|
||||
block_lines.append(lines[i])
|
||||
i += 1
|
||||
if closed:
|
||||
blocks.append("\n".join(block_lines))
|
||||
# Unclosed fences are silently skipped — they indicate malformed markdown
|
||||
# and including them would cause false-positive validation failures.
|
||||
return blocks
|
||||
|
||||
|
||||
def extract_urls(text):
|
||||
return set(URL_REGEX.findall(text))
|
||||
|
||||
|
||||
def extract_paths(text):
|
||||
return set(PATH_REGEX.findall(text))
|
||||
|
||||
|
||||
def count_bullets(text):
|
||||
return len(BULLET_REGEX.findall(text))
|
||||
|
||||
|
||||
def extract_inline_codes(text):
|
||||
text_without_fences = re.sub(r"^```[\s\S]*?^```", "", text, flags=re.MULTILINE)
|
||||
text_without_fences = re.sub(r"^~~~[\s\S]*?^~~~", "", text_without_fences, flags=re.MULTILINE)
|
||||
return re.findall(r"`([^`]+)`", text_without_fences)
|
||||
|
||||
|
||||
# ---------- Validators ----------
|
||||
|
||||
|
||||
def validate_headings(orig, comp, result):
|
||||
h1 = extract_headings(orig)
|
||||
h2 = extract_headings(comp)
|
||||
|
||||
if len(h1) != len(h2):
|
||||
result.add_error(f"Heading count mismatch: {len(h1)} vs {len(h2)}")
|
||||
|
||||
if h1 != h2:
|
||||
result.add_warning("Heading text/order changed")
|
||||
|
||||
|
||||
def validate_code_blocks(orig, comp, result):
|
||||
c1 = extract_code_blocks(orig)
|
||||
c2 = extract_code_blocks(comp)
|
||||
|
||||
if c1 != c2:
|
||||
result.add_error("Code blocks not preserved exactly")
|
||||
|
||||
|
||||
def validate_urls(orig, comp, result):
|
||||
u1 = extract_urls(orig)
|
||||
u2 = extract_urls(comp)
|
||||
|
||||
if u1 != u2:
|
||||
result.add_error(f"URL mismatch: lost={u1 - u2}, added={u2 - u1}")
|
||||
|
||||
|
||||
def validate_paths(orig, comp, result):
|
||||
p1 = extract_paths(orig)
|
||||
p2 = extract_paths(comp)
|
||||
|
||||
if p1 != p2:
|
||||
result.add_warning(f"Path mismatch: lost={p1 - p2}, added={p2 - p1}")
|
||||
|
||||
|
||||
def validate_bullets(orig, comp, result):
|
||||
b1 = count_bullets(orig)
|
||||
b2 = count_bullets(comp)
|
||||
|
||||
if b1 == 0:
|
||||
return
|
||||
|
||||
diff = abs(b1 - b2) / b1
|
||||
|
||||
if diff > 0.15:
|
||||
result.add_warning(f"Bullet count changed too much: {b1} -> {b2}")
|
||||
|
||||
|
||||
def validate_inline_codes(orig, comp, result):
|
||||
c1 = Counter(extract_inline_codes(orig))
|
||||
c2 = Counter(extract_inline_codes(comp))
|
||||
|
||||
if c1 != c2:
|
||||
lost = set(c1.keys()) - set(c2.keys())
|
||||
added = set(c2.keys()) - set(c1.keys())
|
||||
for code, count in c1.items():
|
||||
if code in c2 and c2[code] < count:
|
||||
lost.add(f"{code} (lost {count - c2[code]} of {count} occurrences)")
|
||||
if lost:
|
||||
result.add_error(f"Inline code lost: {lost}")
|
||||
if added:
|
||||
result.add_warning(f"Inline code added: {added}")
|
||||
|
||||
|
||||
# ---------- Main ----------
|
||||
|
||||
|
||||
def validate(original_path: Path, compressed_path: Path) -> ValidationResult:
|
||||
result = ValidationResult()
|
||||
|
||||
orig = read_file(original_path)
|
||||
comp = read_file(compressed_path)
|
||||
|
||||
validate_headings(orig, comp, result)
|
||||
validate_code_blocks(orig, comp, result)
|
||||
validate_urls(orig, comp, result)
|
||||
validate_paths(orig, comp, result)
|
||||
validate_bullets(orig, comp, result)
|
||||
validate_inline_codes(orig, comp, result)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ---------- CLI ----------
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
if len(sys.argv) != 3:
|
||||
print("Usage: python validate.py <original> <compressed>")
|
||||
sys.exit(1)
|
||||
|
||||
orig = Path(sys.argv[1]).resolve()
|
||||
comp = Path(sys.argv[2]).resolve()
|
||||
|
||||
res = validate(orig, comp)
|
||||
|
||||
print(f"\nValid: {res.is_valid}")
|
||||
|
||||
if res.errors:
|
||||
print("\nErrors:")
|
||||
for e in res.errors:
|
||||
print(f" - {e}")
|
||||
|
||||
if res.warnings:
|
||||
print("\nWarnings:")
|
||||
for w in res.warnings:
|
||||
print(f" - {w}")
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
name: diagnose
|
||||
description: Disciplined diagnosis loop for hard bugs and performance regressions. Reproduce → minimise → hypothesise → instrument → fix → regression-test. Use when user says "diagnose this" / "debug this", reports a bug, says something is broken/throwing/failing, or describes a performance regression.
|
||||
---
|
||||
|
||||
# Diagnose
|
||||
|
||||
A discipline for hard bugs. Skip phases only when explicitly justified.
|
||||
|
||||
When exploring the codebase, use the project's domain glossary to get a clear mental model of the relevant modules, and check ADRs in the area you're touching.
|
||||
|
||||
## Phase 1 — Build a feedback loop
|
||||
|
||||
**This is the skill.** Everything else is mechanical. If you have a fast, deterministic, agent-runnable pass/fail signal for the bug, you will find the cause — bisection, hypothesis-testing, and instrumentation all just consume that signal. If you don't have one, no amount of staring at code will save you.
|
||||
|
||||
Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.**
|
||||
|
||||
### Ways to construct one — try them in roughly this order
|
||||
|
||||
1. **Failing test** at whatever seam reaches the bug — unit, integration, e2e.
|
||||
2. **Curl / HTTP script** against a running dev server.
|
||||
3. **CLI invocation** with a fixture input, diffing stdout against a known-good snapshot.
|
||||
4. **Headless browser script** (Playwright / Puppeteer) — drives the UI, asserts on DOM/console/network.
|
||||
5. **Replay a captured trace.** Save a real network request / payload / event log to disk; replay it through the code path in isolation.
|
||||
6. **Throwaway harness.** Spin up a minimal subset of the system (one service, mocked deps) that exercises the bug code path with a single function call.
|
||||
7. **Property / fuzz loop.** If the bug is "sometimes wrong output", run 1000 random inputs and look for the failure mode.
|
||||
8. **Bisection harness.** If the bug appeared between two known states (commit, dataset, version), automate "boot at state X, check, repeat" so you can `git bisect run` it.
|
||||
9. **Differential loop.** Run the same input through old-version vs new-version (or two configs) and diff outputs.
|
||||
10. **HITL bash script.** Last resort. If a human must click, drive _them_ with `scripts/hitl-loop.template.sh` so the loop is still structured. Captured output feeds back to you.
|
||||
|
||||
Build the right feedback loop, and the bug is 90% fixed.
|
||||
|
||||
### Iterate on the loop itself
|
||||
|
||||
Treat the loop as a product. Once you have _a_ loop, ask:
|
||||
|
||||
- Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.)
|
||||
- Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".)
|
||||
- Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.)
|
||||
|
||||
A 30-second flaky loop is barely better than no loop. A 2-second deterministic loop is a debugging superpower.
|
||||
|
||||
### Non-deterministic bugs
|
||||
|
||||
The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not — keep raising the rate until it's debuggable.
|
||||
|
||||
### When you genuinely cannot build a loop
|
||||
|
||||
Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop.
|
||||
|
||||
Do not proceed to Phase 2 until you have a loop you believe in.
|
||||
|
||||
## Phase 2 — Reproduce
|
||||
|
||||
Run the loop. Watch the bug appear.
|
||||
|
||||
Confirm:
|
||||
|
||||
- [ ] The loop produces the failure mode the **user** described — not a different failure that happens to be nearby. Wrong bug = wrong fix.
|
||||
- [ ] The failure is reproducible across multiple runs (or, for non-deterministic bugs, reproducible at a high enough rate to debug against).
|
||||
- [ ] You have captured the exact symptom (error message, wrong output, slow timing) so later phases can verify the fix actually addresses it.
|
||||
|
||||
Do not proceed until you reproduce the bug.
|
||||
|
||||
## Phase 3 — Hypothesise
|
||||
|
||||
Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea.
|
||||
|
||||
Each hypothesis must be **falsifiable**: state the prediction it makes.
|
||||
|
||||
> Format: "If <X> is the cause, then <changing Y> will make the bug disappear / <changing Z> will make it worse."
|
||||
|
||||
If you cannot state the prediction, the hypothesis is a vibe — discard or sharpen it.
|
||||
|
||||
**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it — proceed with your ranking if the user is AFK.
|
||||
|
||||
## Phase 4 — Instrument
|
||||
|
||||
Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.**
|
||||
|
||||
Tool preference:
|
||||
|
||||
1. **Debugger / REPL inspection** if the env supports it. One breakpoint beats ten logs.
|
||||
2. **Targeted logs** at the boundaries that distinguish hypotheses.
|
||||
3. Never "log everything and grep".
|
||||
|
||||
**Tag every debug log** with a unique prefix, e.g. `[DEBUG-a4f2]`. Cleanup at the end becomes a single grep. Untagged logs survive; tagged logs die.
|
||||
|
||||
**Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second.
|
||||
|
||||
## Phase 5 — Fix + regression test
|
||||
|
||||
Write the regression test **before the fix** — but only if there is a **correct seam** for it.
|
||||
|
||||
A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence.
|
||||
|
||||
**If no correct seam exists, that itself is the finding.** Note it. The codebase architecture is preventing the bug from being locked down. Flag this for the next phase.
|
||||
|
||||
If a correct seam exists:
|
||||
|
||||
1. Turn the minimised repro into a failing test at that seam.
|
||||
2. Watch it fail.
|
||||
3. Apply the fix.
|
||||
4. Watch it pass.
|
||||
5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario.
|
||||
|
||||
## Phase 6 — Cleanup + post-mortem
|
||||
|
||||
Required before declaring done:
|
||||
|
||||
- [ ] Original repro no longer reproduces (re-run the Phase 1 loop)
|
||||
- [ ] Regression test passes (or absence of seam is documented)
|
||||
- [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix)
|
||||
- [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location)
|
||||
- [ ] The hypothesis that turned out correct is stated in the commit / PR message — so the next debugger learns
|
||||
|
||||
**Then ask: what would have prevented this bug?** If the answer involves architectural change (no good test seam, tangled callers, hidden coupling) hand off to the `/improve-codebase-architecture` skill with the specifics. Make the recommendation **after** the fix is in, not before — you have more information now than when you started.
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
# Human-in-the-loop reproduction loop.
|
||||
# Copy this file, edit the steps below, and run it.
|
||||
# The agent runs the script; the user follows prompts in their terminal.
|
||||
#
|
||||
# Usage:
|
||||
# bash hitl-loop.template.sh
|
||||
#
|
||||
# Two helpers:
|
||||
# step "<instruction>" → show instruction, wait for Enter
|
||||
# capture VAR "<question>" → show question, read response into VAR
|
||||
#
|
||||
# At the end, captured values are printed as KEY=VALUE for the agent to parse.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
step() {
|
||||
printf '\n>>> %s\n' "$1"
|
||||
read -r -p " [Enter when done] " _
|
||||
}
|
||||
|
||||
capture() {
|
||||
local var="$1" question="$2" answer
|
||||
printf '\n>>> %s\n' "$question"
|
||||
read -r -p " > " answer
|
||||
printf -v "$var" '%s' "$answer"
|
||||
}
|
||||
|
||||
# --- edit below ---------------------------------------------------------
|
||||
|
||||
step "Open the app at http://localhost:3000 and sign in."
|
||||
|
||||
capture ERRORED "Click the 'Export' button. Did it throw an error? (y/n)"
|
||||
|
||||
capture ERROR_MSG "Paste the error message (or 'none'):"
|
||||
|
||||
# --- edit above ---------------------------------------------------------
|
||||
|
||||
printf '\n--- Captured ---\n'
|
||||
printf 'ERRORED=%s\n' "$ERRORED"
|
||||
printf 'ERROR_MSG=%s\n' "$ERROR_MSG"
|
||||
@@ -0,0 +1,142 @@
|
||||
---
|
||||
name: find-skills
|
||||
description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
|
||||
---
|
||||
|
||||
# Find Skills
|
||||
|
||||
This skill helps you discover and install skills from the open agent skills ecosystem.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use this skill when the user:
|
||||
|
||||
- Asks "how do I do X" where X might be a common task with an existing skill
|
||||
- Says "find a skill for X" or "is there a skill for X"
|
||||
- Asks "can you do X" where X is a specialized capability
|
||||
- Expresses interest in extending agent capabilities
|
||||
- Wants to search for tools, templates, or workflows
|
||||
- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.)
|
||||
|
||||
## What is the Skills CLI?
|
||||
|
||||
The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools.
|
||||
|
||||
**Key commands:**
|
||||
|
||||
- `npx skills find [query]` - Search for skills interactively or by keyword
|
||||
- `npx skills add <package>` - Install a skill from GitHub or other sources
|
||||
- `npx skills check` - Check for skill updates
|
||||
- `npx skills update` - Update all installed skills
|
||||
|
||||
**Browse skills at:** https://skills.sh/
|
||||
|
||||
## How to Help Users Find Skills
|
||||
|
||||
### Step 1: Understand What They Need
|
||||
|
||||
When a user asks for help with something, identify:
|
||||
|
||||
1. The domain (e.g., React, testing, design, deployment)
|
||||
2. The specific task (e.g., writing tests, creating animations, reviewing PRs)
|
||||
3. Whether this is a common enough task that a skill likely exists
|
||||
|
||||
### Step 2: Check the Leaderboard First
|
||||
|
||||
Before running a CLI search, check the [skills.sh leaderboard](https://skills.sh/) to see if a well-known skill already exists for the domain. The leaderboard ranks skills by total installs, surfacing the most popular and battle-tested options.
|
||||
|
||||
For example, top skills for web development include:
|
||||
- `vercel-labs/agent-skills` — React, Next.js, web design (100K+ installs each)
|
||||
- `anthropics/skills` — Frontend design, document processing (100K+ installs)
|
||||
|
||||
### Step 3: Search for Skills
|
||||
|
||||
If the leaderboard doesn't cover the user's need, run the find command:
|
||||
|
||||
```bash
|
||||
npx skills find [query]
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
- User asks "how do I make my React app faster?" → `npx skills find react performance`
|
||||
- User asks "can you help me with PR reviews?" → `npx skills find pr review`
|
||||
- User asks "I need to create a changelog" → `npx skills find changelog`
|
||||
|
||||
### Step 4: Verify Quality Before Recommending
|
||||
|
||||
**Do not recommend a skill based solely on search results.** Always verify:
|
||||
|
||||
1. **Install count** — Prefer skills with 1K+ installs. Be cautious with anything under 100.
|
||||
2. **Source reputation** — Official sources (`vercel-labs`, `anthropics`, `microsoft`) are more trustworthy than unknown authors.
|
||||
3. **GitHub stars** — Check the source repository. A skill from a repo with <100 stars should be treated with skepticism.
|
||||
|
||||
### Step 5: Present Options to the User
|
||||
|
||||
When you find relevant skills, present them to the user with:
|
||||
|
||||
1. The skill name and what it does
|
||||
2. The install count and source
|
||||
3. The install command they can run
|
||||
4. A link to learn more at skills.sh
|
||||
|
||||
Example response:
|
||||
|
||||
```
|
||||
I found a skill that might help! The "react-best-practices" skill provides
|
||||
React and Next.js performance optimization guidelines from Vercel Engineering.
|
||||
(185K installs)
|
||||
|
||||
To install it:
|
||||
npx skills add vercel-labs/agent-skills@react-best-practices
|
||||
|
||||
Learn more: https://skills.sh/vercel-labs/agent-skills/react-best-practices
|
||||
```
|
||||
|
||||
### Step 6: Offer to Install
|
||||
|
||||
If the user wants to proceed, you can install the skill for them:
|
||||
|
||||
```bash
|
||||
npx skills add <owner/repo@skill> -g -y
|
||||
```
|
||||
|
||||
The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts.
|
||||
|
||||
## Common Skill Categories
|
||||
|
||||
When searching, consider these common categories:
|
||||
|
||||
| Category | Example Queries |
|
||||
| --------------- | ---------------------------------------- |
|
||||
| Web Development | react, nextjs, typescript, css, tailwind |
|
||||
| Testing | testing, jest, playwright, e2e |
|
||||
| DevOps | deploy, docker, kubernetes, ci-cd |
|
||||
| Documentation | docs, readme, changelog, api-docs |
|
||||
| Code Quality | review, lint, refactor, best-practices |
|
||||
| Design | ui, ux, design-system, accessibility |
|
||||
| Productivity | workflow, automation, git |
|
||||
|
||||
## Tips for Effective Searches
|
||||
|
||||
1. **Use specific keywords**: "react testing" is better than just "testing"
|
||||
2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd"
|
||||
3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills`
|
||||
|
||||
## When No Skills Are Found
|
||||
|
||||
If no relevant skills exist:
|
||||
|
||||
1. Acknowledge that no existing skill was found
|
||||
2. Offer to help with the task directly using your general capabilities
|
||||
3. Suggest the user could create their own skill with `npx skills init`
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
I searched for skills related to "xyz" but didn't find any matches.
|
||||
I can still help you with this task directly! Would you like me to proceed?
|
||||
|
||||
If this is something you do often, you could create your own skill:
|
||||
npx skills init my-xyz-skill
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
0.7.13
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: grill-me
|
||||
description: Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree. Use when user wants to stress-test a plan, get grilled on their design, or mentions "grill me".
|
||||
---
|
||||
|
||||
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
|
||||
|
||||
Ask the questions one at a time.
|
||||
|
||||
If a question can be answered by exploring the codebase, explore the codebase instead.
|
||||
@@ -0,0 +1,47 @@
|
||||
# ADR Format
|
||||
|
||||
ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
|
||||
|
||||
Create the `docs/adr/` directory lazily — only when the first ADR is needed.
|
||||
|
||||
## Template
|
||||
|
||||
```md
|
||||
# {Short title of the decision}
|
||||
|
||||
{1-3 sentences: what's the context, what did we decide, and why.}
|
||||
```
|
||||
|
||||
That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why* — not in filling out sections.
|
||||
|
||||
## Optional sections
|
||||
|
||||
Only include these when they add genuine value. Most ADRs won't need them.
|
||||
|
||||
- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`) — useful when decisions are revisited
|
||||
- **Considered Options** — only when the rejected alternatives are worth remembering
|
||||
- **Consequences** — only when non-obvious downstream effects need to be called out
|
||||
|
||||
## Numbering
|
||||
|
||||
Scan `docs/adr/` for the highest existing number and increment by one.
|
||||
|
||||
## When to offer an ADR
|
||||
|
||||
All three of these must be true:
|
||||
|
||||
1. **Hard to reverse** — the cost of changing your mind later is meaningful
|
||||
2. **Surprising without context** — a future reader will look at the code and wonder "why on earth did they do it this way?"
|
||||
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
|
||||
|
||||
If a decision is easy to reverse, skip it — you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
|
||||
|
||||
### What qualifies
|
||||
|
||||
- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
|
||||
- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
|
||||
- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library — just the ones that would take a quarter to swap out.
|
||||
- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
|
||||
- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
|
||||
- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
|
||||
- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it — otherwise someone will suggest GraphQL again in six months.
|
||||
@@ -0,0 +1,77 @@
|
||||
# CONTEXT.md Format
|
||||
|
||||
## Structure
|
||||
|
||||
```md
|
||||
# {Context Name}
|
||||
|
||||
{One or two sentence description of what this context is and why it exists.}
|
||||
|
||||
## Language
|
||||
|
||||
**Order**:
|
||||
{A concise description of the term}
|
||||
_Avoid_: Purchase, transaction
|
||||
|
||||
**Invoice**:
|
||||
A request for payment sent to a customer after delivery.
|
||||
_Avoid_: Bill, payment request
|
||||
|
||||
**Customer**:
|
||||
A person or organization that places orders.
|
||||
_Avoid_: Client, buyer, account
|
||||
|
||||
## Relationships
|
||||
|
||||
- An **Order** produces one or more **Invoices**
|
||||
- An **Invoice** belongs to exactly one **Customer**
|
||||
|
||||
## Example dialogue
|
||||
|
||||
> **Dev:** "When a **Customer** places an **Order**, do we create the **Invoice** immediately?"
|
||||
> **Domain expert:** "No — an **Invoice** is only generated once a **Fulfillment** is confirmed."
|
||||
|
||||
## Flagged ambiguities
|
||||
|
||||
- "account" was used to mean both **Customer** and **User** — resolved: these are distinct concepts.
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others as aliases to avoid.
|
||||
- **Flag conflicts explicitly.** If a term is used ambiguously, call it out in "Flagged ambiguities" with a clear resolution.
|
||||
- **Keep definitions tight.** One sentence max. Define what it IS, not what it does.
|
||||
- **Show relationships.** Use bold term names and express cardinality where obvious.
|
||||
- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs.
|
||||
- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine.
|
||||
- **Write an example dialogue.** A conversation between a dev and a domain expert that demonstrates how the terms interact naturally and clarifies boundaries between related concepts.
|
||||
|
||||
## Single vs multi-context repos
|
||||
|
||||
**Single context (most repos):** One `CONTEXT.md` at the repo root.
|
||||
|
||||
**Multiple contexts:** A `CONTEXT-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other:
|
||||
|
||||
```md
|
||||
# Context Map
|
||||
|
||||
## Contexts
|
||||
|
||||
- [Ordering](./src/ordering/CONTEXT.md) — receives and tracks customer orders
|
||||
- [Billing](./src/billing/CONTEXT.md) — generates invoices and processes payments
|
||||
- [Fulfillment](./src/fulfillment/CONTEXT.md) — manages warehouse picking and shipping
|
||||
|
||||
## Relationships
|
||||
|
||||
- **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking
|
||||
- **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices
|
||||
- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money`
|
||||
```
|
||||
|
||||
The skill infers which structure applies:
|
||||
|
||||
- If `CONTEXT-MAP.md` exists, read it to find contexts
|
||||
- If only a root `CONTEXT.md` exists, single context
|
||||
- If neither exists, create a root `CONTEXT.md` lazily when the first term is resolved
|
||||
|
||||
When multiple contexts exist, infer which one the current topic relates to. If unclear, ask.
|
||||
@@ -0,0 +1,88 @@
|
||||
---
|
||||
name: grill-with-docs
|
||||
description: Grilling session that challenges your plan against the existing domain model, sharpens terminology, and updates documentation (CONTEXT.md, ADRs) inline as decisions crystallise. Use when user wants to stress-test a plan against their project's language and documented decisions.
|
||||
---
|
||||
|
||||
<what-to-do>
|
||||
|
||||
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
|
||||
|
||||
Ask the questions one at a time, waiting for feedback on each question before continuing.
|
||||
|
||||
If a question can be answered by exploring the codebase, explore the codebase instead.
|
||||
|
||||
</what-to-do>
|
||||
|
||||
<supporting-info>
|
||||
|
||||
## Domain awareness
|
||||
|
||||
During codebase exploration, also look for existing documentation:
|
||||
|
||||
### File structure
|
||||
|
||||
Most repos have a single context:
|
||||
|
||||
```
|
||||
/
|
||||
├── CONTEXT.md
|
||||
├── docs/
|
||||
│ └── adr/
|
||||
│ ├── 0001-event-sourced-orders.md
|
||||
│ └── 0002-postgres-for-write-model.md
|
||||
└── src/
|
||||
```
|
||||
|
||||
If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:
|
||||
|
||||
```
|
||||
/
|
||||
├── CONTEXT-MAP.md
|
||||
├── docs/
|
||||
│ └── adr/ ← system-wide decisions
|
||||
├── src/
|
||||
│ ├── ordering/
|
||||
│ │ ├── CONTEXT.md
|
||||
│ │ └── docs/adr/ ← context-specific decisions
|
||||
│ └── billing/
|
||||
│ ├── CONTEXT.md
|
||||
│ └── docs/adr/
|
||||
```
|
||||
|
||||
Create files lazily — only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed.
|
||||
|
||||
## During the session
|
||||
|
||||
### Challenge against the glossary
|
||||
|
||||
When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y — which is it?"
|
||||
|
||||
### Sharpen fuzzy language
|
||||
|
||||
When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account' — do you mean the Customer or the User? Those are different things."
|
||||
|
||||
### Discuss concrete scenarios
|
||||
|
||||
When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.
|
||||
|
||||
### Cross-reference with code
|
||||
|
||||
When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible — which is right?"
|
||||
|
||||
### Update CONTEXT.md inline
|
||||
|
||||
When a term is resolved, update `CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
|
||||
|
||||
Don't couple `CONTEXT.md` to implementation details. Only include terms that are meaningful to domain experts.
|
||||
|
||||
### Offer ADRs sparingly
|
||||
|
||||
Only offer to create an ADR when all three are true:
|
||||
|
||||
1. **Hard to reverse** — the cost of changing your mind later is meaningful
|
||||
2. **Surprising without context** — a future reader will wonder "why did they do it this way?"
|
||||
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
|
||||
|
||||
If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).
|
||||
|
||||
</supporting-info>
|
||||
@@ -0,0 +1,37 @@
|
||||
# Deepening
|
||||
|
||||
How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**.
|
||||
|
||||
## Dependency categories
|
||||
|
||||
When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam.
|
||||
|
||||
### 1. In-process
|
||||
|
||||
Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed.
|
||||
|
||||
### 2. Local-substitutable
|
||||
|
||||
Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface.
|
||||
|
||||
### 3. Remote but owned (Ports & Adapters)
|
||||
|
||||
Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter.
|
||||
|
||||
Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."*
|
||||
|
||||
### 4. True external (Mock)
|
||||
|
||||
Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter.
|
||||
|
||||
## Seam discipline
|
||||
|
||||
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection.
|
||||
- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them.
|
||||
|
||||
## Testing strategy: replace, don't layer
|
||||
|
||||
- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them.
|
||||
- Write new tests at the deepened module's interface. The **interface is the test surface**.
|
||||
- Tests assert on observable outcomes through the interface, not internal state.
|
||||
- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Interface Design
|
||||
|
||||
When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best.
|
||||
|
||||
Uses the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**, **leverage**.
|
||||
|
||||
## Process
|
||||
|
||||
### 1. Frame the problem space
|
||||
|
||||
Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate:
|
||||
|
||||
- The constraints any new interface would need to satisfy
|
||||
- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md))
|
||||
- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete
|
||||
|
||||
Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel.
|
||||
|
||||
### 2. Spawn sub-agents
|
||||
|
||||
Spawn 3+ sub-agents in parallel using the Agent tool. Each must produce a **radically different** interface for the deepened module.
|
||||
|
||||
Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint:
|
||||
|
||||
- Agent 1: "Minimize the interface — aim for 1–3 entry points max. Maximise leverage per entry point."
|
||||
- Agent 2: "Maximise flexibility — support many use cases and extension."
|
||||
- Agent 3: "Optimise for the most common caller — make the default case trivial."
|
||||
- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies."
|
||||
|
||||
Include both [LANGUAGE.md](LANGUAGE.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language.
|
||||
|
||||
Each sub-agent outputs:
|
||||
|
||||
1. Interface (types, methods, params — plus invariants, ordering, error modes)
|
||||
2. Usage example showing how callers use it
|
||||
3. What the implementation hides behind the seam
|
||||
4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md))
|
||||
5. Trade-offs — where leverage is high, where it's thin
|
||||
|
||||
### 3. Present and compare
|
||||
|
||||
Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**.
|
||||
|
||||
After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Language
|
||||
|
||||
Shared vocabulary for every suggestion this skill makes. Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point.
|
||||
|
||||
## Terms
|
||||
|
||||
**Module**
|
||||
Anything with an interface and an implementation. Deliberately scale-agnostic — applies equally to a function, class, package, or tier-spanning slice.
|
||||
_Avoid_: unit, component, service.
|
||||
|
||||
**Interface**
|
||||
Everything a caller must know to use the module correctly. Includes the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics.
|
||||
_Avoid_: API, signature (too narrow — those refer only to the type-level surface).
|
||||
|
||||
**Implementation**
|
||||
What's inside a module — its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise.
|
||||
|
||||
**Depth**
|
||||
Leverage at the interface — the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface. A module is **shallow** when the interface is nearly as complex as the implementation.
|
||||
|
||||
**Seam** _(from Michael Feathers)_
|
||||
A place where you can alter behaviour without editing in that place. The *location* at which a module's interface lives. Choosing where to put the seam is its own design decision, distinct from what goes behind it.
|
||||
_Avoid_: boundary (overloaded with DDD's bounded context).
|
||||
|
||||
**Adapter**
|
||||
A concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).
|
||||
|
||||
**Leverage**
|
||||
What callers get from depth. More capability per unit of interface they have to learn. One implementation pays back across N call sites and M tests.
|
||||
|
||||
**Locality**
|
||||
What maintainers get from depth. Change, bugs, knowledge, and verification concentrate at one place rather than spreading across callers. Fix once, fixed everywhere.
|
||||
|
||||
## Principles
|
||||
|
||||
- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface.
|
||||
- **The deletion test.** Imagine deleting the module. If complexity vanishes, the module wasn't hiding anything (it was a pass-through). If complexity reappears across N callers, the module was earning its keep.
|
||||
- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape.
|
||||
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it.
|
||||
|
||||
## Relationships
|
||||
|
||||
- A **Module** has exactly one **Interface** (the surface it presents to callers and tests).
|
||||
- **Depth** is a property of a **Module**, measured against its **Interface**.
|
||||
- A **Seam** is where a **Module**'s **Interface** lives.
|
||||
- An **Adapter** sits at a **Seam** and satisfies the **Interface**.
|
||||
- **Depth** produces **Leverage** for callers and **Locality** for maintainers.
|
||||
|
||||
## Rejected framings
|
||||
|
||||
- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead.
|
||||
- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know.
|
||||
- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**.
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
name: improve-codebase-architecture
|
||||
description: Find deepening opportunities in a codebase, informed by the domain language in CONTEXT.md and the decisions in docs/adr/. Use when the user wants to improve architecture, find refactoring opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable.
|
||||
---
|
||||
|
||||
# Improve Codebase Architecture
|
||||
|
||||
Surface architectural friction and propose **deepening opportunities** — refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
|
||||
|
||||
## Glossary
|
||||
|
||||
Use these terms exactly in every suggestion. Consistent language is the point — don't drift into "component," "service," "API," or "boundary." Full definitions in [LANGUAGE.md](LANGUAGE.md).
|
||||
|
||||
- **Module** — anything with an interface and an implementation (function, class, package, slice).
|
||||
- **Interface** — everything a caller must know to use the module: types, invariants, error modes, ordering, config. Not just the type signature.
|
||||
- **Implementation** — the code inside.
|
||||
- **Depth** — leverage at the interface: a lot of behaviour behind a small interface. **Deep** = high leverage. **Shallow** = interface nearly as complex as the implementation.
|
||||
- **Seam** — where an interface lives; a place behaviour can be altered without editing in place. (Use this, not "boundary.")
|
||||
- **Adapter** — a concrete thing satisfying an interface at a seam.
|
||||
- **Leverage** — what callers get from depth.
|
||||
- **Locality** — what maintainers get from depth: change, bugs, knowledge concentrated in one place.
|
||||
|
||||
Key principles (see [LANGUAGE.md](LANGUAGE.md) for the full list):
|
||||
|
||||
- **Deletion test**: imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.
|
||||
- **The interface is the test surface.**
|
||||
- **One adapter = hypothetical seam. Two adapters = real seam.**
|
||||
|
||||
This skill is _informed_ by the project's domain model. The domain language gives names to good seams; ADRs record decisions the skill should not re-litigate.
|
||||
|
||||
## Process
|
||||
|
||||
### 1. Explore
|
||||
|
||||
Read the project's domain glossary and any ADRs in the area you're touching first.
|
||||
|
||||
Then use the Agent tool with `subagent_type=Explore` to walk the codebase. Don't follow rigid heuristics — explore organically and note where you experience friction:
|
||||
|
||||
- Where does understanding one concept require bouncing between many small modules?
|
||||
- Where are modules **shallow** — interface nearly as complex as the implementation?
|
||||
- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)?
|
||||
- Where do tightly-coupled modules leak across their seams?
|
||||
- Which parts of the codebase are untested, or hard to test through their current interface?
|
||||
|
||||
Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want.
|
||||
|
||||
### 2. Present candidates
|
||||
|
||||
Present a numbered list of deepening opportunities. For each candidate:
|
||||
|
||||
- **Files** — which files/modules are involved
|
||||
- **Problem** — why the current architecture is causing friction
|
||||
- **Solution** — plain English description of what would change
|
||||
- **Benefits** — explained in terms of locality and leverage, and also in how tests would improve
|
||||
|
||||
**Use CONTEXT.md vocabulary for the domain, and [LANGUAGE.md](LANGUAGE.md) vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module" — not "the FooBarHandler," and not "the Order service."
|
||||
|
||||
**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly (e.g. _"contradicts ADR-0007 — but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids.
|
||||
|
||||
Do NOT propose interfaces yet. Ask the user: "Which of these would you like to explore?"
|
||||
|
||||
### 3. Grilling loop
|
||||
|
||||
Once the user picks a candidate, drop into a grilling conversation. Walk the design tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
|
||||
|
||||
Side effects happen inline as decisions crystallize:
|
||||
|
||||
- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md` — same discipline as `/grill-with-docs` (see [CONTEXT-FORMAT.md](../grill-with-docs/CONTEXT-FORMAT.md)). Create the file lazily if it doesn't exist.
|
||||
- **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there.
|
||||
- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing — skip ephemeral reasons ("not worth it right now") and self-evident ones. See [ADR-FORMAT.md](../grill-with-docs/ADR-FORMAT.md).
|
||||
- **Want to explore alternative interfaces for the deepened module?** See [INTERFACE-DESIGN.md](INTERFACE-DESIGN.md).
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/Users/johannes/.local/share/mise/installs/node/25.6.0/lib/node_modules/oh-my-mermaid/skills
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
name: ponytail-audit
|
||||
description: >
|
||||
Whole-repo audit for over-engineering. Like ponytail-review, but scans the
|
||||
entire codebase instead of a diff: a ranked list of what to delete, simplify,
|
||||
or replace with stdlib/native equivalents. Use when the user says "audit this
|
||||
codebase", "audit for over-engineering", "what can I delete from this repo",
|
||||
"find bloat", "ponytail-audit", or "/ponytail-audit". One-shot report, does
|
||||
not apply fixes.
|
||||
---
|
||||
|
||||
ponytail-review, repo-wide. Scan the whole tree instead of a diff. Rank
|
||||
findings biggest cut first.
|
||||
|
||||
## Tags
|
||||
|
||||
Same as ponytail-review:
|
||||
|
||||
- `delete:` dead code, unused flexibility, speculative feature. Replacement: nothing.
|
||||
- `stdlib:` hand-rolled thing the standard library ships. Name the function.
|
||||
- `native:` dependency or code doing what the platform already does. Name the feature.
|
||||
- `yagni:` abstraction with one implementation, config nobody sets, layer with one caller.
|
||||
- `shrink:` same logic, fewer lines. Show the shorter form.
|
||||
|
||||
## Hunt
|
||||
|
||||
Deps the stdlib or platform already ships, single-implementation interfaces,
|
||||
factories with one product, wrappers that only delegate, files exporting one
|
||||
thing, dead flags and config, hand-rolled stdlib.
|
||||
|
||||
## Output
|
||||
|
||||
One line per finding, ranked: `<tag> <what to cut>. <replacement>. [path]`.
|
||||
End with `net: -<N> lines, -<M> deps possible.` Nothing to cut: `Lean already. Ship.`
|
||||
|
||||
## Boundaries
|
||||
|
||||
Scope: over-engineering and complexity only. Correctness bugs, security holes,
|
||||
and performance are explicitly out of scope. Route them to a normal review
|
||||
pass. Lists findings, applies nothing. One-shot.
|
||||
"stop ponytail-audit" or "normal mode" to revert.
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
name: ponytail-debt
|
||||
description: >
|
||||
Harvest every `ponytail:` comment in the codebase into a debt ledger, so the
|
||||
deliberate shortcuts and deferrals ponytail leaves behind get tracked instead
|
||||
of rotting into "later means never". Use when the user says "ponytail debt",
|
||||
"/ponytail-debt", "what did ponytail defer", "list the shortcuts", "ponytail
|
||||
ledger", or "what did we mark to do later". One-shot report, changes nothing.
|
||||
---
|
||||
|
||||
Every deliberate ponytail shortcut is marked with a `ponytail:` comment naming
|
||||
its ceiling and upgrade path. This collects them into one ledger so a deferral
|
||||
can't quietly become permanent.
|
||||
|
||||
## Scan
|
||||
|
||||
Grep the repo for comment markers, skipping `node_modules`, `.git`, and build
|
||||
output:
|
||||
|
||||
`grep -rnE '(#|//) ?ponytail:' .` (add other comment prefixes if your stack uses them)
|
||||
|
||||
Each hit is one ledger row. The comment prefix keeps prose that merely mentions
|
||||
the convention out of the ledger.
|
||||
|
||||
## Output
|
||||
|
||||
One row per marker, grouped by file:
|
||||
|
||||
`<file>:<line>, <what was simplified>. ceiling: <the limit named>. upgrade: <the trigger to revisit>.`
|
||||
|
||||
The convention is `ponytail: <ceiling>, <upgrade path>`, so pull the ceiling
|
||||
and the trigger straight from the comment. Want an owner per row too? add
|
||||
`git blame -L<line>,<line>`.
|
||||
|
||||
Flag the rot risk: any `ponytail:` comment that names no upgrade path or
|
||||
trigger gets a `no-trigger` tag, those are the ones that silently rot.
|
||||
|
||||
End with `<N> markers, <M> with no trigger.` Nothing found: `No ponytail: debt. Clean ledger.`
|
||||
|
||||
## Boundaries
|
||||
|
||||
Reads and reports only, changes nothing. To persist it, ask and it writes the
|
||||
ledger to a file (e.g. `PONYTAIL-DEBT.md`). One-shot. "stop ponytail-debt" or
|
||||
"normal mode" to revert.
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
name: ponytail-gain
|
||||
description: >
|
||||
Show ponytail's measured impact as a compact scoreboard: less code, less
|
||||
cost, more speed, from the benchmark medians. One-shot display, not a
|
||||
persistent mode, and not a per-repo number. Trigger: /ponytail-gain,
|
||||
"ponytail gain", "what does ponytail save", "show ponytail impact",
|
||||
"ponytail scoreboard".
|
||||
---
|
||||
|
||||
# Ponytail Gain
|
||||
|
||||
Display this scoreboard when invoked. One-shot: do NOT change mode, write flag
|
||||
files, or persist anything.
|
||||
|
||||
The figures are the published benchmark medians (5 everyday tasks: email
|
||||
validator, debounce, CSV sum, countdown timer, rate limiter; three models:
|
||||
Haiku, Sonnet, Opus). They are measured, not computed from the current repo.
|
||||
Source: `benchmarks/` and the README.
|
||||
|
||||
## Scoreboard
|
||||
|
||||
Render plain ASCII bars. The bar length shows the measured range; the label
|
||||
carries the exact figure:
|
||||
|
||||
```
|
||||
ponytail gain benchmark median · 5 tasks · 3 models
|
||||
|
||||
Lines of code no-skill ████████████████████ 100%
|
||||
ponytail ██▌················· 6–20% ▼ 80–94%
|
||||
Cost no-skill ████████████████████ 100%
|
||||
ponytail █████▌·············· 23–53% ▼ 47–77%
|
||||
Speed ponytail ▸ 3–6× faster
|
||||
|
||||
This repo: /ponytail-debt (shortcuts you deferred)
|
||||
/ponytail-audit (what's still cuttable)
|
||||
```
|
||||
|
||||
## Honesty boundary
|
||||
|
||||
These are benchmark medians, not this repo. NEVER print a per-repo savings
|
||||
number ("you saved X lines/tokens here"): the unbuilt version was never
|
||||
written, so there is no real baseline to subtract from in a live repo. The
|
||||
only real per-repo figures come from `/ponytail-debt` (a counted ledger), and
|
||||
this card points there instead of inventing one.
|
||||
|
||||
## Boundaries
|
||||
|
||||
One-shot display. Edits nothing, changes no mode.
|
||||
"stop ponytail" or "normal mode": revert.
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
name: ponytail-help
|
||||
description: >
|
||||
Quick-reference card for all ponytail modes, skills, and commands.
|
||||
One-shot display, not a persistent mode. Trigger: /ponytail-help,
|
||||
"ponytail help", "what ponytail commands", "how do I use ponytail".
|
||||
---
|
||||
|
||||
# Ponytail Help
|
||||
|
||||
Display this reference card when invoked. One-shot, do NOT change mode,
|
||||
write flag files, or persist anything.
|
||||
|
||||
## Levels
|
||||
|
||||
| Level | Trigger | What change |
|
||||
|-------|---------|-------------|
|
||||
| **Lite** | `/ponytail lite` | Build what's asked, name the lazier alternative in one line. |
|
||||
| **Full** | `/ponytail` | The ladder enforced: YAGNI → stdlib → native → one line → minimum. Default. |
|
||||
| **Ultra** | `/ponytail ultra` | YAGNI extremist. Deletion before addition. Challenges requirements before building. |
|
||||
|
||||
Level sticks until changed or session end.
|
||||
|
||||
## Skills
|
||||
|
||||
| Skill | Trigger | What it does |
|
||||
|-------|---------|--------------|
|
||||
| **ponytail** | `/ponytail` | Lazy mode itself. Simplest solution that works. |
|
||||
| **ponytail-review** | `/ponytail-review` | Over-engineering review: `L42: yagni: factory, one product. Inline.` |
|
||||
| **ponytail-gain** | `/ponytail-gain` | Measured-impact scoreboard: less code, less cost, more speed. |
|
||||
| **ponytail-help** | `/ponytail-help` | This card. |
|
||||
|
||||
Codex uses `@ponytail`, `@ponytail-review`, and `@ponytail-help`; Claude Code
|
||||
and OpenCode use the slash-command forms above (OpenCode ships `/ponytail` and
|
||||
`/ponytail-review`).
|
||||
|
||||
## Deactivate
|
||||
|
||||
Say "stop ponytail" or "normal mode". Resume anytime with `/ponytail`.
|
||||
`/ponytail off` also works.
|
||||
|
||||
## Configure Default Mode
|
||||
|
||||
Default mode = `full`, auto-active every session. Change it:
|
||||
|
||||
**Environment variable** (highest priority):
|
||||
```bash
|
||||
export PONYTAIL_DEFAULT_MODE=ultra
|
||||
```
|
||||
|
||||
**Config file** (`~/.config/ponytail/config.json`, Windows: `%APPDATA%\ponytail\config.json`):
|
||||
```json
|
||||
{ "defaultMode": "lite" }
|
||||
```
|
||||
|
||||
Set `"off"` to disable auto-activation on session start, activate manually
|
||||
with `/ponytail` when wanted.
|
||||
|
||||
Resolution: env var > config file > `full`.
|
||||
|
||||
## Update
|
||||
|
||||
Enable auto-update once: open `/plugin`, go to Marketplaces, pick ponytail, Enable auto-update. Claude Code then pulls new versions at startup (run `/reload-plugins` when it prompts). Manual refresh: `/plugin marketplace update ponytail` then `/reload-plugins`.
|
||||
|
||||
If `/plugin` is not recognized, your Claude Code is out of date. Update it (`npm install -g @anthropic-ai/claude-code@latest`, or `brew upgrade claude-code`) and restart. Other hosts use their own update flow.
|
||||
|
||||
## More
|
||||
|
||||
Full docs + examples: https://github.com/DietrichGebert/ponytail
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
name: ponytail-review
|
||||
description: >
|
||||
Code review focused exclusively on over-engineering. Finds what to delete:
|
||||
reinvented standard library, unneeded dependencies, speculative abstractions,
|
||||
dead flexibility. One line per finding: location, what to cut, what replaces
|
||||
it. Use when the user says "review for over-engineering", "what can we
|
||||
delete", "is this over-engineered", "simplify review", or invokes
|
||||
/ponytail-review. Complements correctness-focused review, this one only
|
||||
hunts complexity.
|
||||
---
|
||||
|
||||
Review diffs for unnecessary complexity. One line per finding: location, what
|
||||
to cut, what replaces it. The diff's best outcome is getting shorter.
|
||||
|
||||
## Format
|
||||
|
||||
`L<line>: <tag> <what>. <replacement>.`, or `<file>:L<line>: ...` for
|
||||
multi-file diffs.
|
||||
|
||||
Tags:
|
||||
|
||||
- `delete:` dead code, unused flexibility, speculative feature. Replacement: nothing.
|
||||
- `stdlib:` hand-rolled thing the standard library ships. Name the function.
|
||||
- `native:` dependency or code doing what the platform already does. Name the feature.
|
||||
- `yagni:` abstraction with one implementation, config nobody sets, layer with one caller.
|
||||
- `shrink:` same logic, fewer lines. Show the shorter form.
|
||||
|
||||
## Examples
|
||||
|
||||
❌ "This EmailValidator class might be more complex than necessary, have you
|
||||
considered whether all these validation rules are needed at this stage?"
|
||||
|
||||
✅ `L12-38: stdlib: 27-line validator class. "@" in email, 1 line, real validation is the confirmation mail.`
|
||||
|
||||
✅ `L4: native: moment.js imported for one format call. Intl.DateTimeFormat, 0 deps.`
|
||||
|
||||
✅ `repo.py:L88: yagni: AbstractRepository with one implementation. Inline it until a second one exists.`
|
||||
|
||||
✅ `L52-71: delete: retry wrapper around an idempotent local call. Nothing replaces it.`
|
||||
|
||||
✅ `L30-44: shrink: manual loop builds dict. dict(zip(keys, values)), 1 line.`
|
||||
|
||||
## Scoring
|
||||
|
||||
End with the only metric that matters: `net: -<N> lines possible.`
|
||||
|
||||
If there is nothing to cut, say `Lean already. Ship.` and stop.
|
||||
|
||||
## Boundaries
|
||||
|
||||
Scope: over-engineering and complexity only. Correctness bugs, security holes,
|
||||
and performance are explicitly out of scope. Route them to a normal review
|
||||
pass, not this one. A single smoke test or `assert`-based
|
||||
self-check is the ponytail minimum, not bloat, never flag it for deletion.
|
||||
Does not apply the fixes, only lists them.
|
||||
"stop ponytail-review" or "normal mode": revert to verbose review style.
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
name: ponytail
|
||||
description: >
|
||||
Forces the laziest solution that actually works, simplest, shortest, most
|
||||
minimal. Channels a senior dev who has seen everything: question whether the
|
||||
task needs to exist at all (YAGNI), reach for the standard library before
|
||||
custom code, native platform features before dependencies, one line before
|
||||
fifty. Supports intensity levels: lite, full (default), ultra. Use whenever
|
||||
the user says "ponytail", "be lazy", "lazy mode", "simplest solution",
|
||||
"minimal solution", "yagni", "do less", or "shortest path", and whenever
|
||||
they complain about over-engineering, bloat, boilerplate, or unnecessary
|
||||
dependencies.
|
||||
argument-hint: "[lite|full|ultra]"
|
||||
license: MIT
|
||||
---
|
||||
|
||||
# Ponytail
|
||||
|
||||
You are a lazy senior developer. Lazy means efficient, not careless. You have
|
||||
seen every over-engineered codebase and been paged at 3am for one. The best
|
||||
code is the code never written.
|
||||
|
||||
## Persistence
|
||||
|
||||
ACTIVE EVERY RESPONSE. No drift back to over-building. Still active if
|
||||
unsure. Off only: "stop ponytail" / "normal mode". Default: **full**.
|
||||
Switch: `/ponytail lite|full|ultra`.
|
||||
|
||||
## The ladder
|
||||
|
||||
Stop at the first rung that holds:
|
||||
|
||||
1. **Does this need to exist at all?** Speculative need = skip it, say so in one line. (YAGNI)
|
||||
2. **Already in this codebase?** A helper, util, type, or pattern that already lives here → reuse it. Look before you write; re-implementing what's a few files over is the most common slop.
|
||||
3. **Stdlib does it?** Use it.
|
||||
4. **Native platform feature covers it?** `<input type="date">` over a picker lib, CSS over JS, DB constraint over app code.
|
||||
5. **Already-installed dependency solves it?** Use it. Never add a new one for what a few lines can do.
|
||||
6. **Can it be one line?** One line.
|
||||
7. **Only then:** the minimum code that works.
|
||||
|
||||
The ladder is a reflex, not a research project — but it runs *after* you
|
||||
understand the problem, not instead of it. Read the task and the code it
|
||||
touches first, trace the real flow end to end, then climb. Two rungs work →
|
||||
take the higher one and move on. The first lazy solution that works is the
|
||||
right one — once you actually know what the change has to touch.
|
||||
|
||||
**Bug fix = root cause, not symptom.** A report names a symptom. Before you
|
||||
edit, grep every caller of the function you're about to touch. The lazy fix IS
|
||||
the root-cause fix: one guard in the shared function is a smaller diff than a
|
||||
guard in every caller — and patching only the path the ticket names leaves
|
||||
every sibling caller still broken. Fix it once, where all callers route through.
|
||||
|
||||
## Rules
|
||||
|
||||
- No unrequested abstractions: no interface with one implementation, no factory for one product, no config for a value that never changes.
|
||||
- No boilerplate, no scaffolding "for later", later can scaffold for itself.
|
||||
- Deletion over addition. Boring over clever, clever is what someone decodes at 3am.
|
||||
- Fewest files possible. Shortest working diff wins — but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug.
|
||||
- Complex request? Ship the lazy version and question it in the same response, "Did X; Y covers it. Need full X? Say so." Never stall on an answer you can default.
|
||||
- Two stdlib options, same size? Take the one that's correct on edge cases. Lazy means writing less code, not picking the flimsier algorithm.
|
||||
- Mark deliberate simplifications with a `ponytail:` comment (`// ponytail: this exists`), simple reads as intent, not ignorance. Shortcut with a known ceiling (global lock, O(n²) scan, naive heuristic)? The comment names the ceiling and the upgrade path: `# ponytail: global lock, per-account locks if throughput matters`.
|
||||
|
||||
## Output
|
||||
|
||||
Code first. Then at most three short lines: what was skipped, when to add it.
|
||||
No essays, no feature tours, no design notes. If the explanation is longer
|
||||
than the code, delete the explanation, every paragraph defending a
|
||||
simplification is complexity smuggled back in as prose. Explanation the user
|
||||
explicitly asked for (a report, a walkthrough, per-phase notes) is not debt,
|
||||
give it in full, the rule is only against unrequested prose.
|
||||
|
||||
Pattern: `[code] → skipped: [X], add when [Y].`
|
||||
|
||||
## Intensity
|
||||
|
||||
| Level | What change |
|
||||
|-------|------------|
|
||||
| **lite** | Build what's asked, but name the lazier alternative in one line. User picks. |
|
||||
| **full** | The ladder enforced. Stdlib and native first. Shortest diff, shortest explanation. Default. |
|
||||
| **ultra** | YAGNI extremist. Deletion before addition. Ship the one-liner and challenge the rest of the requirement in the same breath. |
|
||||
|
||||
Example: "Add a cache for these API responses."
|
||||
- lite: "Done, cache added. FYI: `functools.lru_cache` covers this in one line if you'd rather not own a cache class."
|
||||
- full: "`@lru_cache(maxsize=1000)` on the fetch function. Skipped custom cache class, add when lru_cache measurably falls short."
|
||||
- ultra: "No cache until a profiler says so. When it does: `@lru_cache`. A hand-rolled TTL cache class is a bug farm with a hit rate."
|
||||
|
||||
## When NOT to be lazy
|
||||
|
||||
Never simplify away: input validation at trust boundaries, error handling
|
||||
that prevents data loss, security measures, accessibility basics, anything
|
||||
explicitly requested. User insists on the full version → build it, no
|
||||
re-arguing.
|
||||
|
||||
Never lazy about understanding the problem. The ladder shortens the
|
||||
solution, never the reading. Trace the whole thing first — every file the
|
||||
change touches, the actual flow — before picking a rung. Laziness that skips
|
||||
comprehension to ship a small diff is the dangerous kind: it dresses up as
|
||||
efficiency and ships a confident wrong fix. Read fully, then be lazy.
|
||||
|
||||
Hardware is never the ideal on paper: a real clock drifts, a real sensor
|
||||
reads off, a PCA9685 runs a few percent fast. Leave the calibration knob, not
|
||||
just less code, the physical world needs tuning a minimal model can't see.
|
||||
|
||||
Lazy code without its check is unfinished. Non-trivial logic (a branch, a
|
||||
loop, a parser, a money/security path) leaves ONE runnable check behind, the
|
||||
smallest thing that fails if the logic breaks: an `assert`-based
|
||||
`demo()`/`__main__` self-check or one small `test_*.py`. No frameworks, no
|
||||
fixtures, no per-function suites unless asked. Trivial one-liners need no
|
||||
test, YAGNI applies to tests too.
|
||||
|
||||
## Boundaries
|
||||
|
||||
Ponytail governs what you build, not how you talk (pair with Caveman for
|
||||
terse prose). "stop ponytail" / "normal mode": revert. Level persists until
|
||||
changed or session end.
|
||||
|
||||
The shortest path to done is the right path.
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
name: tdd
|
||||
description: Test-driven development with red-green-refactor loop. Use when user wants to build features or fix bugs using TDD, mentions "red-green-refactor", wants integration tests, or asks for test-first development.
|
||||
---
|
||||
|
||||
# Test-Driven Development
|
||||
|
||||
## Philosophy
|
||||
|
||||
**Core principle**: Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't.
|
||||
|
||||
**Good tests** are integration-style: they exercise real code paths through public APIs. They describe _what_ the system does, not _how_ it does it. A good test reads like a specification - "user can checkout with valid cart" tells you exactly what capability exists. These tests survive refactors because they don't care about internal structure.
|
||||
|
||||
**Bad tests** are coupled to implementation. They mock internal collaborators, test private methods, or verify through external means (like querying a database directly instead of using the interface). The warning sign: your test breaks when you refactor, but behavior hasn't changed. If you rename an internal function and tests fail, those tests were testing implementation, not behavior.
|
||||
|
||||
See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.
|
||||
|
||||
## Anti-Pattern: Horizontal Slices
|
||||
|
||||
**DO NOT write all tests first, then all implementation.** This is "horizontal slicing" - treating RED as "write all tests" and GREEN as "write all code."
|
||||
|
||||
This produces **crap tests**:
|
||||
|
||||
- Tests written in bulk test _imagined_ behavior, not _actual_ behavior
|
||||
- You end up testing the _shape_ of things (data structures, function signatures) rather than user-facing behavior
|
||||
- Tests become insensitive to real changes - they pass when behavior breaks, fail when behavior is fine
|
||||
- You outrun your headlights, committing to test structure before understanding the implementation
|
||||
|
||||
**Correct approach**: Vertical slices via tracer bullets. One test → one implementation → repeat. Each test responds to what you learned from the previous cycle. Because you just wrote the code, you know exactly what behavior matters and how to verify it.
|
||||
|
||||
```
|
||||
WRONG (horizontal):
|
||||
RED: test1, test2, test3, test4, test5
|
||||
GREEN: impl1, impl2, impl3, impl4, impl5
|
||||
|
||||
RIGHT (vertical):
|
||||
RED→GREEN: test1→impl1
|
||||
RED→GREEN: test2→impl2
|
||||
RED→GREEN: test3→impl3
|
||||
...
|
||||
```
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Planning
|
||||
|
||||
When exploring the codebase, use the project's domain glossary so that test names and interface vocabulary match the project's language, and respect ADRs in the area you're touching.
|
||||
|
||||
Before writing any code:
|
||||
|
||||
- [ ] Confirm with user what interface changes are needed
|
||||
- [ ] Confirm with user which behaviors to test (prioritize)
|
||||
- [ ] Identify opportunities for [deep modules](deep-modules.md) (small interface, deep implementation)
|
||||
- [ ] Design interfaces for [testability](interface-design.md)
|
||||
- [ ] List the behaviors to test (not implementation steps)
|
||||
- [ ] Get user approval on the plan
|
||||
|
||||
Ask: "What should the public interface look like? Which behaviors are most important to test?"
|
||||
|
||||
**You can't test everything.** Confirm with the user exactly which behaviors matter most. Focus testing effort on critical paths and complex logic, not every possible edge case.
|
||||
|
||||
### 2. Tracer Bullet
|
||||
|
||||
Write ONE test that confirms ONE thing about the system:
|
||||
|
||||
```
|
||||
RED: Write test for first behavior → test fails
|
||||
GREEN: Write minimal code to pass → test passes
|
||||
```
|
||||
|
||||
This is your tracer bullet - proves the path works end-to-end.
|
||||
|
||||
### 3. Incremental Loop
|
||||
|
||||
For each remaining behavior:
|
||||
|
||||
```
|
||||
RED: Write next test → fails
|
||||
GREEN: Minimal code to pass → passes
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- One test at a time
|
||||
- Only enough code to pass current test
|
||||
- Don't anticipate future tests
|
||||
- Keep tests focused on observable behavior
|
||||
|
||||
### 4. Refactor
|
||||
|
||||
After all tests pass, look for [refactor candidates](refactoring.md):
|
||||
|
||||
- [ ] Extract duplication
|
||||
- [ ] Deepen modules (move complexity behind simple interfaces)
|
||||
- [ ] Apply SOLID principles where natural
|
||||
- [ ] Consider what new code reveals about existing code
|
||||
- [ ] Run tests after each refactor step
|
||||
|
||||
**Never refactor while RED.** Get to GREEN first.
|
||||
|
||||
## Checklist Per Cycle
|
||||
|
||||
```
|
||||
[ ] Test describes behavior, not implementation
|
||||
[ ] Test uses public interface only
|
||||
[ ] Test would survive internal refactor
|
||||
[ ] Code is minimal for this test
|
||||
[ ] No speculative features added
|
||||
```
|
||||
@@ -0,0 +1,33 @@
|
||||
# Deep Modules
|
||||
|
||||
From "A Philosophy of Software Design":
|
||||
|
||||
**Deep module** = small interface + lots of implementation
|
||||
|
||||
```
|
||||
┌─────────────────────┐
|
||||
│ Small Interface │ ← Few methods, simple params
|
||||
├─────────────────────┤
|
||||
│ │
|
||||
│ │
|
||||
│ Deep Implementation│ ← Complex logic hidden
|
||||
│ │
|
||||
│ │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
**Shallow module** = large interface + little implementation (avoid)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ Large Interface │ ← Many methods, complex params
|
||||
├─────────────────────────────────┤
|
||||
│ Thin Implementation │ ← Just passes through
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
When designing interfaces, ask:
|
||||
|
||||
- Can I reduce the number of methods?
|
||||
- Can I simplify the parameters?
|
||||
- Can I hide more complexity inside?
|
||||
@@ -0,0 +1,31 @@
|
||||
# Interface Design for Testability
|
||||
|
||||
Good interfaces make testing natural:
|
||||
|
||||
1. **Accept dependencies, don't create them**
|
||||
|
||||
```typescript
|
||||
// Testable
|
||||
function processOrder(order, paymentGateway) {}
|
||||
|
||||
// Hard to test
|
||||
function processOrder(order) {
|
||||
const gateway = new StripeGateway();
|
||||
}
|
||||
```
|
||||
|
||||
2. **Return results, don't produce side effects**
|
||||
|
||||
```typescript
|
||||
// Testable
|
||||
function calculateDiscount(cart): Discount {}
|
||||
|
||||
// Hard to test
|
||||
function applyDiscount(cart): void {
|
||||
cart.total -= discount;
|
||||
}
|
||||
```
|
||||
|
||||
3. **Small surface area**
|
||||
- Fewer methods = fewer tests needed
|
||||
- Fewer params = simpler test setup
|
||||
@@ -0,0 +1,59 @@
|
||||
# When to Mock
|
||||
|
||||
Mock at **system boundaries** only:
|
||||
|
||||
- External APIs (payment, email, etc.)
|
||||
- Databases (sometimes - prefer test DB)
|
||||
- Time/randomness
|
||||
- File system (sometimes)
|
||||
|
||||
Don't mock:
|
||||
|
||||
- Your own classes/modules
|
||||
- Internal collaborators
|
||||
- Anything you control
|
||||
|
||||
## Designing for Mockability
|
||||
|
||||
At system boundaries, design interfaces that are easy to mock:
|
||||
|
||||
**1. Use dependency injection**
|
||||
|
||||
Pass external dependencies in rather than creating them internally:
|
||||
|
||||
```typescript
|
||||
// Easy to mock
|
||||
function processPayment(order, paymentClient) {
|
||||
return paymentClient.charge(order.total);
|
||||
}
|
||||
|
||||
// Hard to mock
|
||||
function processPayment(order) {
|
||||
const client = new StripeClient(process.env.STRIPE_KEY);
|
||||
return client.charge(order.total);
|
||||
}
|
||||
```
|
||||
|
||||
**2. Prefer SDK-style interfaces over generic fetchers**
|
||||
|
||||
Create specific functions for each external operation instead of one generic function with conditional logic:
|
||||
|
||||
```typescript
|
||||
// GOOD: Each function is independently mockable
|
||||
const api = {
|
||||
getUser: (id) => fetch(`/users/${id}`),
|
||||
getOrders: (userId) => fetch(`/users/${userId}/orders`),
|
||||
createOrder: (data) => fetch('/orders', { method: 'POST', body: data }),
|
||||
};
|
||||
|
||||
// BAD: Mocking requires conditional logic inside the mock
|
||||
const api = {
|
||||
fetch: (endpoint, options) => fetch(endpoint, options),
|
||||
};
|
||||
```
|
||||
|
||||
The SDK approach means:
|
||||
- Each mock returns one specific shape
|
||||
- No conditional logic in test setup
|
||||
- Easier to see which endpoints a test exercises
|
||||
- Type safety per endpoint
|
||||
@@ -0,0 +1,10 @@
|
||||
# Refactor Candidates
|
||||
|
||||
After TDD cycle, look for:
|
||||
|
||||
- **Duplication** → Extract function/class
|
||||
- **Long methods** → Break into private helpers (keep tests on public interface)
|
||||
- **Shallow modules** → Combine or deepen
|
||||
- **Feature envy** → Move logic to where data lives
|
||||
- **Primitive obsession** → Introduce value objects
|
||||
- **Existing code** the new code reveals as problematic
|
||||
@@ -0,0 +1,61 @@
|
||||
# Good and Bad Tests
|
||||
|
||||
## Good Tests
|
||||
|
||||
**Integration-style**: Test through real interfaces, not mocks of internal parts.
|
||||
|
||||
```typescript
|
||||
// GOOD: Tests observable behavior
|
||||
test("user can checkout with valid cart", async () => {
|
||||
const cart = createCart();
|
||||
cart.add(product);
|
||||
const result = await checkout(cart, paymentMethod);
|
||||
expect(result.status).toBe("confirmed");
|
||||
});
|
||||
```
|
||||
|
||||
Characteristics:
|
||||
|
||||
- Tests behavior users/callers care about
|
||||
- Uses public API only
|
||||
- Survives internal refactors
|
||||
- Describes WHAT, not HOW
|
||||
- One logical assertion per test
|
||||
|
||||
## Bad Tests
|
||||
|
||||
**Implementation-detail tests**: Coupled to internal structure.
|
||||
|
||||
```typescript
|
||||
// BAD: Tests implementation details
|
||||
test("checkout calls paymentService.process", async () => {
|
||||
const mockPayment = jest.mock(paymentService);
|
||||
await checkout(cart, payment);
|
||||
expect(mockPayment.process).toHaveBeenCalledWith(cart.total);
|
||||
});
|
||||
```
|
||||
|
||||
Red flags:
|
||||
|
||||
- Mocking internal collaborators
|
||||
- Testing private methods
|
||||
- Asserting on call counts/order
|
||||
- Test breaks when refactoring without behavior change
|
||||
- Test name describes HOW not WHAT
|
||||
- Verifying through external means instead of interface
|
||||
|
||||
```typescript
|
||||
// BAD: Bypasses interface to verify
|
||||
test("createUser saves to database", async () => {
|
||||
await createUser({ name: "Alice" });
|
||||
const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]);
|
||||
expect(row).toBeDefined();
|
||||
});
|
||||
|
||||
// GOOD: Verifies through interface
|
||||
test("createUser makes user retrievable", async () => {
|
||||
const user = await createUser({ name: "Alice" });
|
||||
const retrieved = await getUser(user.id);
|
||||
expect(retrieved.name).toBe("Alice");
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
name: to-issues
|
||||
description: Break a plan, spec, or PRD into independently-grabbable issues on the project issue tracker using tracer-bullet vertical slices. Use when user wants to convert a plan into issues, create implementation tickets, or break down work into issues.
|
||||
---
|
||||
|
||||
# To Issues
|
||||
|
||||
Break a plan into independently-grabbable issues using vertical slices (tracer bullets).
|
||||
|
||||
The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not.
|
||||
|
||||
## Process
|
||||
|
||||
### 1. Gather context
|
||||
|
||||
Work from whatever is already in the conversation context. If the user passes an issue reference (issue number, URL, or path) as an argument, fetch it from the issue tracker and read its full body and comments.
|
||||
|
||||
### 2. Explore the codebase (optional)
|
||||
|
||||
If you have not already explored the codebase, do so to understand the current state of the code. Issue titles and descriptions should use the project's domain glossary vocabulary, and respect ADRs in the area you're touching.
|
||||
|
||||
### 3. Draft vertical slices
|
||||
|
||||
Break the plan into **tracer bullet** issues. Each issue is a thin vertical slice that cuts through ALL integration layers end-to-end, NOT a horizontal slice of one layer.
|
||||
|
||||
Slices may be 'HITL' or 'AFK'. HITL slices require human interaction, such as an architectural decision or a design review. AFK slices can be implemented and merged without human interaction. Prefer AFK over HITL where possible.
|
||||
|
||||
<vertical-slice-rules>
|
||||
- Each slice delivers a narrow but COMPLETE path through every layer (schema, API, UI, tests)
|
||||
- A completed slice is demoable or verifiable on its own
|
||||
- Prefer many thin slices over few thick ones
|
||||
</vertical-slice-rules>
|
||||
|
||||
### 4. Quiz the user
|
||||
|
||||
Present the proposed breakdown as a numbered list. For each slice, show:
|
||||
|
||||
- **Title**: short descriptive name
|
||||
- **Type**: HITL / AFK
|
||||
- **Blocked by**: which other slices (if any) must complete first
|
||||
- **User stories covered**: which user stories this addresses (if the source material has them)
|
||||
|
||||
Ask the user:
|
||||
|
||||
- Does the granularity feel right? (too coarse / too fine)
|
||||
- Are the dependency relationships correct?
|
||||
- Should any slices be merged or split further?
|
||||
- Are the correct slices marked as HITL and AFK?
|
||||
|
||||
Iterate until the user approves the breakdown.
|
||||
|
||||
### 5. Publish the issues to the issue tracker
|
||||
|
||||
For each approved slice, publish a new issue to the issue tracker. Use the issue body template below. Apply the `needs-triage` triage label so each issue enters the normal triage flow.
|
||||
|
||||
Publish issues in dependency order (blockers first) so you can reference real issue identifiers in the "Blocked by" field.
|
||||
|
||||
<issue-template>
|
||||
## Parent
|
||||
|
||||
A reference to the parent issue on the issue tracker (if the source was an existing issue, otherwise omit this section).
|
||||
|
||||
## What to build
|
||||
|
||||
A concise description of this vertical slice. Describe the end-to-end behavior, not layer-by-layer implementation.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Criterion 1
|
||||
- [ ] Criterion 2
|
||||
- [ ] Criterion 3
|
||||
|
||||
## Blocked by
|
||||
|
||||
- A reference to the blocking ticket (if any)
|
||||
|
||||
Or "None - can start immediately" if no blockers.
|
||||
|
||||
</issue-template>
|
||||
|
||||
Do NOT close or modify any parent issue.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
name: to-prd
|
||||
description: Turn the current conversation context into a PRD and publish it to the project issue tracker. Use when user wants to create a PRD from the current context.
|
||||
---
|
||||
|
||||
This skill takes the current conversation context and codebase understanding and produces a PRD. Do NOT interview the user — just synthesize what you already know.
|
||||
|
||||
The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not.
|
||||
|
||||
## Process
|
||||
|
||||
1. Explore the repo to understand the current state of the codebase, if you haven't already. Use the project's domain glossary vocabulary throughout the PRD, and respect any ADRs in the area you're touching.
|
||||
|
||||
2. Sketch out the major modules you will need to build or modify to complete the implementation. Actively look for opportunities to extract deep modules that can be tested in isolation.
|
||||
|
||||
A deep module (as opposed to a shallow module) is one which encapsulates a lot of functionality in a simple, testable interface which rarely changes.
|
||||
|
||||
Check with the user that these modules match their expectations. Check with the user which modules they want tests written for.
|
||||
|
||||
3. Write the PRD using the template below, then publish it to the project issue tracker. Apply the `needs-triage` triage label so it enters the normal triage flow.
|
||||
|
||||
<prd-template>
|
||||
|
||||
## Problem Statement
|
||||
|
||||
The problem that the user is facing, from the user's perspective.
|
||||
|
||||
## Solution
|
||||
|
||||
The solution to the problem, from the user's perspective.
|
||||
|
||||
## User Stories
|
||||
|
||||
A LONG, numbered list of user stories. Each user story should be in the format of:
|
||||
|
||||
1. As an <actor>, I want a <feature>, so that <benefit>
|
||||
|
||||
<user-story-example>
|
||||
1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending
|
||||
</user-story-example>
|
||||
|
||||
This list of user stories should be extremely extensive and cover all aspects of the feature.
|
||||
|
||||
## Implementation Decisions
|
||||
|
||||
A list of implementation decisions that were made. This can include:
|
||||
|
||||
- The modules that will be built/modified
|
||||
- The interfaces of those modules that will be modified
|
||||
- Technical clarifications from the developer
|
||||
- Architectural decisions
|
||||
- Schema changes
|
||||
- API contracts
|
||||
- Specific interactions
|
||||
|
||||
Do NOT include specific file paths or code snippets. They may end up being outdated very quickly.
|
||||
|
||||
## Testing Decisions
|
||||
|
||||
A list of testing decisions that were made. Include:
|
||||
|
||||
- A description of what makes a good test (only test external behavior, not implementation details)
|
||||
- Which modules will be tested
|
||||
- Prior art for the tests (i.e. similar types of tests in the codebase)
|
||||
|
||||
## Out of Scope
|
||||
|
||||
A description of the things that are out of scope for this PRD.
|
||||
|
||||
## Further Notes
|
||||
|
||||
Any further notes about the feature.
|
||||
|
||||
</prd-template>
|
||||
@@ -0,0 +1,231 @@
|
||||
---
|
||||
name: touying-author
|
||||
description: Author, refactor, and troubleshoot Typst slide decks built with Touying
|
||||
---
|
||||
|
||||
# Touying Author
|
||||
|
||||
Guide Typst presentation authoring with Touying, emphasizing clean structure, repeatable configuration, and slide-safe patterns.
|
||||
|
||||
## Quick start
|
||||
- Import Touying and a theme, then apply the theme with `#show: <theme>.with(...)`.
|
||||
- Keep configuration centralized; include slide content from separate files.
|
||||
- Use headings to create slides; use `#slide` for custom layouts or animations.
|
||||
- Start from `examples/simple.typ` for a minimal deck, or `examples/default.typ` for the bare theme.
|
||||
|
||||
Snippet from `examples/simple.typ`:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: [Simple slides],
|
||||
)
|
||||
```
|
||||
|
||||
## Best practices and code structure
|
||||
|
||||
- Use a single entry file (e.g., `main.typ`) that applies `#show` and all `config-*` calls.
|
||||
- For multi-file decks, follow the `globals.typ` + `main.typ` + `content.typ` pattern; use `#include` for content and `#import` for globals to avoid circular refs.
|
||||
- Docs use both `config.typ` (see `docs/start.md`) and `globals.typ` (see `docs/multi-file.md`) for the shared config file; pick one name and use it consistently in your project.
|
||||
- For large decks, move `content.typ` into `sections/` and include `sections/content.typ` (and optional `sections/another-section.typ`) from `main.typ`.
|
||||
- Prefer `config-page`, `config-common`, `config-info`, `config-colors`, `config-methods`, and `config-store` over direct `set page` or ad-hoc global `show`.
|
||||
- Use headings for most slides; use `config-common(slide-level: n)` to choose which heading levels create slides.
|
||||
- Use `#slide` only for custom layout or animation; always wrap slide functions with `touying-slide-wrapper`.
|
||||
- For callback-style animation (`#slide(repeat: n, self => [...])`), set `repeat` explicitly and use `utils.methods(self)` to access `uncover`, `only`, and `alternatives`.
|
||||
|
||||
### Single-file structure
|
||||
|
||||
```
|
||||
.
|
||||
├── globals.typ
|
||||
├── main.typ
|
||||
└── content.typ
|
||||
```
|
||||
|
||||
### Multi-file structure
|
||||
|
||||
```
|
||||
.
|
||||
├── globals.typ
|
||||
├── main.typ
|
||||
└── sections/
|
||||
├── content.typ
|
||||
└── another-section.typ
|
||||
```
|
||||
|
||||
## Core API map (exports)
|
||||
|
||||
- Slides: `touying-slides`, `slide`, `touying-slide`, `touying-slide-wrapper`, `empty-slide`
|
||||
- Dynamics: `pause`, `meanwhile`, `uncover`, `only`, `effect`, `alternatives`, `alternatives-match`, `alternatives-fn`, `alternatives-cases`
|
||||
- Config: `config-common`, `config-page`, `config-info`, `config-colors`, `config-methods`, `config-store`, `default-config`, `touying-set-config`, `appendix`
|
||||
- Utilities: `utils.*` (fit-to-height, fit-to-width, cover helpers, progress, heading helpers)
|
||||
- Components: `components.side-by-side`, `components.adaptive-columns`, `components.progressive-outline`, `components.custom-progressive-outline`
|
||||
- Integrations: `touying-reducer`, `touying-equation`, `touying-mitex`, `speaker-note`, `pdfpc.*`
|
||||
- Recall: `touying-recall`, `touying-fn-wrapper`
|
||||
|
||||
## Slide structure and headings
|
||||
|
||||
- Use heading labels to control numbering/outline/bookmarks: use `<touying:hidden>` (see `docs/code-styles.md`), and see `docs/changelog.md` for `<touying:unnumbered>`, `<touying:unoutlined>`, `<touying:unbookmarked>`, and `<touying:skip>`.
|
||||
- Use `components.adaptive-columns(outline(...))` for a table of contents slide; use `components.progressive-outline` for progress-aware outlines.
|
||||
- Use `== <touying:hidden>` to insert a blank title slide and clear the previous heading context.
|
||||
- Use `#pagebreak()` or `---` to split slides without changing headings.
|
||||
- Use `#empty-slide[...]` for slides without header/footer.
|
||||
- Use `config-common(handout: true)` to keep only the last subslide per slide in handout output.
|
||||
- Use `#show: appendix` to freeze last-slide counts after the main deck.
|
||||
|
||||
Snippet from `examples/default.typ`:
|
||||
|
||||
```typst
|
||||
= Outline <touying:hidden>
|
||||
|
||||
#components.adaptive-columns(outline(title: none, indent: 1em))
|
||||
```
|
||||
|
||||
## Animations and dynamic content
|
||||
|
||||
- Use `#pause` and `#meanwhile` for simple reveals; avoid using them inside `context` where marks are not supported.
|
||||
- Use `#uncover` to reserve layout space; use `#only` to remove layout space when hidden.
|
||||
- When marks cause warnings, use callback-style slides with `repeat` and `utils.methods(self)`.
|
||||
- For math animations, use `pause`/`meanwhile` inside `$ ... $`; use `touying-equation` when you need the helper for inline equation text (you can also use `#pause` or `#pause;`).
|
||||
- See `examples/example.typ` for simple/complex/callback animations and equation animations.
|
||||
|
||||
Snippet from `examples/simple.typ`:
|
||||
|
||||
```typst
|
||||
== Dynamic slide
|
||||
|
||||
Did you know that...
|
||||
|
||||
#pause
|
||||
|
||||
...you can see the current section at the top of the slide?
|
||||
```
|
||||
|
||||
Snippet from `examples/example.typ`:
|
||||
```typst
|
||||
#slide(
|
||||
repeat: 3,
|
||||
self => [
|
||||
#let (uncover, only, alternatives) = utils.methods(self)
|
||||
|
||||
At subslide #self.subslide, we can
|
||||
|
||||
use #uncover("2-")[`#uncover` function] for reserving space,
|
||||
|
||||
use #only("2-")[`#only` function] for not reserving space,
|
||||
|
||||
#alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives.
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
## Layout and theming
|
||||
- Use `composer` in `#slide` for columns; pass `(1fr, 2fr)` or a custom `grid` function.
|
||||
- Use `config-page` for margin, header, footer, and background; do not use `set page` directly.
|
||||
- Use `config-methods(cover: utils.semi-transparent-cover.with(alpha: 85%))` only when layout changes are acceptable.
|
||||
- Use `config-store` to stash theme-specific values for headers/footers or navigation elements.
|
||||
- Use `config-common(new-section-slide-fn: none)` to disable automatic section slides, or provide a custom function to replace them.
|
||||
- Apply global styles either around `#show: <theme>.with(...)` or via `config-methods(init: ...)` in a theme.
|
||||
- Use `config-info(...)` for title/author/date and `config-common(datetime-format: ...)` to control date formatting.
|
||||
|
||||
Snippet from `examples/default.typ`:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.default: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: default-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-common(
|
||||
slide-level: 3,
|
||||
zero-margin-header: false,
|
||||
),
|
||||
config-colors(primary: blue),
|
||||
config-methods(alert: utils.alert-with-primary-color),
|
||||
config-page(
|
||||
header: text(gray, utils.display-current-short-heading(level: 2)),
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
## Speaker notes and presenter tools
|
||||
|
||||
- Add notes with `#speaker-note[...]`.
|
||||
- Show notes on second screen with `config-common(show-notes-on-second-screen: right)` or `bottom`.
|
||||
- Export pdfpc metadata with `enable-pdfpc: true` and `typst query --field value --one "<pdfpc-file>"`.
|
||||
|
||||
## Use bundled docs and examples
|
||||
|
||||
- Read only the specific docs needed for the task; avoid loading the full docs tree.
|
||||
- Read `docs/start.md` and `docs/intro.md` for basics and import patterns.
|
||||
- Read `docs/multi-file.md` for multi-file layout and include patterns.
|
||||
- Read `docs/layout.md` and `docs/sections.md` for slide-level and heading behavior.
|
||||
- Read `docs/code-styles.md` for simple vs block style and pagination tricks.
|
||||
- Read `docs/global-settings.md` for global styles and `config-info` usage.
|
||||
- Read `docs/dynamic/*.md` for `pause`, `meanwhile`, cover behavior, and equation animation.
|
||||
- Read `docs/themes/*.md` for theme-specific APIs and defaults.
|
||||
- Read `docs/external/*.md` for pdfpc and Pympress usage.
|
||||
- Read `docs/integration/*.md` for CeTZ/Fletcher/Theorion/MiTeX integrations.
|
||||
- Use `examples/*.typ` as working templates for each theme.
|
||||
|
||||
## File tree (docs and examples)
|
||||
|
||||
```
|
||||
docs/
|
||||
├── build-your-own-theme.md
|
||||
├── changelog.md
|
||||
├── code-styles.md
|
||||
├── dynamic
|
||||
│ ├── complex.md
|
||||
│ ├── cover.md
|
||||
│ ├── equation.md
|
||||
│ ├── handout.md
|
||||
│ ├── other.md
|
||||
│ └── simple.md
|
||||
├── external
|
||||
│ ├── pdfpc.md
|
||||
│ ├── pympress.md
|
||||
│ └── typst-preview.md
|
||||
├── global-settings.md
|
||||
├── integration
|
||||
│ ├── cetz.md
|
||||
│ ├── codly.md
|
||||
│ ├── fletcher.md
|
||||
│ ├── mitex.md
|
||||
│ ├── pinit.md
|
||||
│ └── theorion.md
|
||||
├── intro.md
|
||||
├── layout.md
|
||||
├── multi-file.md
|
||||
├── progress
|
||||
│ ├── counters.md
|
||||
│ └── sections.md
|
||||
├── sections.md
|
||||
├── start.md
|
||||
├── themes
|
||||
│ ├── aqua.md
|
||||
│ ├── custom.md
|
||||
│ ├── dewdrop.md
|
||||
│ ├── metropolis.md
|
||||
│ ├── simple.md
|
||||
│ ├── stargazer.md
|
||||
│ └── university.md
|
||||
└── utilities
|
||||
└── fit-to.md
|
||||
|
||||
examples/
|
||||
├── aqua-zh.typ
|
||||
├── aqua.typ
|
||||
├── default.typ
|
||||
├── dewdrop.typ
|
||||
├── example.typ
|
||||
├── metropolis.typ
|
||||
├── simple.typ
|
||||
├── stargazer.typ
|
||||
└── university.typ
|
||||
```
|
||||
@@ -0,0 +1,448 @@
|
||||
---
|
||||
sidebar_position: 11
|
||||
---
|
||||
|
||||
# Build Your Own Theme
|
||||
|
||||
Creating your own theme with Touying can be a bit complex due to the many concepts we've introduced. But rest assured, if you do create a theme with Touying, you might deeply appreciate the convenience and powerful customizability that Touying offers. You can refer to the [source code of the themes](https://github.com/touying-typ/touying/tree/main/themes). The main things you need to implement are:
|
||||
|
||||
- Customizing the `xxx-theme` function;
|
||||
- Customizing the color theme, i.e., `config-colors()`;
|
||||
- Customizing the header;
|
||||
- Customizing the footer;
|
||||
- Customizing the `slide` method;
|
||||
- Customizing special slide methods, such as `title-slide` and `focus-slide` methods;
|
||||
|
||||
To demonstrate how to create a theme with Touying, let's step by step create a simple and aesthetically pleasing Bamboo theme.
|
||||
|
||||
## Modifying Existing Themes
|
||||
|
||||
If you want to modify a Touying internal theme locally instead of creating one from scratch, you can achieve this by:
|
||||
|
||||
1. Copying the [theme code](https://github.com/touying-typ/touying/tree/main/themes) from the `themes` directory to your local, for example, copying `themes/university.typ` to your local `university.typ`.
|
||||
2. Replacing the `#import "../src/exports.typ": *` command at the top of the `university.typ` file with `#import "@preview/touying:0.6.1": *`.
|
||||
|
||||
Then you can import and use the theme by:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import "university.typ": *
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
## Importing
|
||||
|
||||
Depending on whether the theme is your own or part of Touying, you can import it in two ways:
|
||||
|
||||
If it's just for your own use, you can directly import Touying:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
```
|
||||
|
||||
If you want the theme to be part of Touying, placed in the Touying `themes` directory, then you should change the import statement above to
|
||||
|
||||
```typst
|
||||
#import "../src/exports.typ": *
|
||||
```
|
||||
|
||||
And add
|
||||
|
||||
```typst
|
||||
#import "bamboo.typ"
|
||||
```
|
||||
|
||||
in Touying's `themes/themes.typ`.
|
||||
|
||||
## register Function and init Method
|
||||
|
||||
Next, we will differentiate between the `bamboo.typ` template file and the `main.typ` file, which is sometimes omitted.
|
||||
|
||||
Generally, the first step in making slides is to determine the font size and page aspect ratio, so we need to register an initialization method:
|
||||
|
||||
```typst
|
||||
// bamboo.typ
|
||||
#import "@preview/touying:0.6.1": *
|
||||
|
||||
#let bamboo-theme(
|
||||
aspect-ratio: "16-9",
|
||||
..args,
|
||||
body,
|
||||
) = {
|
||||
set text(size: 20pt)
|
||||
|
||||
show: touying-slides.with(
|
||||
config-page(paper: "presentation-" + aspect-ratio),
|
||||
config-common(
|
||||
slide-fn: slide,
|
||||
),
|
||||
..args,
|
||||
)
|
||||
|
||||
body
|
||||
}
|
||||
|
||||
// main.typ
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import "bamboo.typ": *
|
||||
|
||||
#show: bamboo-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
= First Section
|
||||
|
||||
== First Slide
|
||||
|
||||
A slide with a title and an *important* information.
|
||||
```
|
||||
|
||||
As you can see, we've created a `bamboo-theme` function and passed in an `aspect-ratio` parameter to set the page aspect ratio. We've also added `set text(size: 20pt)` to set the font size. You can also place some additional global style settings here, such as `set par(justify: true)`, etc. If you need to use `self`, you might consider using `config-methods(init: (self: none, body) => { .. })` to register an `init` method.
|
||||
|
||||
As you can see, later in `main.typ`, we apply our style settings through `#show: bamboo-theme.with(aspect-ratio: "16-9")`, and internally `bamboo` uses `show: touying-slides.with()` for corresponding configurations.
|
||||
|
||||
## Color Theme
|
||||
|
||||
Picking an aesthetically pleasing color theme for your slides is key to making good slides. Touying provides built-in color theme support to minimize API differences between different themes. Touying offers two dimensions of color selection. The first dimension is `neutral`, `primary`, `secondary`, and `tertiary`, which are used to distinguish color tones, with `primary` being the most commonly used theme color. The second dimension is `default`, `light`, `lighter`, `lightest`, `dark`, `darker`, `darkest`, which are used to distinguish brightness levels.
|
||||
|
||||
Since we are creating the Bamboo theme, we have chosen a color close to bamboo for the `primary` theme color, `rgb("#5E8B65")`, and added neutral colors `neutral-lightest`, `neutral-darkest`, respectively, as the background and font colors.
|
||||
|
||||
As shown in the following code, we can use the `config-colors()` method to modify the color theme. Its essence is a wrapper for `self.colors += (..)`.
|
||||
|
||||
```typst
|
||||
#let bamboo-theme(
|
||||
aspect-ratio: "16-9",
|
||||
..args,
|
||||
body,
|
||||
) = {
|
||||
set text(size: 20pt)
|
||||
|
||||
show: touying-slides.with(
|
||||
config-page(paper: "presentation-" + aspect-ratio),
|
||||
config-common(
|
||||
slide-fn: slide,
|
||||
),
|
||||
config-colors(
|
||||
primary: rgb("#5E8B65"),
|
||||
neutral-lightest: rgb("#ffffff"),
|
||||
neutral-darkest: rgb("#000000"),
|
||||
),
|
||||
..args,
|
||||
)
|
||||
|
||||
body
|
||||
}
|
||||
```
|
||||
|
||||
After adding the color theme as shown above, we can access this color through `self.colors.primary`.
|
||||
|
||||
It's also worth noting that users can change the color theme at any time in `main.typ` by using `config-colors()` or
|
||||
|
||||
```typst
|
||||
#show: touying-set-config.with(config-colors(
|
||||
primary: blue,
|
||||
neutral-lightest: rgb("#ffffff"),
|
||||
neutral-darkest: rgb("#000000"),
|
||||
))
|
||||
```
|
||||
|
||||
This feature of being able to change the color theme at any time is a testament to Touying's powerful customizability.
|
||||
|
||||
## Practical: Custom Alert Method
|
||||
|
||||
Generally, we need to provide a `#alert[..]` function for users, similar to `#strong[..]`, both of which are used to emphasize the current text. Typically, `#alert[..]` will change the text color to the theme color, which will look more aesthetically pleasing, and this is our next goal.
|
||||
|
||||
We add a line in the `register` function:
|
||||
|
||||
```typst
|
||||
config-methods(alert: (self: none, it) => text(fill: self.colors.primary, it))
|
||||
```
|
||||
|
||||
This code means to change the text color to `self.colors.primary`, and the `self` here is passed in through the parameter `self: none`, so that we can get the `primary` theme color in real-time.
|
||||
|
||||
We can also use a shorthand.
|
||||
|
||||
```typst
|
||||
config-methods(alert: utils.alert-with-primary-color)
|
||||
```
|
||||
|
||||
## Custom Header and Footer
|
||||
|
||||
Here, I assume you have read the page layout section, so we know that we should add a header and footer to the slides.
|
||||
|
||||
First, we add `config-store(title: none)`, which means that we save the current slide's title as a member variable `self.store.title` inside `self`, making it convenient for us to use in the header and for subsequent modifications. Similarly, we also create a `config-store(footer: footer)` and save the `footer: none` parameter of the `bamboo-theme` function for display in the footer at the bottom left corner.
|
||||
|
||||
Then it's worth noting that our header is actually a content function with `self` as a parameter, like `let header(self) = { .. }`, rather than a simple content, so that we can get the information we need from the latest `self`, such as `self.store.title`. The footer is the same.
|
||||
|
||||
The `components.cell` used here is actually `#let cell = block.with(width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false)`, and `show: components.cell` is also a shorthand for `components.cell(body)`, and the `show: pad.with(.4em)` for the footer is the same.
|
||||
|
||||
Another point to note is that the `utils` module contains many contents and methods related to counters and states, such as `utils.display-current-heading(level: 1)` for displaying the current `section`, and `context utils.slide-counter.display() + " / " + utils.last-slide-number` for displaying the current page number and total number of pages.
|
||||
|
||||
We also find that we use syntax like `utils.call-or-display(self, self.store.footer)` to display `self.store.footer`, which is to deal with the situation of `self.store.footer = self => {..}`, so that we can unify the display of content functions and content.
|
||||
|
||||
To ensure that the header and footer are displayed correctly and have enough spacing from the main text, we need to set the margin, such as `config-page(margin: (top: 4em, bottom: 1.5em, x: 2em))`.
|
||||
|
||||
We also need to customize a `slide` method, which accepts `#let slide(title: auto, ..args) = touying-slide-wrapper(self => {..})`, where `self` in the callback function is a required parameter to get the latest `self`; the second `title` is used to update `self.store.title` for display in the header; the third `..args` is used to collect the remaining parameters and pass them to `touying-slide(self: self, ..args)`, which is also necessary for the normal functioning of Touying's `slide` feature. Moreover, we need to register this method in the `bamboo-theme` function using `config-methods(slide: slide)`.
|
||||
|
||||
```typst
|
||||
// bamboo.typ
|
||||
#import "@preview/touying:0.6.1": *
|
||||
|
||||
#let slide(title: auto, ..args) = touying-slide-wrapper(self => {
|
||||
if title != auto {
|
||||
self.store.title = title
|
||||
}
|
||||
// set page
|
||||
let header(self) = {
|
||||
set align(top)
|
||||
show: components.cell.with(fill: self.colors.primary, inset: 1em)
|
||||
set align(horizon)
|
||||
set text(fill: self.colors.neutral-lightest, size: .7em)
|
||||
utils.display-current-heading(level: 1)
|
||||
linebreak()
|
||||
set text(size: 1.5em)
|
||||
if self.store.title != none {
|
||||
utils.call-or-display(self, self.store.title)
|
||||
} else {
|
||||
utils.display-current-heading(level: 2)
|
||||
}
|
||||
}
|
||||
let footer(self) = {
|
||||
set align(bottom)
|
||||
show: pad.with(.4em)
|
||||
set text(fill: self.colors.neutral-darkest, size: .8em)
|
||||
utils.call-or-display(self, self.store.footer)
|
||||
h(1fr)
|
||||
context utils.slide-counter.display() + " / " + utils.last-slide-number
|
||||
}
|
||||
self = utils.merge-dicts(
|
||||
self,
|
||||
config-page(
|
||||
header: header,
|
||||
footer: footer,
|
||||
),
|
||||
)
|
||||
touying-slide(self: self, ..args)
|
||||
})
|
||||
|
||||
#let bamboo-theme(
|
||||
aspect-ratio: "16-9",
|
||||
footer: none,
|
||||
..args,
|
||||
body,
|
||||
) = {
|
||||
set text(size: 20pt)
|
||||
|
||||
show: touying-slides.with(
|
||||
config-page(
|
||||
paper: "presentation-" + aspect-ratio,
|
||||
margin: (top: 4em, bottom: 1.5em, x: 2em),
|
||||
),
|
||||
config-common(
|
||||
slide-fn: slide,
|
||||
),
|
||||
config-methods(
|
||||
alert: utils.alert-with-primary-color,
|
||||
),
|
||||
config-colors(
|
||||
primary: rgb("#5E8B65"),
|
||||
neutral-lightest: rgb("#ffffff"),
|
||||
neutral-darkest: rgb("#000000"),
|
||||
),
|
||||
config-store(
|
||||
title: none,
|
||||
footer: footer,
|
||||
),
|
||||
..args,
|
||||
)
|
||||
|
||||
body
|
||||
}
|
||||
|
||||
|
||||
// main.typ
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import "bamboo.typ": *
|
||||
|
||||
#show: bamboo-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
= First Section
|
||||
|
||||
== First Slide
|
||||
|
||||
A slide with a title and an *important* information.
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Custom Special Slides
|
||||
|
||||
On the basis of the basic slides we've created, we further add some special slide functions, such as `title-slide`, `focus-slide`, and custom `slides` methods.
|
||||
|
||||
For the `title-slide` method, first, we can obtain the information saved in `self.info` through `let info = self.info + args.named()`, and we can also update the information with `args.named()` passed in through the function parameters for subsequent use in the form of `info.title`. The specific page content `body` will vary for each theme, so I won't go into too much detail here.
|
||||
|
||||
For the `new-section-slide` method, it's the same, but the only thing to note is that we registered `new-section-slide-fn: new-section-slide` in `config-methods()`, so `new-section-slide` will be automatically called when encountering a first-level heading.
|
||||
|
||||
```typst
|
||||
// bamboo.typ
|
||||
#import "@preview/touying:0.6.1": *
|
||||
|
||||
#let slide(title: auto, ..args) = touying-slide-wrapper(self => {
|
||||
if title != auto {
|
||||
self.store.title = title
|
||||
}
|
||||
// set page
|
||||
let header(self) = {
|
||||
set align(top)
|
||||
show: components.cell.with(fill: self.colors.primary, inset: 1em)
|
||||
set align(horizon)
|
||||
set text(fill: self.colors.neutral-lightest, size: .7em)
|
||||
utils.display-current-heading(level: 1)
|
||||
linebreak()
|
||||
set text(size: 1.5em)
|
||||
if self.store.title != none {
|
||||
utils.call-or-display(self, self.store.title)
|
||||
} else {
|
||||
utils.display-current-heading(level: 2)
|
||||
}
|
||||
}
|
||||
let footer(self) = {
|
||||
set align(bottom)
|
||||
show: pad.with(.4em)
|
||||
set text(fill: self.colors.neutral-darkest, size: .8em)
|
||||
utils.call-or-display(self, self.store.footer)
|
||||
h(1fr)
|
||||
context utils.slide-counter.display() + " / " + utils.last-slide-number
|
||||
}
|
||||
self = utils.merge-dicts(
|
||||
self,
|
||||
config-page(
|
||||
header: header,
|
||||
footer: footer,
|
||||
),
|
||||
)
|
||||
touying-slide(self: self, ..args)
|
||||
})
|
||||
|
||||
#let title-slide(..args) = touying-slide-wrapper(self => {
|
||||
let info = self.info + args.named()
|
||||
let body = {
|
||||
set align(center + horizon)
|
||||
block(
|
||||
fill: self.colors.primary,
|
||||
width: 80%,
|
||||
inset: (y: 1em),
|
||||
radius: 1em,
|
||||
text(size: 2em, fill: self.colors.neutral-lightest, weight: "bold", info.title),
|
||||
)
|
||||
set text(fill: self.colors.neutral-darkest)
|
||||
if info.author != none {
|
||||
block(info.author)
|
||||
}
|
||||
if info.date != none {
|
||||
block(utils.display-info-date(self))
|
||||
}
|
||||
}
|
||||
touying-slide(self: self, body)
|
||||
})
|
||||
|
||||
#let new-section-slide(self: none, body) = touying-slide-wrapper(self => {
|
||||
let main-body = {
|
||||
set align(center + horizon)
|
||||
set text(size: 2em, fill: self.colors.primary, weight: "bold", style: "italic")
|
||||
utils.display-current-heading(level: 1)
|
||||
}
|
||||
touying-slide(self: self, main-body)
|
||||
})
|
||||
|
||||
#let focus-slide(body) = touying-slide-wrapper(self => {
|
||||
self = utils.merge-dicts(
|
||||
self,
|
||||
config-page(
|
||||
fill: self.colors.primary,
|
||||
margin: 2em,
|
||||
),
|
||||
)
|
||||
set text(fill: self.colors.neutral-lightest, size: 2em)
|
||||
touying-slide(self: self, align(horizon + center, body))
|
||||
})
|
||||
|
||||
#let bamboo-theme(
|
||||
aspect-ratio: "16-9",
|
||||
footer: none,
|
||||
..args,
|
||||
body,
|
||||
) = {
|
||||
set text(size: 20pt)
|
||||
|
||||
show: touying-slides.with(
|
||||
config-page(
|
||||
paper: "presentation-" + aspect-ratio,
|
||||
margin: (top: 4em, bottom: 1.5em, x: 2em),
|
||||
),
|
||||
config-common(
|
||||
slide-fn: slide,
|
||||
new-section-slide-fn: new-section-slide,
|
||||
),
|
||||
config-methods(alert: utils.alert-with-primary-color),
|
||||
config-colors(
|
||||
primary: rgb("#5E8B65"),
|
||||
neutral-lightest: rgb("#ffffff"),
|
||||
neutral-darkest: rgb("#000000"),
|
||||
),
|
||||
config-store(
|
||||
title: none,
|
||||
footer: footer,
|
||||
),
|
||||
..args,
|
||||
)
|
||||
|
||||
body
|
||||
}
|
||||
|
||||
|
||||
// main.typ
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import "bamboo.typ": *
|
||||
|
||||
#show: bamboo-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: self => self.info.institution,
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
),
|
||||
)
|
||||
|
||||
#title-slide()
|
||||
|
||||
= First Section
|
||||
|
||||
== First Slide
|
||||
|
||||
A slide with a title and an *important* information.
|
||||
|
||||
#focus-slide[
|
||||
Focus on it!
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
## Conclusion
|
||||
|
||||
Congratulations! You've created a simple and elegant theme. Perhaps you may find that Touying introduces a wealth of concepts, making it initially challenging to grasp. This is normal, as Touying opts for functionality over simplicity. However, thanks to Touying's comprehensive and unified approach, you can easily extract commonalities between different themes and transfer your knowledge seamlessly. You can also save global variables, modify existing themes, or switch between themes effortlessly, showcasing the benefits of Touying's decoupling.
|
||||
@@ -0,0 +1,321 @@
|
||||
---
|
||||
sidebar_position: 14
|
||||
---
|
||||
|
||||
# Changelog
|
||||
|
||||
## v0.6.1
|
||||
|
||||
Added support for the [theorion](https://github.com/OrangeX4/typst-theorion) package, and used it as the default math theorem environment.
|
||||
|
||||
## v0.6.0
|
||||
|
||||
It's not a big update, but it's the first touying release since typst 0.13 was released.
|
||||
|
||||
### Features
|
||||
|
||||
- feat: add auto style for display-current-heading.
|
||||
- For users, you can use `show heading: set text(blue)` to change color for heading in some themes like `dewdrop`.
|
||||
- For theme creator, you can use syntax like `utils.display-current-heading(level: 1, style: auto)` to achieve the same result.
|
||||
- feat: apply config-info information to `set document`.
|
||||
- feat: set `stretch: false` by default for `alternatives` functions. This is **a minor breaking change**, but I think it would be more intuitive: no auto empty space.
|
||||
|
||||
### Fixes
|
||||
|
||||
- fix: fix error with uncover using semi-transparent-cover
|
||||
- fix: fix type string comparison https://github.com/touying-typ/touying/pull/153
|
||||
- fix: fix horizontal-line bug in typst 0.13.0
|
||||
- refactor: fix display-current-short-heading
|
||||
|
||||
|
||||
## v0.5.4 & v0.5.5
|
||||
|
||||
### Features
|
||||
|
||||
- docs: improve param documentation and we have better hints for tinymist https://github.com/touying-typ/touying/pull/98
|
||||
- feat: fake frozon states support for `heading` https://github.com/touying-typ/touying/pull/124
|
||||
- feat: add alpha-changing-cover and color-changing-cover https://github.com/touying-typ/touying/pull/129
|
||||
- feat: add effect function https://github.com/touying-typ/touying/issues/111
|
||||
- Example: `#effect(text.with(fill: red), "2-")[Something]` will display `[Something]` if the current slide is 2 or later.
|
||||
- feat: add argument `config: (..)` for `xxx-slide` functions
|
||||
- feat: add `align` argument for university theme
|
||||
|
||||
### Fixes
|
||||
|
||||
- fix: also hide enum numbers with show-hide-set-list-marker-none https://github.com/touying-typ/touying/pull/114
|
||||
- fix: fixed progress bar not to break apart when global figure gutter is set nonzero https://github.com/touying-typ/touying/pull/120
|
||||
- fix: fixed frozen-counters bug with multiple #pause commands https://github.com/touying-typ/touying/pull/124
|
||||
- fix: fixed incorrect page num when draft is true https://github.com/touying-typ/touying/pull/125
|
||||
- fix: fix behaviors of fit-to-height and fit-to-width partially https://github.com/touying-typ/touying/pull/131
|
||||
- fix: duplicated footnotes in headings https://github.com/touying-typ/touying/pull/132
|
||||
- fix: do not hardcode page sizes https://github.com/touying-typ/touying/pull/134
|
||||
- fix: add default numbering for page https://github.com/touying-typ/touying/issues/100
|
||||
- refactor: move show-strong-with-alert to per-slide level https://github.com/touying-typ/touying/issues/123
|
||||
- refactor: remove unnecessary `config-page(fill: ...)`
|
||||
- theme(metropolis): fix color of title page and fix https://github.com/touying-typ/touying/issues/103
|
||||
- theme(metropolis): fixed metropolis slide's header to return content if title is specified https://github.com/touying-typ/touying/pull/126
|
||||
- theme(metropolis): respect colors dict in metropolis theme https://github.com/touying-typ/touying/pull/133
|
||||
|
||||
Thanks for the contributions from [@enklht](https://github.com/enklht).
|
||||
|
||||
|
||||
## v0.5.3
|
||||
|
||||
### Features
|
||||
|
||||
- feat: add `stretch` parameter for `#alternatives[]` function class. This allows us to handle cases where the internal element is a context expression.
|
||||
- feat: add `config-common(align-enum-marker-with-baseline: true)` for aligning the enum marker with the baseline.
|
||||
- feat: add `linebreaks` option to `components.mini-slides`. https://github.com/touying-typ/touying/pull/96
|
||||
- feat: add `<touying:skip>` label to skip a new-section-slide.
|
||||
- feat: add `config-common(show-hide-set-list-marker-none: true)` to make the markers of `list` and `enum` invisible after `#pause`.
|
||||
- feat: add `config-common(bibliography-as-footnote: bibliography(title: none, "ref.bib"))` to display the bibliography in footnotes.
|
||||
- refactor: add `config-common(show-strong-with-alert: true)` configuration to display strong text with an alert. (small breaking change for some themes)
|
||||
- refactor: refactor `display-current-heading` for preserving heading style in title and subtitle. https://github.com/touying-typ/touying/issues/71
|
||||
- refactor: make `new-section-slide-fn` function class can receive `body` parameter. We can use `receive-body-for-new-section-slide-fn` to control it. **(Breaking change)**
|
||||
- For example, you can add `#speaker-note[]` for a new section slide, like `= Section Title \ #speaker-note[]`.
|
||||
- If you don't want to append content to the body of the new section slide, you can use `---` after the section title.
|
||||
|
||||
### Fixes
|
||||
|
||||
- fix outdated documentation.
|
||||
- fix bug of `enable-frozen-states-and-counters` in handout mode.
|
||||
- fix unusable `square()` function. https://github.com/touying-typ/touying/issues/73
|
||||
- fix hidden footer for `show-notes-on-second-screen: bottom`. https://github.com/touying-typ/touying/issues/89
|
||||
- fix metadata element in table cells. https://github.com/touying-typ/touying/issues/77 https://github.com/touying-typ/touying/issues/95
|
||||
- fix `auto-offset-for-heading` to `false` by default.
|
||||
- fix uncover/only hides more content than it should. https://github.com/touying-typ/touying/issues/85
|
||||
- theme(simple): fix wrong title and subtitle. https://github.com/touying-typ/touying/issues/70
|
||||
|
||||
|
||||
## v0.5.1 & v0.5.2
|
||||
|
||||
- Fix somg bugs.
|
||||
|
||||
|
||||
## v0.5.0
|
||||
|
||||
This is a significant disruptive version update. Touying has removed many mistakes that resulted from incorrect decisions. We have redesigned numerous features. The goal of this version is to make Touying more user-friendly, more flexible, and more powerful.
|
||||
|
||||
**Major changes include:**
|
||||
|
||||
- Avoiding closures and OOP syntax, which makes Touying's configuration simpler and allows for the use of document comments to provide more auto-completion information for the slide function.
|
||||
- The existing `#let slide(self: none, ..args) = { .. }` is now `#let slide(..args) = touying-slide-wrapper(self => { .. })`, where `self` is automatically injected.
|
||||
- We can use `config-xxx` syntax to configure Touying, for example, `#show: university-theme.with(aspect-ratio: "16-9", config-colors(primary: blue))`.
|
||||
- The `touying-slide` function no longer includes parameters like `section`, `subsection`, and `title`. These will be automatically inserted into the slide as invisible level 1, 2, or 3 headings via `self.headings` (controlled by the `slide-level` configuration).
|
||||
- We can leverage the powerful headings provided by Typst to support numbering, outlines, and bookmarks.
|
||||
- Headings within the `#slide[= XXX]` function will be adjusted to level `slide-level + 1` using the `offset` parameter.
|
||||
- We can use labels on headings to control many aspects, such as supporting the `<touying:hidden>` and other special labels, implementing short headings, or recalling a slide with `#touying-recall()`.
|
||||
- Touying now supports the normal use of `set` and `show` rules at any position, without requiring them to be in specific locations.
|
||||
|
||||
A simple usage example is shown below, and more examples can be found in the `examples` directory:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: "1.1")
|
||||
|
||||
#title-slide()
|
||||
|
||||
= The Section
|
||||
|
||||
== Slide Title
|
||||
|
||||
#lorem(40)
|
||||
```
|
||||
|
||||
**Theme Migration Guide:**
|
||||
|
||||
For detailed changes to specific themes, you can refer to the `themes` directory. Generally, if you want to migrate an existing theme, you should:
|
||||
|
||||
1. Rename the `register` function to `xxx-theme` and remove the `self` parameter.
|
||||
2. Add a `show: touying-slides.with(..)` configuration.
|
||||
- Change `self.methods.colors` to `config-colors(primary: rgb("#xxxxxx"))`.
|
||||
- Change `self.page-args` to `config-page()`.
|
||||
- Change `self.methods.slide = slide` to `config-methods(slide: slide)`.
|
||||
- Change `self.methods.new-section-slide = new-section-slide` to `config-methods(new-section-slide: new-section-slide)`.
|
||||
- Change private theme variables like `self.xxx-footer` to `config-store(footer: [..])`, which you can access through `self.store.footer`.
|
||||
- Move the configuration of headers and footers into the `slide` function rather than in the `xxx-theme` function.
|
||||
- You can directly use `set` or `show` rules in `xxx-theme` or configure them through `config-methods(init: (self: none, body) => { .. })` to fully utilize the `self` parameter.
|
||||
3. For `states.current-section-with-numbering`, you can use `utils.display-current-heading(level: 1)` instead.
|
||||
- If you only need the previous heading regardless of whether it is a section or a subsection, use `utils.display-current-heading()`.
|
||||
4. The `alert` function can be replaced with `config-methods(alert: utils.alert-with-primary-color)`.
|
||||
5. The `touying-outline()` function is no longer needed; you can use `components.adaptive-columns(outline())` instead. Consider using `components.progressive-outline()` or `components.custom-progressive-outline()`.
|
||||
6. Replace `states.slide-counter.display() + " / " + states.last-slide-number` with `context utils.slide-counter.display() + " / " + utils.last-slide-number`. That is, we no longer use `states` but `utils`.
|
||||
7. Remove the `slides` function; we no longer need this function. Instead of implicitly injecting `title-slide()`, explicitly use `#title-slide()`. If necessary, consider adding it in the `xxx-theme` function.
|
||||
8. Change `#let slide(self: none, ..args) = { .. }` to `#let slide(..args) = touying-slide-wrapper(self => { .. })`, where `self` is automatically injected.
|
||||
- Change specific parameter configurations to `self = utils.merge-dicts(self, config-page(fill: self.colors.neutral-lightest))`.
|
||||
- Remove `self = utils.empty-page(self)` and use `config-common(freeze-slide-counter: true)` and `config-page(margin: 0em)` instead.
|
||||
- Change `(self.methods.touying-slide)()` to `touying-slide()`.
|
||||
9. You can insert visible headings into slides by configuring `config-common(subslide-preamble: self => text(1.2em, weight: "bold", utils.display-current-heading(depth: self.slide-level)))`.
|
||||
10. Finally, don't forget to add document comments to your functions so your users can get better auto-completion hints, especially when using the Tinymist plugin.
|
||||
|
||||
**Other Changes:**
|
||||
|
||||
- theme(stargazer): new stargazer theme modified from [Coekjan/touying-buaa](https://github.com/Coekjan/touying-buaa).
|
||||
- feat: implemented fake frozen states support, allowing you to use numbering and `#pause` normally. This behavior can be controlled with `enable-frozen-states-and-counters`, `frozen-states`, and `frozen-counters` in `config-common()`.
|
||||
- feat: implemented `label-only-on-last-subslide` functionality to prevent non-unique label warnings when working with `@equation` and `@figure` in conjunction with `#pause` animations.
|
||||
- feat: added the `touying-recall(<label>)` function to replay a specific slide.
|
||||
- feat: implemented `nontight-list-enum-and-terms`, which defaults to `true` and forces `list`, `enum`, and `terms` to have their `tight` parameter set to `false`. You can control spacing size with `#set list(spacing: 1em)`.
|
||||
- feat: replaced `list` with `terms` implementation to achieve `align-list-marker-with-baseline`, which is off by default.
|
||||
- feat: implemented `scale-list-items`, scaling list items by a factor, e.g., `scale-list-items: 0.8` scales list items by 0.8.
|
||||
- feat: supported direct use of `#pause` and `#meanwhile` in math expressions, such as `$x + pause y$`.
|
||||
- feat: provided `#pause` and `#meanwhile` support for most layout functions, such as `grid` and `table`.
|
||||
- feat: added `#show: appendix` support, essentially equivalent to `#show: touying-set-config.with((appendix: true))`.
|
||||
- feat: Introduced special labels `<touying:hidden>`, `<touying:unnumbered>`, `<touying:unoutlined>`, `<touying:unbookmarked>` to simplify control over heading behavior.
|
||||
- feat: added basic `utils.short-heading` support to display short headings using labels, such as displaying `<sec:my-section>` as "My Section".
|
||||
- feat: added `#components.adaptive-columns()` to achieve adaptive columns that span a page, typically used with the `outline()` function.
|
||||
- feat: added `#show: magic.bibliography-as-footnote.with(bibliography("ref.bib"))` to display the bibliography in footnotes.
|
||||
- feat: added components like `custom-progressive-outline`, `mini-slides`.
|
||||
- feat: removed `touying-outline()`, which can be directly replaced with `outline()`.
|
||||
- fix: replaced potentially incompatible code, such as `type(s) == "string"` and `locate(loc => { .. })`.
|
||||
- fix: Fixed some bugs.
|
||||
|
||||
|
||||
|
||||
## v0.4.2
|
||||
|
||||
- theme(metropolis): decoupled text color with `neutral-dark` (Breaking change)
|
||||
- feat: add mark-style uncover, only and alternatives
|
||||
- feat: add warning for styled block for slides
|
||||
- feat: add warning for touying-temporary-mark
|
||||
- feat: add markup-text for speaker-note
|
||||
- fix: fix bug of slides
|
||||
|
||||
|
||||
## v0.4.1
|
||||
|
||||
### Features
|
||||
|
||||
- feat: support builtin outline and bookmark
|
||||
- feat: support speaker note for dual-screen
|
||||
- feat: add touying-mitex function
|
||||
- feat: touying offers [a gallery page](https://github.com/touying-typ/touying/wiki) via wiki
|
||||
|
||||
### Fixes
|
||||
|
||||
- fix: add outline-slide for dewdrop theme
|
||||
- fix: fix regression of default value "auto" for repeat
|
||||
|
||||
### Miscellaneous Improvements
|
||||
|
||||
- feat: add list support for `touying-outline` function
|
||||
- feat: add auto-reset-footnote
|
||||
- feat: add `freeze-in-empty-page` for better page counter
|
||||
- feat: add `..args` for register method to capture unused arguments
|
||||
|
||||
|
||||
## v0.4.0
|
||||
|
||||
### Features
|
||||
|
||||
- **feat:** support `#footnote[]` for all themes.
|
||||
- **feat:** access subslide and repeat in footer and header by `self => self.subslide`.
|
||||
- **feat:** support numbered theorem environments by [ctheorems](https://typst.app/universe/package/ctheorems).
|
||||
- **feat:** support numbering for sections and subsections.
|
||||
|
||||
### Fixes
|
||||
|
||||
- **fix:** make nested includes work correctly.
|
||||
- **fix:** disable multi-page slides from creating the same section multiple times.
|
||||
|
||||
## Breaking changes
|
||||
|
||||
- **refactor:** remove `self.padding` and add `self.full-header` `self.full-footer` config.
|
||||
|
||||
|
||||
## v0.3.3
|
||||
|
||||
- **template:** move template to `touying-aqua` package, make Touying searchable in [Typst Universe Packages](https://typst.app/universe/search?kind=packages)
|
||||
- **themes:** fix bugs in university and dewdrop theme
|
||||
- **feat:** make set-show rule work without `setting` parameter
|
||||
- **feat:** make `composer` parameter more simpler
|
||||
- **feat:** add `empty-slide` function
|
||||
|
||||
## v0.3.2
|
||||
|
||||
- **fix critical bug:** fix `is-sequence` function, make `grid` and `table` work correctly in touying
|
||||
- **theme:** add aqua theme, thanks for pride7
|
||||
- **theme:** make university theme more configurable
|
||||
- **refactor:** don't export variable `s` by default anymore, it will be extracted by `register` function (**Breaking Change**)
|
||||
- **meta:** add `categories` and `template` config to `typst.toml` for Typst 0.11
|
||||
|
||||
|
||||
## v0.3.1
|
||||
|
||||
- fix some typos
|
||||
- fix slide-level bug
|
||||
- fix bug of pdfpc label
|
||||
|
||||
|
||||
## v0.3.0
|
||||
|
||||
### Features
|
||||
|
||||
- better show-slides mode.
|
||||
- support align and pad.
|
||||
|
||||
### Documentation
|
||||
|
||||
- Add more detailed documentation.
|
||||
|
||||
### Refactor
|
||||
|
||||
- simplify theme.
|
||||
|
||||
### Fix
|
||||
|
||||
- fix many bugs.
|
||||
|
||||
## v0.2.1
|
||||
|
||||
### Features
|
||||
|
||||
- **Touying-reducer**: support cetz and fletcher animation
|
||||
- **university theme**: add university theme
|
||||
|
||||
### Fix
|
||||
|
||||
- fix footer progress in metropolis theme
|
||||
- fix some bugs in simple and dewdrop themes
|
||||
- fix bug that outline does not display more than 4 sections
|
||||
|
||||
|
||||
## v0.2.0
|
||||
|
||||
- **Object-oriented programming:** Singleton `s`, binding methods `utils.methods(s)` and `(self: obj, ..) => {..}` methods.
|
||||
- **Page arguments management:** Instead of using `#set page(..)`, you should use `self.page-args` to retrieve or set page parameters, thereby avoiding unnecessary creation of new pages.
|
||||
- **`#pause` for sequence content:** You can use #pause at the outermost level of a slide, including inline and list.
|
||||
- **`#pause` for layout functions:** You can use the `composer` parameter to add yourself layout function like `utils.side-by-side`, and simply use multiple pos parameters like `#slide[..][..]`.
|
||||
- **`#meanwhile` for synchronous display:** Provide a `#meanwhile` for resetting subslides counter.
|
||||
- **`#pause` and `#meanwhile` for math equation:** Provide a `#touying-equation("x + y pause + z")` for math equation animations.
|
||||
- **Slides:** Create simple slides using standard headings.
|
||||
- **Callback-style `uncover`, `only` and `alternatives`:** Based on the concise syntax provided by Polylux, allow precise control of the timing for displaying content.
|
||||
- You should manually control the number of subslides using the `repeat` parameter.
|
||||
- **Transparent cover:** Enable transparent cover using oop syntax like `#let s = (s.methods.enable-transparent-cover)(self: s)`.
|
||||
- **Handout mode:** enable handout mode by `#let s = (s.methods.enable-handout-mode)(self: s)`.
|
||||
- **Fit-to-width and fit-to-height:** Fit-to-width for title in header and fit-to-height for image.
|
||||
- `utils.fit-to-width(grow: true, shrink: true, width, body)`
|
||||
- `utils.fit-to-height(width: none, prescale-width: none, grow: true, shrink: true, height, body)`
|
||||
- **Slides counter:** `states.slide-counter.display() + " / " + states.last-slide-number` and `states.touying-progress(ratio => ..)`.
|
||||
- **Appendix:** Freeze the `last-slide-number` to prevent the slide number from increasing further.
|
||||
- **Sections:** Touying's built-in section support can be used to display the current section title and show progress.
|
||||
- `section` and `subsection` parameter in `#slide` to register a new section or subsection.
|
||||
- `states.current-section-title` to get the current section.
|
||||
- `states.touying-outline` or `s.methods.touying-outline` to display a outline of sections.
|
||||
- `states.touying-final-sections(sections => ..)` for custom outline display.
|
||||
- `states.touying-progress-with-sections((current-sections: .., final-sections: .., current-slide-number: .., last-slide-number: ..) => ..)` for powerful progress display.
|
||||
- **Navigation bar**: Navigation bar like [here](https://github.com/zbowang/BeamerTheme) by `states.touying-progress-with-sections(..)`, in `dewdrop` theme.
|
||||
- **Pdfpc:** pdfpc support and export `.pdfpc` file without external tool by `typst query` command simply.
|
||||
@@ -0,0 +1,150 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Code Style
|
||||
|
||||
## Simple Style
|
||||
|
||||
If we just need to use it simply, we can directly input content under the title, just like writing a normal Typst document. The titles here serve to separate pages, and we can also normally use commands like `#pause` to achieve animation effects.
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
= Title
|
||||
|
||||
== First Slide
|
||||
|
||||
Hello, Touying!
|
||||
|
||||
#pause
|
||||
|
||||
Hello, Typst!
|
||||
```
|
||||
|
||||

|
||||
|
||||
And you can use an empty title `== <touying:hidden>` to create a new page, which is also helpful to clear the continued application of the previous title.
|
||||
|
||||
If we need to maintain the current title and just want to add a new page, we can use `#pagebreak()`, or directly use `---` to split the page, the latter is parsed as `#pagebreak()` in Touying.
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
= Title
|
||||
|
||||
== First Slide
|
||||
|
||||
Hello, Touying!
|
||||
|
||||
---
|
||||
|
||||
Hello, Typst!
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Block Style
|
||||
|
||||
Many times, using only the simple style cannot achieve all the functions we need. For more powerful functions and clearer structure, we can also use the block style in the form of `#slide[...]`.
|
||||
|
||||
For example, the above example can be transformed into
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
= Title
|
||||
|
||||
== First Slide
|
||||
|
||||
#slide[
|
||||
Hello, Touying!
|
||||
|
||||
#pause
|
||||
|
||||
Hello, Typst!
|
||||
]
|
||||
```
|
||||
|
||||
And `#empty-slide[]` can create an empty Slide without a header and footer.
|
||||
|
||||
There are many benefits to doing this:
|
||||
|
||||
1. Many times, we need more than the default `#slide[...]`, we also need special `slide` functions like `#focus-slide[...]`;
|
||||
2. The `#slide[...]` function of different themes may have more parameters than the default, for example, the `#slide[...]` function of the metropolis theme will have an `align` parameter that can set the alignment;
|
||||
3. Only `slide` functions can use callback-style content blocks to use `#only` and `#uncover` functions to achieve complex animation effects.
|
||||
4. It can have a clearer structure, by identifying `#slide[...]` blocks, we can easily distinguish the specific pagination effects of slides.
|
||||
|
||||
## Convention Over Configuration
|
||||
|
||||
You may have noticed that when using the simple theme, using a first-level title automatically creates a section slide. This is because the simple theme registers a `config-common(slide-fn: slide, new-section-slide-fn: new-section-slide)` function, so Touying will call this function by default.
|
||||
|
||||
If we do not want it to automatically create such a section slide, we can remove this method:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-common(new-section-slide-fn: none),
|
||||
)
|
||||
|
||||
= Title
|
||||
|
||||
== First Slide
|
||||
|
||||
Hello, Touying!
|
||||
|
||||
#pause
|
||||
|
||||
Hello, Typst!
|
||||
```
|
||||
|
||||

|
||||
|
||||
As you can see, this will only result in two pages, and the default section slide will disappear.
|
||||
|
||||
Similarly, we can also register a new section slide:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-common(new-section-slide-fn: section => {
|
||||
touying-slide-wrapper(self => {
|
||||
touying-slide(
|
||||
self: self,
|
||||
{
|
||||
set align(center + horizon)
|
||||
set text(size: 2em, fill: self.colors.primary, style: "italic", weight: "bold")
|
||||
utils.display-current-heading(level: 1)
|
||||
},
|
||||
)
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
= Title
|
||||
|
||||
== First Slide
|
||||
|
||||
Hello, Touying!
|
||||
|
||||
#pause
|
||||
|
||||
Hello, Typst!
|
||||
```
|
||||
|
||||

|
||||
@@ -0,0 +1,94 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Complex Animations
|
||||
|
||||
Thanks to the syntax provided by [Polylux](https://polylux.dev/book/dynamic/syntax.html), we can also use `only`, `uncover`, and `alternatives` in Touying.
|
||||
|
||||
|
||||
## Mark-Style Functions
|
||||
|
||||
We can use mark-style functions, which are very convenient to use.
|
||||
|
||||
```typst
|
||||
At subslide #touying-fn-wrapper((self: none) => str(self.subslide)), we can
|
||||
|
||||
use #uncover("2-")[`#uncover` function] for reserving space,
|
||||
|
||||
use #only("2-")[`#only` function] for not reserving space,
|
||||
|
||||
#alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives.
|
||||
```
|
||||
|
||||
However, this does not work in all cases, for example if you put `uncover` into the context expression, you will get an error.
|
||||
|
||||
|
||||
## Callback-Style Functions
|
||||
|
||||
To overcome the limitations of layout functions mentioned earlier, Touying cleverly implements always-effective `only`, `uncover`, and `alternatives` using callback functions. Specifically, you need to introduce these three functions as follows:
|
||||
|
||||
```typst
|
||||
#slide(repeat: 3, self => [
|
||||
#let (uncover, only, alternatives) = utils.methods(self)
|
||||
|
||||
At subslide #self.subslide, we can
|
||||
|
||||
use #uncover("2-")[`#uncover` function] for reserving space,
|
||||
|
||||
use #only("2-")[`#only` function] for not reserving space,
|
||||
|
||||
#alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives.
|
||||
])
|
||||
```
|
||||
|
||||

|
||||
|
||||
Notice that we no longer pass a content block but instead pass a callback function with a `self` parameter. Later, we extract `only`, `uncover`, and `alternatives` functions from `self` using:
|
||||
|
||||
```typst
|
||||
#let (uncover, only, alternatives) = utils.methods(self)
|
||||
```
|
||||
|
||||
We then call these functions in subsequent steps.
|
||||
|
||||
Here's an interesting fact: the `self.subslide` of type int indicates the current subslide index, and in fact, the `only`, `uncover`, and `alternatives` functions rely on `self.subslide` to determine the current subslide index.
|
||||
|
||||
:::warning[Warning]
|
||||
|
||||
We manually specify the `repeat: 3` parameter, indicating the display of 3 subslides. We need to do this manually because Touying cannot infer how many subslides `only`, `uncover`, and `alternatives` should display.
|
||||
|
||||
:::
|
||||
|
||||
## only
|
||||
|
||||
The `only` function means it "appears" only on selected subslides. If it doesn't appear, it completely disappears and doesn't occupy any space. In other words, `#only(index, body)` is either `body` or `none`.
|
||||
|
||||
The index can be an int type or a str type like `"2-"` or `"2-3"`. For more usage, refer to [Polylux](https://polylux.dev/book/dynamic/complex.html).
|
||||
|
||||
## uncover
|
||||
|
||||
The `uncover` function means it "displays" only on selected subslides; otherwise, it will be covered by the `cover` function but still occupies the original space. In other words, `#uncover(index, body)` is either `body` or `cover(body)`.
|
||||
|
||||
The index can be an int type or a str type like `"2-"` or `"2-3"`. For more usage, refer to [Polylux](https://polylux.dev/book/dynamic/complex.html).
|
||||
|
||||
You may also have noticed that `#pause` actually uses the `cover` function, providing a more convenient syntax. In reality, their effects are almost identical.
|
||||
|
||||
## alternatives
|
||||
|
||||
The `alternatives` function displays a series of different content in different subslides. For example:
|
||||
|
||||
```typst
|
||||
#slide(repeat: 3, self => [
|
||||
#let (uncover, only, alternatives) = utils.methods(self)
|
||||
|
||||
#alternatives[Ann][Bob][Christopher]
|
||||
likes
|
||||
#alternatives[chocolate][strawberry][vanilla]
|
||||
ice cream.
|
||||
])
|
||||
```
|
||||
|
||||

|
||||
|
||||
As you can see, `alternatives` can automatically expand to the most suitable width and height, a capability that `only` and `uncover` lack. In fact, `alternatives` has other parameters, such as `start: 2`, `repeat-last: true`, and `position: center + horizon`. For more usage, refer to [Polylux](https://polylux.dev/book/dynamic/alternatives.html).
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Cover Function
|
||||
|
||||
As you already know, both `uncover` and `#pause` use the `cover` function to conceal content that is not visible. So, what exactly is the `cover` function here?
|
||||
|
||||
## Default Cover Function: `hide`
|
||||
|
||||
The `cover` function is a method stored in `s.methods.cover`, which is later used by `uncover` and `#pause`.
|
||||
|
||||
The default `cover` function is the [hide](https://typst.app/docs/reference/layout/hide/) function. This function makes the internal content invisible without affecting the layout.
|
||||
|
||||
## Updating the Cover Function
|
||||
|
||||
In some cases, you might want to use your own `cover` function. In that case, you can set your own `cover` function using:
|
||||
|
||||
```typst
|
||||
config-methods(cover: (self: none, body) => hide(body))
|
||||
```
|
||||
|
||||
## hack: handle enum and list
|
||||
|
||||
You will find that the existing cover function cannot hide the mark of enum and list, refer to [here](https://github.com/touying-typ/touying/issues/10), so you can hack:
|
||||
|
||||
```typst
|
||||
config-methods(cover: (self: none, body) => box(scale(x: 0%, body)))
|
||||
```
|
||||
|
||||
## Semi-Transparent Cover Function
|
||||
|
||||
Touying supports a semi-transparent cover function, which can be enabled by adding:
|
||||
|
||||
```typst
|
||||
config-methods(cover: utils.semi-transparent-cover.with(alpha: 85%))
|
||||
```
|
||||
|
||||
You can adjust the transparency through the `alpha: ..` parameter.
|
||||
|
||||
:::warning[Warning]
|
||||
|
||||
Note that the `transparent-cover` here does not preserve text layout like `hide` does because it adds an extra layer of `box`, which may disrupt the original structure of the page.
|
||||
|
||||
:::
|
||||
|
||||
:::tip[Internals]
|
||||
|
||||
The `utils.semi-transparent-cover` method is defined as:
|
||||
|
||||
```typst
|
||||
#let semi-transparent-cover(self: none, constructor: rgb, alpha: 85%, body) = {
|
||||
cover-with-rect(
|
||||
fill: update-alpha(
|
||||
constructor: constructor,
|
||||
self.page.fill,
|
||||
alpha,
|
||||
),
|
||||
body,
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
It creates a semi-transparent rectangular mask with the same color as the background to simulate the effect of transparent content. Here, `constructor: rgb` and `alpha: 85%` indicate the background color's construction function and transparency level, respectively.
|
||||
|
||||
:::
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Math Equation Animations
|
||||
|
||||
Touying also provides a unique and highly useful feature—math equation animations, allowing you to conveniently use `pause` and `meanwhile` within math equations.
|
||||
|
||||
## Simple Animation
|
||||
|
||||
Let's start with an example:
|
||||
|
||||
```typst
|
||||
#slide[
|
||||
Touying equation with pause:
|
||||
|
||||
$
|
||||
f(x) &= pause x^2 + 2x + 1 \
|
||||
&= pause (x + 1)^2 \
|
||||
$
|
||||
|
||||
#meanwhile
|
||||
|
||||
Touying equation is very simple.
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
We use the `touying-equation` function to incorporate `pause` and `meanwhile` within the text of math equations (in fact, you can also use `#pause` or `#pause;`).
|
||||
|
||||
As you would expect, the math equation is displayed step by step, making it suitable for presenters to demonstrate their math reasoning.
|
||||
|
||||
## Complex Animation
|
||||
|
||||
In fact, we can also use `only`, `uncover`, and `alternatives`:
|
||||
|
||||
```typst
|
||||
#slide(repeat: 3, self => [
|
||||
#let (uncover, only, alternatives) = utils.methods(self)
|
||||
|
||||
$
|
||||
f(x) &= pause x^2 + 2x + uncover("3-", 1) \
|
||||
&= pause (x + 1)^2 \
|
||||
$
|
||||
])
|
||||
```
|
||||
|
||||

|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
# Handout Mode
|
||||
|
||||
While watching slides and attending lectures, the audience often wishes to have handouts for reviewing challenging concepts. Therefore, it's beneficial for the author to provide handouts for the audience, preferably before the lecture for better preparation.
|
||||
|
||||
The handout mode differs from the regular mode as it doesn't require intricate animation effects. It retains only the last subslide of each slide.
|
||||
|
||||
Enabling handout mode is simple:
|
||||
|
||||
```typst
|
||||
config-common(handout: true)
|
||||
```
|
||||
@@ -0,0 +1,100 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Other Animations
|
||||
|
||||
Touying also provides `touying-reducer`, which adds `pause` and `meanwhile` animations to cetz and fletcher.
|
||||
|
||||
## Simple Animations
|
||||
|
||||
Here's an example:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
#import "@preview/cetz:0.3.2"
|
||||
#import "@preview/fletcher:0.5.5" as fletcher: node, edge
|
||||
|
||||
// cetz and fletcher bindings for touying
|
||||
#let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true))
|
||||
#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)
|
||||
|
||||
#show: university-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
// cetz animation
|
||||
#slide[
|
||||
Cetz in Touying:
|
||||
|
||||
#cetz-canvas({
|
||||
import cetz.draw: *
|
||||
|
||||
rect((0,0), (5,5))
|
||||
|
||||
(pause,)
|
||||
|
||||
rect((0,0), (1,1))
|
||||
rect((1,1), (2,2))
|
||||
rect((2,2), (3,3))
|
||||
|
||||
(pause,)
|
||||
|
||||
line((0,0), (2.5, 2.5), name: "line")
|
||||
})
|
||||
]
|
||||
|
||||
// fletcher animation
|
||||
#slide[
|
||||
Fletcher in Touying:
|
||||
|
||||
#fletcher-diagram(
|
||||
node-stroke: .1em,
|
||||
node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%),
|
||||
spacing: 4em,
|
||||
edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
|
||||
node((0,0), `reading`, radius: 2em),
|
||||
edge((0,0), (0,0), `read()`, "--|>", bend: 130deg),
|
||||
pause,
|
||||
edge(`read()`, "-|>"),
|
||||
node((1,0), `eof`, radius: 2em),
|
||||
pause,
|
||||
edge(`close()`, "-|>"),
|
||||
node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)),
|
||||
edge((0,0), (2,0), `close()`, "-|>", bend: -40deg),
|
||||
)
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
|
||||
## only and uncover
|
||||
|
||||
In fact, we can also use `only` and `uncover` within cetz, just requiring a bit of skill:
|
||||
|
||||
```typst
|
||||
#slide(repeat: 3, self => [
|
||||
#let (uncover, only) = utils.methods(self)
|
||||
|
||||
Cetz in Touying in subslide #self.subslide:
|
||||
|
||||
#cetz.canvas({
|
||||
import cetz.draw: *
|
||||
let self = utils.merge-dicts(
|
||||
self,
|
||||
config-methods(cover: utils.method-wrapper(hide.with(bounds: true))),
|
||||
)
|
||||
let (uncover,) = utils.methods(self)
|
||||
|
||||
rect((0,0), (5,5))
|
||||
|
||||
uncover("2-3", {
|
||||
rect((0,0), (1,1))
|
||||
rect((1,1), (2,2))
|
||||
rect((2,2), (3,3))
|
||||
})
|
||||
|
||||
only(3, line((0,0), (2.5, 2.5), name: "line"))
|
||||
})
|
||||
])
|
||||
```
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Simple Animations
|
||||
|
||||
Touying provides two markers for simple animation effects: `#pause` and `#meanwhile`.
|
||||
|
||||
## pause
|
||||
|
||||
The purpose of `#pause` is straightforward – it separates the subsequent content into the next subslide. You can use multiple `#pause` to create multiple subslides. Here's a simple example:
|
||||
|
||||
```typst
|
||||
#slide[
|
||||
First #pause Second
|
||||
|
||||
#pause
|
||||
|
||||
Third
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
This example will create three subslides, gradually revealing the content.
|
||||
|
||||
As you can see, `#pause` can be used inline or on a separate line.
|
||||
|
||||
## meanwhile
|
||||
|
||||
In some cases, you may need to display additional content simultaneously with `#pause`. In such cases, you can use `#meanwhile`.
|
||||
|
||||
```typst
|
||||
#slide[
|
||||
First
|
||||
|
||||
#pause
|
||||
|
||||
Second
|
||||
|
||||
#meanwhile
|
||||
|
||||
Third
|
||||
|
||||
#pause
|
||||
|
||||
Fourth
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
This example will create only two subslides, with "First" and "Third" displayed simultaneously, and "Second" and "Fourth" displayed simultaneously.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Pdfpc
|
||||
|
||||
[pdfpc](https://pdfpc.github.io/) is a "Presenter Console with multi-monitor support for PDF files." This means you can use it to display slides in the form of PDF pages and it comes with some known excellent features, much like PowerPoint.
|
||||
|
||||
pdfpc has a JSON-formatted `.pdfpc` file that can provide additional information for PDF slides. While you can manually write this file, you can also manage it through Touying.
|
||||
|
||||
|
||||
## Adding Metadata
|
||||
|
||||
Touying remains consistent with [Polylux](https://polylux.dev/book/external/pdfpc.html) to avoid conflicts between APIs.
|
||||
|
||||
For example, you can add notes using `#pdfpc.speaker-note("This is a note that only the speaker will see.")`.
|
||||
|
||||
|
||||
## Pdfpc Configuration
|
||||
|
||||
To add pdfpc configurations, you can use
|
||||
|
||||
```typst
|
||||
#pdfpc.config(
|
||||
duration-minutes: 30,
|
||||
start-time: datetime(hour: 14, minute: 10, second: 0),
|
||||
end-time: datetime(hour: 14, minute: 40, second: 0),
|
||||
last-minutes: 5,
|
||||
note-font-size: 12,
|
||||
disable-markdown: false,
|
||||
default-transition: (
|
||||
type: "push",
|
||||
duration-seconds: 2,
|
||||
angle: ltr,
|
||||
alignment: "vertical",
|
||||
direction: "inward",
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
Add the corresponding configurations. Refer to [Polylux](https://polylux.dev/book/external/pdfpc.html) for specific configuration details.
|
||||
|
||||
|
||||
## Exporting .pdfpc File
|
||||
|
||||
Assuming your document is `./example.typ`, you can export the `.pdfpc` file directly using:
|
||||
|
||||
```sh
|
||||
typst query --root . ./example.typ --field value --one "<pdfpc-file>" > ./example.pdfpc
|
||||
```
|
||||
|
||||
With the compatibility of Touying and Polylux, you can make Polylux also support direct export by adding the following code:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1"
|
||||
|
||||
#context touying.pdfpc.pdfpc-file(here())
|
||||
```
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Pympress
|
||||
|
||||
[Pympress](https://github.com/Cimbali/pympress) is a PDF presentation tool designed for dual-screen setups such as presentations and public talks. Highly configurable, fully-featured, and portable
|
||||
|
||||
|
||||
## Speaker Notes
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-common(show-notes-on-second-screen: right),
|
||||
)
|
||||
|
||||
= Animation
|
||||
|
||||
== Simple Animation
|
||||
|
||||
We can use `#pause` to #pause display something later.
|
||||
|
||||
#pause
|
||||
|
||||
Just like this.
|
||||
|
||||
#meanwhile
|
||||
|
||||
Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously.
|
||||
|
||||
#speaker-note[
|
||||
+ This is a speaker note.
|
||||
+ You won't see it unless you use `config-common(show-notes-on-second-screen: right)`
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
Then we can use the pympress to show it.
|
||||
|
||||

|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Typst Preview in Tinymist
|
||||
|
||||
The Tinymist extension for VS Code provides an excellent slide mode, allowing us to preview and present slides.
|
||||
|
||||
Press `Ctrl/Cmd + Shift + P` and type `Typst Preview: Preview current file in slide mode` to open the preview in slide mode.
|
||||
|
||||
Press `Ctrl/Cmd + Shift + P` and type `Typst Preview: Preview current file in browser and slide mode` to open the slide mode in the browser.
|
||||
|
||||
Now, you can press keys like `F11` to enter fullscreen mode in the browser, making it suitable for slide presentations.
|
||||
|
||||
Since Typst Preview is based on SVG, it can play GIF animations, which is very helpful for dynamic slides.
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
# Global Settings
|
||||
|
||||
## Global Styles
|
||||
|
||||
For Touying, global styles refer to set rules or show rules that need to be applied everywhere, such as `#set text(size: 20pt)`.
|
||||
|
||||
Themes in Touying encapsulate some of their own global styles, which are placed in `#self.methods.init`. For example, the simple theme encapsulates:
|
||||
|
||||
```typst
|
||||
config-methods(
|
||||
init: (self: none, body) => {
|
||||
set text(fill: self.colors.neutral-darkest, size: 25pt)
|
||||
show footnote.entry: set text(size: .6em)
|
||||
show strong: self.methods.alert.with(self: self)
|
||||
show heading.where(level: self.slide-level + 1): set text(1.4em)
|
||||
|
||||
body
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
If you are not a theme creator but simply want to add some of your own global styles to your slides, you can easily place them before or after `#show: xxx-theme.with()`. For example, the metropolis theme recommends that you add the following global styles yourself:
|
||||
|
||||
```typst
|
||||
#set text(font: "Fira Sans", weight: "light", size: 20pt)
|
||||
#show math.equation: set text(font: "Fira Math")
|
||||
#set strong(delta: 100)
|
||||
#set par(justify: true)
|
||||
```
|
||||
|
||||
## Global Information
|
||||
|
||||
Like Beamer, Touying helps you better maintain global information through a unified API design, allowing you to easily switch between different themes. Global information is a typical example of this.
|
||||
|
||||
You can set the title, subtitle, author, date, and institution information of your slides with:
|
||||
|
||||
```typc
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
)
|
||||
```
|
||||
|
||||
Later on, you can access them through `self.info`.
|
||||
|
||||
This information is generally used in the theme's `title-slide`, `header`, and `footer`, such as `#show: metropolis-theme.with(aspect-ratio: "16-9", footer: self => self.info.institution)`.
|
||||
|
||||
The `date` can accept `datetime` format and `content` format, and the date display format of the `datetime` format can be changed with:
|
||||
|
||||
```typc
|
||||
config-common(datetime-format: "[year]-[month]-[day]")
|
||||
```
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# CeTZ
|
||||
|
||||
Touying provides the `touying-reducer`, which adds `pause` and `meanwhile` animations to CeTZ and Fletcher.
|
||||
|
||||
## Simple Animation
|
||||
|
||||
An example:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.metropolis: *
|
||||
#import "@preview/cetz:0.3.2"
|
||||
#import "@preview/fletcher:0.5.5" as fletcher: node, edge
|
||||
|
||||
// cetz and fletcher bindings for touying
|
||||
#let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true))
|
||||
#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)
|
||||
|
||||
#show: metropolis-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
// cetz animation
|
||||
#slide[
|
||||
Cetz in Touying:
|
||||
|
||||
#cetz-canvas({
|
||||
import cetz.draw: *
|
||||
|
||||
rect((0,0), (5,5))
|
||||
|
||||
(pause,)
|
||||
|
||||
rect((0,0), (1,1))
|
||||
rect((1,1), (2,2))
|
||||
rect((2,2), (3,3))
|
||||
|
||||
(pause,)
|
||||
|
||||
line((0,0), (2.5, 2.5), name: "line")
|
||||
})
|
||||
]
|
||||
|
||||
// fletcher animation
|
||||
#slide[
|
||||
Fletcher in Touying:
|
||||
|
||||
#fletcher-diagram(
|
||||
node-stroke: .1em,
|
||||
node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%),
|
||||
spacing: 4em,
|
||||
edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
|
||||
node((0,0), `reading`, radius: 2em),
|
||||
edge((0,0), (0,0), `read()`, "--|>", bend: 130deg),
|
||||
pause,
|
||||
edge(`read()`, "-|>"),
|
||||
node((1,0), `eof`, radius: 2em),
|
||||
pause,
|
||||
edge(`close()`, "-|>"),
|
||||
node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)),
|
||||
edge((0,0), (2,0), `close()`, "-|>", bend: -40deg),
|
||||
)
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
|
||||
## only and uncover
|
||||
|
||||
In fact, we can also use `only` and `uncover` within CeTZ, but it requires a bit of technique:
|
||||
|
||||
```typst
|
||||
#slide(repeat: 3, self => [
|
||||
#let (uncover, only) = utils.methods(self)
|
||||
|
||||
Cetz in Touying in subslide #self.subslide:
|
||||
|
||||
#cetz.canvas({
|
||||
import cetz.draw: *
|
||||
let self = (self.methods.update-cover)(self: self, hide.with(bounds: true))
|
||||
let (uncover,) = utils.methods(self)
|
||||
|
||||
rect((0,0), (5,5))
|
||||
|
||||
uncover("2-3", {
|
||||
rect((0,0), (1,1))
|
||||
rect((1,1), (2,2))
|
||||
rect((2,2), (3,3))
|
||||
})
|
||||
|
||||
only(3, line((0,0), (2.5, 2.5), name: "line"))
|
||||
})
|
||||
])
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Codly
|
||||
|
||||
When using Codly, we should initialize it using the `config-common(preamble: {..})` method.
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
#import "@preview/codly:1.0.0": *
|
||||
|
||||
#show: codly-init.with()
|
||||
|
||||
#show: simple-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-common(preamble: {
|
||||
codly(languages: (
|
||||
rust: (
|
||||
name: "Rust",
|
||||
icon: text(font: "tabler-icons", "\u{fa53}"),
|
||||
color: rgb("#CE412B"),
|
||||
),
|
||||
))
|
||||
}),
|
||||
)
|
||||
|
||||
== First slide
|
||||
|
||||
#raw(lang: "rust", block: true,
|
||||
`pub fn main() {
|
||||
println!("Hello, world!");
|
||||
}`.text)
|
||||
```
|
||||
|
||||

|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Fletcher
|
||||
|
||||
Touying provides the `touying-reducer`, which adds `pause` and `meanwhile` animations to Fletcher.
|
||||
|
||||
An example:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.metropolis: *
|
||||
#import "@preview/cetz:0.3.2"
|
||||
#import "@preview/fletcher:0.5.5" as fletcher: node, edge
|
||||
|
||||
// cetz and fletcher bindings for touying
|
||||
#let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true))
|
||||
#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)
|
||||
|
||||
#show: metropolis-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
// cetz animation
|
||||
#slide[
|
||||
Cetz in Touying:
|
||||
|
||||
#cetz-canvas({
|
||||
import cetz.draw: *
|
||||
|
||||
rect((0,0), (5,5))
|
||||
|
||||
(pause,)
|
||||
|
||||
rect((0,0), (1,1))
|
||||
rect((1,1), (2,2))
|
||||
rect((2,2), (3,3))
|
||||
|
||||
(pause,)
|
||||
|
||||
line((0,0), (2.5, 2.5), name: "line")
|
||||
})
|
||||
]
|
||||
|
||||
// fletcher animation
|
||||
#slide[
|
||||
Fletcher in Touying:
|
||||
|
||||
#fletcher-diagram(
|
||||
node-stroke: .1em,
|
||||
node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%),
|
||||
spacing: 4em,
|
||||
edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
|
||||
node((0,0), `reading`, radius: 2em),
|
||||
edge((0,0), (0,0), `read()`, "--|>", bend: 130deg),
|
||||
pause,
|
||||
edge(`read()`, "-|>"),
|
||||
node((1,0), `eof`, radius: 2em),
|
||||
pause,
|
||||
edge(`close()`, "-|>"),
|
||||
node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)),
|
||||
edge((0,0), (2,0), `close()`, "-|>", bend: -40deg),
|
||||
)
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# MiTeX
|
||||
|
||||
During the process of creating slides, we often already have a LaTeX math equation that we simply want to paste into the slides without transcribing it into a Typst math equation. In such cases, we can use [MiTeX](https://github.com/mitex-rs/mitex).
|
||||
|
||||
Example:
|
||||
|
||||
```typst
|
||||
#import "@preview/mitex:0.2.5": *
|
||||
|
||||
Write inline equations like #mi("x") or #mi[y].
|
||||
|
||||
Also block equations (this case is from #text(blue.lighten(20%), link("https://katex.org/")[katex.org])):
|
||||
|
||||
#mitex(`
|
||||
\newcommand{\f}[2]{#1f(#2)}
|
||||
\f\relax{x} = \int_{-\infty}^\infty
|
||||
\f\hat\xi\,e^{2 \pi i \xi x}
|
||||
\,d\xi
|
||||
`)
|
||||
```
|
||||
|
||||

|
||||
|
||||
Touying also provides a `touying-mitex` function, which can be used for example
|
||||
|
||||
```typst
|
||||
#touying-mitex(mitex, `
|
||||
f(x) &= \pause x^2 + 2x + 1 \\
|
||||
&= \pause (x + 1)^2 \\
|
||||
`)
|
||||
```
|
||||
@@ -0,0 +1,116 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Pinit
|
||||
|
||||
[Pinit](https://github.com/OrangeX4/typst-pinit/) package provides the ability to perform absolute positioning based on the page and relative positioning based on "pins," making it convenient to implement arrow pointing and explanatory effects for slides.
|
||||
|
||||
## Simple Example
|
||||
|
||||
```typst
|
||||
#import "@preview/pinit:0.2.2": *
|
||||
|
||||
#set text(size: 24pt)
|
||||
|
||||
A simple #pin(1)highlighted text#pin(2).
|
||||
|
||||
#pinit-highlight(1, 2)
|
||||
|
||||
#pinit-point-from(2)[It is simple.]
|
||||
```
|
||||
|
||||

|
||||
|
||||
Another [example](https://github.com/OrangeX4/typst-pinit/blob/main/examples/equation-desc.typ):
|
||||
|
||||

|
||||
|
||||
|
||||
## Complex Example
|
||||
|
||||

|
||||
|
||||
An example of shared usage with Touying:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.default: *
|
||||
#import "@preview/pinit:0.2.2": *
|
||||
|
||||
#set text(size: 20pt, font: "Calibri", ligatures: false)
|
||||
#show heading: set text(weight: "regular")
|
||||
#show heading: set block(above: 1.4em, below: 1em)
|
||||
#show heading.where(level: 1): set text(size: 1.5em)
|
||||
|
||||
// Useful functions
|
||||
#let crimson = rgb("#c00000")
|
||||
#let greybox(..args, body) = rect(fill: luma(95%), stroke: 0.5pt, inset: 0pt, outset: 10pt, ..args, body)
|
||||
#let redbold(body) = {
|
||||
set text(fill: crimson, weight: "bold")
|
||||
body
|
||||
}
|
||||
#let blueit(body) = {
|
||||
set text(fill: blue)
|
||||
body
|
||||
}
|
||||
|
||||
#show: default-theme.with(aspect-ratio: "4-3")
|
||||
|
||||
// Main body
|
||||
#slide[
|
||||
#set heading(offset: 0)
|
||||
|
||||
= Asymptotic Notation: $O$
|
||||
|
||||
Use #pin("h1")asymptotic notations#pin("h2") to describe asymptotic efficiency of algorithms.
|
||||
(Ignore constant coefficients and lower-order terms.)
|
||||
|
||||
#pause
|
||||
|
||||
#greybox[
|
||||
Given a function $g(n)$, we denote by $O(g(n))$ the following *set of functions*:
|
||||
#redbold(${f(n): "exists" c > 0 "and" n_0 > 0, "such that" f(n) <= c dot g(n) "for all" n >= n_0}$)
|
||||
]
|
||||
|
||||
#pinit-highlight("h1", "h2")
|
||||
|
||||
#pause
|
||||
|
||||
$f(n) = O(g(n))$: #pin(1)$f(n)$ is *asymptotically smaller* than $g(n)$.#pin(2)
|
||||
|
||||
#pause
|
||||
|
||||
$f(n) redbold(in) O(g(n))$: $f(n)$ is *asymptotically* #redbold[at most] $g(n)$.
|
||||
|
||||
#only("4-", pinit-line(stroke: 3pt + crimson, start-dy: -0.25em, end-dy: -0.25em, 1, 2))
|
||||
|
||||
#pause
|
||||
|
||||
#block[Insertion Sort as an #pin("r1")example#pin("r2"):]
|
||||
|
||||
- Best Case: $T(n) approx c n + c' n - c''$ #pin(3)
|
||||
- Worst case: $T(n) approx c n + (c' \/ 2) n^2 - c''$ #pin(4)
|
||||
|
||||
#pinit-rect("r1", "r2")
|
||||
|
||||
#pause
|
||||
|
||||
#pinit-place(3, dx: 15pt, dy: -15pt)[#redbold[$T(n) = O(n)$]]
|
||||
#pinit-place(4, dx: 15pt, dy: -15pt)[#redbold[$T(n) = O(n)$]]
|
||||
|
||||
#pause
|
||||
|
||||
#blueit[Q: Is $n^(3) = O(n^2)$#pin("que")? How to prove your answer#pin("ans")?]
|
||||
|
||||
#pause
|
||||
|
||||
#pinit-point-to("que", fill: crimson, redbold[No.])
|
||||
#pinit-point-from("ans", body-dx: -150pt)[
|
||||
Show that the equation $(3/2)^n >= c$ \
|
||||
has infinitely many solutions for $n$.
|
||||
]
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
# Theorion
|
||||
|
||||
Touying can work properly with the [Theorion](https://github.com/OrangeX4/typst-theorion) package, you can directly use the [theorion](https://github.com/OrangeX4/typst-theorion) package. Additionally, you can use `#set heading(numbering: "1.1")` to set numbering for sections and subsections.
|
||||
|
||||
**Note: To make animation commands like `#pause` work properly with theorion, you need to use `config-common(frozen-counters: (theorem-counter,))` to bind counters that need to be frozen.**
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
#import "@preview/theorion:0.3.2": *
|
||||
#import cosmos.clouds: *
|
||||
#show: show-theorion
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-common(frozen-counters: (theorem-counter,)), // freeze theorem counter for animation
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
= Theorems
|
||||
|
||||
== Prime numbers
|
||||
|
||||
#definition[
|
||||
A natural number is called a #highlight[_prime number_] if it is greater
|
||||
than 1 and cannot be written as the product of two smaller natural numbers.
|
||||
]
|
||||
#example[
|
||||
The numbers $2$, $3$, and $17$ are prime.
|
||||
@cor_largest_prime shows that this list is not exhaustive!
|
||||
]
|
||||
|
||||
#pause
|
||||
|
||||
#theorem(title: "Euclid")[
|
||||
There are infinitely many primes.
|
||||
]
|
||||
|
||||
#pagebreak(weak: true)
|
||||
|
||||
#proof[
|
||||
Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration
|
||||
of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list,
|
||||
it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since
|
||||
$p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a
|
||||
contradiction.
|
||||
]
|
||||
|
||||
#corollary[
|
||||
There is no largest prime number.
|
||||
] <cor_largest_prime>
|
||||
#corollary[
|
||||
There are infinitely many composite numbers.
|
||||
]
|
||||
|
||||
#theorem[
|
||||
There are arbitrarily long stretches of composite numbers.
|
||||
]
|
||||
|
||||
#proof[
|
||||
For any $n > 2$, consider $
|
||||
n! + 2, quad n! + 3, quad ..., quad n! + n
|
||||
$
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Introduction to Touying
|
||||
|
||||
[Touying](https://github.com/touying-typ/touying) is a slide/presentation package developed for Typst. Touying is similar to LaTeX Beamer but benefits from Typst, providing faster rendering speed and a more concise syntax. After, we use "slides" to refer to slideshows, "slide" for a single slide, and "subslide" for a sub-slide.
|
||||
|
||||
## Why Use Touying
|
||||
|
||||
- Unlike **PowerPoint**, Touying is not a "what you see is what you get" tool. You can write your slides in a "content and style separation" manner, especially with Typst, which offers a concise yet powerful syntax, better supporting content like code blocks, mathematical formulas, and theorems. Another advantage is that, with templates, writing slides with Touying is much faster than PowerPoint. Therefore, Touying is more suitable for users with a demand for "research writing."
|
||||
- Compared to **Markdown Slides**, Touying, relying on Typst, has more powerful typesetting control, such as headers, footers, layout, and convenient custom functions. These are capabilities that Markdown struggles to provide, or does not do well. Additionally, Touying offers `#pause` and `#meanwhile` markers, providing more convenient dynamic slide capabilities.
|
||||
- Compared to **Beamer**, Touying has faster compilation speed, a more concise syntax, and simpler theme customization capabilities. Touying's compilation speed can be maintained in milliseconds or tens of milliseconds, compared to Beamer's compilation time of seconds or tens of seconds. Touying's syntax is more concise than Beamer, making it easier to change templates and create your own templates. In terms of features, Touying supports most of Beamer's capabilities and provides some convenient features that Beamer lacks.
|
||||
- Compared to **Polylux**, Touying offers a concise yet powerful syntax and functionality, capable of providing 'global variables' capabilities through automatic injection, making it easier to write themes. Moreover, Touying does not rely on `counter` and `locate` to implement `#pause`, thus offering better performance. Touying is positioned as a community-driven project (we welcome more people to join), and it does not overly emphasize maintaining API consistency. Instead, it chooses to maintain documentation for multiple versions, thereby providing more innovative but powerful features.
|
||||
|
||||
## About the Name
|
||||
|
||||
"Touying" is derived from the Chinese word "投影" (tóuyǐng), which means "projection" In English, it also conveys the meaning of a "project". In comparison, the term "beamer" in LaTeX means a projector in German.
|
||||
|
||||
## About the Documentation
|
||||
|
||||
This documentation is powered by [Docusaurus](https://docusaurus.io/). We will maintain English and Chinese versions of the documentation for Touying, and for each major version, we will maintain a documentation copy. This allows you to easily refer to old versions of the Touying documentation and migrate to new versions.
|
||||
|
||||
Docusaurus creates a new version:
|
||||
|
||||
```sh
|
||||
npm run docusaurus docs:version 0.y.x
|
||||
```
|
||||
|
||||
## Contribution
|
||||
|
||||
Touying is free, open-source, and community-driven. If you're interested, you can visit [GitHub](https://github.com/touying-typ/touying) anytime and raise issues or submit pull requests. We also welcome you to join the [touying-typ](https://github.com/touying-typ) organization.
|
||||
|
||||
## 🥤A cup of coffee
|
||||
|
||||
If you feel that this project has helped you in your work, you can donate to Touying's development work in the following ways to keep the project going.
|
||||
|
||||
Sponsor: https://afdian.com/a/orangex4
|
||||
|
||||
QR Code:
|
||||
|
||||

|
||||
|
||||
|
||||
## Gallery
|
||||
|
||||
Touying offers [a gallery page](https://github.com/touying-typ/touying/wiki) via wiki, where you can browse elegant slides created by Touying users. You're also encouraged to contribute your own beautiful slides here!
|
||||
|
||||
## License
|
||||
|
||||
Touying is released under the [MIT license](https://github.com/touying-typ/touying/blob/main/LICENSE).
|
||||
@@ -0,0 +1,144 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Page Layout
|
||||
|
||||
## Basic Concepts
|
||||
|
||||
To create stylish slides using Typst, it's essential to understand Typst's page model correctly. If you're not concerned with customizing page styles, you can choose to skip this section. However, it's still recommended to go through it.
|
||||
|
||||
Let's illustrate Typst's default page model through a specific example.
|
||||
|
||||
```typst
|
||||
#let container = rect.with(height: 100%, width: 100%, inset: 0pt)
|
||||
#let innerbox = rect.with(stroke: (dash: "dashed"))
|
||||
|
||||
#set text(size: 30pt)
|
||||
#set page(
|
||||
paper: "presentation-16-9",
|
||||
header: container[#innerbox[Header]],
|
||||
header-ascent: 30%,
|
||||
footer: container[#innerbox[Footer]],
|
||||
footer-descent: 30%,
|
||||
)
|
||||
|
||||
#place(top + right)[Margin→]
|
||||
#container[
|
||||
#container[
|
||||
#innerbox[Content]
|
||||
]
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
We need to distinguish the following concepts:
|
||||
|
||||
1. **Model:** Typst has a model similar to the CSS Box Model, divided into Margin, Padding, and Content. However, padding is not a property of `set page(..)` but is obtained by manually adding `#pad(..)`.
|
||||
2. **Margin:** Margins are the edges of the page, divided into top, bottom, left, and right. They are the core of Typst's page model, and all other properties are influenced by margins, especially Header and Footer. Header and Footer are actually located within the Margin.
|
||||
4. **Header:** The Header is the content at the top of the page, divided into container and innerbox. We can observe that the edge of the header container and padding does not align but has some space in between, which is actually `header-ascent: 30%`, where the percentage is relative to the margin-top. Additionally, we notice that the header innerbox is actually located at the bottom left corner of the header container, meaning innerbox defaults to `#set align(left + bottom)`.
|
||||
5. **Footer:** The Footer is the content at the bottom of the page, similar to the Header but in the opposite direction.
|
||||
6. **Place:** The `place` function enables absolute positioning relative to the parent container without affecting other elements inside the parent container. It allows specifying `alignment`, `dx`, and `dy`, making it suitable for placing decorative elements like logos.
|
||||
|
||||
Therefore, to apply Typst to create slides, we only need to set:
|
||||
|
||||
```typst
|
||||
#set page(
|
||||
margin: (x: 4em, y: 2em),
|
||||
header: align(top)[Header],
|
||||
footer: align(bottom)[Footer],
|
||||
header-ascent: 0em,
|
||||
footer-descent: 0em,
|
||||
)
|
||||
```
|
||||
|
||||
However, we still need to address how the header occupies the entire page width. Here, we use negative padding to achieve this. For instance:
|
||||
|
||||
```typst
|
||||
#let container = rect.with(stroke: (dash: "dashed"), height: 100%, width: 100%, inset: 0pt)
|
||||
#let innerbox = rect.with(fill: rgb("#d0d0d0"))
|
||||
#let margin = (x: 4em, y: 2em)
|
||||
|
||||
// negative padding for header and footer
|
||||
#let negative-padding = pad.with(x: -margin.x, y: 0em)
|
||||
|
||||
#set text(size: 30pt)
|
||||
#set page(
|
||||
paper: "presentation-16-9",
|
||||
margin: margin,
|
||||
header: negative-padding[#container[#align(top)[#innerbox(width: 100%)[Header]]]],
|
||||
header-ascent: 0em,
|
||||
footer: negative-padding[#container[#align(bottom)[#innerbox(width: 100%)[Footer]]]],
|
||||
footer-descent: 0em,
|
||||
)
|
||||
|
||||
#place(top + right)[↑Margin→]
|
||||
#container[
|
||||
#container[
|
||||
#innerbox[Content]
|
||||
]
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Page Management
|
||||
|
||||
In Typst, using the `set page(..)` command to modify page parameters results in the creation of a new page, rather than modifying the current one. Therefore, Touying opts to maintain a `self.page` member variable.
|
||||
|
||||
For example, the previous example can be rewritten as:
|
||||
|
||||
```typst
|
||||
#show: default-theme.with(
|
||||
config-page(
|
||||
margin: (x: 4em, y: 2em),
|
||||
header: align(top)[Header],
|
||||
footer: align(bottom)[Footer],
|
||||
header-ascent: 0em,
|
||||
footer-descent: 0em,
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
Touying will automatically detect the value of `margin.x` and determine whether to apply negative padding to the header if `config-common(zero-margin-header: true)` is set, which is equivalent to `self.zero-margin-header = true`.
|
||||
|
||||
Similarly, if you are not satisfied with the style of the header or footer of a particular theme, you can also modify it through:
|
||||
|
||||
```typst
|
||||
config-page(footer: [Custom Footer])
|
||||
```
|
||||
|
||||
:::warning[Warning]
|
||||
|
||||
Therefore, you should not use the `set page(..)` command yourself, as it will be reset by Touying.
|
||||
|
||||
:::
|
||||
|
||||
With this approach, we can also query the current page parameters in real-time using `self.page`, which is very useful for functions that need to obtain the page margins or the current page background color, such as `transparent-cover`. This is somewhat equivalent to context get rule, and in practice, it is more convenient to use.
|
||||
|
||||
## Page Columnization
|
||||
|
||||
If you need to divide a page into two or three columns, you can use the `composer` feature provided by the default `slide` function in Touying. The simplest example is as follows:
|
||||
|
||||
```typst
|
||||
#slide[
|
||||
First column.
|
||||
][
|
||||
Second column.
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
|
||||
If you need to change the way columns are divided, you can modify the `composer` parameter of `slide`, where the default parameter is `components.side-by-side.with(columns: auto, gutter: 1em)`. If we want the left column to take up the remaining width, we can use:
|
||||
|
||||
```typst
|
||||
#slide(composer: (1fr, auto))[
|
||||
First column.
|
||||
][
|
||||
Second column.
|
||||
]
|
||||
```
|
||||
|
||||

|
||||
@@ -0,0 +1,106 @@
|
||||
---
|
||||
sidebar_position: 7
|
||||
---
|
||||
|
||||
# Multi-File Architecture
|
||||
|
||||
Touying features a syntax as concise as native Typst documents, along with numerous customizable configuration options, yet it still maintains real-time incremental compilation performance, making it suitable for writing large-scale slides.
|
||||
|
||||
If you need to write a large set of slides, such as a course manual spanning tens or hundreds of pages, you can also try Touying's multi-file architecture.
|
||||
|
||||
## Configuration and Content Separation
|
||||
|
||||
A simple Touying multi-file architecture consists of three files: a global configuration file `globals.typ`, a main entry file `main.typ`, and a content file `content.typ` for storing the actual content.
|
||||
|
||||
These three files are separated to allow both `main.typ` and `content.typ` to import `globals.typ` without causing circular references.
|
||||
|
||||
`globals.typ` can be used to store some global custom functions and initialize Touying themes:
|
||||
|
||||
```typst
|
||||
// globals.typ
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
|
||||
// as well as some utility functions
|
||||
```
|
||||
|
||||
`main.typ`, as the main entry point of the project, applies show rules by importing `globals.typ` and includes `content.typ` using `#include`:
|
||||
|
||||
```typst
|
||||
// main.typ
|
||||
#import "/globals.typ": *
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
|
||||
#include "content.typ"
|
||||
```
|
||||
|
||||
`content.typ` is where you write the actual content:
|
||||
|
||||
```typst
|
||||
// content.typ
|
||||
#import "/globals.typ": *
|
||||
|
||||
= The Section
|
||||
|
||||
== Slide Title
|
||||
|
||||
Hello, Touying!
|
||||
|
||||
#focus-slide[
|
||||
Focus on me.
|
||||
]
|
||||
```
|
||||
|
||||
## Multiple Sections
|
||||
|
||||
Implementing multiple sections is also straightforward. You only need to create a `sections` directory and move the `content.typ` file to the `sections.typ` directory, for example:
|
||||
|
||||
```typst
|
||||
// main.typ
|
||||
#import "/globals.typ": *
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
|
||||
#include "sections/content.typ"
|
||||
// #include "sections/another-section.typ"
|
||||
```
|
||||
|
||||
And
|
||||
|
||||
```typst
|
||||
// sections/content.typ
|
||||
#import "/globals.typ": *
|
||||
|
||||
= The Section
|
||||
|
||||
== Slide Title
|
||||
|
||||
Hello, Touying!
|
||||
|
||||
#focus-slide[
|
||||
Focus on me.
|
||||
]
|
||||
```
|
||||
|
||||
Now, you have learned how to use Touying to achieve a multi-file architecture for large-scale slides.
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Touying Counters
|
||||
|
||||
The utils of Touying are placed under the `utils` namespace, including all counters.
|
||||
|
||||
## Slide Counter
|
||||
|
||||
You can access the slide counter using `utils.slide-counter` and display the current slide number with `utils.slide-counter.display()`.
|
||||
|
||||
## Last-Slide Counter
|
||||
|
||||
In some cases, we may need to add an appendix to slides, leading to the requirement to freeze the last-slide counter. Therefore, a second counter is maintained here.
|
||||
|
||||
You can use `utils.last-slide-number` to display the number of the last slide before the appendix.
|
||||
|
||||
## Progress
|
||||
|
||||
You can use
|
||||
|
||||
```typst
|
||||
#utils.touying-progress(ratio => ..)
|
||||
```
|
||||
|
||||
to show the current progress.
|
||||
|
||||
## Appendix
|
||||
|
||||
You can use
|
||||
|
||||
```typst
|
||||
#show: appendix
|
||||
|
||||
= Appendix
|
||||
|
||||
appendix
|
||||
```
|
||||
|
||||
syntax to enter the appendix.
|
||||
|
||||
Additionally, label `<touying:unoutlined>` can be used to hide the appendix section from the outline.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Touying Sections
|
||||
|
||||
Touying adds invisible headings to each slide, so you can use `query(heading)` to retrieve the current section information.
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Sections and Subsections
|
||||
|
||||
## Structure
|
||||
|
||||
Like Beamer, Touying also has the concept of sections and subsections.
|
||||
|
||||
Generally, first-level, second-level, and third-level headings correspond to sections, subsections, and subsubsections, respectively, such as in the dewdrop theme.
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.dewdrop: *
|
||||
|
||||
#show: dewdrop-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
= Section
|
||||
|
||||
== Subsection
|
||||
|
||||
=== Title
|
||||
|
||||
Hello, Touying!
|
||||
```
|
||||
|
||||

|
||||
|
||||
However, there are many times when we do not need subsections, so we also use first-level and second-level headings to correspond to sections and titles, respectively, such as in the university theme.
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
|
||||
#show: university-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
= Section
|
||||
|
||||
== Title
|
||||
|
||||
Hello, Touying!
|
||||
```
|
||||
|
||||

|
||||
|
||||
In fact, we can control this behavior through the `slide-level` parameter of the `config-common` function. `slide-level` represents the complexity of the nesting structure, starting from 0. For example, `#show: university-theme.with(config-common(slide-level: 2))` is equivalent to both `section` and `subsection` creating new slides; while `#show: university-theme.with(config-common(slide-level: 3))` is equivalent to `section`, `subsection`, and `subsubsection` all creating new slides.
|
||||
|
||||
## Numbering
|
||||
|
||||
To add numbering to sections and subsections, we simply use
|
||||
|
||||
```typst
|
||||
#set heading(numbering: "1.1")
|
||||
#show heading.where(level: 1): set heading(numbering: "1.")
|
||||
```
|
||||
|
||||
This sets the default numbering to `1.1`, and the section corresponds to the numbering `1.`.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
Displaying a table of contents in Touying is straightforward:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#show: simple-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
= Section
|
||||
|
||||
== Subsection
|
||||
|
||||
#components.adaptive-columns(outline(indent: 1em))
|
||||
```
|
||||
|
||||

|
||||
|
||||
The `outline(indent: 1em)` is a native Typst function for the table of contents. The `#components.adaptive-columns()` function ensures that the table of contents occupies only one page, adapting by setting `#columns(1, body)` or `#columns(2, body)`, and so on.
|
||||
|
||||
If you need a `outline` function that can display the current progress, you might consider using `#components.progressive-outline()` or `#components.custom-progressive-outline()`, as seen in the dewdrop theme.
|
||||
@@ -0,0 +1,256 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Getting Started
|
||||
|
||||
Before you begin, make sure you have the Typst environment installed. If not, you can use the [Web App](https://typst.app/) or install the [Tinymist LSP](https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist) plugins for VS Code.
|
||||
|
||||
To use Touying, you just need to include the following in your document:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(aspect-ratio: "16-9")
|
||||
|
||||
= Title
|
||||
|
||||
== First Slide
|
||||
|
||||
Hello, Touying!
|
||||
|
||||
#pause
|
||||
|
||||
Hello, Typst!
|
||||
```
|
||||
|
||||

|
||||
|
||||
It's that simple! You've created your first Touying slides. Congratulations! 🎉
|
||||
|
||||
**Tip:** You can use Typst syntax like `#import "config.typ": *` or `#include "content.typ"` to implement Touying's multi-file architecture.
|
||||
|
||||
## More Complex Examples
|
||||
|
||||
In fact, Touying provides various styles for slide writing. You can also use the `#slide[..]` syntax to access more powerful features provided by Touying.
|
||||
|
||||
Touying offers many built-in themes to easily create beautiful slides. For example, in this case:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
#import "@preview/cetz:0.3.2"
|
||||
#import "@preview/fletcher:0.5.5" as fletcher: node, edge
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
#import "@preview/theorion:0.3.2": *
|
||||
#import cosmos.clouds: *
|
||||
#show: show-theorion
|
||||
|
||||
// cetz and fletcher bindings for touying
|
||||
#let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true))
|
||||
#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
// align: horizon,
|
||||
// config-common(handout: true),
|
||||
config-common(frozen-counters: (theorem-counter,)), // freeze theorem counter for animation
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
|
||||
== Outline <touying:hidden>
|
||||
|
||||
#components.adaptive-columns(outline(title: none, indent: 1em))
|
||||
|
||||
= Animation
|
||||
|
||||
== Simple Animation
|
||||
|
||||
We can use `#pause` to #pause display something later.
|
||||
|
||||
#pause
|
||||
|
||||
Just like this.
|
||||
|
||||
#meanwhile
|
||||
|
||||
Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously.
|
||||
|
||||
#speaker-note[
|
||||
+ This is a speaker note.
|
||||
+ You won't see it unless you use `config-common(show-notes-on-second-screen: right)`
|
||||
]
|
||||
|
||||
|
||||
== Complex Animation
|
||||
|
||||
At subslide #touying-fn-wrapper((self: none) => str(self.subslide)), we can
|
||||
|
||||
use #uncover("2-")[`#uncover` function] for reserving space,
|
||||
|
||||
use #only("2-")[`#only` function] for not reserving space,
|
||||
|
||||
#alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives.
|
||||
|
||||
|
||||
== Callback Style Animation
|
||||
|
||||
#slide(
|
||||
repeat: 3,
|
||||
self => [
|
||||
#let (uncover, only, alternatives) = utils.methods(self)
|
||||
|
||||
At subslide #self.subslide, we can
|
||||
|
||||
use #uncover("2-")[`#uncover` function] for reserving space,
|
||||
|
||||
use #only("2-")[`#only` function] for not reserving space,
|
||||
|
||||
#alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives.
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
== Math Equation Animation
|
||||
|
||||
Equation with `pause`:
|
||||
|
||||
$
|
||||
f(x) &= pause x^2 + 2x + 1 \
|
||||
&= pause (x + 1)^2 \
|
||||
$
|
||||
|
||||
#meanwhile
|
||||
|
||||
Here, #pause we have the expression of $f(x)$.
|
||||
|
||||
#pause
|
||||
|
||||
By factorizing, we can obtain this result.
|
||||
|
||||
|
||||
== CeTZ Animation
|
||||
|
||||
CeTZ Animation in Touying:
|
||||
|
||||
#cetz-canvas({
|
||||
import cetz.draw: *
|
||||
|
||||
rect((0, 0), (5, 5))
|
||||
|
||||
(pause,)
|
||||
|
||||
rect((0, 0), (1, 1))
|
||||
rect((1, 1), (2, 2))
|
||||
rect((2, 2), (3, 3))
|
||||
|
||||
(pause,)
|
||||
|
||||
line((0, 0), (2.5, 2.5), name: "line")
|
||||
})
|
||||
|
||||
|
||||
== Fletcher Animation
|
||||
|
||||
Fletcher Animation in Touying:
|
||||
|
||||
#fletcher-diagram(
|
||||
node-stroke: .1em,
|
||||
node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%),
|
||||
spacing: 4em,
|
||||
edge((-1, 0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
|
||||
node((0, 0), `reading`, radius: 2em),
|
||||
edge((0, 0), (0, 0), `read()`, "--|>", bend: 130deg),
|
||||
pause,
|
||||
edge(`read()`, "-|>"),
|
||||
node((1, 0), `eof`, radius: 2em),
|
||||
pause,
|
||||
edge(`close()`, "-|>"),
|
||||
node((2, 0), `closed`, radius: 2em, extrude: (-2.5, 0)),
|
||||
edge((0, 0), (2, 0), `close()`, "-|>", bend: -40deg),
|
||||
)
|
||||
|
||||
|
||||
= Theorems
|
||||
|
||||
== Prime numbers
|
||||
|
||||
#definition[
|
||||
A natural number is called a #highlight[_prime number_] if it is greater
|
||||
than 1 and cannot be written as the product of two smaller natural numbers.
|
||||
]
|
||||
#example[
|
||||
The numbers $2$, $3$, and $17$ are prime.
|
||||
@cor_largest_prime shows that this list is not exhaustive!
|
||||
]
|
||||
|
||||
#theorem(title: "Euclid")[
|
||||
There are infinitely many primes.
|
||||
]
|
||||
#pagebreak(weak: true)
|
||||
#proof[
|
||||
Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration
|
||||
of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list,
|
||||
it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since
|
||||
$p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a
|
||||
contradiction.
|
||||
]
|
||||
|
||||
#corollary[
|
||||
There is no largest prime number.
|
||||
] <cor_largest_prime>
|
||||
#corollary[
|
||||
There are infinitely many composite numbers.
|
||||
]
|
||||
|
||||
#theorem[
|
||||
There are arbitrarily long stretches of composite numbers.
|
||||
]
|
||||
|
||||
#proof[
|
||||
For any $n > 2$, consider $
|
||||
n! + 2, quad n! + 3, quad ..., quad n! + n
|
||||
$
|
||||
]
|
||||
|
||||
|
||||
= Others
|
||||
|
||||
== Side-by-side
|
||||
|
||||
#slide(composer: (1fr, 1fr))[
|
||||
First column.
|
||||
][
|
||||
Second column.
|
||||
]
|
||||
|
||||
|
||||
== Multiple Pages
|
||||
|
||||
#lorem(200)
|
||||
|
||||
|
||||
#show: appendix
|
||||
|
||||
= Appendix
|
||||
|
||||
== Appendix
|
||||
|
||||
Please pay attention to the current slide number.
|
||||
```
|
||||
|
||||

|
||||
|
||||
For more detailed tutorials on themes, you can refer to the following sections.
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Aqua Theme
|
||||
|
||||

|
||||
|
||||
This theme is created by [@pride7](https://github.com/pride7), featuring beautiful backgrounds made with Typst's visualization capabilities.
|
||||
|
||||
## Initialization
|
||||
|
||||
You can initialize it with the following code:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.aqua: *
|
||||
|
||||
#show: aqua-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
),
|
||||
)
|
||||
|
||||
#title-slide()
|
||||
|
||||
#outline-slide()
|
||||
```
|
||||
|
||||
The `register` function in the Aqua theme accepts the following parameters:
|
||||
|
||||
- `aspect-ratio`: The aspect ratio of the slides, which can be "16-9" or "4-3", with a default of "16-9".
|
||||
- `header`: The content displayed in the header of the slides, with a default of `utils.display-current-heading()`. You can also provide a function like `self => self.info.title` to customize the header content.
|
||||
- `footer`: The content displayed on the right side of the footer, with a default of `context utils.slide-counter.display()`.
|
||||
|
||||
Additionally, the Aqua theme provides a `#alert[..]` function, which you can use with the `#show strong: alert` syntax to emphasize text within your slides.
|
||||
|
||||
## Color Theme
|
||||
|
||||
The Aqua theme uses the following color scheme by default:
|
||||
|
||||
```typst
|
||||
config-colors(
|
||||
primary: rgb("#003F88"),
|
||||
primary-light: rgb("#2159A5"),
|
||||
primary-lightest: rgb("#F2F4F8"),
|
||||
neutral-lightest: rgb("#FFFFFF"),
|
||||
)
|
||||
```
|
||||
|
||||
You can modify this color scheme using the `config-colors()` function to suit your preferences or to match the branding of your presentation.
|
||||
|
||||
|
||||
## Slide Function Family
|
||||
|
||||
Aqua theme offers a series of custom slide functions:
|
||||
|
||||
```typst
|
||||
#title-slide(..args)
|
||||
```
|
||||
|
||||
`title-slide` will read information from `self.info` for display.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#let outline-slide(self: none, enum-args: (:), leading: 50pt)
|
||||
```
|
||||
|
||||
Display an outline slide.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#slide(
|
||||
repeat: auto,
|
||||
setting: body => body,
|
||||
composer: components.side-by-side,
|
||||
// Aqua theme
|
||||
title: auto,
|
||||
)[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
A default ordinary slide function with title and footer, where `title` defaults to the current section title.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#focus-slide[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Used to draw the audience's attention. The background color is `self.colors.primary`.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#new-section-slide(title)
|
||||
```
|
||||
|
||||
Start a new section with the given title.
|
||||
|
||||
|
||||
## Example
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.aqua: *
|
||||
|
||||
#show: aqua-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
),
|
||||
)
|
||||
|
||||
#title-slide()
|
||||
|
||||
#outline-slide()
|
||||
|
||||
= The Section
|
||||
|
||||
== Slide Title
|
||||
|
||||
#lorem(40)
|
||||
|
||||
#focus-slide[
|
||||
Another variant with primary color in background...
|
||||
]
|
||||
|
||||
== Summary
|
||||
|
||||
#slide(self => [
|
||||
#align(center + horizon)[
|
||||
#set text(size: 3em, weight: "bold", fill: self.colors.primary)
|
||||
THANKS FOR ALL
|
||||
]
|
||||
])
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
sidebar_position: 7
|
||||
---
|
||||
|
||||
# Custom Theme
|
||||
|
||||
You could consider making your own theme, you can refer to the "Build Your Own Theme" section later.
|
||||
|
||||
If you have any questions or need to customize a template, you can also contact orangex4@qq.com for free or inexpensive paid help. All forms are welcome.
|
||||
|
||||
## 🥤A cup of coffee
|
||||
|
||||
If you feel that this project has helped you in your work, you can donate to Touying's development work in the following ways to keep the project going.
|
||||
|
||||
Sponsor: https://afdian.com/a/orangex4
|
||||
|
||||
QR Code:
|
||||
|
||||

|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Dewdrop Theme
|
||||
|
||||

|
||||
|
||||
This theme takes inspiration from Zhibo Wang's [BeamerTheme](https://github.com/zbowang/BeamerTheme) and has been modified by [OrangeX4](https://github.com/OrangeX4).
|
||||
|
||||
The Dewdrop theme features an elegantly designed navigation, including two modes: `sidebar` and `mini-slides`.
|
||||
|
||||
## Initialization
|
||||
|
||||
You can initialize it using the following code:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.dewdrop: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: dewdrop-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: self => self.info.institution,
|
||||
navigation: "mini-slides",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
),
|
||||
)
|
||||
|
||||
#title-slide()
|
||||
|
||||
#outline-slide()
|
||||
```
|
||||
|
||||
The `register` function in the Dewdrop theme accepts the following parameters:
|
||||
|
||||
- `aspect-ratio`: The aspect ratio of the slides, which can be "16-9" or "4-3", with a default of "16-9".
|
||||
- `navigation`: The style of the navigation bar, which can be `"sidebar"`, `"mini-slides"`, or `none`, with a default of `"sidebar"`.
|
||||
- `sidebar`: Settings for the sidebar navigation, with default values of `(width: 10em, filled: false, numbered: false, indent: .5em, short-heading: true)`.
|
||||
- `mini-slides`: Settings for the mini-slides navigation, with default values of `(height: 4em, x: 2em, display-section: false, display-subsection: true, short-heading: true)`.
|
||||
- `height`: The height of the mini-slides, with a default of `2em`.
|
||||
- `x`: The x-axis padding for the mini-slides, with a default of `2em`.
|
||||
- `section`: Whether to display slides after the section and before the subsection, with a default of `false`.
|
||||
- `subsection`: Whether to separate mini-slides based on subsections, with a default of `true`. Setting this to `false` will squash them into a single line.
|
||||
- `footer`: The content displayed in the footer of the slides, with a default of an empty array `[]`. You can customize it with a function, such as `self => self.info.author`.
|
||||
- `footer-right`: The content displayed on the right side of the footer, with a default of `context utils.slide-counter.display() + " / " + utils.last-slide-number`.
|
||||
- `primary`: The primary color of the theme, with a default of `rgb("#0c4842")`.
|
||||
- `alpha`: The transparency level, with a default of `70%`.
|
||||
|
||||
Additionally, the Dewdrop theme provides a `#alert[..]` function, which you can use with the `#show strong: alert` syntax to create emphasized alert text.
|
||||
|
||||
## Color Theme
|
||||
|
||||
The Dewdrop theme uses the following color scheme by default:
|
||||
|
||||
```typc
|
||||
config-colors(
|
||||
neutral-darkest: rgb("#000000"),
|
||||
neutral-dark: rgb("#202020"),
|
||||
neutral-light: rgb("#f3f3f3"),
|
||||
neutral-lightest: rgb("#ffffff"),
|
||||
primary: primary,
|
||||
)
|
||||
```
|
||||
|
||||
You can modify this color scheme using the `config-colors()` function. This allows you to tailor the color palette of your slides to match the aesthetic you're aiming for or to conform to a specific branding guideline.
|
||||
|
||||
|
||||
## Slide Function Family
|
||||
|
||||
The Dewdrop theme provides a variety of custom slide functions:
|
||||
|
||||
```typst
|
||||
#title-slide(extra: none, ..args)
|
||||
```
|
||||
|
||||
`title-slide` reads information from `self.info` for display, and you can also pass in an `extra` parameter to display additional information.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#slide(
|
||||
config: (:),
|
||||
repeat: auto,
|
||||
setting: body => body,
|
||||
composer: components.side-by-side,
|
||||
)[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
A default slide with navigation and footer, where the footer is what you set.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#focus-slide[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Used to draw attention, with the background color set to `self.colors.primary`.
|
||||
|
||||
## Example
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.dewdrop: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: dewdrop-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: self => self.info.institution,
|
||||
navigation: "mini-slides",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
|
||||
#outline-slide()
|
||||
|
||||
= Section A
|
||||
|
||||
== Subsection A.1
|
||||
|
||||
$ x_(n+1) = (x_n + a/x_n) / 2 $
|
||||
|
||||
== Subsection A.2
|
||||
|
||||
A slide without a title but with *important* infos
|
||||
|
||||
= Section B
|
||||
|
||||
== Subsection B.1
|
||||
|
||||
#lorem(80)
|
||||
|
||||
#focus-slide[
|
||||
Wake up!
|
||||
]
|
||||
|
||||
== Subsection B.2
|
||||
|
||||
We can use `#pause` to #pause display something later.
|
||||
|
||||
#pause
|
||||
|
||||
Just like this.
|
||||
|
||||
#meanwhile
|
||||
|
||||
Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously.
|
||||
|
||||
#show: appendix
|
||||
|
||||
= Appendix
|
||||
|
||||
== Appendix
|
||||
|
||||
Please pay attention to the current slide number.
|
||||
```
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Metropolis Theme
|
||||
|
||||

|
||||
|
||||
This theme draws inspiration from Matthias Vogelgesang's [Metropolis beamer](https://github.com/matze/mtheme) theme and has been modified by [Enivex](https://github.com/Enivex).
|
||||
|
||||
The Metropolis theme is elegant and suitable for everyday use. It is recommended to have Fira Sans and Fira Math fonts installed on your computer for the best results.
|
||||
|
||||
## Initialization
|
||||
|
||||
You can initialize it using the following code:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.metropolis: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: metropolis-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: self => self.info.institution,
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.city,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
```
|
||||
|
||||
The `metropolis-theme` in the theme accepts the following parameters:
|
||||
|
||||
- `aspect-ratio`: The aspect ratio of the slides, which can be "16-9" or "4-3", with a default of "16-9".
|
||||
- `align`: The alignment of the content within the slides, with a default of `horizon` (horizontal alignment).
|
||||
- `header`: The content displayed in the header of the slides, with a default that displays the current heading adjusted to fit the width (`utils.display-current-heading(setting: utils.fit-to-width.with(grow: false, 100%))`). Alternatively, you can provide a function like `self => self.info.title` to customize the header content.
|
||||
- `header-right`: The content displayed on the right side of the header, with a default that shows the logo specified in `self.info.logo`.
|
||||
- `footer`: The content displayed in the footer of the slides, with a default of an empty array `[]`. You can customize it with a function, for example, to display the author's information: `self => self.info.author`.
|
||||
- `footer-right`: The content displayed on the right side of the footer, with a default that shows the slide number and the total number of slides (`context utils.slide-counter.display() + " / " + utils.last-slide-number`).
|
||||
- `footer-progress`: A boolean value indicating whether to display a progress bar at the bottom of the slides, with a default of `true`.
|
||||
|
||||
|
||||
|
||||
## Color Theme
|
||||
|
||||
Metropolis uses the following default color theme:
|
||||
|
||||
```typc
|
||||
config-colors(
|
||||
primary: rgb("#eb811b"),
|
||||
primary-light: rgb("#d6c6b7"),
|
||||
secondary: rgb("#23373b"),
|
||||
neutral-lightest: rgb("#fafafa"),
|
||||
neutral-dark: rgb("#23373b"),
|
||||
neutral-darkest: rgb("#23373b"),
|
||||
)
|
||||
```
|
||||
|
||||
You can modify this color theme using `config-colors()`.
|
||||
|
||||
## Slide Function Family
|
||||
|
||||
The Metropolis theme provides a variety of custom slide functions:
|
||||
|
||||
```typst
|
||||
#title-slide(extra: none, ..args)
|
||||
```
|
||||
|
||||
`title-slide` reads information from `self.info` for display, and you can also pass in an `extra` parameter to display additional information.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#slide(
|
||||
config: (:),
|
||||
repeat: auto,
|
||||
setting: body => body,
|
||||
composer: components.side-by-side,
|
||||
// metropolis theme
|
||||
title: auto,
|
||||
footer: auto,
|
||||
align: horizon,
|
||||
)[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
A default slide with headers and footers, where the title defaults to the current section title, and the footer is what you set.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#focus-slide[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Used to draw attention, with the background color set to `self.colors.primary-dark`.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#new-section-slide(short-title: auto, title)
|
||||
```
|
||||
|
||||
Creates a new section with the given title.
|
||||
|
||||
## Example
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.metropolis: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: metropolis-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: self => self.info.institution,
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.city,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
|
||||
= Outline <touying:hidden>
|
||||
|
||||
#outline(title: none, indent: 1em, depth: 1)
|
||||
|
||||
= First Section
|
||||
|
||||
---
|
||||
|
||||
A slide without a title but with some *important* information.
|
||||
|
||||
== A long long long long long long long long long long long long long long long long long long long long long long long long Title
|
||||
|
||||
=== sdfsdf
|
||||
|
||||
A slide with equation:
|
||||
|
||||
$ x_(n+1) = (x_n + a/x_n) / 2 $
|
||||
|
||||
#lorem(200)
|
||||
|
||||
= Second Section
|
||||
|
||||
#focus-slide[
|
||||
Wake up!
|
||||
]
|
||||
|
||||
== Simple Animation
|
||||
|
||||
We can use `#pause` to #pause display something later.
|
||||
|
||||
#meanwhile
|
||||
|
||||
Meanwhile, #pause we can also use `#meanwhile` to display other content synchronously.
|
||||
|
||||
#speaker-note[
|
||||
+ This is a speaker note.
|
||||
+ You won't see it unless you use `config-common(show-notes-on-second-screen: right)`
|
||||
]
|
||||
|
||||
#show: appendix
|
||||
|
||||
= Appendix
|
||||
|
||||
---
|
||||
|
||||
Please pay attention to the current slide number.
|
||||
```
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Simple Theme
|
||||
|
||||

|
||||
|
||||
This theme originates from [Polylux](https://polylux.dev/book/themes/gallery/simple.html), created by Andreas Kröpelin.
|
||||
|
||||
Considered a relatively straightforward theme, you can use it to create simple slides and freely incorporate features you like.
|
||||
|
||||
## Initialization
|
||||
|
||||
You can initialize it using the following code:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: [Simple slides],
|
||||
)
|
||||
```
|
||||
|
||||
The `register` function in the theme accepts the following parameters:
|
||||
|
||||
- `aspect-ratio`: The aspect ratio of the slides, which can be "16-9" or "4-3", with a default of "16-9".
|
||||
- `header`: The content displayed in the header, with a default of `utils.display-current-heading(setting: utils.fit-to-width.with(grow: false, 100%))`. You can also pass a function like `self => self.info.title`.
|
||||
- `header-right`: The content displayed on the right side of the header, with a default of `self => self.info.logo`.
|
||||
- `footer`: The content displayed in the footer, with a default of `[]` (empty). You can also pass a function like `self => self.info.author`.
|
||||
- `footer-right`: The content displayed on the right side of the footer, with a default of `context utils.slide-counter.display() + " / " + utils.last-slide-number`.
|
||||
- `primary`: The primary color of the theme, with a default of `aqua.darken(50%)`.
|
||||
- `subslide-preamble`: By default, it adds the subsection title to the current slide.
|
||||
|
||||
|
||||
## Slide Function Family
|
||||
|
||||
The Simple theme provides a variety of custom slide functions:
|
||||
|
||||
```typst
|
||||
#centered-slide(section: ..)[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
A slide with content centered, and the `section` parameter can be used to create a new section.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#title-slide[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Similar to `centered-slide`, this is provided for consistency with Polylux syntax.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#slide(
|
||||
config: (:),
|
||||
repeat: auto,
|
||||
setting: body => body,
|
||||
composer: components.side-by-side,
|
||||
)[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
A default slide with headers and footers, where the header corresponds to the current section, and the footer is what you set.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#focus-slide(foreground: ..., background: ...)[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Used to draw attention, it optionally accepts a foreground color (defaulting to `white`) and a background color (defaulting to `auto`, i.e., `self.colors.primary`).
|
||||
|
||||
|
||||
## Example
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: [Simple slides],
|
||||
)
|
||||
|
||||
#title-slide[
|
||||
= Keep it simple!
|
||||
#v(2em)
|
||||
|
||||
Alpha #footnote[Uni Augsburg] #h(1em)
|
||||
Bravo #footnote[Uni Bayreuth] #h(1em)
|
||||
Charlie #footnote[Uni Chemnitz] #h(1em)
|
||||
|
||||
July 23
|
||||
]
|
||||
|
||||
== First slide
|
||||
|
||||
#lorem(20)
|
||||
|
||||
#focus-slide[
|
||||
_Focus!_
|
||||
|
||||
This is very important.
|
||||
]
|
||||
|
||||
= Let's start a new section!
|
||||
|
||||
== Dynamic slide
|
||||
|
||||
Did you know that...
|
||||
|
||||
#pause
|
||||
|
||||
...you can see the current section at the top of the slide?
|
||||
```
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
# Stargazer Theme
|
||||
|
||||

|
||||
|
||||
The Stargazer theme, originally created by [Coekjan](https://github.com/Coekjan/) for the [touying-buaa](https://github.com/Coekjan/touying-buaa) project, is an aesthetically pleasing and versatile theme suitable for everyday use.
|
||||
|
||||
## Initialization
|
||||
|
||||
You can initialize the theme with the following code:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.stargazer: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: stargazer-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Stargazer in Touying: Customize Your Slide Title Here],
|
||||
subtitle: [Customize Your Slide Subtitle Here],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
|
||||
#outline-slide()
|
||||
```
|
||||
|
||||
The `stargazer-theme` accepts the following parameters:
|
||||
|
||||
- `aspect-ratio`: The aspect ratio of the slides, either "16-9" or "4-3", with a default of "16-9".
|
||||
- `align`: The alignment of the slides, with a default of `horizon`.
|
||||
- `alpha`: The transparency of the slides, with a default of `20%`.
|
||||
- `title`: The content displayed in the header, with a default of `utils.display-current-heading()`, or you can pass a function like `self => self.info.title`.
|
||||
- `progress-bar`: Whether to display a progress bar at the bottom of the slide, with a default of `true`.
|
||||
- `footer-columns`: The widths of the three footer columns, with a default of `(25%, 25%, 1fr, 5em)`.
|
||||
- `footer-a`: The first column, with a default of `self => self.info.author`.
|
||||
- `footer-b`: The second column, with a default of `self => utils.display-info-date(self)`.
|
||||
- `footer-c`: The third column, with a default of `self => if self.info.short-title == auto { self.info.title } else { self.info.short-title }`.
|
||||
- `footer-d`: The fourth column, with a default of `context utils.slide-counter.display() + " / " + utils.last-slide-number`.
|
||||
|
||||
## Color Theme
|
||||
|
||||
The Stargazer theme uses the following color scheme by default:
|
||||
|
||||
```typc
|
||||
config-colors(
|
||||
primary: rgb("#005bac"),
|
||||
primary-dark: rgb("#004078"),
|
||||
secondary: rgb("#ffffff"),
|
||||
tertiary: rgb("#005bac"),
|
||||
neutral-lightest: rgb("#ffffff"),
|
||||
neutral-darkest: rgb("#000000"),
|
||||
)
|
||||
```
|
||||
|
||||
You can modify this color scheme using `config-colors()`.
|
||||
|
||||
## Slide Function Family
|
||||
|
||||
The Stargazer theme offers a variety of custom slide functions:
|
||||
|
||||
```typst
|
||||
#title-slide(extra: none, ..args)
|
||||
```
|
||||
|
||||
`title-slide` reads information from `self.info` for display, and you can also pass an `extra` parameter for additional information.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#slide(
|
||||
config: (:),
|
||||
repeat: auto,
|
||||
setting: body => body,
|
||||
composer: components.side-by-side,
|
||||
// stargazer theme
|
||||
title: auto,
|
||||
footer: auto,
|
||||
align: horizon,
|
||||
)[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
A standard slide function with a title and footer by default, where `title` defaults to the current section title, and the footer is the one you set.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#outline-slide[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Used to add a table of contents slide.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#focus-slide[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Used to draw the audience's attention. The background color is `self.colors.primary-dark`.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#new-section-slide(short-title: auto, title)
|
||||
```
|
||||
|
||||
Start a new section with the given title.
|
||||
|
||||
## Example
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.stargazer: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: stargazer-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Stargazer in Touying: Customize Your Slide Title Here],
|
||||
subtitle: [Customize Your Slide Subtitle Here],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
|
||||
#outline-slide()
|
||||
|
||||
= Section A
|
||||
|
||||
== Subsection A.1
|
||||
|
||||
#tblock(title: [Theorem])[
|
||||
A simple theorem.
|
||||
|
||||
$ x_(n+1) = (x_n + a / x_n) / 2 $
|
||||
]
|
||||
|
||||
== Subsection A.2
|
||||
|
||||
A slide without a title but with *important* information.
|
||||
|
||||
= Section B
|
||||
|
||||
== Subsection B.1
|
||||
|
||||
#lorem(80)
|
||||
|
||||
#focus-slide[
|
||||
Wake up!
|
||||
]
|
||||
|
||||
== Subsection B.2
|
||||
|
||||
We can use `#pause` to #pause display something later.
|
||||
|
||||
#pause
|
||||
|
||||
Just like this.
|
||||
|
||||
#meanwhile
|
||||
|
||||
Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously.
|
||||
|
||||
#show: appendix
|
||||
|
||||
= Appendix
|
||||
|
||||
== Appendix
|
||||
|
||||
Please pay attention to the current slide number.
|
||||
```
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# University Theme
|
||||
|
||||

|
||||
|
||||
This aesthetically pleasing theme is courtesy of [Pol Dellaiera](https://github.com/drupol).
|
||||
|
||||
## Initialization
|
||||
|
||||
You can initialize the theme with the following code:
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
```
|
||||
|
||||
The `register` function accepts the following parameters:
|
||||
|
||||
- `aspect-ratio`: The aspect ratio of the slides, either "16-9" or "4-3", with a default of "16-9".
|
||||
- `progress-bar`: Whether to display a progress bar at the top of the slide, with a default of `true`.
|
||||
- `header`: The content displayed in the header, with a default of `utils.display-current-heading(level: 2)`, or you can pass a function like `self => self.info.title`.
|
||||
- `header-right`: The content displayed on the right side of the header, with a default of `self => self.info.logo`.
|
||||
- `footer-columns`: The widths of the three columns in the footer, with a default of `(25%, 1fr, 25%)`.
|
||||
- `footer-a`: The first column, with a default of `self => self.info.author`.
|
||||
- `footer-b`: The second column, with a default of `self => if self.info.short-title == auto { self.info.title } else { self.info.short-title }`.
|
||||
- `footer-c`: The third column, with a default of
|
||||
|
||||
```typst
|
||||
self => {
|
||||
h(1fr)
|
||||
utils.display-info-date(self)
|
||||
h(1fr)
|
||||
context utils.slide-counter.display() + " / " + utils.last-slide-number
|
||||
h(1fr)
|
||||
}
|
||||
```
|
||||
|
||||
## Color Theme
|
||||
|
||||
The University theme uses the following color scheme by default:
|
||||
|
||||
```typc
|
||||
config-colors(
|
||||
primary: rgb("#04364A"),
|
||||
secondary: rgb("#176B87"),
|
||||
tertiary: rgb("#448C95"),
|
||||
neutral-lightest: rgb("#ffffff"),
|
||||
neutral-darkest: rgb("#000000"),
|
||||
)
|
||||
```
|
||||
|
||||
You can modify this color scheme using `config-colors()`.
|
||||
|
||||
## Slide Function Family
|
||||
|
||||
The University theme provides a series of custom slide functions:
|
||||
|
||||
```typst
|
||||
#title-slide(logo: none, authors: none, ..args)
|
||||
```
|
||||
|
||||
The `title-slide` function reads information from `self.info` for display, and you can also pass a `logo` parameter and an array-type `authors` parameter.
|
||||
|
||||
---
|
||||
|
||||
```typst
|
||||
#slide(
|
||||
config: (:),
|
||||
repeat: auto,
|
||||
setting: body => body,
|
||||
composer: components.side-by-side,
|
||||
// university theme
|
||||
title: none,
|
||||
)[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
A standard slide function with a title and footer by default, where `title` defaults to the current section title, and the footer is the one you set.
|
||||
|
||||
### Focus Slide
|
||||
|
||||
```typst
|
||||
#focus-slide(background-img: ..., background-color: ...)[
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Used to capture the audience's attention. The default background color is `self.colors.primary`.
|
||||
|
||||
### Matrix Slide
|
||||
|
||||
```typst
|
||||
#matrix-slide(columns: ..., rows: ...)[
|
||||
...
|
||||
][
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Refer to the [documentation](https://polylux.dev/book/themes/gallery/university.html).
|
||||
|
||||
## Example
|
||||
|
||||
```typst
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide(authors: ([Author A], [Author B]))
|
||||
|
||||
= The Section
|
||||
|
||||
== Slide Title
|
||||
|
||||
#lorem(40)
|
||||
|
||||
#focus-slide[
|
||||
Another variant with primary color in background...
|
||||
]
|
||||
|
||||
#matrix-slide[
|
||||
left
|
||||
][
|
||||
middle
|
||||
][
|
||||
right
|
||||
]
|
||||
|
||||
#matrix-slide(columns: 1)[
|
||||
top
|
||||
][
|
||||
bottom
|
||||
]
|
||||
|
||||
#matrix-slide(columns: (1fr, 2fr, 1fr), ..(lorem(8),) * 9)
|
||||
```
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Fit to Height / Width
|
||||
|
||||
Thanks to [ntjess](https://github.com/ntjess) for the code.
|
||||
|
||||
## Fit to Height
|
||||
|
||||
If you need to make an image fill the remaining slide height, you can try the `fit-to-height` function:
|
||||
|
||||
```typst
|
||||
#utils.fit-to-height(1fr)[BIG]
|
||||
```
|
||||
|
||||
Function definition:
|
||||
|
||||
```typst
|
||||
#let fit-to-height(
|
||||
width: none, prescale-width: none, grow: true, shrink: true, height, body
|
||||
) = { .. }
|
||||
```
|
||||
|
||||
Parameters:
|
||||
|
||||
- `width`: If specified, this will determine the width of the content after scaling. So, if you want the scaled content to fill half of the slide width, you can use `width: 50%`.
|
||||
- `prescale-width`: This parameter allows you to make Typst's layout assume that the given content is to be laid out in a container of a certain width before scaling. For example, you can use `prescale-width: 200%` assuming the slide's width is twice the original.
|
||||
- `grow`: Whether it can grow, default is `true`.
|
||||
- `shrink`: Whether it can shrink, default is `true`.
|
||||
- `height`: The specified height.
|
||||
- `body`: The specific content.
|
||||
|
||||
## Fit to Width
|
||||
|
||||
If you need to limit the title width to exactly fill the slide width, you can try the `fit-to-width` function:
|
||||
|
||||
```typst
|
||||
#utils.fit-to-width(1fr)[#lorem(20)]
|
||||
```
|
||||
|
||||
Function definition:
|
||||
|
||||
```typst
|
||||
#let fit-to-width(grow: true, shrink: true, width, body) = { .. }
|
||||
```
|
||||
|
||||
Parameters:
|
||||
|
||||
- `grow`: Whether it can grow, default is `true`.
|
||||
- `shrink`: Whether it can shrink, default is `true`.
|
||||
- `width`: The specified width.
|
||||
- `body`: The specific content.
|
||||
@@ -0,0 +1,43 @@
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.aqua: *
|
||||
|
||||
#show: aqua-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [标题],
|
||||
subtitle: [副标题],
|
||||
author: [作者],
|
||||
date: datetime.today(),
|
||||
institution: [机构],
|
||||
),
|
||||
)
|
||||
|
||||
#set text(lang: "zh")
|
||||
|
||||
#title-slide()
|
||||
|
||||
#outline-slide()
|
||||
|
||||
= 第一节
|
||||
|
||||
== 小标题
|
||||
|
||||
#slide[
|
||||
#lorem(40)
|
||||
]
|
||||
|
||||
#slide[
|
||||
#lorem(40)
|
||||
]
|
||||
|
||||
== 总结
|
||||
|
||||
#slide(self => [
|
||||
#align(center + horizon)[
|
||||
#set text(size: 3em, weight: "bold", self.colors.primary)
|
||||
|
||||
THANKS FOR ALL
|
||||
|
||||
敬请指正!
|
||||
]
|
||||
])
|
||||
@@ -0,0 +1,37 @@
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.aqua: *
|
||||
|
||||
#show: aqua-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
),
|
||||
)
|
||||
|
||||
#title-slide()
|
||||
|
||||
#outline-slide()
|
||||
|
||||
= The Section
|
||||
|
||||
== Slide Title
|
||||
|
||||
#lorem(40)
|
||||
|
||||
#focus-slide[
|
||||
Another variant with primary color in background...
|
||||
]
|
||||
|
||||
== Summary
|
||||
|
||||
#slide(self => [
|
||||
#align(center + horizon)[
|
||||
#set text(size: 3em, weight: "bold", fill: self.colors.primary)
|
||||
THANKS FOR ALL
|
||||
]
|
||||
])
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.default: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: default-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
config-common(
|
||||
slide-level: 3,
|
||||
zero-margin-header: false,
|
||||
),
|
||||
config-colors(primary: blue),
|
||||
config-methods(alert: utils.alert-with-primary-color),
|
||||
config-page(
|
||||
header: text(gray, utils.display-current-short-heading(level: 2)),
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
= Outline <touying:hidden>
|
||||
|
||||
#components.adaptive-columns(outline(title: none, indent: 1em))
|
||||
|
||||
= Title
|
||||
|
||||
== Recall <recall>
|
||||
|
||||
*Recall*
|
||||
|
||||
#speaker-note[Recall]
|
||||
|
||||
#show: touying-set-config.with(config-methods(
|
||||
cover: utils.semi-transparent-cover,
|
||||
))
|
||||
|
||||
== Animation
|
||||
|
||||
#set math.equation(numbering: "(1)")
|
||||
|
||||
Simple
|
||||
|
||||
#pause
|
||||
|
||||
$ x + y $
|
||||
|
||||
animation
|
||||
|
||||
#touying-recall(<recall>)
|
||||
|
||||
|
||||
#show: appendix
|
||||
|
||||
= Appendix
|
||||
|
||||
Appendix
|
||||
@@ -0,0 +1,63 @@
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.dewdrop: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: dewdrop-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: self => self.info.institution,
|
||||
navigation: "mini-slides",
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
|
||||
#outline-slide()
|
||||
|
||||
= Section A
|
||||
|
||||
== Subsection A.1
|
||||
|
||||
$ x_(n+1) = (x_n + a / x_n) / 2 $
|
||||
|
||||
== Subsection A.2
|
||||
|
||||
A slide without a title but with *important* infos
|
||||
|
||||
= Section B
|
||||
|
||||
== Subsection B.1
|
||||
|
||||
#lorem(80)
|
||||
|
||||
#focus-slide[
|
||||
Wake up!
|
||||
]
|
||||
|
||||
== Subsection B.2
|
||||
|
||||
We can use `#pause` to #pause display something later.
|
||||
|
||||
#pause
|
||||
|
||||
Just like this.
|
||||
|
||||
#meanwhile
|
||||
|
||||
Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously.
|
||||
|
||||
#show: appendix
|
||||
|
||||
= Appendix
|
||||
|
||||
== Appendix
|
||||
|
||||
Please pay attention to the current slide number.
|
||||
@@ -0,0 +1,220 @@
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.university: *
|
||||
#import "@preview/cetz:0.4.1"
|
||||
#import "@preview/fletcher:0.5.8" as fletcher: edge, node
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
#import "@preview/theorion:0.4.1": *
|
||||
#import cosmos.clouds: *
|
||||
#show: show-theorion
|
||||
|
||||
// cetz and fletcher bindings for touying
|
||||
#let cetz-canvas = touying-reducer.with(
|
||||
reduce: cetz.canvas,
|
||||
cover: cetz.draw.hide.with(bounds: true),
|
||||
)
|
||||
#let fletcher-diagram = touying-reducer.with(
|
||||
reduce: fletcher.diagram,
|
||||
cover: fletcher.hide,
|
||||
)
|
||||
|
||||
#show: university-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
// align: horizon,
|
||||
// config-common(handout: true),
|
||||
config-common(frozen-counters: (theorem-counter,)), // freeze theorem counter for animation
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.school,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
|
||||
== Outline <touying:hidden>
|
||||
|
||||
#components.adaptive-columns(outline(title: none, indent: 1em))
|
||||
|
||||
= Animation
|
||||
|
||||
== Simple Animation
|
||||
|
||||
We can use `#pause` to #pause display something later.
|
||||
|
||||
#pause
|
||||
|
||||
Just like this.
|
||||
|
||||
#meanwhile
|
||||
|
||||
Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously.
|
||||
|
||||
#speaker-note[
|
||||
+ This is a speaker note.
|
||||
+ You won't see it unless you use `config-common(show-notes-on-second-screen: right)`
|
||||
]
|
||||
|
||||
|
||||
== Complex Animation
|
||||
|
||||
At subslide #touying-fn-wrapper((self: none) => str(self.subslide)), we can
|
||||
|
||||
use #uncover("2-")[`#uncover` function] for reserving space,
|
||||
|
||||
use #only("2-")[`#only` function] for not reserving space,
|
||||
|
||||
#alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives.
|
||||
|
||||
|
||||
== Callback Style Animation
|
||||
|
||||
#slide(
|
||||
repeat: 3,
|
||||
self => [
|
||||
#let (uncover, only, alternatives) = utils.methods(self)
|
||||
|
||||
At subslide #self.subslide, we can
|
||||
|
||||
use #uncover("2-")[`#uncover` function] for reserving space,
|
||||
|
||||
use #only("2-")[`#only` function] for not reserving space,
|
||||
|
||||
#alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives.
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
== Math Equation Animation
|
||||
|
||||
Equation with `pause`:
|
||||
|
||||
$
|
||||
f(x) & = pause x^2 + 2x + 1 \
|
||||
& = pause (x + 1)^2 \
|
||||
$
|
||||
|
||||
#meanwhile
|
||||
|
||||
Here, #pause we have the expression of $f(x)$.
|
||||
|
||||
#pause
|
||||
|
||||
By factorizing, we can obtain this result.
|
||||
|
||||
|
||||
== CeTZ Animation
|
||||
|
||||
CeTZ Animation in Touying:
|
||||
|
||||
#cetz-canvas({
|
||||
import cetz.draw: *
|
||||
|
||||
rect((0, 0), (5, 5))
|
||||
|
||||
(pause,)
|
||||
|
||||
rect((0, 0), (1, 1))
|
||||
rect((1, 1), (2, 2))
|
||||
rect((2, 2), (3, 3))
|
||||
|
||||
(pause,)
|
||||
|
||||
line((0, 0), (2.5, 2.5), name: "line")
|
||||
})
|
||||
|
||||
|
||||
== Fletcher Animation
|
||||
|
||||
Fletcher Animation in Touying:
|
||||
|
||||
#fletcher-diagram(
|
||||
node-stroke: .1em,
|
||||
node-fill: gradient.radial(
|
||||
blue.lighten(80%),
|
||||
blue,
|
||||
center: (30%, 20%),
|
||||
radius: 80%,
|
||||
),
|
||||
spacing: 4em,
|
||||
edge((-1, 0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
|
||||
node((0, 0), `reading`, radius: 2em),
|
||||
edge((0, 0), (0, 0), `read()`, "--|>", bend: 130deg),
|
||||
pause,
|
||||
edge(`read()`, "-|>"),
|
||||
node((1, 0), `eof`, radius: 2em),
|
||||
pause,
|
||||
edge(`close()`, "-|>"),
|
||||
node((2, 0), `closed`, radius: 2em, extrude: (-2.5, 0)),
|
||||
edge((0, 0), (2, 0), `close()`, "-|>", bend: -40deg),
|
||||
)
|
||||
|
||||
|
||||
= Theorems
|
||||
|
||||
== Prime numbers
|
||||
|
||||
#definition[
|
||||
A natural number is called a #highlight[_prime number_] if it is greater
|
||||
than 1 and cannot be written as the product of two smaller natural numbers.
|
||||
]
|
||||
#example[
|
||||
The numbers $2$, $3$, and $17$ are prime.
|
||||
@cor_largest_prime shows that this list is not exhaustive!
|
||||
]
|
||||
|
||||
#theorem(title: "Euclid")[
|
||||
There are infinitely many primes.
|
||||
]
|
||||
#pagebreak(weak: true)
|
||||
#proof[
|
||||
Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration
|
||||
of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list,
|
||||
it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since
|
||||
$p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a
|
||||
contradiction.
|
||||
]
|
||||
|
||||
#corollary[
|
||||
There is no largest prime number.
|
||||
] <cor_largest_prime>
|
||||
#corollary[
|
||||
There are infinitely many composite numbers.
|
||||
]
|
||||
|
||||
#theorem[
|
||||
There are arbitrarily long stretches of composite numbers.
|
||||
]
|
||||
|
||||
#proof[
|
||||
For any $n > 2$, consider $ n! + 2, quad n! + 3, quad ..., quad n! + n $
|
||||
]
|
||||
|
||||
|
||||
= Others
|
||||
|
||||
== Side-by-side
|
||||
|
||||
#slide(composer: (1fr, 1fr))[
|
||||
First column.
|
||||
][
|
||||
Second column.
|
||||
]
|
||||
|
||||
|
||||
== Multiple Pages
|
||||
|
||||
#lorem(200)
|
||||
|
||||
|
||||
#show: appendix
|
||||
|
||||
= Appendix
|
||||
|
||||
== Appendix
|
||||
|
||||
Please pay attention to the current slide number.
|
||||
@@ -0,0 +1,68 @@
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.metropolis: *
|
||||
|
||||
#import "@preview/numbly:0.1.0": numbly
|
||||
|
||||
#show: metropolis-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: self => self.info.institution,
|
||||
config-info(
|
||||
title: [Title],
|
||||
subtitle: [Subtitle],
|
||||
author: [Authors],
|
||||
date: datetime.today(),
|
||||
institution: [Institution],
|
||||
logo: emoji.city,
|
||||
),
|
||||
)
|
||||
|
||||
#set heading(numbering: numbly("{1}.", default: "1.1"))
|
||||
|
||||
#title-slide()
|
||||
|
||||
= Outline <touying:hidden>
|
||||
|
||||
#outline(title: none, indent: 1em, depth: 1)
|
||||
|
||||
= First Section
|
||||
|
||||
---
|
||||
|
||||
A slide without a title but with some *important* information.
|
||||
|
||||
== A long long long long long long long long long long long long long long long long long long long long long long long long Title
|
||||
|
||||
=== sdfsdf
|
||||
|
||||
A slide with equation:
|
||||
|
||||
$ x_(n+1) = (x_n + a / x_n) / 2 $
|
||||
|
||||
#lorem(200)
|
||||
|
||||
= Second Section
|
||||
|
||||
#focus-slide[
|
||||
Wake up!
|
||||
]
|
||||
|
||||
== Simple Animation
|
||||
|
||||
We can use `#pause` to #pause display something later.
|
||||
|
||||
#meanwhile
|
||||
|
||||
Meanwhile, #pause we can also use `#meanwhile` to display other content synchronously.
|
||||
|
||||
#speaker-note[
|
||||
+ This is a speaker note.
|
||||
+ You won't see it unless you use `config-common(show-notes-on-second-screen: right)`
|
||||
]
|
||||
|
||||
#show: appendix
|
||||
|
||||
= Appendix
|
||||
|
||||
---
|
||||
|
||||
Please pay attention to the current slide number.
|
||||
@@ -0,0 +1,38 @@
|
||||
#import "@preview/touying:0.6.1": *
|
||||
#import themes.simple: *
|
||||
|
||||
#show: simple-theme.with(
|
||||
aspect-ratio: "16-9",
|
||||
footer: [Simple slides],
|
||||
)
|
||||
|
||||
#title-slide[
|
||||
= Keep it simple!
|
||||
#v(2em)
|
||||
|
||||
Alpha #footnote[Uni Augsburg] #h(1em)
|
||||
Bravo #footnote[Uni Bayreuth] #h(1em)
|
||||
Charlie #footnote[Uni Chemnitz] #h(1em)
|
||||
|
||||
July 23
|
||||
]
|
||||
|
||||
== First slide
|
||||
|
||||
#lorem(20)
|
||||
|
||||
#focus-slide[
|
||||
_Focus!_
|
||||
|
||||
This is very important.
|
||||
]
|
||||
|
||||
= Let's start a new section!
|
||||
|
||||
== Dynamic slide
|
||||
|
||||
Did you know that...
|
||||
|
||||
#pause
|
||||
|
||||
...you can see the current section at the top of the slide?
|
||||
Loaded 100 of 454 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user