//! Library for sanitizing and converting HTML strings to something that [Pango] can render. //! //! This library contains several functions to (pre)process text to [Pango Markup]. //! What to use and when depends on the type of input and the desired result. This can range from //! just escaping to converting and sanitizing. See the examples below for what is available //! based on the input type. //! //! The functions below convert strings to strings. If your input can contain several block //! elements such as headings, lists, code or quote blocks, see the [`block`] module to convert an //! input string into a list of these blocks. //! //! # Markdown/body HTML //! //! To handle more HTML, use the [`markup_html`] function. This function supports HTML body markup //! such as HTML resulting from a [Markdown]-to-HTML conversion. It tries to convert the input to //! [Pango Markup] such that rendering by Pango will make it similar like what a browser would. //! This involves adding newlines for paragraphs and lists, converting font styles, etc. //! //! ```rust //! # use html2pango::markup_html; //! let m = markup_html("
this is some red text!").unwrap(); //! assert_eq!(m, "this is some red text!"); //! //! let m = markup_html("a nice link").unwrap(); //! assert_eq!(m, "a nice link"); //! //! let m = markup_html("some items:`, etc.
//! For the full list of supported tags and how they are replaced, see [`markup_from_raw`].
//!
//!
//! ## With sanitization
//!
//! If you use [`markup`], supported tags are replaced (if necessary), malformed tags are removed
//! and HTML reserved characters are escaped.
//!
//! ```rust
//! # use html2pango::markup;
//! let m = markup("this is &sanitized
");
//! assert_eq!(m, "this is &sanitized");
//! ```
//!
//! Other unsupported, but valid tags are escaped.
//!
//! ```rust
//! # use html2pango::markup;
//! let m = markup("this is a tag");
//! assert_eq!(m, "this is <span>a tag</span>");
//! ```
//!
//! URIs are replaced by links.
//!
//! ```rust
//! # use html2pango::markup;
//! let m = markup("go to: https://gnome.org");
//! assert_eq!(m, "go to: https://gnome.org");
//! ```
//!
//! ## Without sanitization
//!
//! Use [`markup_from_raw`] if you have already sanitized input:
//!
//! ```rust
//! # use html2pango::markup_from_raw;
//! let m = markup_from_raw("this is already sanitized
");
//! assert_eq!(m, "this is <unsupported>already sanitized</unsupported>");
//! ```
//!
//! ## Links
//!
//! To just replace URIs by links, use [`markup_links`]:
//!
//! ```rust
//! # use html2pango::markup_links;
//! let m = markup_links("go to: https://gnome.org");
//! assert_eq!(m, "go to: https://gnome.org");
//! ```
//!
//! [Markdown]: https://daringfireball.net/projects/markdown/
//! [Matrix]: https://matrix.org/
//! [Matrix specification]: https://spec.matrix.org/v1.1/client-server-api/#mroommessage-msgtypes
//! [Pango]: https://pango.gnome.org
//! [Pango Markup]: https://docs.gtk.org/Pango/pango_markup.html
use html5ever::tendril::TendrilSink;
use html5ever::tree_builder::TreeBuilderOpts;
use html5ever::{parse_document, ParseOpts};
use markup5ever_rcdom::Node;
use markup5ever_rcdom::NodeData;
use markup5ever_rcdom::RcDom;
use linkify::{LinkFinder, LinkKind};
use maplit::{hashmap, hashset};
use once_cell::sync::Lazy;
use regex::{Captures, Regex};
use std::fmt::Write as _;
use std::borrow::Cow;
pub mod block;
/// Sanitizes and converts simple HTML markup to Pango Markup.
///
/// This will sanitize the input string using the [`ammonia`][ammonia] crate's defaults and then
/// use [`markup_from_raw`] to convert the sanitized string to [Pango Markup].
///
/// # Examples
///
/// ```rust
/// # use html2pango::markup;
/// let m = markup("this is parsed");
/// assert_eq!(m, "this is parsed");
///
/// let m = markup("this is &ssd ");
/// assert_eq!(m, "this is &ssd");
///
/// let m = markup("this is parsed");
/// assert_eq!(m, "this is <span>parsed</span>");
///
/// let m = markup("with links: http://gnome.org");
/// assert_eq!(m, "with links: http://gnome.org");
/// ```
///
/// [Pango Markup]: https://docs.gtk.org/Pango/pango_markup.html
/// [ammonia]: https://docs.rs/ammonia/3.1.2/ammonia/fn.clean.html
pub fn markup(s: &str) -> String {
let sanitized_html = ammonia::Builder::new().link_rel(None).clean(s).to_string();
markup_from_raw(&sanitized_html)
}
/// Converts simple HTML markup to Pango Markup.
///
/// This will convert the input string to [Pango Markup] and replace URIs by links.
///
/// Currently it support conversion of the following HTML tags:
/// * `` and `
` => `""`
/// * ``, `` and ``,` ` => `` and ``
/// * ``, `` and ``, `` => `` and ``
/// * `` and `` => `` and ``
/// * `` and `` => `` and ``
/// * `` and `` => `` and ``
/// * `|
|", r"||",
r"||",
r"||",
r"||",
r"||",
r"<|>|",
r" |",
// Url
r"https?://", // Protocol
r#"[^\s,)("]+"#, // Domain
r"(\?((&)?\w+(=[\w._-]+)?)*)*", // Parameters
r"(#[\w._-]+)?", // Hash
])
.unwrap()
});
TAGS.replace_all(s.trim(), |captures: &Captures<'_>| {
let m = captures.get(0).unwrap().as_str();
// Keep this in sync with the TAGS regex
match m {
"" | "
" => Cow::Borrowed(""), "" => Cow::Borrowed(""),
"" => Cow::Borrowed(""),
"" | "" => Cow::Borrowed(""),
"" | "" => Cow::Borrowed(""),
"" => Cow::Borrowed(""),
"" => Cow::Borrowed(""),
"" => Cow::Borrowed(""),
"" => Cow::Borrowed(""),
"<" => Cow::Borrowed("<"),
">" => Cow::Borrowed(">"),
" " => Cow::Borrowed(" "),
_ => Cow::Owned(format!(r#"{}"#, m, m)),
}
})
.into()
}
/// Sanitizes and convert Matrix custom HTML markup (formatted body) to Pango Markup.
///
/// First sanitizes the input string by leaving in only the HTML tags and attributes allowed
/// by the [Matrix specification] and then uses [`markup_html`] to convert the sanitized string to
/// [Pango Markup].
///
/// # Errors
///
/// Returns an error if reading from the strings fails.
///
/// # Examples
///
/// TODO
///
/// [Matrix specification]: https://spec.matrix.org/v1.1/client-server-api/#mroommessage-msgtypes
/// [Pango Markup]: https://docs.gtk.org/Pango/pango_markup.html
// WIP: only allow the html subset that matrix uses.
pub fn matrix_html_to_markup(s: &str) -> String {
// https://github.com/matrix-org/matrix-react-sdk/blob/4bf5e44b2043bbe95faa66943878acad23dfb823/src/HtmlUtils.js#L178-L184
#[rustfmt::skip]
let allowed_tags = hashset![
"font", // custom to matrix for IRC-style font coloring
"del", // for markdown
"h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "p", "a", "ul", "ol", "sup", "sub",
"nl", "li", "b", "i", "u", "strong", "em", "strike", "code", "hr", "br", "div",
"table", "thead", "caption", "tbody", "tr", "th", "td", "pre", "span", "img",
];
// https://github.com/matrix-org/matrix-react-sdk/blob/4bf5e44b2043bbe95faa66943878acad23dfb823/src/HtmlUtils.js#L185-L193
let allowed_attributes = hashmap![
// custom ones first:
"font" => hashset!["color", "data-mx-bg-color", "data-mx-color", "style"],
"span" => hashset!["data-mx-bg-color", "data-mx-color", "style"],
// remote target: custom to matrix
"a" => hashset!["href", "name", "target", "rel"],
"img" => hashset!["src", "width", "height", "alt", "title"],
"ol" => hashset!["start"],
// We don't actually allow all classes, TODO: we should filter them afterwards
"code" => hashset!["class"],
];
// https://github.com/matrix-org/matrix-react-sdk/blob/4bf5e44b2043bbe95faa66943878acad23dfb823/src/HtmlUtils.js#L48
let allowed_urls = hashset!["http", "https", "ftp", "mailto", "magnet"];
let sanitized_html = ammonia::Builder::new()
.url_schemes(allowed_urls)
.tags(allowed_tags)
.tag_attributes(allowed_attributes)
.link_rel(None)
.clean(s)
.to_string();
markup_html(&sanitized_html)
.map(|x| x.trim_matches('\n').to_string())
.unwrap_or_else(|_| markup_from_raw(&sanitized_html))
}
/// Escapes the HTML reserved characters.
///
/// This replaces the HTML reserved characters by their respective entities in the input string.
///
/// # Examples
///
/// ```rust
/// # use html2pango::html_escape;
/// let s = html_escape("this is a `, `` and
/// ` this this
`, this function tries to convert HTML body markup so that the resulting [Pango Markup]
/// will render to something that is similar to what a browser would render.
///
/// # Errors
///
/// Returns an error if reading from the strings fails.
///
/// # Examples
///
/// ```rust
/// # use html2pango::markup_html;
/// let m = markup_html("this is some red text!").unwrap();
/// assert_eq!(m, "this is some red text!");
///
/// let m = markup_html("a nice link").unwrap();
/// assert_eq!(m, "a nice link");
///
/// let m = markup_html("some items:
Result
is &ssdf;
is &ssdf;
gnome
and other link http://gnome.org",
"This is a test message with markdown\ngnome\nand other link http://gnome.org"),
];
for &(s, e) in strings.iter() {
let m = markup_html(s).unwrap();
assert_eq!(&m, e);
}
}
#[test]
fn test_ending_quote_link() {
let strings = [
("