Logo

index : gist

Random things

  • summary
  • about
  • tree
  • log
  • branches
<< path: root/public/gist.git/html/jai/word_wrap/word_wrap.jai blob: 622edf195bf57aafd9187ce445b1d3badfee6f03 [raw] [clear marker]

        
0#import "Basic";
1
2
3FOO :: #string STR_END
4Teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeest
5Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test
6
7AnotherTest AnotherTest AnotherTest AnotherTest
8
9END OF STRING IG
10STR_END;
11
12
13main :: () {
14 text := word_wrap(FOO, 40);
15 log("%", text);
16}
17
18word_wrap :: (text: string, width: int) -> string {
19 buf: String_Builder;
20 init_string_builder(*buf);
21
22 idx := 0;
23 line_len := 0;
24
25 while idx < text.count {
26
27 if is_space(text[idx]) {
28 append(*buf, text[idx]);
29 line_len += 1;
30 idx += 1;
31 continue;
32 }
33
34 start := idx;
35 while idx < text.count && !is_space(text[idx]) {
36 idx += 1;
37 }
38
39 word_len := idx - start;
40
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;
50
51 while remaining > 0 {
52 chunk := min(width, remaining);
53
54 if line_len != 0 {
55 append(*buf, "\n");
56 }
57
58 for i: 0..chunk-1 {
59 append(*buf, text[pos + i]);
60 }
61
62 pos += chunk;
63 remaining -= chunk;
64 line_len = chunk;
65
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 }
80
81 // Minus trailing \n
82 // b := get_current_buffer(*buf);
83 // b.count -= 1;
84
85 return builder_to_string(*buf);
86}
87
88
Copyright 2026  E766CB298A6D1E64 | Git-Thing heavily inspired by cgit