typst-writer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypst Writer
Typst 代码编写指南
This skill provides guidance for writing correct Typst code, with emphasis on avoiding common syntax errors from conflating Typst with other languages.
本技能为编写正确的Typst代码提供指导,重点在于避免因混淆Typst与其他语言而产生的常见语法错误。
Core Principles
核心原则
- Never assume syntax from other languages applies - Typst has its own semantics, especially for data structures
- Verify uncertain syntax - When unsure, check official documentation
- Use idiomatic patterns - Follow Typst conventions for clean, maintainable code
- 绝不假设其他语言的语法适用 - Typst有自己的语义,尤其是在数据结构方面
- 验证不确定的语法 - 存疑时,请查阅官方文档
- 使用地道的写法 - 遵循Typst的约定,编写清晰、可维护的代码
Quick Syntax Reference
快速语法参考
Critical distinctions:
- Arrays: - parentheses
(item1, item2) - Dictionaries: - parentheses with colons
(key: value, key2: value2) - Content blocks: - square brackets
[markup content] - NO tuples - Typst only has arrays
For detailed syntax rules and common patterns, see references/syntax.md.
关键区别:
- 数组:- 使用圆括号
(item1, item2) - 字典:- 使用带冒号的圆括号
(key: value, key2: value2) - 内容块:- 使用方括号
[markup content] - 无元组 - Typst仅支持数组
如需详细语法规则和常见写法,请参阅 references/syntax.md。
Documentation Resources
文档资源
Official Documentation
官方文档
- Core language reference: https://typst.app/docs/reference/
- Typst Universe - Central package & template registry:
- main page (JS SPA): https://typst.app/universe
- whole registry is just a regular GitHub repo: https://github.com/typst/packages
- 核心语言参考:https://typst.app/docs/reference/
- Typst Universe - 中央包与模板注册表:
- 主页面(JS单页应用):https://typst.app/universe
- 整个注册表是一个常规GitHub仓库:https://github.com/typst/packages
Searching for Typst Packages
搜索Typst包
Typst Universe (the official package registry) doesn't have a programmatic API, but you can search for packages via GitHub:
- Most packages are hosted on GitHub
- Use , or SearXNG's repos search (see the
gh searchSkill)searxng-search - Example: Search for "typst diagram" or "typst table" in repositories
Typst Universe(官方包注册表)没有程序化API,但你可以通过GitHub搜索包:
- 大多数包托管在GitHub上
- 使用 ,或SearXNG的仓库搜索(请参考
gh search技能)searxng-search - 示例:在仓库中搜索"typst diagram"或"typst table"
With GitHub CLI
使用GitHub CLI
Direct GitHub search examples:
bash
undefinedGitHub直接搜索示例:
bash
undefinedSearch for typst repos about some topic
搜索与特定主题相关的Typst仓库
gh search repos --language "typst" --json "url,language,description" diagram arrows ...
gh search repos --language "typst" --json "url,language,description" diagram arrows ...
List all files in a given repo
列出指定仓库中的所有文件
gh search code --repo "Jollywatt/typst-fletcher"
gh search code --repo "Jollywatt/typst-fletcher"
In a repo, search through all files of some type
在仓库中搜索特定类型的所有文件
gh search code --repo "Jollywatt/typst-fletcher" --extension "md" arrow node ...
undefinedgh search code --repo "Jollywatt/typst-fletcher" --extension "md" arrow node ...
undefinedVia SearXNG
使用SearXNG
Requires Skill
searxng-searchbash
curl "http://localhost:<searxng-port>/search?q=typst+diagram&format=json&categories=repos" | jq '.results[] | select(.engines[] == "github")'需要技能
searxng-searchbash
curl "http://localhost:<searxng-port>/search?q=typst+diagram&format=json&categories=repos" | jq '.results[] | select(.engines[] == "github")'When to Consult Documentation
何时查阅文档
- Uncertain about function signatures or parameters
- Need to verify syntax for less common features
- Looking for built-in functions or methods
- Exploring available packages (e.g., for diagrams,
fletcherfor margin notes,draftingfor advanced tables)tablex
Use WebFetch when needed to retrieve current documentation for verification.
- 不确定函数签名或参数时
- 需要验证不常见功能的语法时
- 查找内置函数或方法时
- 探索可用包(例如,用于图表的、用于边注的
fletcher、用于高级表格的drafting)时tablex
必要时使用WebFetch来获取最新文档进行验证。
Workflow
工作流程
- Before writing: If syntax is unclear, consult references/syntax.md or documentation
- While writing:
- Use proper data structure syntax (arrays with , content with
())[] - Define functions with
#let name(params) = { ... } - Use blocks when accessing state
context
- Use proper data structure syntax (arrays with
- After writing: Review for Python/other language syntax leaking in
- 编写前:如果语法不清晰,请查阅references/syntax.md或官方文档
- 编写中:
- 使用正确的数据结构语法(数组用,内容用
())[] - 使用定义函数
#let name(params) = { ... } - 访问状态时使用块
context
- 使用正确的数据结构语法(数组用
- 编写后:检查是否混入了Python或其他语言的语法
Common Mistakes to Avoid
需避免的常见错误
- ❌ Calling things "tuples" (Typst only has arrays)
- ❌ Using for arrays (use
[]instead)() - ❌ Accessing array elements with (use
arr[0])arr.at(0) - ❌ Forgetting prefix for code in markup context
# - ❌ Mixing up content blocks with code blocks
[]{}
- ❌ 将数组称为"元组"(Typst仅支持数组)
- ❌ 使用定义数组(应使用
[])() - ❌ 使用访问数组元素(应使用
arr[0])arr.at(0) - ❌ 在标记语境中忘记代码前缀
# - ❌ 混淆内容块与代码块
[]{}
Example Workflow
示例工作流程
typst
// Define custom functions for document elements
#let important(body) = {
box(
fill: red.lighten(80%),
stroke: red + 1pt,
inset: 8pt,
body
)
}
// Use state for counters
#let example-counter = state("examples", 1)
#let example(body) = context {
let num = example-counter.get()
important[Example #num: #body]
example-counter.update(x => x + 1)
}
// Arrays for data
#let factions = (
(name: "Merchants", color: blue),
(name: "Artisans", color: green)
)
// Iterate and render
#for faction in factions [
- #text(fill: faction.color, faction.name)
]typst
// 为文档元素定义自定义函数
#let important(body) = {
box(
fill: red.lighten(80%),
stroke: red + 1pt,
inset: 8pt,
body
)
}
// 使用状态管理计数器
#let example-counter = state("examples", 1)
#let example(body) = context {
let num = example-counter.get()
important[示例 #num: #body]
example-counter.update(x => x + 1)
}
// 数组存储数据
#let factions = (
(name: "Merchants", color: blue),
(name: "Artisans", color: green)
)
// 遍历并渲染
#for faction in factions [
- #text(fill: faction.color, faction.name)
]Reading contents from a Typst file
读取Typst文件内容
Besides compiling, the CLI command can also run queries against a Typst file with , using Typst selectors,
and get the result as JSON.
typsttypst queryFor instance, will list all the level-1 section titles present in
the document. Sadly, it will not tell you their exact positions in the file, but Typst file are easy to grep.
typst query the_document.typ "heading.where(level: 1)" | jq ".[].body.text"See [https://typst.app/docs/reference/introspection/query/#command-line-queries](the online docs about ) for more info.
query除编译外, CLI命令还可以通过结合Typst选择器对Typst文件执行查询,并以JSON格式返回结果。
typsttypst query例如,将列出文档中所有一级章节标题。遗憾的是,它无法告诉你标题在文件中的准确位置,但Typst文件很容易用grep查找。
typst query the_document.typ "heading.where(level: 1)" | jq ".[].body.text"有关的更多信息,请参阅在线文档https://typst.app/docs/reference/introspection/query/#command-line-queries。
queryPackage Usage
包的使用
When needing specialized functionality:
- Search for packages at https://typst.app/universe/
- Import with
#import "@preview/package:version" - Consult package documentation for API
Popular packages:
- : annotations/comments for work-in-progress docs
drafting - : callouts, tips, notes, admonitions
gentle-clues - : general-purpose, customizable text boxes, with headers and footers. E.g. for definitions, theorems or highlighting important paragraphs
showybox - : nice layouts for item lists, enums, checklists, tree lists, etc.
itemize - : general diagrams/drawings, with explicit placing (coordinates) - basis of most Typst drawing libraries
cetz - : graphs, flowcharts, automata, trees, etc. - automatic placing
fletcher - : sequence diagrams
chronos - : Gantt charts
timeliney - : linear timelines
herodot - : data visualization and plots
lilaq - : write tables in markdown-like table format - easy control over strokes, merged cells...
tablem - : render Markdown (inlined or from separate file) as part as a Typst doc
cmarker - : presentations, slides
polylux - : random number generation in Typst code
suiji - : code listings with line numbers, highlighted lines, inlined Typst comments/explanations etc.
zebraw - : algorithms/pseudo-code
lovelace - : lyrics with overlayed chord changes, guitar shapes and tabs
conchord - : math equations to actual, callable Typst functions
eqalc - : Typst as a Julia notebook: embed Julia code inside Typst to generate content, visualizations etc.
jlyfish - : embed and call non-I/O Python code inside Typst
pyrunner
需要特定功能时:
- 在https://typst.app/universe/搜索包
- 使用导入
#import "@preview/package:version" - 查阅包文档了解API
热门包:
- :用于待完成文档的注释/批注
drafting - :提示框、技巧、注释、警告框
gentle-clues - :通用可自定义文本框,带页眉和页脚,例如用于定义、定理或高亮重要段落
showybox - :项目列表、枚举、复选框、树形列表等的美观布局
itemize - :通用图表/绘图,支持精确定位(坐标)- 大多数Typst绘图库的基础
cetz - :图形、流程图、自动机、树状图等 - 自动布局
fletcher - :序列图
chronos - :甘特图
timeliney - :线性时间线
herodot - :数据可视化与图表
lilaq - :类Markdown格式编写表格 - 易于控制边框、合并单元格等
tablem - :将Markdown(内联或来自单独文件)渲染为Typst文档的一部分
cmarker - :演示文稿、幻灯片
polylux - :Typst代码中的随机数生成
suiji - :带行号、高亮行、内联Typst注释/说明等的代码列表
zebraw - :算法/伪代码
lovelace - :带叠加和弦变化、吉他和弦指法与六线谱的歌词
conchord - :将数学方程转换为可调用的Typst函数
eqalc - :将Typst作为Julia笔记本:在Typst中嵌入Julia代码以生成内容、可视化等
jlyfish - :在Typst中嵌入并调用非I/O Python代码
pyrunner
Working with Templates
模板使用
Typst Universe hosts many pre-built templates for reports, papers, CVs, presentations, and more. Templates provide complete document styling and structure.
Typst Universe托管了许多预构建模板,适用于报告、论文、简历、演示文稿等。模板提供完整的文档样式和结构。
Finding Templates
查找模板
- Browse templates: https://typst.app/universe/search/?kind=templates
- Filter by category: report, paper, thesis, cv, etc.
- Check the template's documentation for parameters and examples
- 浏览模板:https://typst.app/universe/search/?kind=templates
- 按类别筛选:报告、论文、学位论文、简历等
- 查看模板文档了解参数和示例
Using a Template
使用模板
- Import the template:
#import "@preview/template-name:version": * - Apply it with
#show: template-name.with(param: value, ...) - Consult template documentation for required and optional parameters
Example:
typst
#import "@preview/bubble:0.2.2": bubble
// Some templates (like bubble) don't use the standard metadata set by `#set document(...)` (for now?),
// so we factor it out:
#let doc-md = (
title: [My report],
author: "Claude",
date: datetime(year: 2025, month: 12, day: 8) // ALWAYS include explicit date in code (so we don't default to date of PDF build)
)
#set document(..doc-md)
#show: bubble.with(
..doc-md,
date: doc-md.date.display("[day]-[month]-[year]"), // some templates want a string here, not a `datetime` object, so we override date here
subtitle: "A detailed analysis",
affiliation: "Your Organization",
main-color: rgb("#FF6B35"),
color-words: ("important", "key", "critical"),
)
// Your content follows
= Introduction
...Key differences from packages:
- Templates typically use to apply styling to the entire document, via one single "main" function
#show: - Packages provide functions/components you call explicitly
- Templates often have a title page and document structure built-in
Popular templates: (IEEE papers), (colorful reports), (CVs)
charged-ieeebubblemodern-cv- 导入模板:
#import "@preview/template-name:version": * - 使用应用模板
#show: template-name.with(param: value, ...) - 查阅模板文档了解必填和可选参数
示例:
typst
#import "@preview/bubble:0.2.2": bubble
// 某些模板(如bubble)目前不使用`#set document(...)`设置的标准元数据,因此我们单独提取:
#let doc-md = (
title: [我的报告],
author: "Claude",
date: datetime(year: 2025, month: 12, day: 8) // 代码中始终包含明确日期(避免默认使用PDF生成日期)
)
#set document(..doc-md)
#show: bubble.with(
..doc-md,
date: doc-md.date.display("[day]-[month]-[year]"), // 某些模板此处需要字符串而非`datetime`对象,因此我们在此覆盖日期
subtitle: "详细分析",
affiliation: "你的组织",
main-color: rgb("#FF6B35"),
color-words: ("important", "key", "critical"),
)
// 以下是你的内容
= 引言
...与包的主要区别:
- 模板通常使用通过单个"主"函数将样式应用于整个文档
#show: - 包提供你需显式调用的函数/组件
- 模板通常内置标题页和文档结构
热门模板:(IEEE论文)、(彩色报告)、(简历)
charged-ieeebubblemodern-cvBibliographies and Citations
参考文献与引用
Typst supports citations and bibliographies using BibTeX (.bib) or Hayagriva (.yml) format files.
See references/bibliography.md
ALWAYS include proper URLs in the bibliography file AS MUCH AS POSSIBLE.
ALWAYS include citations in text WHEREVER A REF IS RELEVANT. A good bibliography is useless if not cited.
@ref-nameTypst支持使用BibTeX(.bib)或Hayagriva(.yml)格式文件的引用和参考文献。
请参阅references/bibliography.md
请尽可能在参考文献文件中包含正确的URL。
只要相关,就务必在正文中包含引用。好的参考文献如果没有引用就毫无用处。
@ref-nameComplete Document Structure Patterns
完整文档结构示例
This shows an example for academic papers.
Most reports you will have to write won't need to be that formal, but it's sort of the canonical example.
以下是学术论文的示例。大多数你需要撰写的报告不需要这么正式,但这是一个典型的规范示例。
"Manual" layout (If needed, e.g. if the user gave specific layout requirements)
"手动"布局(必要时使用,例如用户给出特定布局要求)
typst
#set document(
title: "Document Title",
author: "Your Name",
date: auto,
)
#set page(
paper: "a4",
margin: (x: 2.5cm, y: 2.5cm),
numbering: "1",
)
#set text(size: 11pt)
#set par(justify: true)
#set heading(numbering: "1.")
// Title page
#align(center)[
#text(size: 24pt, weight: "bold")[Document Title]
#v(1cm)
#text(size: 14pt)[Your Name]
#v(0.5cm)
#datetime.today().display()
]
#pagebreak()
// Table of contents
#outline(title: "Table of Contents", indent: auto)
#pagebreak()
// Main content
= Introduction
Your introduction text...
= Methods
...
= Results
...
= Conclusion
...
#pagebreak()
// Bibliography
#bibliography("refs.bib", title: "References", style: "ieee")typst
#set document(
title: "文档标题",
author: "你的姓名",
date: auto,
)
#set page(
paper: "a4",
margin: (x: 2.5cm, y: 2.5cm),
numbering: "1",
)
#set text(size: 11pt)
#set par(justify: true)
#set heading(numbering: "1.")
// 标题页
#align(center)[
#text(size: 24pt, weight: "bold")[文档标题]
#v(1cm)
#text(size: 14pt)[你的姓名]
#v(0.5cm)
#datetime.today().display()
]
#pagebreak()
// 目录
#outline(title: "目录", indent: auto)
#pagebreak()
// 主要内容
= 引言
你的引言文本...
= 方法
...
= 结果
...
= 结论
...
#pagebreak()
// 参考文献
#bibliography("refs.bib", title: "参考文献", style: "ieee")Using Templates (Simpler)
使用模板(更简单)
typst
#import "@preview/charged-ieee:0.1.4": *
#show: ieee.with(
title: "Your Paper Title",
authors: (
(name: "Author One", email: "author1@example.com"),
(name: "Author Two", email: "author2@example.com"),
),
abstract: [
Your abstract text here...
],
index-terms: ("keyword1", "keyword2", "keyword3"),
bibliography: bibliography("refs.bib"), // the ieee template takes care of bibliography itself. That's not always the case
)
// Content starts immediately
= Introduction
Your introduction text...
= Methods
...
= Results
...
= Conclusion
...typst
#import "@preview/charged-ieee:0.1.4": *
#show: ieee.with(
title: "你的论文标题",
authors: (
(name: "作者一", email: "author1@example.com"),
(name: "作者二", email: "author2@example.com"),
),
abstract: [
你的摘要文本...
],
index-terms: ("keyword1", "keyword2", "keyword3"),
bibliography: bibliography("refs.bib"), // IEEE模板会自行处理参考文献,并非所有模板都如此
)
// 内容直接开始
= 引言
你的引言文本...
= 方法
...
= 结果
...
= 结论
...Troubleshooting
故障排除
Missing Font Warnings
字体缺失警告
If you see "unknown font family" warnings, remove the font specification to use system defaults
Note: Font warnings don't prevent compilation; the document will use fallback fonts
如果看到"未知字体系列"警告,请移除字体指定以使用系统默认字体
注意:字体警告不会阻止编译;文档将使用备用字体
Template/Package Not Found
模板/包未找到
If import fails with "package not found":
- Verify exact package name and version on Typst Universe
- Check for typos in syntax
@preview/package:version - Ensure network connectivity (packages download on first use)
- Remember: Typst uses fully qualified imports with specific versions - there's no package cache to update
如果导入失败并提示"package not found":
- 在Typst Universe上验证包的准确名称和版本
- 检查语法中的拼写错误
@preview/package:version - 确保网络连接正常(包在首次使用时下载)
- 请记住:Typst使用带特定版本的完全限定导入 - 没有可更新的包缓存
Compilation Errors
编译错误
Common fixes:
- "expected content, found ...": You're using code where markup is expected - wrap in or use proper syntax
#{ } - "expected expression, found ...": Missing prefix in markup context
# - "unknown variable": Check spelling, ensure imports are correct
- Array/dictionary errors: Review syntax - use for both, dictionaries need
(), singleton arrays arekey: value(elem,)
常见修复方法:
- "expected content, found ...":你在需要标记的地方使用了代码 - 用包裹或使用正确语法
#{ } - "expected expression, found ...":在标记语境中缺少前缀
# - "unknown variable":检查拼写,确保导入正确
- 数组/字典错误:复查语法 - 两者都使用,字典需要
(),单元素数组为key: value(elem,)
Performance Issues
性能问题
For large documents:
- Use to split into multiple files
#include "file.typ" - Compile specific pages:
typst compile doc.typ output.pdf --pages 1-5 - Profile compilation (experimental):
typst compile --timings doc.typ
对于大型文档:
- 使用将文档拆分为多个文件
#include "file.typ" - 编译特定页面:
typst compile doc.typ output.pdf --pages 1-5 - 分析编译性能(实验性):",
typst compile --timings doc.typ