stupid but working autolinking

This commit is contained in:
Tomáš Mládek 2020-10-09 22:45:29 +02:00
parent 73534faec9
commit f06de3ba13
2 changed files with 25 additions and 2 deletions

View file

@ -25,4 +25,5 @@ tera = "1"
chrono = "0.4" chrono = "0.4"
regex = "1" regex = "1"
linkify = "0.4"
percent-encoding = "2.1.0" percent-encoding = "2.1.0"

View file

@ -9,6 +9,7 @@ use actix_web::error::ErrorInternalServerError;
use actix_web::{error, get, http, middleware, web, App, Error, HttpResponse, HttpServer}; use actix_web::{error, get, http, middleware, web, App, Error, HttpResponse, HttpServer};
use chrono::{DateTime, Local}; use chrono::{DateTime, Local};
use clap::{App as ClapApp, Arg}; use clap::{App as ClapApp, Arg};
use linkify::LinkFinder;
use log::info; use log::info;
use percent_encoding::utf8_percent_encode; use percent_encoding::utf8_percent_encode;
use pulldown_cmark::{html, Options, Parser}; use pulldown_cmark::{html, Options, Parser};
@ -197,8 +198,9 @@ async fn render(
fn preprocess(string: String) -> String { fn preprocess(string: String) -> String {
let double_brackets = Regex::new(r"\[\[(?P<inner>[\w .]+)\]\]").unwrap(); let double_brackets = Regex::new(r"\[\[(?P<inner>[\w .]+)\]\]").unwrap();
let finder = LinkFinder::new();
double_brackets let result = double_brackets
.replace_all(string.as_str(), |caps: &Captures| { .replace_all(string.as_str(), |caps: &Captures| {
format!( format!(
"[{}]({})", "[{}]({})",
@ -206,5 +208,25 @@ fn preprocess(string: String) -> String {
utf8_percent_encode(&caps[1], percent_encoding::NON_ALPHANUMERIC) 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
} }