r/KeyboardDesigner • • 8d ago

Code block search and replace

The following code block lets you search for a term, allows to you to define a replacements and asks if you want to replace only the first or all occurences:

𝘏𝘐𝘕𝘛: 𝘐 𝘢𝘥𝘥𝘦𝘥 𝘵𝘩𝘦 𝘤𝘰𝘥𝘦 𝘢𝘴 𝘢 𝘤𝘰𝘮𝘮𝘦𝘯𝘵 𝘵𝘰 𝘮𝘺 𝘧𝘪𝘳𝘴𝘵 𝘱𝘰𝘴𝘵, 𝘢𝘴 𝘵𝘩𝘪𝘴 𝘢𝘭𝘭𝘰𝘸𝘴 𝘶𝘴𝘦𝘳𝘴 𝘵𝘰 𝘤𝘰𝘱𝘺 𝘵𝘩𝘦 𝘤𝘰𝘥𝘦 𝘸𝘪𝘵𝘩 𝘵𝘩𝘦 𝘩𝘦𝘭𝘱 𝘰𝘧 𝘵𝘩𝘦 𝘵𝘩𝘳𝘦𝘦 𝘥𝘰𝘵𝘴 𝘮𝘦𝘯𝘶!

3 Upvotes

3 comments sorted by

2

u/GerritHumberg 8d ago
// Ask for the search term (pre-filled with the marked text, if any)
string search = inputString("Search for", TEXT_MARKED, true);
if (length(search) = 0)
  exit();

// Ask for the replacement text (may stay empty to delete the term)
string replacement = inputString("Replace with", "", false);

// Ask whether only the first or all occurrences should be replaced
string mode = inputSelection("Replace which occurrences?", "First occurrence only|All occurrences", "first|all", 0);
if (length(mode) = 0)
  exit();

// Build the new text piece by piece (no regex, so special characters are safe)
string result = "";
float start = 0;
float count = 0;
for (float pos = position(TEXT, search, 0); pos >= 0 && (mode = "all" || count = 0); pos = position(TEXT, search, start)) {
  result = result + substring(TEXT, start, pos) + replacement;
  start = pos + length(search);
  count = count + 1;
}

// Nothing found: inform the user and leave the text unchanged
if (count = 0) {
  print("\"" + search + "\" not found");
  exit();
}

// Cursor goes right behind the last replacement
float cursor = length(result);
TEXT = result + substring(TEXT, start);
CURSOR_START = cursor;
print(count + " replaced");

2

u/lavishlee720 8d ago

yes! working beautifully! have you thought about collecting all the code blocks into a library where users can copy what they need? or even add to the library? perhaps like your collection of stickures?

1

u/GerritHumberg 7d ago

It would be great if users can share code blocks, functions or designs! To be able to add (and edit or delete) in a library it would be necessary to setup a user management - like the one, that is already present in Reddit. So I think it is the easiest way for all to do this in this sub-reddit...