mod max_length_zero;
pub mod rebuilder;
use crate::markdown_it::{JsError, js};
use rebuilder::{REBuilder, REBuilderOptions, mail_name_validator};
#[derive(Debug, Clone, PartialEq)]
pub struct LinkifyOptions {
pub fuzzy_link: bool,
pub fuzzy_email: bool,
pub fuzzy_ip: bool,
pub triple_dash: bool,
pub url_auth: bool,
pub max_length: usize,
}
impl Default for LinkifyOptions {
fn default() -> Self {
LinkifyOptions {
fuzzy_link: false,
fuzzy_email: true,
fuzzy_ip: false,
triple_dash: false,
url_auth: false,
max_length: 10000,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Schema {
Web,
Relative,
Mailto,
}
const DEFAULT_SCHEMAS: [(&str, Schema); 5] = [
("http:", Schema::Web),
("https:", Schema::Web),
("ftp:", Schema::Web),
("//", Schema::Relative),
("mailto:", Schema::Mailto),
];
const TLDS_2CH: &str = "a:cdefgilmnoqrstuwxz|b:abdefghijmnorstvwyz|c:acdfghiklmnoruvwxyz|d:ejkmoz|e:cegrstu|f:ijkmor|g:abdefghilmnpqrstuwy|h:kmnrtu|i:delmnoqrst|j:emop|k:eghimnprwyz|l:abcikrstuvy|m:acdeghklmnopqrstuvwxyz|n:acefgilopruz|o:m|p:aefghklmnrstwy|q:a|r:eosuw|s:abcdeghijklmnortuvxyz|t:cdfghjklmnortvwz|u:agksyz|v:aceginu|w:fs|y:et|z:amw";
const TLDS_DEFAULT: &str =
"biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф";
fn unpack_tlds() -> Vec<Vec<u16>> {
let mut result: Vec<Vec<u16>> = TLDS_DEFAULT.split('|').map(js::to_utf16).collect();
for item in TLDS_2CH.split('|') {
let (prefix, suffixes) = item.split_once(':').expect("prefix:suffixes");
for suffix in suffixes.chars() {
result.push(js::to_utf16(&format!("{prefix}{suffix}")));
}
}
result
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Match {
pub schema: Vec<u16>,
pub index: usize,
pub last_index: usize,
pub raw: Vec<u16>,
pub text: Vec<u16>,
pub url: Vec<u16>,
}
impl Match {
fn new(text: &[u16], schema: &[u16], index: usize, last_index: usize) -> Self {
let raw = js::slice_to(text, index, last_index).to_vec();
Match {
schema: js::to_lower_case(schema),
index,
last_index,
text: raw.clone(),
url: raw.clone(),
raw,
}
}
}
#[derive(Debug, Clone)]
struct Candidate {
schema: Vec<u16>,
index: usize,
last_index: usize,
}
fn earlier(a: &Candidate, b: &Candidate) -> bool {
a.index < b.index || (a.index == b.index && a.last_index > b.last_index)
}
#[derive(Debug, Clone, PartialEq)]
pub struct LinkifyIt {
opts: LinkifyOptions,
schemas: Vec<(Vec<u16>, Schema)>,
pub re: REBuilder,
normalizer: Option<Normalizer>,
}
#[derive(Debug, Clone, Copy)]
struct Normalizer(fn(&mut Match));
impl PartialEq for Normalizer {
fn eq(&self, other: &Self) -> bool {
std::ptr::fn_addr_eq(self.0, other.0)
}
}
impl Default for LinkifyIt {
fn default() -> Self {
Self::new()
}
}
impl LinkifyIt {
pub fn new() -> Self {
Self::with_options(LinkifyOptions::default())
}
pub fn with_options(options: LinkifyOptions) -> Self {
let schemas: Vec<(Vec<u16>, Schema)> = DEFAULT_SCHEMAS
.iter()
.map(|&(name, schema)| (js::to_utf16(name), schema))
.collect();
let re = Self::rebuild(&options, &schemas);
LinkifyIt {
opts: options,
schemas,
re,
normalizer: None,
}
}
pub fn set_normalizer(&mut self, normalizer: Option<fn(&mut Match)>) -> &mut Self {
self.normalizer = normalizer.map(Normalizer);
self
}
fn normalize_match(&self, m: &mut Match) {
match self.normalizer {
Some(Normalizer(normalize)) => normalize(m),
None => self.normalize(m),
}
}
pub fn set(&mut self, options: LinkifyOptions) -> &mut Self {
self.opts = options;
self.re = Self::rebuild(&self.opts, &self.schemas);
self
}
pub fn options(&self) -> &LinkifyOptions {
&self.opts
}
fn rebuild(opts: &LinkifyOptions, schemas: &[(Vec<u16>, Schema)]) -> REBuilder {
REBuilder::new(REBuilderOptions {
triple_dash: opts.triple_dash,
fuzzy_ip: opts.fuzzy_ip,
schema_names: schemas.iter().map(|(name, _)| name.clone()).collect(),
tlds: unpack_tlds(),
url_auth: opts.url_auth,
max_length: opts.max_length,
})
}
fn schema(&self, name: &[u16]) -> Option<Schema> {
self.schemas
.iter()
.find(|(n, _)| n == name)
.map(|&(_, schema)| schema)
}
pub fn test(&self, text: &[u16]) -> Result<bool, JsError> {
if text.is_empty() {
return Ok(false);
}
let mut last_index = 0;
while let Some((m, k)) = self.re.schema_search(text, last_index) {
last_index = m.end;
let schema = &text[m.end - self.re.opts.schema_names[k].len()..m.end];
if self.test_schema_at(text, schema, last_index)? != 0 {
return Ok(true);
}
}
if self.opts.fuzzy_link && self.schema(&js::to_utf16("http:")).is_some() {
self.path_regex()?;
if self.re.fuzzy_link_search(text, 0).is_some() {
return Ok(true);
}
}
if self.opts.fuzzy_email && self.schema(&js::to_utf16("mailto:")).is_some() {
if text.contains(&0x40) {
let mut last_index = 0;
while let Some(m) = self.re.fuzzy_mail_host_search(text, last_index) {
last_index = m.end;
let name = &text[m.index.saturating_sub(65)..m.index];
if mail_name_validator(name).is_some() {
return Ok(true);
}
}
}
}
Ok(false)
}
pub fn test_schema_at(
&self,
text: &[u16],
schema: &[u16],
pos: usize,
) -> Result<usize, JsError> {
let Some(kind) = self.schema(&js::to_lower_case(schema)) else {
return Ok(0);
};
if kind != Schema::Mailto {
self.path_regex()?;
}
let text = &text[..pos.saturating_add(self.opts.max_length).min(text.len())];
Ok(match kind {
Schema::Web => self.re.http_validator(text, pos).unwrap_or(0),
Schema::Relative => match self.re.relative_proto_validator(text, pos) {
Some(_) if pos >= 3 && text[pos - 3] == 0x3A => 0,
Some(_) if pos >= 3 && text[pos - 3] == 0x2F => 0,
Some(len) => len,
None => 0,
},
Schema::Mailto => self.re.mailto_validator(text, pos).unwrap_or(0),
})
}
fn path_regex(&self) -> Result<(), JsError> {
if self.opts.max_length != 0 {
return Ok(());
}
let dash = if self.opts.triple_dash {
max_length_zero::DASH_TRIPLE
} else {
max_length_zero::DASH_PLAIN
};
Err(JsError::new(
"SyntaxError",
[
max_length_zero::BEFORE_DASH,
dash,
max_length_zero::AFTER_DASH,
]
.concat(),
))
}
pub fn match_all(&self, text: &[u16]) -> Result<Option<Vec<Match>>, JsError> {
let mut result: Vec<Match> = Vec::new();
let mut schema_re_last = 0;
let mut fuzzy_link_re_last = 0;
let mut mail_host_re_last = 0;
let mut fuzzy_link_candidate: Option<Candidate> = None;
let mut fuzzy_email_candidate: Option<Candidate> = None;
let mut schema_prefix: Option<Candidate> = None;
let mut schema_done = false;
let mut fuzzy_link_done = false;
let mut fuzzy_email_done = false;
let mut pos: usize = 0;
if text.is_empty() {
return Ok(None);
}
let fuzzy_link = self.opts.fuzzy_link && self.schema(&js::to_utf16("http:")).is_some();
if fuzzy_link {
self.path_regex()?;
}
let fuzzy_email = self.opts.fuzzy_email && self.schema(&js::to_utf16("mailto:")).is_some();
loop {
let scan_from = pos.saturating_sub(1);
if fuzzy_email
&& !fuzzy_email_done
&& fuzzy_email_candidate.as_ref().is_none_or(|c| c.index < pos)
{
if mail_host_re_last < scan_from {
mail_host_re_last = scan_from;
}
loop {
let Some(m) = self.re.fuzzy_mail_host_search(text, mail_host_re_last) else {
fuzzy_email_done = true;
fuzzy_email_candidate = None;
break;
};
mail_host_re_last = m.end;
let name = &text[m.index.saturating_sub(65)..m.index];
let Some(name_start) = mail_name_validator(name) else {
continue;
};
let candidate = Candidate {
schema: js::to_utf16("mailto:"),
index: m.index - (name.len() - name_start),
last_index: m.end,
};
let index = candidate.index;
fuzzy_email_candidate = Some(candidate);
if index >= pos {
break;
}
if mail_host_re_last < scan_from {
mail_host_re_last = scan_from;
}
}
}
if fuzzy_link
&& !fuzzy_link_done
&& fuzzy_link_candidate.as_ref().is_none_or(|c| c.index < pos)
{
if fuzzy_link_re_last < scan_from {
fuzzy_link_re_last = scan_from;
}
loop {
let Some(m) = self.re.fuzzy_link_search(text, fuzzy_link_re_last) else {
fuzzy_link_done = true;
fuzzy_link_candidate = None;
break;
};
fuzzy_link_re_last = m.end;
let index = m.index + m.prefix;
fuzzy_link_candidate = Some(Candidate {
schema: Vec::new(),
index,
last_index: m.end,
});
if index >= pos {
break;
}
if fuzzy_link_re_last < scan_from {
fuzzy_link_re_last = scan_from;
}
}
}
let mut fuzzy_candidate = fuzzy_email_candidate.as_ref();
if let Some(link) = &fuzzy_link_candidate
&& fuzzy_candidate.is_none_or(|c| earlier(link, c))
{
fuzzy_candidate = Some(link);
}
let fuzzy_candidate_index = fuzzy_candidate.map(|c| c.index);
let mut schema_candidate: Option<Candidate> = None;
if !schema_done {
loop {
let prefix = match schema_prefix.take() {
Some(prefix) => prefix,
None => {
if schema_re_last < scan_from {
schema_re_last = scan_from;
}
let Some((m, k)) = self.re.schema_search(text, schema_re_last) else {
schema_done = true;
break;
};
schema_re_last = m.end;
let len = self.re.opts.schema_names[k].len();
Candidate {
schema: text[m.end - len..m.end].to_vec(),
index: m.index + m.prefix,
last_index: m.end,
}
}
};
if prefix.index < pos {
continue;
}
if fuzzy_candidate_index.is_some_and(|index| prefix.index > index) {
schema_prefix = Some(prefix);
break;
}
let len = self.test_schema_at(text, &prefix.schema, prefix.last_index)?;
if len != 0 {
schema_candidate = Some(Candidate {
last_index: prefix.last_index + len,
..prefix
});
break;
}
}
}
#[derive(PartialEq)]
enum Which {
Schema,
Email,
Link,
}
let mut candidate = schema_candidate.map(|c| (c, Which::Schema));
if let Some(email) = &fuzzy_email_candidate
&& candidate.as_ref().is_none_or(|(c, _)| earlier(email, c))
{
candidate = Some((email.clone(), Which::Email));
}
if let Some(link) = &fuzzy_link_candidate
&& candidate.as_ref().is_none_or(|(c, _)| earlier(link, c))
{
candidate = Some((link.clone(), Which::Link));
}
let Some((candidate, which)) = candidate else {
break;
};
if which == Which::Email {
fuzzy_email_candidate = None;
} else if which == Which::Link {
fuzzy_link_candidate = None;
}
let mut m = Match::new(
text,
&candidate.schema,
candidate.index,
candidate.last_index,
);
self.normalize_match(&mut m);
result.push(m);
pos = candidate.last_index;
}
if !result.is_empty() {
return Ok(Some(result));
}
Ok(None)
}
pub fn match_at_start(&self, text: &[u16]) -> Result<Option<Match>, JsError> {
if text.is_empty() {
return Ok(None);
}
let Some((m, k)) = self.re.schema_at_start(text) else {
return Ok(None);
};
let schema = &text[m.end - self.re.opts.schema_names[k].len()..m.end];
let len = self.test_schema_at(text, schema, m.end)?;
if len == 0 {
return Ok(None);
}
let mut found = Match::new(text, schema, m.index + m.prefix, m.end + len);
self.normalize_match(&mut found);
Ok(Some(found))
}
pub fn normalize(&self, m: &mut Match) {
if m.schema.is_empty() {
let mut url = js::to_utf16("http://");
url.extend_from_slice(&m.url);
m.url = url;
}
if m.schema == js::to_utf16("mailto:") && !starts_with_mailto(&m.url) {
let mut url = js::to_utf16("mailto:");
url.extend_from_slice(&m.url);
m.url = url;
}
}
}
pub(crate) fn starts_with_mailto(url: &[u16]) -> bool {
let p = js::to_utf16("mailto:");
url.len() >= p.len() && url.iter().zip(&p).all(|(&c, &p)| rebuilder::eq_ci(c, p))
}
#[cfg(test)]
mod tests;