Skip to content

Commit 91b102d

Browse files
authored
add doc.zero_width_string function
* add doc.zero_width_string function * add doc.zero_width_string example test * update changelog
1 parent 314f5ec commit 91b102d

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## Unreleased
44

55
- Remove the `doc.to_string_builder` method.
6+
- The `doc` module gains the `zero_width_string` function
67

78
## v1.3.0 - 2023-01-03
89

src/glam/doc.gleam

+23
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,29 @@ pub fn from_string(string: String) -> Document {
236236
Text(string, string.length(string))
237237
}
238238

239+
/// Turns a string into a document, without impacting in the line length in which
240+
/// the string is used.
241+
///
242+
/// This kind of string can be used to render non-visible characters
243+
/// e.g. ansi color codes
244+
///
245+
/// ## Examples
246+
///
247+
/// ```gleam
248+
/// // Should break in two lines, but doesn't because of the zero_width_string
249+
/// [
250+
/// zero_width_string("\u{001b}[1;31m"),
251+
/// from_string("I'm a red"),
252+
/// break(", ", ","),
253+
/// from_string("bold text"),
254+
/// ] |> concat |> group |> to_string(20)
255+
/// // -> "\u{001b}[1;31mI'm a red, bold text"
256+
/// ```
257+
///
258+
pub fn zero_width_string(string: String) -> Document {
259+
Text(string, 0)
260+
}
261+
239262
/// Allows the pretty printer to break the `break` documents inside the given
240263
/// group.
241264
///

test/glam/doc_test.gleam

+29
Original file line numberDiff line numberDiff line change
@@ -200,3 +200,32 @@ pub fn flex_break_with_group_and_nesting_test() {
200200
doc.to_string(list, 1)
201201
|> should.equal("[\n 1,\n 2,\n 3,\n 4,\n 5,\n]")
202202
}
203+
204+
pub fn zero_width_string_test() {
205+
let string_with_break_and_zero_string =
206+
[
207+
doc.from_string("doc"),
208+
doc.break(" ", ""),
209+
doc.from_string("with"),
210+
doc.break(" ", ""),
211+
doc.zero_width_string("zero width"),
212+
]
213+
|> doc.concat
214+
|> doc.group
215+
216+
doc.to_string(string_with_break_and_zero_string, 10)
217+
|> should.equal("doc with zero width")
218+
}
219+
220+
pub fn zero_width_string_example_test() {
221+
[
222+
doc.zero_width_string("\u{001b}[1;31m"),
223+
doc.from_string("I'm a red"),
224+
doc.break(", ", ","),
225+
doc.from_string("bold text"),
226+
]
227+
|> doc.concat
228+
|> doc.group
229+
|> doc.to_string(20)
230+
|> should.equal("\u{001b}[1;31mI'm a red, bold text")
231+
}

0 commit comments

Comments
 (0)