Skip to content

code_block

A fenced code block for code, tagged with language.

The fence is at least three backticks and one longer than the longest run of backticks in the code, so code that itself contains a fence stays inside the block. The result ends with a newline and the code keeps its own line breaks (a single trailing newline is not doubled). Whitespace and backticks are removed from language, which must be a single word (rust, sh, json, or empty for none).

use helpers4::markdown::code_block;

Cargo feature markdown (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features markdown

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.6", default-features = false, features = ["markdown"] }
pub fn code_block(code: &str, language: &str) -> String
ParameterTypeDescription
code&strThe code to show.
language&strThe language tag for syntax highlighting, or "".

String — The fenced block, ending with a newline.

use helpers4::markdown::code_block;

assert_eq!(code_block("let x = 1;", "rust"), "```rust\nlet x = 1;\n```\n");
assert_eq!(code_block("```\nnested\n```", ""), "````\n```\nnested\n```\n````\n");

src/markdown/code_block.rs