#import "Basic"; FOO :: #string STR_END Teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeest Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test AnotherTest AnotherTest AnotherTest AnotherTest END OF STRING IG STR_END; main :: () { text := word_wrap(FOO, 40); log("%", text); } word_wrap :: (text: string, width: int) -> string { buf: String_Builder; init_string_builder(*buf); idx := 0; line_len := 0; while idx < text.count { if is_space(text[idx]) { append(*buf, text[idx]); line_len += 1; idx += 1; continue; } start := idx; while idx < text.count && !is_space(text[idx]) { idx += 1; } word_len := idx - start; if line_len + word_len <= width { for i: start..idx-1 { append(*buf, text[i]); } line_len += word_len; } else { if word_len > width { remaining := word_len; pos := start; while remaining > 0 { chunk := min(width, remaining); if line_len != 0 { append(*buf, "\n"); } for i: 0..chunk-1 { append(*buf, text[pos + i]); } pos += chunk; remaining -= chunk; line_len = chunk; if remaining > 0 { append(*buf, "\n"); line_len = 0; } } } else { append(*buf, "\n"); for i: start..idx-1 { append(*buf, text[i]); } line_len = word_len; } } } // Minus trailing \n // b := get_current_buffer(*buf); // b.count -= 1; return builder_to_string(*buf); }