0#import "Basic";
3FOO :: #string STR_END
4Teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeest
5Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test
7AnotherTest AnotherTest AnotherTest AnotherTest
9END OF STRING IG
10STR_END;
13main :: () {
14 text := word_wrap(FOO, 40);
15 log("%", text);
16}
18word_wrap :: (text: string, width: int) -> string {
19 buf: String_Builder;
20 init_string_builder(*buf);
22 idx := 0;
23 line_len := 0;
25 while idx < text.count {
27 if is_space(text[idx]) {
28 append(*buf, text[idx]);
29 line_len += 1;
30 idx += 1;
31 continue;
32 }
34 start := idx;
35 while idx < text.count && !is_space(text[idx]) {
36 idx += 1;
37 }
39 word_len := idx - start;
41 if line_len + word_len <= width {
42 for i: start..idx-1 {
43 append(*buf, text[i]);
44 }
45 line_len += word_len;
46 } else {
47 if word_len > width {
48 remaining := word_len;
49 pos := start;
51 while remaining > 0 {
52 chunk := min(width, remaining);
54 if line_len != 0 {
55 append(*buf, "\n");
56 }
58 for i: 0..chunk-1 {
59 append(*buf, text[pos + i]);
60 }
62 pos += chunk;
63 remaining -= chunk;
64 line_len = chunk;
66 if remaining > 0 {
67 append(*buf, "\n");
68 line_len = 0;
69 }
70 }
71 } else {
72 append(*buf, "\n");
73 for i: start..idx-1 {
74 append(*buf, text[i]);
75 }
76 line_len = word_len;
77 }
78 }
79 }
81 // Minus trailing \n
82 // b := get_current_buffer(*buf);
83 // b.count -= 1;
85 return builder_to_string(*buf);
86}