Simplified markdown regex string

This commit is contained in:
Erik Reider
2022-05-08 19:37:56 +02:00
parent 19beafa528
commit 7251bb0a57

View File

@@ -57,7 +57,6 @@ namespace SwayNotificationCenter {
private int carousel_empty_widget_index = 0; private int carousel_empty_widget_index = 0;
private static Regex tag_regex; private static Regex tag_regex;
private static Regex tag_replace_regex;
private static Regex tag_unescape_regex; private static Regex tag_unescape_regex;
private const string[] TAGS = { "b", "u", "i" }; private const string[] TAGS = { "b", "u", "i" };
private const string[] UNESCAPE_CHARS = { private const string[] UNESCAPE_CHARS = {
@@ -95,8 +94,7 @@ namespace SwayNotificationCenter {
construct { construct {
try { try {
string joined_tags = string.joinv ("|", TAGS); string joined_tags = string.joinv ("|", TAGS);
tag_regex = new Regex ("</?(%s)>".printf (joined_tags)); tag_regex = new Regex ("<(/?(?:%s))>".printf (joined_tags));
tag_replace_regex = new Regex ("</?|>");
string unescaped = string.joinv ("|", UNESCAPE_CHARS); string unescaped = string.joinv ("|", UNESCAPE_CHARS);
tag_unescape_regex = new Regex ("&(?=%s)".printf (unescaped)); tag_unescape_regex = new Regex ("&(?=%s)".printf (unescaped));
} catch (Error e) { } catch (Error e) {
@@ -260,11 +258,9 @@ namespace SwayNotificationCenter {
string escaped = Markup.escape_text (text); string escaped = Markup.escape_text (text);
// Replace all valid tags brackets with <,</,> so that the // Replace all valid tags brackets with <,</,> so that the
// markup parser only parses valid tags // markup parser only parses valid tags
escaped = tag_regex.replace_eval (escaped, // Ex: &lt;b&gt;BOLD&lt;/b&gt; -> <b>BOLD</b>
escaped.length, escaped = tag_regex.replace (escaped, escaped.length, 0, "<\\1>");
0,
RegexMatchFlags.NOTEMPTY,
this.regex_tag_eval_cb);
// Unescape a few characters that may have been double escaped // Unescape a few characters that may have been double escaped
// Sending "<" in Discord would result in "&amp;lt;" without this // Sending "<" in Discord would result in "&amp;lt;" without this
// &amp;lt; -> &lt; // &amp;lt; -> &lt;
@@ -285,24 +281,6 @@ namespace SwayNotificationCenter {
} }
} }
/**
* Replaces "&gt;" and "&lt;" with their character counterpart if the
* tag is valid.
*/
private bool regex_tag_eval_cb (MatchInfo match_info,
StringBuilder result) {
try {
string tag = match_info.fetch (0);
// Removes the tag backets: </b> -> b
var res = tag_replace_regex.replace (tag, tag.length, 0, "");
if (!(res in TAGS)) return false;
result.append (tag.replace ("&lt;", "<").replace ("&gt;", ">"));
} catch (Error e) {
stderr.printf ("Regex eval error: %s\n", e.message);
}
return false;
}
public void click_default_action () { public void click_default_action () {
action_clicked (param.default_action, true); action_clicked (param.default_action, true);
} }