Skip to main content

link

Function link 

Source
pub fn link(
    label: &str,
    destination: &str,
    title: Option<&str>,
    in_table_cell: bool,
) -> String
Expand description

An inline link: [label](destination), or [label](destination "title").

label is inline Markdown the writer has already rendered — its text escaped and styled the writer’s own way (**bold**, <u>…</u>, a code span). What this adds is what keeps that Markdown inside the link, which no display setting may turn off:

  • an unescaped [ or ] is escaped — an unbalanced ] ends the link text early, and a [x](y) inside it would be a second link, which CommonMark does not nest;
  • a line ending becomes a space, so a blank line cannot end the paragraph mid-link;
  • a backslash at the very end is doubled, since it would otherwise escape the closing ];
  • inside a table cell, an unescaped | is escaped, code spans included — a GFM table splits its cells before it reads anything else.

Code spans are left as they are (apart from that |): a code span binds more tightly than the link’s brackets, so a ] inside one does not end the link, and a backslash inside one would be printed. Backslash escapes the label already carries (\*, \[) are kept as they are. The label is not expected to hold a link, an image, an autolink or raw HTML with a bracket in it.

The destination is written by link_destination. The title, when there is one and it is not empty, is written in double quotes: " is escaped, a backslash that would escape the character after it is doubled, an & that would start a character reference is escaped, a line ending becomes a space, and inside a table cell | is escaped.

use unparser_shared::markdown::link;

assert_eq!(link("see [3]", "https://example.com", None, false), r"[see \[3\]](https://example.com)");
assert_eq!(link("**bold** `a]b`", "u", None, false), "[**bold** `a]b`](u)");
assert_eq!(link("x", "u", Some(r#"say "hi""#), false), r#"[x](u "say \"hi\"")"#);
assert_eq!(link("a | b", "u", None, true), r"[a \| b](u)");