Usage | laravel-markdown-rust | Spatie       

 SPATIE  

laravel-markdown-rust
=====================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-markdown-rust](https://spatie.be/docs/laravel-markdown-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-markdown-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-markdown-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-markdown-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-markdown-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-markdown-rust/v1/usage)
- [ Extensions and front matter ](https://spatie.be/docs/laravel-markdown-rust/v1/extensions)
- [ Testing ](https://spatie.be/docs/laravel-markdown-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-markdown-rust/v1/changelog)
- [ Views and components ](https://spatie.be/docs/laravel-markdown-rust/v1/views)

 Usage
=====

###  On this page 

1. [ Rendering and trust ](#content-rendering-and-trust)
2. [ Configuration ](#content-configuration)
3. [ Highlighting themes ](#content-highlighting-themes)
4. [ Highlighting and focusing lines ](#content-highlighting-and-focusing-lines)
5. [ Cached rendering ](#content-cached-rendering)
6. [ Application markup and CSS contract ](#content-application-markup-and-css-contract)

Rendering and trust
-----------------------------------------------------------------------------------------------------------------

```
use spatie_markdown::{MarkdownRenderer, RawHtml};

let renderer = MarkdownRenderer::new()
    .raw_html(RawHtml::Allow)
    .render_anchors_as_links(true);

let html = renderer.to_html("## Introduction\n\n<div class=\"series\">Contents</div>")?;
assert!(html.contains("<div class=\"series\">Contents</div>"));
assert!(html.contains("href=\"#introduction\""));
```

- Use `RawHtml::Allow` only for trusted editorial content. It is unsanitized: source scripts, event handlers and dangerous URLs can execute.
- Templates must insert the result as HTML and enforce the author's trust level before rendering. A rendered string does not carry a safety type.
- The default `RawHtml::Escape` escapes source HTML, then sanitizes generated HTML with Ammonia. Unsafe link and image schemes are removed; relative and HTTPS URLs remain usable. Links receive Ammonia's default `rel` policy.
- Code content is escaped in both modes. The renderer never fetches URLs.
- Apply application input-size limits and run expensive renders off the async request executor. This crate imposes no document-size or execution-time limit.

Configuration
-----------------------------------------------------------------------------------------------

```
use spatie_markdown::MarkdownRenderer;

let renderer = MarkdownRenderer::new()
    .highlight_code(false)
    .render_anchors(false)
    .github_flavored(true);

assert_eq!(renderer.to_html("~~gone~~")?, "<p><del>gone</del></p>\n");
```

- Setters consume and return the renderer. Clone it when you need a variant; settings never leak between renders.
- Use `commonmark_options(Options::ENABLE_FOOTNOTES)` to enable individual parser options. It replaces the previous option set.
- `ENABLE_HEADING_ATTRIBUTES` preserves explicit IDs and classes such as `# Title {#custom .note}`. Enabled anchors still disambiguate duplicate IDs and target the final ID. Safe-mode sanitization applies to additional attributes.
- See [extensions and front matter](extensions) for custom syntax and renderers.

Highlighting themes
-----------------------------------------------------------------------------------------------------------------

The default `HighlightTheme::Classes` retains the `hl-*` CSS contract below. Select a bundled palette for inline colors:

```
use spatie_markdown::{HighlightTheme, MarkdownRenderer};

let renderer = MarkdownRenderer::new().highlight_theme(HighlightTheme::Dual {
    light: "InspiredGitHub".into(),
    dark: "base16-ocean.dark".into(),
});
let html = renderer.to_html("```php\necho 'Hello';\n```")?;
assert!(html.contains("--markdown-light:"));
assert!(html.contains("--markdown-dark:"));
```

- `HighlightTheme::Single("InspiredGitHub".into())` emits one palette.
- `Dual` emits both palettes on each span. Light colors are active by default. The application chooses when dark colors apply.
- Other bundled names are `base16-eighties.dark`, `base16-mocha.dark`, `base16-ocean.light`, `Solarized (dark)` and `Solarized (light)`.
- An unknown theme returns `Error::Theme` when highlighting a known language. Disabled highlighting and unknown languages remain escaped plain code.
- Themes do not change the code text. No style sheet or JavaScript is injected.

To supply a custom `.tmTheme` file, read it in the application or embed its contents, then use `Palette::Custom(xml)`. Either side of `Dual` accepts a custom palette too. The XML contents participate in the cache key, so changing a file cannot reuse an older palette's cached HTML. Invalid XML returns `Error::CustomTheme`.

```
use spatie_markdown::{HighlightTheme, MarkdownRenderer, Palette};

let renderer = MarkdownRenderer::new()
    .highlight_theme(HighlightTheme::Single(Palette::Custom(xml.into())));
assert!(renderer.to_html("```php\necho 'Hello';\n```")?.contains("color:#123456"));
```

For an application-owned dark-mode class, use:

```
.dark code span[style*="--markdown-dark:"] {
    color: var(--markdown-dark) !important;
    background-color: var(--markdown-dark-bg) !important;
}
```

Highlighting and focusing lines
-----------------------------------------------------------------------------------------------------------------------------------------------------

Enable `code_annotations(true)` to interpret line metadata in fences:

```
use spatie_markdown::MarkdownRenderer;

let renderer = MarkdownRenderer::new().code_annotations(true);
let html = renderer.to_html("```php{1,3-4}{2-3}\necho 'one';\n+ echo 'added';\n- echo 'deleted';\necho 'four';\n```")?;
assert!(html.contains("class=\"line focus add\""));
assert!(html.contains("class=\"line highlight focus del\""));
```

- The first braces select highlighted lines; the optional second braces select focused lines. Numbers start at one. Commas select multiple lines and ascending ranges include both endpoints. `php{}{4}` focuses only line four.
- Each line gets `.line`, plus `.highlight`, `.focus`, `.add` or `.del` as applicable. The `pre` gets `.code-annotations` and, when focus ranges are present, `.has-focus`.
- Leading `+ ` and `- ` mark added/deleted lines and are removed before syntax parsing. This is why annotations are opt-in: ordinary code keeps its literal text by default. Disabling highlighting also disables annotations.
- Invalid ranges return `Error::CodeAnnotation`. Out-of-document ranges are harmless and do not allocate extra lines. Extra fence attributes and filenames are not interpreted.
- The application owns the appearance. For example, use `.line.highlight { background: #fff3bf; }`, `.line.add { background: #d3f9d8; }`, `.line.del { background: #ffe3e3; }`, `.has-focus .line { opacity: .4; }` and `.has-focus .line.focus { opacity: 1; }`.

Cached rendering
--------------------------------------------------------------------------------------------------------

Pass a real framework repository and an explicit `Duration`. Resolve a named store with `laravel::cache::store("markdown")` or use the application's default store. In a handler the framework context already exists. This self-contained example creates one:

```
use std::time::Duration;
use laravel::{Application, config::{Env, cache::StoreConfig}};
use spatie_markdown::MarkdownRenderer;

let app = Application::configure()
    .replace_env(Env::default())
    .with_config(|config, _| {
        config.cache.add_store("markdown", StoreConfig::Memory);
    })
    .create();

app.scope(async || -> laravel::Result<()> {
    let cache = laravel::cache::store("markdown")?;
    let renderer = MarkdownRenderer::new();
    let html = renderer
        .to_html_cached("# Cached", &cache, Duration::from_secs(3600))
        .await?;
    assert_eq!(html, "<h1 id=\"cached\">Cached</h1>\n");
    cache.forget(&renderer.cache_key("# Cached")).await?;
    Ok(())
}).await?;
```

- The key hashes the source, package/render format version, HTML policy, theme, heading settings, front matter, parser options and extension identities/priorities.
- Extensions must include every output-affecting setting in `Extension::cache_key`.
- TTL is not part of the key. Changing it does not renew existing entries. `Duration::ZERO` bypasses reads and writes.
- Corrupt entries and backend failures return `Error::Cache`; they do not silently recompute. Failed renders are never cached.
- Concurrent cold requests may render the same document more than once. There is no stampede lock, and the renderer never flushes a shared store.
- Use `MarkdownConfig::render(markdown).await` for configuration-selected stores. It defaults to a one-hour TTL, and its `renderer` accepts the same builders and extensions.

Application markup and CSS contract
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

- Headings keep their level (`h1` through `h6`). IDs use transliterated, lowercase, hyphenated visible text, including inline code and link labels, not formatting tags. Repeated IDs get `-2`, `-3`, and so on, avoiding earlier suffixed IDs too. Empty slugs use `section`. IDs are unique among generated headings in one document; trusted raw HTML IDs and footnote IDs are not reserved. Existing stored HTML must be regenerated to pick up this policy. Audit inbound heading-fragment links when regenerating old posts with formatted headings.
- `render_anchors_as_links(true)` appends `<a class="heading-anchor" href="#id" aria-label="Link to this section">#</a>` inside the heading. It does not wrap the heading or nest existing links. `render_anchors(false)` disables both IDs and permalinks. Style `.heading-anchor` and heading scroll margins in the app.
- Code uses `<pre><code class="language-X" data-lang="X">…</code></pre>`. Fenced `sh`, `shell` and `zsh` normalize to `bash`. The first info-string word contains the language and optional line metadata described above. Language labels accept ASCII letters, numbers, `_`, `+`, `-`, up to 64 bytes. Missing or invalid labels and indented blocks have no language attributes. Unknown languages retain their valid label but use escaped plain text.
- Highlight spans use `.hl-keyword` (keywords, storage and builtins), `.hl-value` (strings), `.hl-variable`, `.hl-comment`, `.hl-number` (constants) and `.hl-type` (named entities/types). A token may span several adjacent spans, and scope classification follows bundled grammars. Without annotations, syntax highlighting never changes the code's text content. Bash parsing handles quoted comments, shell parameters, functions and heredocs with the native shell grammar rather than regex replacement over generated HTML.
- PHP fences that do not begin with `<?` are parsed as PHP fragments. The parser enters PHP mode without adding an opening tag to the output. Fences beginning with `<?` retain the grammar's normal document mode.
- Class-based output injects no inline styles. The app owns `pre` overflow, whitespace, typography, colors and theme switching. Define `.hl-*` rules in application CSS. Class names are stable within this package version, but grammar updates may change span boundaries.
- Expand application-specific markers before calling the renderer. Excerpt selection, lazy embeds, URL tagging and persistence belong to the application.
- Extensions are caller-supplied Rust implementations, not dynamically loaded classes or executable files.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
