Skip to content

Commit

Permalink
fix: Escape double quotes in link titles. (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
Byron committed Nov 24, 2023
2 parents b1f77e0 + 4767b2f commit 9a64f6b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use std::{
borrow::{Borrow, Cow},
collections::HashSet,
fmt,
fmt::{self, Write},
};

use pulldown_cmark::{Alignment as TableAlignment, Event, HeadingLevel, LinkType};
Expand Down Expand Up @@ -588,7 +588,7 @@ where
write!(f, "]{}{uri}", separator, uri = uri)?;
}
if !title.is_empty() {
write!(f, " \"{title}\"", title = title)?;
write!(f, " \"{title}\"", title = EscapeLinkTitle(title))?;
}
if link_type != LinkType::Shortcut {
f.write_char(')')?;
Expand All @@ -597,6 +597,24 @@ where
Ok(())
}

struct EscapeLinkTitle<'a>(&'a str);

/// Writes a link title with double quotes escaped.
/// See https://spec.commonmark.org/0.30/#link-title for the rules around
/// link titles and the characters they may contain.
impl fmt::Display for EscapeLinkTitle<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for c in self.0.chars() {
match c {
'"' => f.write_str(r#"\""#)?,
'\\' => f.write_str(r"\\")?,
c => f.write_char(c)?,
}
}
Ok(())
}
}

impl<'a> State<'a> {
pub fn finalize<F>(mut self, mut formatter: F) -> Result<Self, fmt::Error>
where
Expand Down
34 changes: 34 additions & 0 deletions tests/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,40 @@ mod escapes {
);
}

#[test]
fn link_titles() {
// See https://spec.commonmark.org/0.30/#link-title for the rules around
// link titles and the characters they may contain
assert_eq!(
fmts(r#"[link](http://example.com "'link title'")"#).0,
r#"[link](http://example.com "'link title'")"#
);
assert_eq!(
fmts(r#"[link](http://example.com "\\\"link \\ title\"")"#).0,
r#"[link](http://example.com "\\\"link \\ title\"")"#
);
assert_eq!(
fmts(r#"[link](http://example.com "\"link title\"")"#).0,
r#"[link](http://example.com "\"link title\"")"#
);
assert_eq!(
fmts(r#"[link](http://example.com '"link title"')"#).0,
r#"[link](http://example.com "\"link title\"")"#
);
assert_eq!(
fmts(r#"[link](http://example.com '\'link title\'')"#).0,
r#"[link](http://example.com "'link title'")"#
);
assert_eq!(
fmts(r#"[link](http://example.com (\(link title\)))"#).0,
r#"[link](http://example.com "(link title)")"#
);
assert_eq!(
fmts(r#"[link](http://example.com (你好👋))"#).0,
r#"[link](http://example.com "你好👋")"#
);
}

#[test]
fn it_does_esscape_lone_square_brackets_in_text() {
assert_eq!(
Expand Down

0 comments on commit 9a64f6b

Please sign in to comment.