aboutsummaryrefslogtreecommitdiff
path: root/docs/text.md
blob: 47f60e32c946cb705a9deaf85b796cd391b4e7fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
# Text

`Text` is Tomo's datatype to represent text. The name `Text` is used instead of
"string" because Tomo text represents immutable, normalized unicode data with
fast indexing that has an implementation that is efficient for concatenation.
These are _not_ C-style NULL-terminated character arrays. GNU libunistring is
used for full Unicode functionality (grapheme cluster counts, capitalization,
etc.).

## Implementation

Internally, Tomo text's implementation is based on [Raku's
strings](https://docs.raku.org/language/unicode). Strings store their grapheme
cluster count and either a compact array of 8-bit ASCII characters (for ASCII
text), an array of 32-bit normal-form grapheme cluster values (see below), or a
flat subarray of multiple texts that are either ASCII or graphemes (the
structure is not arbitrarily nested).

### Normal-Form Graphemes

In order to maintain compact storage, fast indexing, and fast slicing,
non-ASCII text is stored as 32-bit normal-form graphemes. A normal-form
grapheme is either a positive value representing a Unicode codepoint that
corresponds to a grapheme cluster (most Unicode letters used in natural
language fall into this category after normalization) or a negative value
representing an index into an internal array of "synthetic grapheme cluster
codepoints." Here are some examples:

- `A` is a normal codepoint that is also a grapheme cluster, so it would
  be represented as the number `65`
- `ABC` is three separate grapheme clusters, one for `A`, one for `B`, one
  for `C`.
- `Å` is also a single codepoint (`LATIN CAPITAL LETTER A WITH RING ABOVE`)
  that is also a grapheme cluster, so it would be represented as the number
  `197`.
- `家` (Japanese for "house") is a single codepoint (`CJK Unified
  Ideograph-5BB6`) that is also a grapheme cluster, so it would be represented
  as the number `23478`
-`👩🏽‍🚀` is a single graphical cluster, but it's made up of several
  combining codepoints (`["WOMAN", "EMOJI MODIFIER FITZPATRICK TYPE-4", "ZERO
  WITDH JOINER", "ROCKET"]`). Since this can't be represented with a single
  codepoint, we must create a synthetic codepoint for it. If this was the `n`th
  synthetic codepoint that we've found, then we would represent it with the
  number `-n`, which can be used to look it up in a lookup table. The lookup
  table holds the full sequence of codepoints used in the grapheme cluster.

## Syntax

Text has a flexible syntax designed to make it easy to hold values from
different languages without the need to have lots of escape sequences and
without using printf-style string formatting.

```
// Basic text:
str := "Hello world"
str2 := 'Also text'
str3 := `Backticks too`
```

### Line Splits

Long text can be split across multiple lines by having two or more dots at the
start of a new line on the same indentation level that started the text:

```
str := "This is a long
....... line that is split in code"
```

### Multi-line Text

Multi-line text has indented (i.e. at least one tab more than the start of the
text) text inside quotation marks. The leading and trailing newline are
ignored:

```
multi_line := "
    This text has multiple lines.
    Line two.

    You can split a line
.... using two or more dots to make an elipsis.

    Remember to include whitespace after the elipsis if desired.

    Or don't if you're splitting a long word like supercalifragilisticexpia
....lidocious

        This text is indented by one level in the text

    "quotes" are ignored unless they're at the same indentation level as the
.... start of the text.

    The end (no newline after this).
"
```

## Text Interpolations

Inside double quoted text, you can use a dollar sign (`$`) to insert an
expression that you want converted to text. This is called text interpolation:

```
// Interpolation:
my_var := 5
str := "My var is $my_var!"
// Equivalent to "My var is 5!"

// Using parentheses:
str := "Sum: $(1 + 2)"
// equivalent to "Sum: 3"
```

Single-quoted text does not have interpolations:

```
// No interpolation here:
str := 'Sum: $(1 + 2)'
```

### Text Escapes

Unlike other languages, backslash is *not* a special character inside of text.
For example, `"x\ny"` has the characters `x`, `\`, `n`, `y`, not a newline.
Instead, a series of character escapes act as complete text literals without
quotation marks:

```
newline := \n
crlf := \r\n
quote := \"
```

These text literals can be used as interpolation values with or without
parentheses, depending on which you find more readable:

```
two_lines := "one$(\n)two"
has_quotes := "some $\"quotes$\" here"
```

However, in general it is best practice to use multi-line text to avoid these problems:

```
str := "
    This has
    multiple lines and "quotes" too!
"
```

### Customizable `$`-Text

Sometimes you might need to use a lot of literal `$`s or quotation marks in
text. In such cases, you can use the more customizable form of text. The
customizable form lets you explicitly specify which character to use for
interpolation and which characters to use for delimiting the text.

The first character after the `$` is the custom interpolation character, which
can be any of the following symbols: `~!@#$%^&*+=\?`. If none of these
characters is used, the default interpolation character is `$`. Since this is
the default, you can disable interpolation altogether by using `$` here (i.e. a
double `$$`).

The next thing in a customizable text is the character used to delimit the
text. The text delimiter can be any of the following symbols: `` "'`|/;([{< ``
If the text delimiter is one of `([{<`, then the text will continue until a
matching `)]}>` is found, not terminating unless the delimiters are balanced
(i.e. nested pairs of delimiters are considered part of the text).

Here are some examples:

```
$"Equivalent to normal text with dollar interps: $(1 + 2)"
$@"The same, but the AT symbol interpolates: @(1 + 2)"
$$"No interpolation here, $ is just a literal character"
$|This text is pipe-delimited, so it can have "quotes" and 'single quotes' and interpolates with dollar sign: $(1+2)|
$(This text is parens-delimited, so you can have (nested) parens without ending the text)
$=[This text is square-bracket delimited [which can be nested] and uses equals for interps: =(1 + 2)]
$@/look ma, regex literals!/
```

When text is delimited by matching pairs (`()`, `[]`, `{}`, or `<>`), they
can only be closed by a matched closing character at the same indentation
level, ignoring nested pairs:

```
$$(Inside parens, you can have (nested ()) parens no problem)
$$"But only (), [], {}, and <> are matching pairs, you can't have nested quotes"
$$(
    When indented, an unmatched ) won't close the text
    An unmatched ( won't mess things up either
    Only matching pairs on the same indentation level are counted:
)
$$(Multi-line text with nested (parens) and
.. line continuation)
```

As a special case, when you use the same character for interpolation and text
delimiting, no interpolations are allowed:

```
plain := $""This text has {no interpolations}!"
```

**Note:** Normal doubly quoted text with no dollar sign (e.g. `"foo"`) are a
shorthand for `${}"foo"`. Singly quoted text with no dollar sign (e.g.
`'foo'`) are shorthand for `$''foo'`.

## Operations

### Concatenation

Concatenation in the typical case is a fast operation: `"{x}{y}"` or `x ++ y`.

Because text concatenation is typically fast, there is no need for a separate
"string builder" class in the language and no need to use an array of text
fragments.

### Text Length

Text length gives you the number of grapheme clusters in the text, according to
the unicode standard. This corresponds to what you would intuitively think of
when you think of "letters" in a string. If you have text with an emoji that has
several joining modifiers attached to it, that text has a length of 1.

```tomo
>> "hello".length
= 5
>> "👩🏽‍🚀".length
= 1
```

### Iteration

Iteration is *not* supported for text. It is rarely ever the case that you will
need to iterate over text, but if you do, you can iterate over the length of
the text and retrieve 1-wide slices. Alternatively, you can split the text into
its constituent grapheme clusters with `text:split()` and iterate over those.

### Equality, Comparison, and Hashing

All text is compared and hashed using unicode normalization. Unicode provides
several different ways to represent the same text. For example, the single
codepoint `U+E9` (latin small e with accent) is rendered the same as the two
code points `U+65 U+301` (latin small e, acute combining accent) and has an
equivalent linguistic meaning. These are simply different ways to represent the
same "letter." In order to make it easy to write correct code that takes this
into account, Tomo uses unicode normalization for all text comparisons and
hashing. Normalization does the equivalent of converting text to a canonical
form before performing comparisons or hashing. This means that if a table is
created that has text with the codepoint `U+E9` as a key, then a lookup with
the same text but with `U+65 U+301` instead of `U+E9` will still succeed in
finding the value because the two texts are equivalent under normalization.

# Patterns

As an alternative to full regular expressions, Tomo provides a limited string
matching pattern syntax that is intended to solve 80% of use cases in 1% of the
code size (PCRE's codebase is roughly 150k lines of code, and Tomo's entire
Text codebase is around 1.5K lines of code).

For more advanced use cases, consider linking against a C library for regular
expressions or pattern matching.

`Pattern` is a [domain-specific language](docs/langs.md), in other words, it's
like a `Text`, but it has a distinct type. As a convenience, you can use
`$/.../` to write pattern literals instead of using the general-purpose DSL
syntax of `$Pattern"..."`.

Patterns are used in a small, but very powerful API that handles many text
functions that would normally be handled by a more extensive API:

```
Text.has(pattern:Pattern)->Bool
Text.find(pattern:Pattern, start=1, length=!&Int64?)->Int
Text.find_all(pattern:Pattern)->[Text]
Text.split(pattern:Pattern)->[Text]
Text.replace(pattern:Pattern, replacement:Text, placeholder:Pattern=$//)->[Text]
Text.replace_all(replacements:{Pattern:Text}, placeholder:Pattern=$//)->[Text]
Text.replace_chain(patterns:[Pattern], replacements:[Text], placeholder:Pattern=$//)->[Text]
```

See [Text Functions](#Text-Functions) for the full API documentation.

## Syntax

Patterns have three types of syntax:

- `{` followed by an optional count (`n`, `n-m`, or `n+`), followed by an
  optional `!` to negate the pattern, followed by an optional pattern name or
  Unicode character name, followed by a required `}`.

- Any matching pair of quotes or parentheses or braces with a `?` in the middle
  (e.g. `"?"` or `(?)`).

- Any other character is treated as a literal to be matched exactly.

## Named Patterns

Named patterns match certain pre-defined patterns that are commonly useful. To
use a named pattern, use the syntax `{name}`. Names are case-insensitive and
mostly ignore spaces, underscores, and dashes.

- `..` - Any character (note that a single `.` would mean the literal period
  character).
- `digit` - A unicode digit
- `email` - an email address
- `emoji` - an emoji
- `end` - the very end of the text
- `id` - A unicode identifier
- `int` - One or more digits with an optional `-` (minus sign) in front
- `ip` - an IP address (IPv4 or IPv6)
- `ipv4` - an IPv4 address
- `ipv6` - an IPv6 address
- `num` - One or more digits with an optional `-` (minus sign) in front and an optional `.` and more digits after
- `start` - the very start of the text
- `uri` - a URI
- `url` - a URL (URI that specifically starts with `http://`, `https://`, `ws://`, `wss://`, or `ftp://`)

For non-alphabetic characters, any single character is treated as matching
exactly that character. For example, `{1{}` matches exactly one `{`
character. Or, `{1.}` matches exactly one `.` character.

Patterns can also use any Unicode property name. Some helpful ones are:

- `hex` - Hexidecimal digits
- `lower` - Lowercase letters
- `space` - The space character
- `upper` - Uppercase letters
- `whitespace` - Whitespace characters

Patterns may also use exact Unicode codepoint names. For example: `{1 latin
small letter A}` matches `a`.

## Negating Patterns

If an exclamation mark (`!`) is placed before a pattern's name, then characters
are matched only when they _don't_ match the pattern. For example, `{!alpha}`
will match all characters _except_ alphabetic ones.

## Interpolating Text and Escaping

To escape a character in a pattern (e.g. if you want to match the literal
character `?`), you can use the syntax `{1 ?}`. This is almost never necessary
unless you have text that looks like a Tomo text pattern and has something like
`{` or `(?)` inside it.

However, if you're trying to do an exact match of arbitrary text values, you'll
want to have the text automatically escaped. Fortunately, Tomo's injection-safe
DSL text interpolation supports automatic text escaping. This means that if you
use text interpolation with the `$` sign to insert a text value, the value will
be automatically escaped using the `{1 ?}` rule described above:

```tomo
# Risk of code injection (would cause an error because 'xxx' is not a valid
# pattern name:
>> user_input := get_user_input()
= "{xxx}"

# Interpolation automatically escapes:
>> $/$user_input/
= $/{1{}..xxx}/

# No error:
>> some_text:find($/$user_input/)
= 0
```

If you prefer, you can also use this to insert literal characters:

```tomo
>> $/literal $"{..}"/
= $/literal {1{}..}/
```

## Repetitions

By default, named patterns match 1 or more repetitions, but you can specify how
many repetitions you want by putting a number or range of numbers first using
`n` (exactly `n` repetitions), `n-m` (between `n` and `m` repetitions), or `n+`
(`n` or more repetitions):

```
{4-5 alpha}
0x{hex}
{4 digit}-{2 digit}-{2 digit}
{2+ space}
{0-1 question mark}
```

# Text Functions

## `as_c_string`

**Description:**  
Converts a `Text` value to a C-style string.

**Usage:**  
```tomo
as_c_string(text: Text) -> CString
```

**Parameters:**

- `text`: The text to be converted to a C-style string.

**Returns:**  
A C-style string (`CString`) representing the text.

**Example:**  
```tomo
>> "Hello":as_c_string()
= CString("Hello")
```

---

## `utf8_bytes`

**Description:**  
Converts a `Text` value to an array of bytes representing a UTF8 encoding of
the text.

**Usage:**  
```tomo
bytes(text: Text) -> [Int8]
```

**Parameters:**

- `text`: The text to be converted to UTF8 bytes.

**Returns:**  
An array of bytes (`[Int8]`) representing the text in UTF8 encoding.

**Example:**  
```tomo
>> "Amélie":utf8_bytes()
= [65_i8, 109_i8, -61_i8, -87_i8, 108_i8, 105_i8, 101_i8] : [Int8]
```

---

## `codepoint_names`

**Description:**  
Returns an array of the names of each codepoint in the text.

**Usage:**  
```tomo
codepoint_names(text: Text) -> [Text]
```

**Parameters:**

- `text`: The text from which to extract codepoint names.

**Returns:**  
An array of codepoint names (`[Text]`).

**Example:**  
```tomo
>> "Amélie":codepoint_names()
= ["LATIN CAPITAL LETTER A", "LATIN SMALL LETTER M", "LATIN SMALL LETTER E WITH ACUTE", "LATIN SMALL LETTER L", "LATIN SMALL LETTER I", "LATIN SMALL LETTER E"]
```

---

## `utf32_codepoints`

**Description:**  
Returns an array of Unicode code points for UTF32 encoding of the text.

**Usage:**  
```tomo
utf32_codepoints(text: Text) -> [Int32]
```

**Parameters:**

- `text`: The text from which to extract Unicode code points.

**Returns:**  
An array of 32-bit integer Unicode code points (`[Int32]`).

**Example:**  
```tomo
>> "Amélie":utf32_codepoints()
= [65_i32, 109_i32, 233_i32, 108_i32, 105_i32, 101_i32] : [Int32]
```

---

## `from_c_string`

**Description:**  
Converts a C-style string to a `Text` value.

**Usage:**  
```tomo
from_c_string(str: CString) -> Text
```

**Parameters:**

- `str`: The C-style string to be converted.

**Returns:**  
A `Text` value representing the C-style string.

**Example:**  
```tomo
>> Text.from_c_string(CString("Hello"))
= "Hello"
```

---

## `from_codepoint_names`

**Description:**  
Returns text that has the given codepoint names (according to the Unicode
specification) as its codepoints. Note: the text will be normalized, so the
resulting text's codepoints may not exactly match the input codepoints.

**Usage:**  
```tomo
from_codepoint_names(codepoint_names: [Text]) -> [Text]
```

**Parameters:**

- `codepoint_names`: The names of each codepoint in the desired text. Names
  are case-insentive.

**Returns:**  
A new text with the specified codepoints after normalization has been applied.
Any invalid names are ignored.

**Example:**  
```tomo
>> Text.from_codepoint_names([
  "LATIN CAPITAL LETTER A WITH RING ABOVE",
  "LATIN SMALL LETTER K",
  "LATIN SMALL LETTER E",
]
= "Åke"
```

---

## `from_codepoints`

**Description:**  
Returns text that has been constructed from the given UTF32 codepoints. Note:
the text will be normalized, so the resulting text's codepoints may not exactly
match the input codepoints.

**Usage:**  
```tomo
from_codepoint_names(codepoints: [Int32]) -> [Text]
```

**Parameters:**

- `codepoints`: The UTF32 codepoints in the desired text.

**Returns:**  
A new text with the specified codepoints after normalization has been applied.

**Example:**  
```tomo
>> Text.from_codepoints([197_i32, 107_i32, 101_i32])
= "Åke"
```

---

## `from_bytes`

**Description:**  
Returns text that has been constructed from the given UTF8 bytes. Note: the
text will be normalized, so the resulting text's UTF8 bytes may not exactly
match the input.

**Usage:**  
```tomo
from_codepoint_names(codepoints: [Int32]) -> [Text]
```

**Parameters:**

- `codepoints`: The UTF32 codepoints in the desired text.

**Returns:**  
A new text based on the input UTF8 bytes after normalization has been applied.

**Example:**  
```tomo
>> Text.from_bytes([-61_i8, -123_i8, 107_i8, 101_i8])
= "Åke"
```

---

## `find`

**Description:**  
Finds the first occurrence of a pattern in the given text (if any).
See: [Patterns](#Patterns) for more information on patterns.

**Usage:**  
```tomo
find(text: Text, pattern: Text, start: Int = 1, length: &Int64? = !&Int64) -> Int
```

**Parameters:**

- `text`: The text to be searched.
- `pattern`: The pattern to search for.
- `start`: The index to start the search.
- `length`: If non-null, this pointer's value will be set to the length of the
  match, or `-1` if there is no match.

**Returns:**  
`0` if the target pattern is not found, otherwise the index where the match was
found.

**Example:**  
```tomo
>> " one   two  three   ":find("{id}", start=-999)
= 0
>> " one   two  three   ":find("{id}", start=999)
= 0
>> " one   two  three   ":find("{id}")
= 2
>> " one   two  three   ":find("{id}", start=5)
= 8

>> len := 0_i64
>> "   one  ":find("{id}", length=&len)
= 4
>> len
= 3_i64
```

---

## `find_all`

**Description:**  
Finds all occurrences of a pattern in the given text.
See: [Patterns](#Patterns) for more information on patterns.

**Usage:**  
```tomo
find_all(text: Text, pattern: Text) -> [Text]
```

**Parameters:**

- `text`: The text to be searched.
- `pattern`: The pattern to search for.

**Returns:**  
An array of every match of the pattern in the given text.
Note: if `text` or `pattern` is empty, an empty array will be returned.

**Example:**  
```tomo
>> " one  two three   ":find_all("{alpha}")
= ["one", "two", "three"]

>> " one  two three   ":find_all("{!space}")
= ["one", "two", "three"]

>> "    ":find_all("{alpha}")
= []

>> " foo(baz(), 1)  doop() ":find_all("{id}(?)")
= ["foo(baz(), 1)", "doop()"]

>> "":find_all("")
= []

>> "Hello":find_all("")
= []
```

---

## `has`

**Description:**  
Checks if the `Text` contains a target pattern (see: [Patterns](#Patterns)).

**Usage:**  
```tomo
has(text: Text, pattern: Text) -> Bool
```

**Parameters:**

- `text`: The text to be searched.
- `pattern`: The pattern to search for.

**Returns:**  
`yes` if the target pattern is found, `no` otherwise.

**Example:**  
```tomo
>> "hello world":has("wo")
= yes
>> "hello world":has("{alpha}")
= yes
>> "hello world":has("{digit}")
= no
>> "hello world":has("{start}he")
= yes
```

---

## `join`

**Description:**  
Joins an array of text pieces with a specified glue.

**Usage:**  
```tomo
join(glue: Text, pieces: [Text]) -> Text
```

**Parameters:**

- `glue`: The text used to join the pieces.
- `pieces`: The array of text pieces to be joined.

**Returns:**  
A single `Text` value with the pieces joined by the glue.

**Example:**  
```tomo
>> ", ":join(["one", "two", "three"])
= "one, two, three"
```

---

## `lines`

**Description:**  
Splits the text into an array of lines of text, preserving blank lines,
ignoring trailing newlines, and handling `\r\n` the same as `\n`.

**Usage:**  
```tomo
split(text: Text) -> [Text]
```

**Parameters:**

- `text`: The text to be split into lines.

**Returns:**  
An array of substrings resulting from the split.

**Example:**  
```tomo
>> "one$(\n)two$(\n)three":lines()
= ["one", "two", "three"]
>> "one$(\n)two$(\n)three$(\n)":lines()
= ["one", "two", "three"]
>> "one$(\n)two$(\n)three$(\n\n)":lines()
= ["one", "two", "three", ""]
>> "one$(\r\n)two$(\r\n)three$(\r\n)":lines()
= ["one", "two", "three"]
>> "":lines()
= []
```

---

## `lower`

**Description:**  
Converts all characters in the text to lowercase.

**Usage:**  
```tomo
lower(text: Text) -> Text
```

**Parameters:**

- `text`: The text to be converted to lowercase.

**Returns:**  
The lowercase version of the text.

**Example:**  
```tomo
>> "AMÉLIE":lower()
= "amélie"
```

---

## `quoted`

**Description:**  
Formats the text as a quoted string.

**Usage:**  
```tomo
quoted(text: Text, color: Bool = no) -> Text
```

**Parameters:**

- `text`: The text to be quoted.
- `color`: Whether to add color formatting (default is `no`).

**Returns:**  
The text formatted as a quoted string.

**Example:**  
```tomo
>> "one$(\n)two":quoted()
= "\"one\\ntwo\""
```

---

## `replace`

**Description:**  
Replaces occurrences of a pattern in the text with a replacement string.
See [Patterns](#patterns) for more information about patterns.

**Usage:**  
```tomo
replace(text: Text, pattern: Text, replacement: Text, placeholder: Pattern = $//) -> Text
```

**Parameters:**

- `text`: The text in which to perform replacements.
- `pattern`: The pattern to be replaced.
- `replacement`: The text to replace the pattern with.
- `placeholder`: If non-empty, the replacement text will have occurrences of the placeholder
  pattern replaced with the matching text.

**Returns:**  
The text with occurrences of the pattern replaced.

**Example:**  
```tomo
>> "Hello world":replace("world", "there")
= "Hello there"

>> "Hello world":replace("{id}", "xxx")
= "xxx xxx"

>> "Hello world":replace("{id}", "(@)", placeholder=$/@/)
= "(Hello) (world)"
```

---

## `replace_all`

**Description:**  
Takes a table mapping patterns to replacement texts and performs all the
replacements in the table on the whole text. At each position, the first
matching pattern's replacement is applied and the pattern matching moves on to
*after* the replacement text, so replacement text is not recursively modified.
See [Patterns](#patterns) for more information about patterns.

**Usage:**  
```tomo
replace_all(replacements:{Pattern:Text}, placeholder: Pattern = $//) -> Text
```

**Parameters:**

- `text`: The text in which to perform replacements.
- `replacements`: A table mapping from patterns to the replacement text
  associated with that pattern.
- `placeholder`: If non-empty, the replacement text will have occurrences of
  the placeholder pattern replaced with the matching text.

**Returns:**  
The text with all occurrences of the patterns replaced with their corresponding
replacement text.

**Example:**  
```tomo
>> "A <tag> & an amperand":replace_all({
    $/&/: "&amp;",
    $/</: "&lt;",
    $/>/: "&gt;",
    $/"/: "&quot",
    $/'/: "&#39;",
}
= "A &lt;tag&gt; &amp; an ampersand"

>> "Hello":replace_all({$/{lower}/:"[@]", $/{upper}/:"{@}"}, placeholder=$/@/)
= "{H}[ello]"
```

---

## `replace_chain`

**Description:**  
Takes an array of patterns and a corresponding array of replacement texts and
if all patterns in the patterns array match _consecutively_, then the
replacement texts are substituted for the corresponding matches. This is useful
if you want to replace parts of a match with new text while leaving other parts
unchanged.

As as special case, if a pattern `$/?/` is sandwiched between corresponding
matching quotes or matching braces, it will match the inside part of the nested
or quoted pair.

See [Patterns](#patterns) for more information about patterns.

**Usage:**  
```tomo
replace_chain(patterns:[Pattern], replacements:[Text], placeholder: Pattern = $//) -> Text
```

**Parameters:**

- `text`: The text in which to perform replacements.
- `patterns`: An array of patterns to be matched consecutively.
- `replacements`: An array of replacement texts corresponding to each pattern.
  This must be the same length as `patterns` or an error will be raised.
- `placeholder`: If non-empty, the replacement text will have occurrences of
  the placeholder pattern replaced with the matching text.

**Returns:**  
The text with all occurrences of the patterns replaced with their corresponding
replacement text.

**Example:**  
```tomo
>> "  foo(blah(), 2)  ":replace_chain([$/foo(/, $/?/, $/)/], ["baz(", "@", ")"], placeholder=$/@/)
= "  baz(blah(), 2)  "

>> "  foo.field_name  ":replace_chain([$/{id}/, $/.field_name/], ["@", ".other_field"], placeholder=$/@/)
= "  foo.other_field  "
```

---

## `split`

**Description:**  
Splits the text into an array of substrings based on a pattern.
See [Patterns](#patterns) for more information about patterns.

**Usage:**  
```tomo
split(text: Text, pattern: Text = "") -> [Text]
```

**Parameters:**

- `text`: The text to be split.
- `pattern`: The pattern used to split the text. If the pattern is the empty
  string, the text will be split into individual grapheme clusters.

**Returns:**  
An array of substrings resulting from the split.

**Example:**  
```tomo
>> "one,two,three":split(",")
= ["one", "two", "three"]

>> "abc":split()
= ["a", "b", "c"]

>> "a    b  c":split("{space}")
= ["a", "b", "c"]

>> "a,b,c,":split(",")
= ["a", "b", "c", ""]
```

---

## `title`

**Description:**  
Converts the text to title case (capitalizing the first letter of each word).

**Usage:**  
```tomo
title(text: Text) -> Text
```

**Parameters:**

- `text`: The text to be converted to title case.

**Returns:**  
The text in title case.

**Example:**  
```tomo
>> "amélie":title()
= "Amélie"
```

---

## `upper`

**Description:**  
Converts all characters in the text to uppercase.

**Usage:**  
```tomo
upper(text: Text) -> Text
```

**Parameters:**

- `text`: The text to be converted to uppercase.

**Returns:**  
The uppercase version of the text.

**Example:**  
```tomo
>> "amélie":upper()
= "AMÉLIE"
```