Skip to content

AI Tone Rewriter — C source

Rewrite any message in a new tone — professional, friendly, concise, formal, or playful — with your own free Groq key, called straight from your browser.

This is the C implementation — the same logic the interactive tool runs, in a shareable, citable form.

/*
 * tone-rewriter — tone registry, prompt building, and reply cleanup.
 *
 * Language: C (C11, standard library only — C has no regex in its standard
 *           library, so the fence stripper is hand-rolled like rust.rs)
 * CosmoDev polyglot showcase port of the `tone-rewriter` tool, ported from
 * src/lib/tone-rewriter.ts (the canonical TypeScript implementation).
 *
 * Why this file exists: the tone rewriter is an AI tool, but its contract is
 * pure — which registers exist, how the system prompt is assembled, and how a
 * raw model reply is cleaned for display. No provider, no keys, no network.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 *
 * Build: cc -std=c11 c.c && ./a.out
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/** Payload cap for the user text (the TS MAX_INPUT_CHARS). */
#define TR_MAX_INPUT_CHARS 12000

/** Marker appended under the cap: newline, U+2026, and the note. */
#define TR_TRUNC_SUFFIX "\n\xe2\x80\xa6 (text truncated)"

/** The five supported registers (the TS `Tone` string-literal union). */
typedef enum {
    TONE_PROFESSIONAL, TONE_FRIENDLY, TONE_CONCISE, TONE_FORMAL, TONE_PLAYFUL,
    TONE_COUNT
} Tone;

/** A registry entry — the TS `ToneOption` (wire id + human label). */
typedef struct {
    const char *id;
    const char *label;
} ToneOption;

/** The five-register registry — the SSOT for the picker, in order. */
static const ToneOption TONES[TONE_COUNT] = {
    { "professional", "Professional" },
    { "friendly",     "Friendly"     },
    { "concise",      "Concise"      },
    { "formal",       "Formal"       },
    { "playful",      "Playful"      },
};

/** Per-tone register sentence embedded in the system prompt. */
static const char *TONE_CONTRACT[TONE_COUNT] = {
    "polished and businesslike, no slang, clear and direct — the register "
    "of a status update to stakeholders",
    "warm and approachable, contractions welcome, like a teammate chatting "
    "— never stiff",
    "as short as possible while keeping every fact; prefer one sentence; "
    "cut filler words without exception",
    "ceremonial register, no contractions, complete sentences — the "
    "register of official correspondence",
    "light and witty, a touch of humor, emojis allowed (at most two) — "
    "but the facts stay exact",
};

/** One chat message; `content` is heap-owned, `role` is static text. */
typedef struct {
    const char *role;
    char *content;
} Message;

/** Malloc a NUL-terminated copy of the first `n` bytes of `s`. */
static char *tr_copy(const char *s, size_t n)
{
    char *out = malloc(n + 1);
    if (out != NULL) memcpy(out, s, n), out[n] = '\0';
    return out;
}

/** True for the six bytes isspace() recognizes in the C locale. */
static int tr_is_space(char c)
{
    return c == ' ' || c == '\t' || c == '\n'
        || c == '\v' || c == '\f' || c == '\r';
}

/** The user message body: text, sliced and tagged when over the cap. C
 *  strings are byte sequences, so the slice counts bytes where the TS lib
 *  counts UTF-16 units — they agree outside the astral planes. */
static char *tr_body(const char *text)
{
    size_t len = strlen(text);
    if (len <= TR_MAX_INPUT_CHARS) return tr_copy(text, len);

    char *body = malloc(TR_MAX_INPUT_CHARS + sizeof TR_TRUNC_SUFFIX);
    if (body == NULL) return NULL;
    memcpy(body, text, TR_MAX_INPUT_CHARS);
    memcpy(body + TR_MAX_INPUT_CHARS, TR_TRUNC_SUFFIX, sizeof TR_TRUNC_SUFFIX);
    return body;
}

/**
 * Build the [system, user] chat messages into the caller's `out` array.
 *
 * Both content strings are malloc'd — release them with tr_free_messages.
 */
void tr_build_prompt_messages(const char *text, Tone tone, Message out[2])
{
    static const char SYSTEM_FMT[] =
        "You rewrite text in a target tone. Rewrite the user's text in a %s "
        "tone: %s. Keep the same meaning and the same facts — only the "
        "register changes. Output ONLY the rewritten text, no preamble, no "
        "notes.";
    const char *id = TONES[tone].id, *contract = TONE_CONTRACT[tone];
    int need = snprintf(NULL, 0, SYSTEM_FMT, id, contract);

    out[0].role = "system";
    out[0].content = malloc((size_t)need + 1);
    if (out[0].content != NULL)
        snprintf(out[0].content, (size_t)need + 1, SYSTEM_FMT, id, contract);
    out[1].role = "user";
    out[1].content = tr_body(text);
}

/** Release the two content strings filled in by tr_build_prompt_messages. */
void tr_free_messages(Message msgs[2])
{
    free(msgs[0].content);
    free(msgs[1].content);
}

/**
 * Clean the model's reply into displayable rewritten text.
 *
 * Hand-rolled equivalent of the TS /```[a-z]*\n?/g regex: drop every "```"
 * marker, any lowercase language tag right after it, and one optional
 * following newline; then trim whitespace on both ends. Returns a malloc'd
 * string, or NULL when nothing survives.
 */
char *tr_parse_rewrite(const char *text)
{
    size_t len = strlen(text);
    char *out = malloc(len + 1);
    if (out == NULL) return NULL;

    size_t o = 0, i = 0;
    while (i < len) {
        if (i + 3 <= len && memcmp(text + i, "```", 3) == 0) {
            i += 3;
            while (i < len && text[i] >= 'a' && text[i] <= 'z') i += 1;
            if (i < len && text[i] == '\n') i += 1;
            continue;
        }
        out[o++] = text[i++];
    }
    size_t start = 0; /* trim both ends, then close the gap */
    while (start < o && tr_is_space(out[start])) start += 1;
    while (o > start && tr_is_space(out[o - 1])) o -= 1;
    memmove(out, out + start, o - start);
    out[o - start] = '\0';
    if (o == start) { free(out); return NULL; } /* nothing survived */
    return out;
}

int main(void)
{
    Message msgs[2];
    tr_build_prompt_messages("The Q3 numbers are in.", TONE_PROFESSIONAL, msgs);
    printf("system: %.72s...\nuser: %s\n", msgs[0].content, msgs[1].content);
    tr_free_messages(msgs);

    char *rewrite = tr_parse_rewrite("```text\nHere you go!\n```\n");
    printf("cleaned: %s\n", rewrite != NULL ? rewrite : "(null)");
    free(rewrite);

    rewrite = tr_parse_rewrite("``` \n"); /* a fence and nothing else */
    printf("empty reply: %s\n", rewrite != NULL ? rewrite : "(null)");
    free(rewrite);
    return 0;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →