Extensions: Add regex engine

Regex is a method that is commonly used to find and replace parts
of a string using a single pattern. Add support for using regex in
SillyTavern which allows users to dynamically change various aspects
of the chatting experience.

Users are able to choose where a given regex script should apply
(both invasive and non-invasive options!). Invasive options alter
chat history while non-invasive alters markdown display for the
entire chat.

A new variable called {{match}} is added in regex scripts which
substitutes in the found match from the original find regex script.

There is a lot more that can be added to this extension, but for now,
this is enough.

Signed-off-by: kingbri <bdashore3@proton.me>
This commit is contained in:
kingbri
2023-07-03 21:25:35 -04:00
parent 6bc9535040
commit ef7aa3941b
11 changed files with 470 additions and 5 deletions

View File

@@ -22,6 +22,9 @@ import {
} from "../script.js";
import { humanizedDateTime } from "./RossAscends-mods.js";
import { resetSelectedGroup } from "./group-chats.js";
import { extension_settings } from "./extensions.js";
import { runRegexScript } from "./extensions/regex/engine.js";
import { REGEX_PLACEMENT } from "./extensions/regex/index.js";
import { chat_styles, power_user } from "./power-user.js";
export {
executeSlashCommands,
@@ -218,14 +221,22 @@ async function sendMessageAs(_, text) {
}
const parts = text.split('\n');
if (parts.length <= 1) {
toastr.warning('Both character name and message are required. Separate them with a new line.');
return;
}
const name = parts.shift().trim();
const mesText = parts.join('\n').trim();
let mesText = parts.join('\n').trim();
extension_settings.regex.forEach((script) => {
if (script.placement.includes(REGEX_PLACEMENT.sendas)) {
const regexResult = runRegexScript(script, mesText);
if (regexResult) {
mesText = regexResult;
}
}
});
// Messages that do nothing but set bias will be hidden from the context
const bias = extractMessageBias(mesText);
const isSystem = replaceBiasMarkup(mesText).trim().length === 0;
@@ -268,6 +279,15 @@ async function sendNarratorMessage(_, text) {
return;
}
extension_settings.regex.forEach((script) => {
if (script.placement.includes(REGEX_PLACEMENT.system)) {
const regexResult = runRegexScript(script, text);
if (regexResult) {
text = regexResult;
}
}
});
const name = chat_metadata[NARRATOR_NAME_KEY] || NARRATOR_NAME_DEFAULT;
// Messages that do nothing but set bias will be hidden from the context
const bias = extractMessageBias(text);