### TypeScript Server Example with Metadata Source: https://github.com/unjs/md4x/blob/main/website/samples/2.code-and-tables.md An example of a TypeScript server setup using the 'bun' runtime. The code block includes metadata for the filename (server.ts) and highlights lines 2 through 4, demonstrating server initialization and request handling. ```ts import { serve } from "bun"; serve({ port: 3000, fetch(req) { return new Response("Hello!"); }, }); ``` -------------------------------- ### Node Format Examples Source: https://github.com/unjs/md4x/blob/main/docs/comark-ast.md Examples showing how various markdown elements are represented in the Comark AST format. ```APIDOC ## Node Format Examples ### Paragraphs Markdown: `This is a paragraph with **bold** text.` AST Representation: ```json ["p", {}, "This is a paragraph with ", ["strong", {}, "bold"], " text."] ``` ### Links Markdown: `[Link text](https://example.com)` AST Representation: ```json ["a", { "href": "https://example.com" }, "Link text"] ``` ### Code Blocks Markdown: ```javascript [app.js] {1-2} const a = 1 ``` AST Representation: ```json ["pre", { "language": "javascript", "filename": "app.js", "highlights": [1, 2] }, ["code", {}, "const a = 1"]] ``` ``` -------------------------------- ### CLI Usage Examples for MD4X Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Demonstrates various command-line interface commands for using MD4X to parse and render markdown files. Includes examples for local files, remote URLs, GitHub repositories, npm packages, stdin, and outputting to files. ```bash npx md4x README.md # ANSI output npx md4x README.md -t html # HTML output npx md4x README.md -t text # Plain text output (strip markdown) npx md4x README.md -t ast # JSON AST output (comark) npx md4x README.md -t meta # Metadata JSON output npx md4x README.md -t markdown # Clean markdown (strip MDC/frontmatter/HTML) npx md4x README.md -t heal # Heal incomplete markdown npx md4x README.md --heal # Heal before rendering (any format) npx md4x README.md --heal -t json # Heal + JSON AST output # Remote sources npx md4x https://nitro.build/guide # Fetch and render any URL npx md4x gh:nitrojs/nitro # GitHub repo → README.md npx md4x npm:vue@3 # npm package at specific version # Stdin echo "# Hello" | npx md4x -t text cat README.md | npx md4x -t html # Output to file npx md4x README.md -t meta -o README.json # Full HTML document npx md4x README.md -t html -f --html-title="My Docs" # Wrap in full HTML with
npx md4x README.md -t html -f --html-css=style.css # Add CSS link ``` -------------------------------- ### Markdown Inline Link Syntax Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt A collection of examples demonstrating various inline link configurations, including optional titles, empty destinations, and handling of spaces using pointy brackets. ```markdown [link](/uri "title") [link](/uri) [](./target.md) [link]() [link](<>) []() [link]() [a]() ``` ```html ``` -------------------------------- ### HTML Block Example: Closing Tag Start Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates an HTML block that begins with a closing tag (e.g., ). This is a valid way to start an HTML block, and subsequent Markdown content is parsed normally after the block. ```markdown *foo* . *foo* ``` -------------------------------- ### Handling URL Fragments and Queries Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Examples of including fragment identifiers and query parameters within link destinations. ```markdown [link](#fragment) [link](https://example.com#fragment) [link](https://example.com?foo=3#frag) ``` -------------------------------- ### Complex Permissive URL Autolink Example Source: https://github.com/unjs/md4x/blob/main/test/spec-permissive-autolinks.txt A comprehensive example combining scheme, host, path, query, and fragment for permissive URL autolinks, demonstrating various valid formats. ```markdown http://commonmark.org (Visit https://encrypted.google.com/search?q=Markup+(business)) Anonymous FTP is available at ftp://foo.bar.baz. ``` ```html(Visit https://encrypted.google.com/search?q=Markup+(business))
Anonymous FTP is available at ftp://foo.bar.baz.
``` -------------------------------- ### AUR Installation for MD4X Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Provides the command to install MD4X from the Arch User Repository (AUR). ```bash yay -S md4x # md4x-git ``` -------------------------------- ### List and Table Formatting Source: https://github.com/unjs/md4x/blob/main/test/spec-markdown.txt Examples of ordered, unordered, and task lists, as well as aligned markdown tables. ```markdown - [x] done - [ ] todo | left | center | right | |:-----|:------:|------:| | a | b | c | ``` -------------------------------- ### HTML Block Example: Partial Tag Start Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows an HTML block where the opening tag is split across lines. This is permissible as long as the split occurs where whitespace would normally be, demonstrating flexibility in tag definition. ```markdown . ``` -------------------------------- ### MD4X CLI Usage Source: https://github.com/unjs/md4x/blob/main/README.md Examples of how to use the MD4X command-line interface for parsing and rendering markdown files. ```APIDOC ## MD4X CLI Usage ### Description This section details various ways to use the MD4X CLI tool to process markdown files, including rendering to different formats, fetching remote content, and handling input/output. ### Examples #### Local Files ```sh # Render to ANSI terminal output npx md4x README.md # Render to HTML output npx md4x README.md -t html # Render to plain text (strip markdown) npx md4x README.md -t text # Render to JSON AST output (Comark) npx md4x README.md -t ast # Render to metadata JSON output npx md4x README.md -t meta # Render as clean standard markdown npx md4x README.md -t markdown # Heal incomplete markdown before rendering npx md4x README.md -t heal # Heal and render to JSON AST npx md4x README.md --heal -t json ``` #### Remote Sources ```sh # Fetch and render any URL npx md4x https://nitro.build/guide # Render README.md from a GitHub repository npx md4x gh:nitrojs/nitro # Render from a specific npm package version npx md4x npm:vue@3 ``` #### Stdin and File Output ```sh # Pipe markdown content via stdin to CLI echo "# Hello" | npx md4x -t text cat README.md | npx md4x -t html # Output metadata to a JSON file npx md4x README.md -t meta -o README.json ``` #### Full HTML Document ```sh # Wrap markdown in a full HTML document with a custom title npx md4x README.md -t html -f --html-title="My Docs" # Wrap in full HTML and include a CSS file npx md4x README.md -t html -f --html-css=style.css ``` ``` -------------------------------- ### HTML Block Example: Div Element Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows an HTML block starting with a``` -------------------------------- ### Markdown Block Parsing Example Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates the step-by-step creation of a document tree from Markdown input, showing how lines are processed to form block elements like block quotes, paragraphs, and lists. ```markdown > Lorem ipsum dolor sit amet. > - Qui *quodsi iracundia* > - aliquando id ``` -------------------------------- ### HTML Comment Parsing Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows examples of valid HTML comments, including those with hyphens and special characters, as parsed by MD4X. ```html foo .
one
two
foo
``` ```html foo foo --> foo foo --> .foo foo -->
foo foo -->
``` -------------------------------- ### C Library Rendering Source: https://github.com/unjs/md4x/blob/main/README.md Examples of using the md4x C library to render markdown into various formats like HTML, JSON, ANSI, and plain text. ```c #include "md4x.h" #include "md4x-html.h" void output(const MD_CHAR* text, MD_SIZE size, void* userdata) { fwrite(text, 1, size, (FILE*) userdata); } md_html(input, input_size, output, stdout, MD_DIALECT_GITHUB, 0); ``` -------------------------------- ### JavaScript Code Block Example Source: https://github.com/unjs/md4x/blob/main/test/fuzzers/seed-corpus/alerts.md Demonstrates a simple JavaScript code block within a Markdown alert. This example shows how to render code directly inside a note. ```javascript code block ``` -------------------------------- ### GitHub Flavored Markdown Syntax Examples Source: https://context7.com/unjs/md4x/llms.txt Showcases supported GFM extensions including tables, task lists, strikethrough, autolinks, and GitHub alerts. ```markdown | Left | Center | Right | | :------ | :-----: | ------: | | foo | bar | baz | - [x] Completed task - [ ] Pending task ~~deleted text~~ Visit https://example.com or email user@example.com > [!NOTE] > Useful information for users. > [!TIP] > Helpful advice for doing things better. > [!WARNING] > Urgent info requiring immediate attention. > [!CAUTION] > Negative consequences of an action. ``` -------------------------------- ### Markdown Block Quote Formatting Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt A collection of Markdown block quote examples demonstrating standard usage, paragraph separation, and how block quotes interact with other elements like horizontal rules and paragraphs. ```markdown > foo > bar ``` ```markdown > foo > > bar ``` ```markdown > aaa *** > bbb ``` ```markdown > > > foo bar ``` ```markdown > code > not code ``` -------------------------------- ### MDC Component Syntax Examples Source: https://context7.com/unjs/md4x/llms.txt Demonstrates the usage of Markdown Components (MDC) for inline and block-level elements, including support for props, slots, and nested components. ```markdown Check out this :badge[New]{color="blue"} feature. Click :icon-star to favorite. ::alert{type="warning" #my-alert .custom-class} This is a **warning** message with full markdown support. :: :::danger STOP Do not proceed without reading this. ::: :::outer ::inner Nested content :: ::: ::card #header ``` -------------------------------- ### Custom Code Highlighting Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Shows how to use the `highlighter` option in `renderToHtml` for custom syntax highlighting of code blocks, using Shiki as an example. ```APIDOC ## Custom Code Highlighting ### Description `renderToHtml` supports a `highlighter` option for custom syntax highlighting of fenced code blocks. The highlighter receives the raw code (HTML-unescaped) and block metadata (language, filename, highlighted lines), and returns a replacement HTML string or `undefined` to keep the default. ### Method Synchronous Rendering with Custom Highlighter ### Endpoint N/A (Client-side library) ### Parameters #### Request Body - **highlighter** (function) - A function that accepts `code` (string) and `block` (object) as arguments and returns an HTML string or `undefined`. - `block` object contains: - **lang** (string) - The language specified in the code block. - **filename** (string) - The filename specified in the code block. - **highlights** (array of numbers) - Lines to highlight. ### Request Example ````js import { renderToHtml } from "md4x"; import { createHighlighter } from "shiki"; const highlighter = await createHighlighter({ themes: ["github-dark"], langs: ["js", "ts", "html", "css"], }); const html = renderToHtml("```js\nconst x = 1;\n```", { highlighter: (code, block) => { if (!block.lang) return; // keep default for unknown languages return highlighter.codeToHtml(code, { lang: block.lang, theme: "github-dark", }); }, }); ```` ### Response #### Success Response (200) - **html** (string) - Rendered HTML content with custom highlighted code blocks. #### Response Example ```htmlconst x = 1;
```
### Code Block Metadata Parsing
Code block metadata from the info string is parsed automatically.
````md
```ts [app.ts] {1,3-5}
// block.lang = "ts"
// block.filename = "app.ts"
// block.highlights = [1, 3, 4, 5]
```
````
```
--------------------------------
### Basic Setext Heading Syntax
Source: https://github.com/unjs/md4x/blob/main/test/spec.txt
Examples demonstrating level 1 and level 2 headings using '=' and '-' underlines. The content can span multiple lines and is parsed as CommonMark inline content.
```markdown
Foo *bar*
=========
Foo *bar*
---------
```
--------------------------------
### Standalone Inline Component Example
Source: https://github.com/unjs/md4x/blob/main/test/spec-components.txt
Demonstrates a basic inline component without content or properties, rendering as a self-closing HTML tag.
```markdown
:icon-star
.
one
two
</a href="foo">
``` -------------------------------- ### HTML Tag Parsing Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates the parsing of various HTML open tags, including those with attributes, custom names, and empty elements. It also shows how illegal tag names are handled. ```htmlFoo
<33> <__>
``` -------------------------------- ### Enable Frontmatter with MD_FLAG_FRONTMATTER Source: https://github.com/unjs/md4x/blob/main/test/spec-frontmatter.txt Demonstrates the syntax for defining a YAML-style frontmatter block at the start of a document. The block must be delimited by at least three dashes and appear on the first line. ```markdown --- title: Hello date: 2024-01-01 --- ``` -------------------------------- ### Implement Web Standard Server Source: https://github.com/unjs/md4x/blob/main/packages/md4x/test/fixtures/nitro-index.md Create a server entry point using the native Web Fetch API. This approach is framework-agnostic and works across various runtimes. ```typescript export default { async fetch(req: Request): Promisehttps://example.com http://example.com ftp://example.com
ssh://example.com
``` -------------------------------- ### WASM Initialization and Rendering Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Demonstrates how to initialize the MD4X WASM module and render Markdown to HTML. The `init()` function must be called once before rendering. ```APIDOC ## WASM Initialization and Rendering ### Description Works anywhere with WebAssembly support. Requires a one-time async initialization. ### Method Async Initialization and Synchronous Rendering ### Endpoint N/A (Client-side library) ### Parameters #### Request Body `init()` accepts an optional options object with a `wasm` property (`ArrayBuffer`, `Response`, `WebAssembly.Module`, or `Promisewww.google.com/search?q=Markdown
``` -------------------------------- ### Ordered List Item Starting with Indented Code Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows an ordered list item where the first element is an indented code block, followed by other blocks. This example highlights the structure and indentation. ```markdown 1. indented code paragraph more code ``` ```htmlindented code
paragraph
more code
**Hello**, _world_. |
**Hello**,world.
1234567890. not ok
``` -------------------------------- ### JavaScript Usage of MD4X WASM Target Source: https://github.com/unjs/md4x/blob/main/docs/js-bindings.md Demonstrates how to use the MD4X WASM module from JavaScript via the 'md4x/wasm' wrapper. It shows the asynchronous initialization process and synchronous rendering methods after initialization. The 'init' function can accept options to specify the WASM binary. ```js import { init, renderToHtml } from "md4x/wasm"; await init(); // load WASM binary (call once before using render methods) const html = renderToHtml("# Hello"); // sync after init ``` -------------------------------- ### Initialization API Source: https://context7.com/unjs/md4x/llms.txt The `init()` function initializes the MD4X module. For WASM builds, this must be called before any render methods. For NAPI (Node.js native), it's optional as the binding loads lazily on first use. ```APIDOC ## Initialization API ### Description The `init()` function initializes the MD4X module. For WASM builds, this must be called before any render methods. For NAPI (Node.js native), it's optional as the binding loads lazily on first use. ### Method `init(options?: { wasm?: ArrayBuffer | Response | WebAssembly.Module | Promise  &x; &#; &#x; � &#abcdef0; &ThisIsNotDefined; &hi?;
``` -------------------------------- ### Ordered List with Negative Start Number Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates that a negative number is not a valid start number for an ordered list item and is rendered as plain text. ```markdown -1. not ok ``` ```html-1. not ok
``` -------------------------------- ### Execute MD4X CLI Commands Source: https://github.com/unjs/md4x/blob/main/README.md Examples of using the MD4X CLI to render Markdown files, remote URLs, or npm packages into various formats like HTML, JSON AST, or plain text. These commands support features like streaming healing and outputting to files. ```shell npx md4x README.md npx md4x README.md -t html npx md4x README.md -t ast npx md4x https://nitro.build/guide echo "# Hello" | npx md4x -t text npx md4x README.md -t html -f --html-title="My Docs" ``` -------------------------------- ### Ordered List with Leading Zeros in Start Number Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Illustrates how leading zeros in the start number of an ordered list are handled correctly. The parser interprets '003' as the number 3. ```markdown 003. ok ``` ```html``` ## Basic WARNING alert ### Description Displays a standard warning alert. ### Method N/A (Markdown Syntax) ### Endpoint N/A (Markdown Syntax) ### Parameters N/A ### Request Example ```markdown > [!WARNING] > This is a warning ``` ### Response #### Success Response (200) ```htmlThis is a note
``` ``` -------------------------------- ### Specialized Alerts Source: https://github.com/unjs/md4x/blob/main/test/spec-alerts.txt Shows examples for TIP, IMPORTANT, and CAUTION alerts. ```APIDOC ## TIP alert ### Description Displays a tip alert. ### Method N/A (Markdown Syntax) ### Endpoint N/A (Markdown Syntax) ### Parameters N/A ### Request Example ```markdown > [!TIP] > Tip content ``` ### Response #### Success Response (200) ```htmlThis is a warning
``` ## IMPORTANT alert ### Description Displays an important alert. ### Method N/A (Markdown Syntax) ### Endpoint N/A (Markdown Syntax) ### Parameters N/A ### Request Example ```markdown > [!IMPORTANT] > Important content ``` ### Response #### Success Response (200) ```htmlTip content
``` ## CAUTION alert ### Description Displays a caution alert. ### Method N/A (Markdown Syntax) ### Endpoint N/A (Markdown Syntax) ### Parameters N/A ### Request Example ```markdown > [!CAUTION] > Caution content ``` ### Response #### Success Response (200) ```htmlImportant content
``` ``` -------------------------------- ### Normal Blockquote (No Alert Syntax) Source: https://github.com/unjs/md4x/blob/main/test/spec-alerts.txt Example of a standard blockquote that does not use the alert syntax. ```markdown > Normal blockquote ``` ```htmlCaution content
``` -------------------------------- ### Render AST to Formats Source: https://github.com/unjs/md4x/blob/main/docs/comark-ast.md Shows how to use the md4x rendering utilities to convert an AST back into HTML or Markdown strings. ```typescript import { renderHTML, renderMarkdown } from "comark/string"; const tree = await parse("# Hello **World**"); const html = renderHTML(tree); const markdown = renderMarkdown(tree); ``` -------------------------------- ### Markdown Heading Rendering Source: https://github.com/unjs/md4x/blob/main/test/spec-markdown.txt Examples of how different heading levels (H1-H6) are rendered in the markdown output. ```markdown # Heading 1 ## Heading 2 ### Heading 3 ###### Heading 6 ``` -------------------------------- ### Entity References in URLs Example Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Illustrates that entity and numeric character references are recognized within URLs. ```html . ``` -------------------------------- ### Build NAPI Target for MD4X Source: https://github.com/unjs/md4x/blob/main/docs/js-bindings.md Builds Node.js Native Addon (NAPI) binaries for MD4X using Zig. This command builds for all 9 platforms, outputting platform-specific .node files. It requires the 'node-api-headers' package. Individual platform targets can also be built. ```sh bunx nypm add node-api-headers zig build napi-all -Dnapi-include=node_modules/node-api-headers/include ``` -------------------------------- ### Implement Custom Syntax Highlighting Source: https://github.com/unjs/md4x/blob/main/README.md Shows how to provide a custom highlighter function to renderToHtml. This allows integration with libraries like Shiki to process fenced code blocks based on language and metadata. ```javascript import { renderToHtml } from "md4x"; import { createHighlighter } from "shiki"; const highlighter = await createHighlighter({ themes: ["github-dark"], langs: ["js", "ts", "html", "css"], }); const html = renderToHtml("```js\nconst x = 1;\n```", { highlighter: (code, block) => { if (!block.lang) return; // keep default for unknown languages return highlighter.codeToHtml(code, { lang: block.lang, theme: "github-dark", }); }, }); ``` -------------------------------- ### Define GitHub-style Alerts Source: https://github.com/unjs/md4x/blob/main/CHANGELOG.md Enable GitHub-style alerts using the MD_FLAG_ALERTS flag. Alerts are parsed from blockquotes starting with [!TYPE]. ```c /* Enable alerts in parser flags */ int flags = MD_DIALECT_GITHUB | MD_FLAG_ALERTS; // Use flags during document parsing ``` -------------------------------- ### Basic Wiki Link Syntax Source: https://github.com/unjs/md4x/blob/main/test/spec-wiki-links.txt Demonstrates the basic usage of wiki links with and without explicit labels. The destination is defined within double brackets, and an optional label can be provided after a pipe character. ```markdown [[foo]] [[foo|bar]] ``` -------------------------------- ### Invalid Autolink Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates patterns that do not trigger autolink parsing, such as those containing spaces, invalid schemes, or missing brackets. ```markdownNormal blockquote
``` -------------------------------- ### Initialize MD4X Module Source: https://context7.com/unjs/md4x/llms.txt Initializes the MD4X module. This is mandatory for WASM builds to load the binary, while optional for NAPI-based Node.js environments. ```javascript import { init, renderToHtml } from "md4x/wasm"; // WASM requires initialization before rendering await init(); // Optional: provide custom WASM source await init({ wasm: fetch("/path/to/md4x.wasm"), }); const html = renderToHtml("# Hello, **world**!"); ``` -------------------------------- ### Standard ATX Heading Syntax Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates the basic usage of ATX headings from level 1 to 6. Each level is defined by the number of leading hash characters. ```markdown # foo ## foo ### foo #### foo ##### foo ###### foo ``` -------------------------------- ### Undefined Entity References Example Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows that entity references not present in the HTML5 named entities list are treated as literal text. ```html &MadeUpEntity; .Some text [!NOTE] More text
&MadeUpEntity;
``` -------------------------------- ### Initialize MD4X Parser Source: https://github.com/unjs/md4x/blob/main/docs/parser-api.md The md_parse function is the entry point for parsing Markdown text. It requires a text buffer, size, and a configured MD_PARSER structure containing callback functions. ```c int md_parse(const MD_CHAR* text, MD_SIZE size, const MD_PARSER* parser, void* userdata); ``` -------------------------------- ### CLI Usage Source: https://context7.com/unjs/md4x/llms.txt The md4x CLI allows rendering markdown files, URLs, or stdin into various formats including HTML, AST, and plain text. ```APIDOC ## CLI Usage ### Description The md4x CLI renders markdown files to various output formats. It supports local files, stdin, HTTP URLs, GitHub repos, and npm packages. ### Usage npx md4x [source] [options] ### Options - **-t** (string) - Optional - Target format: html, text, ast, meta, markdown, heal. - **-o** (string) - Optional - Output file path. - **-f** (boolean) - Optional - Generate full HTML document. - **-s** (boolean) - Optional - Show performance stats. ``` -------------------------------- ### Permissive URL Autolinks with Fragment Source: https://github.com/unjs/md4x/blob/main/test/spec-permissive-autolinks.txt Demonstrates permissive URL autolinks that include a fragment identifier. The fragment starts with '#' and can contain various characters. ```markdown https://example.com#fragment ``` ```html ``` -------------------------------- ### Run md4x Performance Benchmarks Source: https://github.com/unjs/md4x/blob/main/docs/js-bindings.md Command to execute the benchmarking suite using mitata. This compares the performance of md4x against other markdown parsers like md4w and markdown-it. ```shell bun packages/md4x/bench/index.mjs ``` -------------------------------- ### Build md4x with Zig Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Commands to compile the library using the Zig build system for various targets including WASM and NAPI. ```shell zig build zig build -Doptimize=Debug zig build wasm zig build napi ``` -------------------------------- ### Parse Email Autolinks Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Examples of how email addresses enclosed in angle brackets are converted into mailto links. Note that backslash-escapes are not supported inside these blocks. ```markdown" ആ ಫ
``` -------------------------------- ### Generate JSON AST with C API Source: https://context7.com/unjs/md4x/llms.txt Demonstrates how to render markdown into a Comark AST JSON format using the C library's AST renderer. ```c #include "md4x.h" #include "md4x-ast.h" #includeCard Title
This is the main content
Footer text
Default content
Card Title
This has bold and italic text.
Text here
#not-a-slot
```