Something went wrong. Try again.
Reading, writing and creating MIME and RFC 5322 email messages in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! `text/plain; format=flowed` — RFC 3676, and the reason a plain text message//! from a modern client looks wrong in one that has never heard of it.//!//! Mail wraps its lines at seventy-odd characters, and has to: a line may not//! exceed 998 octets, and nothing that displays mail in a fixed-width column//! wants longer ones. But a *paragraph* is not seventy characters, so a//! wrapped message shows its author's paragraphs broken in places the author//! did not choose — and when the reader's window is narrower than the wrap//! width, every one of those lines wraps again, giving the ragged//! long-short-long-short that everyone recognises and nobody wants.//!//! Format=flowed is the smallest possible fix. **A line that ends in a space//! is a line that was wrapped**, and the reader may join it to the next one//! and re-wrap the result to whatever width it has. A line that does not end//! in a space is a line the author ended. That is the whole format, and it is//! backwards compatible: a reader that knows nothing about it sees ordinary//! wrapped text with a few trailing spaces.//!//! Three details hang off that one idea://!//! * **Space-stuffing.** A line that would otherwise begin with a space is//! given another one, which the reader removes. Without it the format could//! not represent a line that genuinely starts with a space, since a leading//! space is also what a quoted line's content starts with. Lines beginning//! `>` or `From ` are stuffed as well, for the older reasons those two//! shapes have always needed protecting.//! * **Quoting.** The quote prefix is a run of `>` with nothing between them,//! and it is counted before anything else. Two lines join only if they are//! quoted to the same depth: a reply nested inside a reply is a different//! paragraph from the text around it.//! * **DelSp.** `delsp=yes` says the trailing space is *only* a marker and is//! deleted when the lines are joined, rather than being the space between//! two words. It exists for scripts that do not put spaces between words,//! where a wrap point is not a space at all.//!//! And one exception, which is older than the format: a line that is exactly//! `-- ` is the Usenet signature separator. It ends in a space and is not a//! wrapped line, and a reader that joins it to what follows swallows the//! signature into the message.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const testing = std.testing;
const line_ending = @import("line_ending.zig");
/// The signature separator, which ends in a space and is not flowed.pub const signature_separator = "-- ";
pub const UnflowOptions = struct { /// From the `delsp` parameter. See the module comment. delete_space: bool = false, /// What ends a line on the way out. Mail is CRLF; a caller that is about /// to display the result may prefer otherwise. ending: line_ending.Ending = .crlf,};
/// Joins the wrapped lines of a flowed body back into paragraphs, so that/// whatever displays it can wrap them itself.////// The quote prefix is written back onto every line, because that is what a/// reader needs in order to show it as a quotation at all; the space-stuffing/// is removed, because it was never part of the text.pub fn unflowWriter( w: *Io.Writer, text: []const u8, options: UnflowOptions,) Io.Writer.Error!void { var lines: LineIterator = .init(text); var pending: ?Line = null;
while (true) { const first = pending orelse lines.next() orelse break; pending = null;
try w.splatByteAll('>', first.depth); var content = first.content;
while (isFlowed(content)) { // A flowed line joins the next one, but only if that one is part // of the same quotation. const next = lines.next() orelse break; if (next.depth != first.depth) { pending = next; break; } try w.writeAll(if (options.delete_space) content[0 .. content.len - 1] else content); content = next.content; } try w.writeAll(content); try w.writeAll(options.ending.bytes()); }}
pub fn unflowAlloc( gpa: Allocator, text: []const u8, options: UnflowOptions,) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); unflowWriter(&out.writer, text, options) catch return error.OutOfMemory; return out.toOwnedSlice();}
/// Whether a line continues into the next one.fn isFlowed(content: []const u8) bool { if (content.len == 0 or content[content.len - 1] != ' ') return false; // The signature separator ends in a space and is not a wrapped line. return !std.mem.eql(u8, content, signature_separator);}
pub const FlowOptions = struct { /// Where to wrap, not counting the quote prefix or the line ending. RFC /// 3676 asks for 78 or less and everything uses 72, which leaves room for /// a few levels of quoting before a reply has to rewrap. width: usize = 72, /// Emit `delsp=yes` form. Only useful for a script that does not separate /// its words with spaces; see the module comment. delete_space: bool = false, ending: line_ending.Ending = .crlf,};
/// Wraps text into flowed lines.////// **Each line of the input is a paragraph.** That is the shape a composer/// holds text in — what the author typed, with the line breaks the author/// made — and it is the only input from which the flowed form can be produced/// without guessing: text that has already been hard-wrapped no longer says/// which of its breaks the author meant.pub fn flowWriter( w: *Io.Writer, text: []const u8, options: FlowOptions,) Io.Writer.Error!void { const width = @max(options.width, 1); var lines: LineIterator = .initPlain(text); while (lines.next()) |line| { // The separator goes out exactly as it is, trailing space and all, // at whatever depth it was quoted to. if (std.mem.eql(u8, line.content, signature_separator)) { try w.splatByteAll('>', line.depth); try w.writeAll(signature_separator); try w.writeAll(options.ending.bytes()); continue; }
var content = line.content; while (true) { // Space-stuffing is a property of a *line*, not of a paragraph. // A break that lands inside a run of spaces leaves the next line // starting with one, and a continuation that is not stuffed loses // it to the reader's unstuffing. const stuffed = needsStuffing(content); // The quote prefix, the stuffing and -- with DelSp -- the marker // that is not part of the content all take room from it. const room = width -| (line.depth + @intFromBool(stuffed) + @intFromBool(options.delete_space));
var take = wrapAt(content, @max(room, 1)); // A wrapped line whose content came out as exactly `-- ` would be // read back as the signature separator, which is a *fixed* line — // so the paragraph would not join, and everything after it would // become a signature. Push the break out to the next word rather // than emit one. if (take != content.len and std.mem.eql(u8, content[0..take], signature_separator)) { take = if (std.mem.findScalarPos(u8, content, take, ' ')) |at| at + 1 else content.len; } const last = take == content.len;
try w.splatByteAll('>', line.depth); if (stuffed) try w.writeByte(' '); try w.writeAll(content[0..take]); if (!last) { // A break that is not the end of the paragraph always lands // just after a space -- `wrapAt` guarantees it -- so the text // already ends in one. Without DelSp that space *is* the // marker and does both jobs; with it the marker is deleted on // joining, so it has to be an extra one. // // Writing the content up to the break rather than trimming it // is what keeps a run of several spaces at a wrap point: a // trim would collapse all of them into the single marker. std.debug.assert(content[take - 1] == ' '); if (options.delete_space) try w.writeByte(' '); } try w.writeAll(options.ending.bytes()); if (last) break; content = content[take..]; } }}
pub fn flowAlloc( gpa: Allocator, text: []const u8, options: FlowOptions,) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); flowWriter(&out.writer, text, options) catch return error.OutOfMemory; return out.toOwnedSlice();}
/// Whether a line has to be given a space it did not have, so that what it/// does begin with survives.////// The `>` case cannot arise on the generating path, because a leading run of/// them has already been read as the quote prefix — a line of plain text/// beginning with `>` *is* a quotation, and there is no way to say otherwise./// It is here because the rule is the rule.fn needsStuffing(content: []const u8) bool { if (content.len == 0) return false; if (content[0] == ' ' or content[0] == '>') return true; return std.mem.startsWith(u8, content, "From ");}
/// How much of `content` goes on a line of `room` characters: as many whole/// words as fit, including the space after the last of them.////// A single word longer than the line — a URL, most often — is not broken,/// because breaking it would change it and because a reader that rewraps will/// not be able to put it back.fn wrapAt(content: []const u8, room: usize) usize { if (content.len <= room) return content.len;
// The last space at or before the wrap point. `room` rather than `room - // 1` because a space *at* the wrap point can be the break itself. var i = @min(room, content.len); while (i > 0) : (i -= 1) { if (content[i - 1] == ' ') return i; }
// No space to break at, so run on to the end of the word. const next = std.mem.findScalarPos(u8, content, room, ' ') orelse return content.len; return next + 1;}
/// One line of a flowed body, taken apart: how deeply it is quoted and what it/// says.const Line = struct { depth: usize, /// The text after the quote prefix, with the space-stuffing removed. content: []const u8,};
const LineIterator = struct { source: []const u8, index: usize = 0, /// Whether to take a leading space off the content. /// /// True when reading a flowed body, where that space was put there by the /// generator and is not part of the text. False when reading the plain /// text that is about to be *made* flowed, where nothing has been stuffed /// yet and a leading space is the author's own — removing it there is how /// an indented line loses its indentation every time a message is sent. unstuff: bool,
fn init(source: []const u8) LineIterator { return .{ .source = source, .unstuff = true }; }
fn initPlain(source: []const u8) LineIterator { return .{ .source = source, .unstuff = false }; }
fn next(self: *LineIterator) ?Line { if (self.index >= self.source.len) return null; const nl = std.mem.findScalarPos(u8, self.source, self.index, '\n'); const end = if (nl) |at| (if (at > self.index and self.source[at - 1] == '\r') at - 1 else at) else self.source.len; var text = self.source[self.index..end]; self.index = if (nl) |at| at + 1 else self.source.len;
// The quote prefix is a run of `>` and nothing else; anything between // them is content. var depth: usize = 0; while (depth < text.len and text[depth] == '>') depth += 1; text = text[depth..];
// And then one space, if there is one, which was put there so that // what follows it could be read. if (self.unstuff and text.len != 0 and text[0] == ' ') text = text[1..]; return .{ .depth = depth, .content = text }; }};
test "a wrapped paragraph is joined" { const flowed = "This is a paragraph that the sender's composer \r\n" ++ "wrapped in three places, and which a reader \r\n" ++ "should be free to wrap somewhere else.\r\n"; const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings( "This is a paragraph that the sender's composer wrapped in three " ++ "places, and which a reader should be free to wrap somewhere else.\r\n", joined, );}
test "a line that was not wrapped is left alone" { const flowed = "One line.\r\nAnother line.\r\n\r\nAnd a paragraph after a gap.\r\n"; const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(flowed, joined);}
test "space-stuffing is removed" { const flowed = " indented by one\r\n >not a quote\r\n From the desk of\r\n"; const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(" indented by one\r\n>not a quote\r\nFrom the desk of\r\n", joined);}
test "quotes join only at their own depth" { const flowed = "> a quoted paragraph \r\n" ++ "> continued here\r\n" ++ ">> nested, and separate\r\n" ++ "unquoted\r\n"; const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings( ">a quoted paragraph continued here\r\n" ++ ">>nested, and separate\r\n" ++ "unquoted\r\n", joined, );}
test "a flowed line whose quote depth changes does not eat the next line" { const flowed = "> quoted and flowed \r\nunquoted\r\n"; const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(">quoted and flowed \r\nunquoted\r\n", joined);}
test "the signature separator is not a wrapped line" { const flowed = "the message\r\n-- \r\nJeff\r\n"; const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(flowed, joined);}
test "DelSp deletes the marker rather than keeping it" { const flowed = "日本語のテ \r\nキストです\r\n"; const joined = try unflowAlloc(testing.allocator, flowed, .{ .delete_space = true }); defer testing.allocator.free(joined); try testing.expectEqualStrings("日本語のテキストです\r\n", joined);
// And without it the space is the text's own. const kept = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(kept); try testing.expectEqualStrings("日本語のテ キストです\r\n", kept);}
test "wrapping marks every line but the last" { const text = "This is a paragraph long enough that it has to be wrapped more " ++ "than once at a width of thirty characters.\r\n"; const flowed = try flowAlloc(testing.allocator, text, .{ .width = 30 }); defer testing.allocator.free(flowed);
var lines = std.mem.splitSequence(u8, std.mem.trimEnd(u8, flowed, "\r\n"), "\r\n"); var count: usize = 0; while (lines.next()) |line| { try testing.expect(line.len <= 30); count += 1; } try testing.expect(count > 3);
// Every line but the last ends in a space, and joining gives back the // paragraph. const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(text, joined);}
test "wrapping stuffs what has to be stuffed" { const flowed = try flowAlloc(testing.allocator, " indented\r\nFrom here\r\n", .{}); defer testing.allocator.free(flowed); try testing.expectEqualStrings(" indented\r\n From here\r\n", flowed);
// A leading `>` in the text being flowed is a quotation, not a character // needing protection, so it is not stuffed and comes back as itself. const quoted = try flowAlloc(testing.allocator, ">angle\r\n", .{}); defer testing.allocator.free(quoted); try testing.expectEqualStrings(">angle\r\n", quoted);
const joined = try unflowAlloc(testing.allocator, quoted, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(">angle\r\n", joined);}
test "wrapping keeps a quote prefix on every line" { const flowed = try flowAlloc( testing.allocator, ">>a nested quotation long enough to need wrapping at this width\r\n", .{ .width = 24 }, ); defer testing.allocator.free(flowed); var lines = std.mem.splitSequence(u8, std.mem.trimEnd(u8, flowed, "\r\n"), "\r\n"); while (lines.next()) |line| { try testing.expect(std.mem.startsWith(u8, line, ">>")); try testing.expect(line.len <= 24); }}
test "a word longer than the line is not broken" { const url = "https://example.com/" ++ &@as([100]u8, @splat('a')); const text = "See " ++ url ++ " for more.\r\n"; const flowed = try flowAlloc(testing.allocator, text, .{ .width = 40 }); defer testing.allocator.free(flowed); try testing.expect(std.mem.find(u8, flowed, url) != null);
const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(text, joined);}
test "a round trip through both directions" { const paragraphs = "A first paragraph, long enough that wrapping it will take several lines " ++ "and so exercise the joining as well as the breaking.\r\n" ++ "\r\n" ++ "> A quoted paragraph, also long enough to be wrapped more than once by " ++ "any reasonable width.\r\n" ++ "\r\n" ++ " A line that begins with a space.\r\n" ++ "From the desk of somebody.\r\n" ++ "-- \r\n" ++ "A signature.\r\n"; for ([_]usize{ 20, 40, 72, 1000 }) |width| { const flowed = try flowAlloc(testing.allocator, paragraphs, .{ .width = width }); defer testing.allocator.free(flowed); const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(paragraphs, joined); }}
test "a round trip with DelSp" { const text = "日本語のテキストです、とても長い行になるように書いています。\r\n"; const flowed = try flowAlloc(testing.allocator, text, .{ .width = 20, .delete_space = true }); defer testing.allocator.free(flowed); const joined = try unflowAlloc(testing.allocator, flowed, .{ .delete_space = true }); defer testing.allocator.free(joined); try testing.expectEqualStrings(text, joined);}
test "nothing at all" { const joined = try unflowAlloc(testing.allocator, "", .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings("", joined);
const flowed = try flowAlloc(testing.allocator, "", .{}); defer testing.allocator.free(flowed); try testing.expectEqualStrings("", flowed);}
test "a run of spaces at a wrap point is not collapsed" { // The bug this pins: trimming the break down to a single marker space // silently deleted the rest of the run, so a body came back with its // spacing changed. Every width is tried because only some of them put the // break inside the run. const text = "hello" ++ " " ++ "world and some more text after it\r\n"; for (6..40) |width| { const flowed = try flowAlloc(testing.allocator, text, .{ .width = width }); defer testing.allocator.free(flowed); const joined = try unflowAlloc(testing.allocator, flowed, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(text, joined); }}
test "a wrap point never invents a signature separator" { // The bug this pins: a paragraph beginning `-- ` wrapped at a narrow // width produced a line whose content was exactly the separator, which // the reader then treated as fixed -- so the rest of the paragraph became // a signature. for ([_][]const u8{ "-- i", "-- and then some more words after it", "-- \t" }) |paragraph| { const text = try std.fmt.allocPrint(testing.allocator, "{s}\r\n", .{paragraph}); defer testing.allocator.free(text); for (1..20) |width| { const wrapped = try flowAlloc(testing.allocator, text, .{ .width = width }); defer testing.allocator.free(wrapped); const joined = try unflowAlloc(testing.allocator, wrapped, .{}); defer testing.allocator.free(joined); try testing.expectEqualStrings(text, joined); } }
// And a line that really is the separator still is, quoted or not. const signed = try flowAlloc(testing.allocator, "text\r\n-- \r\nJeff\r\n>-- \r\n", .{}); defer testing.allocator.free(signed); try testing.expectEqualStrings("text\r\n-- \r\nJeff\r\n>-- \r\n", signed);}