提示:本教程存在过时问题,更详细教程请阅读 小蓝书Typst 中文社区导航 FAQ
注意:该中文文档为社区驱动的非官网文档,可能存在错译、漏译或过时等问题,请以官网文档 Documentation 为准,如发现错漏,也欢迎 您的贡献镜像)。Typst 非官方中文交流 QQ 群:793548390
Warning: the Chinese document is a community-driven non-official document, there may be mistranslation, omission or outdated problems, please refer to the official website documentation.
Typst 中文文档

plugin

A WebAssembly plugin.

Typst is capable of interfacing with plugins compiled to WebAssembly. Plugin functions may accept multiple byte buffers as arguments and return a single byte buffer. They should typically be wrapped in idiomatic Typst functions that perform the necessary conversions between native Typst types and bytes.

Plugins run in isolation from your system, which means that printing, reading files, or anything like that will not be supported for security reasons. To run as a plugin, a program needs to be compiled to a 32-bit shared WebAssembly library. Many compilers will use the WASI ABI by default or as their only option (e.g. emscripten), which allows printing, reading files, etc. This ABI will not directly work with Typst. You will either need to compile to a different target or stub all functions.

Plugins and Packages

Plugins are distributed as packages. A package can make use of a plugin simply by including a WebAssembly file and loading it. Because the byte-based plugin interface is quite low-level, plugins are typically exposed through wrapper functions, that also live in the same package.

Purity

Plugin functions must be pure: Given the same arguments, they must always return the same value. The reason for this is that Typst functions must be pure (which is quite fundamental to the language design) and, since Typst function can call plugin functions, this requirement is inherited. In particular, if a plugin function is called twice with the same arguments, Typst might cache the results and call your function only once.

Example

#let myplugin = plugin("hello.wasm")
#let concat(a, b) = str(
  myplugin.concatenate(
    bytes(a),
    bytes(b),
  )
)

#concat("hello", "world")
Preview

Protocol

To be used as a plugin, a WebAssembly module must conform to the following protocol:

Exports

A plugin module can export functions to make them callable from Typst. To conform to the protocol, an exported function should:

Imports

Plugin modules need to import two functions that are provided by the runtime. (Types and functions are described using WAT syntax.)

Resources

For more resources, check out the wasm-minimal-protocol repository. It contains:

构造函数
如果类型具有构造函数,可以像函数一样调用它来创建一个该类型的值。

Creates a new plugin from a WebAssembly file.

plugin() -> plugin

path
str
必需参数位置参数
位置参数按顺序传入,不带名称。

Path to a WebAssembly file.