Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/wikitext. Event-stream based wikitext parser
Something went wrong. Try again.
# Examples
These examples show the most common ways to use the parser without reading the
deeper architecture notes first.
They start with the simplest paths and then move toward more inspection-heavy
flows.
## Build a tree for normal document work
Use `parse()` when you want a tree and you do not need diagnostics.
```ts
import { parse } from '@okikio/wikitext';
const tree = parse('== Heading ==\n\nA paragraph with [[Main Page|a link]].');
console.log(tree.type); // 'root'
```
This is the cheapest tree path. It is a good fit when the source is mostly
ordinary wikitext and you do not need the parser's explanation of malformed
regions.
## Inspect headings without building a tree
Use `outlineEvents()` when you only care about block structure such as headings
or lists.
```ts
import { outlineEvents } from '@okikio/wikitext';
const headings = [];
for (const event of outlineEvents('== One ==\n\nText\n\n=== Two ===')) {
if (event.kind === 'enter' && event.node_type === 'heading') {
headings.push(event);
}
}
```
## Keep diagnostics while preserving the default tree
Use `parseWithDiagnostics()` when you want the parser's default tolerant tree
and also want to know where malformed input was detected.
```ts
import { parseWithDiagnostics } from '@okikio/wikitext';
const result = parseWithDiagnostics('Paragraph with <ref name="x">note');
console.log(result.tree.children[0]?.type);
console.log(result.diagnostics.map((diagnostic) => diagnostic.code));
```
This is the best current fit for the "recover on my behalf, but tell me what
you did" style of usage.
## Keep the same default tree but branch on recovery explicitly
Use `parseWithRecovery()` when you want the same default tree and diagnostics
as `parseWithDiagnostics()`, but you also want a cheap boolean for control
flow.
```ts
import { parseWithRecovery } from '@okikio/wikitext';
const result = parseWithRecovery('Paragraph with <ref name="x">note');
if (result.recovered) {
console.log(result.diagnostics.map((diagnostic) => diagnostic.code));
}…