Textractor/extensions/regexreplacer.cpp

74 lines
2.1 KiB
C++
Raw Normal View History

2021-10-18 22:57:36 +02:00
#include "extension.h"
#include "module.h"
#include "blockmarkup.h"
#include <fstream>
extern const wchar_t* REGEX_REPLACER_INSTRUCTIONS;
const char* REGEX_REPLACEMENTS_SAVE_FILE = "SavedRegexReplacements.txt";
std::optional<std::wregex> regex;
concurrency::reader_writer_lock m;
BOOL WINAPI DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
if (!std::ifstream(REGEX_REPLACEMENTS_SAVE_FILE).good())
2021-10-29 09:25:54 +02:00
{
2021-10-18 22:57:36 +02:00
auto file = std::ofstream(REGEX_REPLACEMENTS_SAVE_FILE, std::ios::binary) << "\xff\xfe";
for (auto ch : std::wstring_view(REGEX_REPLACER_INSTRUCTIONS))
file << (ch == L'\n' ? std::string_view("\r\0\n", 4) : std::string_view((char*)&ch, 2));
_spawnlp(_P_DETACH, "notepad", "notepad", REGEX_REPLACEMENTS_SAVE_FILE, NULL); // show file to user
}
}
break;
case DLL_PROCESS_DETACH:
{
}
break;
}
return TRUE;
}
bool ProcessSentence(std::wstring& sentence, SentenceInfo sentenceInfo)
{
if (!sentenceInfo["current select"] || sentenceInfo["text number"] == 0) return false;
2021-10-29 09:25:54 +02:00
std::regex::flag_type mod;
std::regex_constants::match_flag_type flag;
2021-10-18 22:57:36 +02:00
std::ifstream stream(REGEX_REPLACEMENTS_SAVE_FILE, std::ios::binary);
2021-10-27 22:59:25 +02:00
BlockMarkupIterator savedFilters(stream, Array<std::wstring_view>{ L"|REGEX|", L"|BECOMES|", L"|MODIFIER|" });
2021-10-18 22:57:36 +02:00
concurrency::reader_writer_lock::scoped_lock_read readLock(m);
2021-10-29 09:25:54 +02:00
while (auto read = savedFilters.Next()) {
2021-10-27 22:59:25 +02:00
const auto& [regex, replacement, modifier] = read.value();
2021-10-29 09:25:54 +02:00
if (modifier == L"g")
{
mod = std::regex::ECMAScript;
flag = std::regex_constants::format_default;
}
else if (modifier == L"gi" || modifier == L"ig")
{
mod = std::regex::icase;
flag = std::regex_constants::format_default;
}
else if (modifier == L"i")
{
mod = std::regex::icase;
flag = std::regex_constants::format_first_only;
}
else
{
mod = std::regex::ECMAScript;
flag = std::regex_constants::format_first_only;
}
try { ::regex = std::wregex(regex, mod); }
2021-10-18 22:57:36 +02:00
catch (std::regex_error) { continue; }
2021-10-29 09:25:54 +02:00
sentence = std::regex_replace(sentence, ::regex.value(), replacement, flag);
2021-10-18 22:57:36 +02:00
}
return true;
}