From f06de3ba13aff90f73a34416cc27010a73c39362 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Ml=C3=A1dek?= Date: Fri, 9 Oct 2020 22:45:29 +0200 Subject: [PATCH] stupid but working autolinking --- Cargo.toml | 1 + src/main.rs | 26 ++++++++++++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 27022d0..3e539a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,4 +25,5 @@ tera = "1" chrono = "0.4" regex = "1" +linkify = "0.4" percent-encoding = "2.1.0" diff --git a/src/main.rs b/src/main.rs index 7a6c777..7f7ad4e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ use actix_web::error::ErrorInternalServerError; use actix_web::{error, get, http, middleware, web, App, Error, HttpResponse, HttpServer}; use chrono::{DateTime, Local}; use clap::{App as ClapApp, Arg}; +use linkify::LinkFinder; use log::info; use percent_encoding::utf8_percent_encode; use pulldown_cmark::{html, Options, Parser}; @@ -197,8 +198,9 @@ async fn render( fn preprocess(string: String) -> String { let double_brackets = Regex::new(r"\[\[(?P[\w .]+)\]\]").unwrap(); + let finder = LinkFinder::new(); - double_brackets + let result = double_brackets .replace_all(string.as_str(), |caps: &Captures| { format!( "[{}]({})", @@ -206,5 +208,25 @@ fn preprocess(string: String) -> String { utf8_percent_encode(&caps[1], percent_encoding::NON_ALPHANUMERIC) ) }) - .to_string() + .to_string(); + + let result_vec = Vec::from(result.as_str()); + let start_delims = vec![b'(', b'<']; + let end_delims = vec![b')', b'>']; + let links = finder.links(result.as_str()).filter(|link| { + (link.start() == 0 || link.end() == result.len()) + || (!start_delims.contains(&result_vec[link.start() - 1]) + && !end_delims.contains(&result_vec[link.end() + 1])) + }); + + let mut offset = 0; + let mut result_string = result.to_string(); + for link in links { + let orig = link.as_str(); + let new = format!("<{}>", orig); + result_string.replace_range((link.start() + offset)..(link.end() + offset), new.as_str()); + offset += new.len() - orig.len(); + } + + result_string }