From 65039b4c23a0aa9a06805daeeb1c2c66d3e8e20d Mon Sep 17 00:00:00 2001 From: fiaxh Date: Fri, 21 Feb 2020 19:03:24 +0100 Subject: Improve code block regex --- main/src/ui/util/helper.vala | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) (limited to 'main/src/ui/util') diff --git a/main/src/ui/util/helper.vala b/main/src/ui/util/helper.vala index 807d94e3..6b095376 100644 --- a/main/src/ui/util/helper.vala +++ b/main/src/ui/util/helper.vala @@ -7,6 +7,7 @@ using Xmpp; namespace Dino.Ui.Util { private static Regex URL_REGEX; +private static Regex CODE_BLOCK_REGEX; private static Map MATCHING_CHARS; private const unichar[] NON_TRAILING_CHARS = {'\'', '"', ',', '.', ';', '!', '?', '»', '”', '’', '`', '~', '‽', ':', '>', '*', '_'}; private const string[] ALLOWED_SCHEMAS = {"http", "https", "ftp", "ftps", "irc", "ircs", "xmpp", "mailto", "sms", "smsto", "mms", "tel", "geo", "openpgp4fpr", "im", "news", "nntp", "sip", "ssh", "bitcoin", "sftp", "magnet", "vnc"}; @@ -259,6 +260,13 @@ public static Regex get_url_regex() { return URL_REGEX; } +public static Regex get_code_block_regex() { + if (CODE_BLOCK_REGEX == null) { + CODE_BLOCK_REGEX = /(?:^|\n)(```([^\n]*)\n(?:[^\n]|\n[^`]|\n`[^`]|\n``[^`]|\n```[^\n])+\n```)(?:\n|$)/s; + } + return CODE_BLOCK_REGEX; +} + public static Map get_matching_chars() { if (MATCHING_CHARS == null) { MATCHING_CHARS = new HashMap(); @@ -344,21 +352,16 @@ public static string parse_add_markup(string s_, string? highlight_word, bool pa if (parse_text_markup) { // Try to match preformatted code blocks first - try { - Regex regex = new Regex("(?:^|\n)(```(?:(?!\n\n|```)(?:.|\n))+(?:$|```|\n\n))"); - MatchInfo match_info; - regex.match(s.down().strip(), 0, out match_info); - if (match_info.matches()) { - int start, end; - match_info.fetch_pos(1, out start, out end); - return parse_add_markup(s[0:start], highlight_word, parse_links, parse_text_markup, already_escaped) + - "" + - s[start:end] + - "" + - parse_add_markup(s[end:s.length], highlight_word, parse_links, parse_text_markup, already_escaped); - } - } catch (RegexError e) { - assert_not_reached(); + MatchInfo code_block_match_info; + get_code_block_regex().match(s.down().strip(), 0, out code_block_match_info); + if (code_block_match_info.matches()) { + int start, end; + code_block_match_info.fetch_pos(1, out start, out end); + return parse_add_markup(s[0:start], highlight_word, parse_links, parse_text_markup, already_escaped) + + "" + + s[start:end] + + "" + + parse_add_markup(s[end:s.length], highlight_word, parse_links, parse_text_markup, already_escaped); } string[] markup_string = new string[]{"`", "_", "*", "~"}; -- cgit v1.2.3-54-g00ecf