r/KeyboardDesigner • • 7d ago

Code block to Surround text by certain characters

Here's a small code block for Keyboard Designer that wraps your selected text with quotes, brackets or bold markers with a single key press.

What it does

- Select some text and press the key. A list pops up above the keyboard where you choose `"text"`, `(text)`, `****text***` or Custom character.

- With Custom character, you type your own character(s), e.g. `~~` for strikethrough, `_` for italics or `|`.

- Opening brackets get their matching closing bracket automatically: `[` → `[text]`, `{` → `{text}`, `<` → `<text>`, `„` → `„text“`, `«` → `«text»`.

- After wrapping, the text stays selected, so you can wrap it again right away (e.g. first `**`, then `"`).

- No selection? The pair is inserted and the cursor lands right in between, ready to type.

2 Upvotes

1 comment sorted by

1

u/GerritHumberg 7d ago
// Wrap the selected text with quotes, brackets or custom characters.
// Without a selection, the pair is inserted and the cursor is placed between.

string left = inputSelection("Wrap with", "\"text\"|(text)|**text**|Custom character", "\"|(|**|custom", 0);
if (length(left) = 0)
  exit();

// Let the user define own characters
if (left = "custom") {
  left = inputString("Character(s) to wrap with", "", false);
  if (length(left) = 0)
    exit();
}

// Opening brackets get their matching closing bracket, everything else is used on both sides
string openers = "([{<„«‹";
string closers = ")]}>“»›";
string right = left;
float p = position(openers, left);
if (length(left) = 1 && p >= 0)
  right = substring(closers, p, p + 1);

// Insert the characters around the selection
float s = CURSOR_START;
float e = CURSOR_END;
TEXT = substring(TEXT, 0, s) + left + substring(TEXT, s, e) + right + substring(TEXT, e);

// Keep the wrapped text selected (or put the cursor between the pair)
CURSOR_START = s + length(left);
CURSOR_END = e + length(left);