From e0e0db80d50841883ab301e4e9b1b1799f3ca974 Mon Sep 17 00:00:00 2001 From: Albert S Date: Sun, 18 Apr 2021 12:24:28 +0200 Subject: [PATCH] Linkparser: Use callbacks, so app can influence how the HTML gets rendered exactly In particular, this allows making dynamic decisions: Some links may for example require a different CSS class or so, therefore a static hardcoded template is not enough for those cases. --- include/maddy/callbackreplacer.h | 36 ++++++++++++++++++++++++++++++++ include/maddy/linkparser.h | 19 ++++++++++++++--- 2 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 include/maddy/callbackreplacer.h diff --git a/include/maddy/callbackreplacer.h b/include/maddy/callbackreplacer.h new file mode 100644 index 0000000..fb24e72 --- /dev/null +++ b/include/maddy/callbackreplacer.h @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. For more information see the + * LICENSE file. + */ +#pragma once + +#include +#include +#include + +namespace maddy { + +inline std::string regex_callback_replacer(std::regex ®ex, const std::string &input, + std::function &callback) +{ + std::string result; + auto tagsbegin = std::sregex_iterator(input.begin(), input.end(), regex); + auto tagsend = std::sregex_iterator(); + auto matchbegin = 0; + for(std::sregex_iterator i = tagsbegin; i != tagsend; ++i) + { + std::smatch match = *i; + + auto matchlength = match.length(0); + auto matchpos = match.position(); + + result += input.substr(matchbegin, matchpos - matchbegin); + result += callback(match); + matchbegin = matchpos + matchlength; + } + result += input.substr(matchbegin); + return result; +} + +} + diff --git a/include/maddy/linkparser.h b/include/maddy/linkparser.h index e382f21..79ca390 100644 --- a/include/maddy/linkparser.h +++ b/include/maddy/linkparser.h @@ -10,6 +10,7 @@ #include #include "maddy/lineparser.h" +#include "maddy/callbackreplacer.h" // ----------------------------------------------------------------------------- @@ -26,6 +27,16 @@ namespace maddy { */ class LinkParser : public LineParser { +private: + std::function callback = [](std::smatch & match){ + std::string inner = match.str(1); + std::string link = match.str(2); + return "" + inner + ""; + }; + + std::regex re = std::regex("\\[([^\\]]*)\\]\\(([^\\]]*)\\)"); + + public: /** * Parse @@ -41,10 +52,12 @@ public: void Parse(std::string& line) override { - static std::regex re("\\[([^\\]]*)\\]\\(([^\\]]*)\\)"); - static std::string replacement = "$1"; + line = regex_callback_replacer(re,line,callback); + } - line = std::regex_replace(line, re, replacement); + void setCallback(std::function callback) + { + this->callback = callback; } }; // class LinkParser