cjkfmt 0.0.7

Formatter for CJK text files
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
//! Define [`LineBreaker`] that finds a line break with adherence to kinsoku rule.
use unicode_linebreak::{BreakClass, break_property};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use crate::{_log::test_log, config::AmbiguousWidth};

/// Grapheme clusters prohibited at the start of a line.
pub const PROHIBITED_START: &str = ")]}〕〉》」』】〙〗〟'\"⦆»\
    ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻\
    ‐゠–〜\
    ? ! ‼ ⁇ ⁈ ⁉\
    ・、:;,\
    。.";

/// Grapheme clusters prohibited at the end of a line.
pub const PROHIBITED_END: &str = "([{〔〈《「『【〘〖〝'\"⦅«";

/// A line break point detected by [`LineBreaker`].
#[derive(Debug, PartialEq, Eq)]
pub enum BreakPoint {
    /// A line break caused by an EOL code such as CR+LF or LF.
    EndOfLine(usize),

    /// A line break detected by the [`LineBreaker`].
    ///
    /// This is a point where the line exceeds the maximum width and should be
    /// wrapped. `WrapPoint` contains the following fields:
    ///
    /// - `overflow_pos`: The position of the character that caused the overflow.
    ///   This is the byte index of the character in the original line.
    /// - `adjustment`: The number of bytes to backtrack to find an acceptable break point.
    WrapPoint {
        overflow_pos: usize,
        adjustment: usize,
    },

    /// End of the input text.
    EndOfText(usize),
}

/// Find a line break with adherence to kinsoku rule.
///
/// Use [`LineBreaker::builder`] to create a new instance of [`LineBreaker`].
#[derive(Debug)]
pub struct LineBreaker {
    ambiguous_width: AmbiguousWidth,
    max_width: u32,
    prohibited_start: Vec<String>,
    prohibited_end: Vec<String>,
}

/// Build a [`LineBreaker`].
pub struct LineBreakerBuilder {
    line_breaker: LineBreaker,
}

impl LineBreakerBuilder {
    /// Sets how to treat width of characters in the Ambiguous category.
    ///
    /// The width is measured in terms of fullwidth characters.
    /// For example, the width of "あ" is 2, and the width of "a" is 1.
    pub fn ambiguous_width(mut self, ambiguous_width: AmbiguousWidth) -> Self {
        self.line_breaker.ambiguous_width = ambiguous_width;
        self
    }

    /// Sets the maximum width of a line.
    ///
    /// The width is measured in terms of fullwidth characters.
    /// For example, the width of "あ" is 2, and the width of "a" is 1.
    pub fn max_width(mut self, max_width: u32) -> Self {
        self.line_breaker.max_width = max_width;
        self
    }

    /// Sets the grapheme clusters that are prohibited at the start of a line.
    ///
    /// This method replaces the default set of prohibited grapheme clusters.
    fn prohibited_start<S: AsRef<str>>(mut self, graphemes: S) -> Self {
        self.line_breaker.prohibited_start = graphemes
            .as_ref()
            .graphemes(true)
            .map(|s| s.to_owned())
            .collect();
        self
    }

    /// Sets the grapheme clusters that are prohibited at the end of a line.
    ///
    /// This method replaces the default set of prohibited grapheme clusters.
    fn prohibited_end<S: AsRef<str>>(mut self, graphemes: S) -> Self {
        self.line_breaker.prohibited_end = graphemes
            .as_ref()
            .graphemes(true)
            .map(|s| s.to_string())
            .collect();
        self
    }

    /// Finish building and returns a [`LineBreaker`].
    pub fn build(self) -> anyhow::Result<LineBreaker> {
        if self.line_breaker.max_width < 2 {
            anyhow::bail!(
                "max_width out of range: {} (cannot be below 2)",
                self.line_breaker.max_width
            )
        } else {
            Ok(self.line_breaker)
        }
    }
}

impl LineBreaker {
    /// Builds a new [`LineBreaker`] with default settings.
    pub fn builder() -> LineBreakerBuilder {
        LineBreakerBuilder {
            line_breaker: LineBreaker {
                ambiguous_width: AmbiguousWidth::Wide,
                max_width: 80,
                prohibited_start: Vec::new(),
                prohibited_end: Vec::new(),
            },
        }
        .prohibited_start(PROHIBITED_START)
        .prohibited_end(PROHIBITED_END)
    }

    /// Returns how to treat width of characters in the Ambiguous category.
    /// Returns the maximum width of a line.
    pub fn max_width(&self) -> u32 {
        self.max_width
    }

    // TODO: Remove this method
    fn prohibited_start<'a>(&'a self) -> Vec<&'a str> {
        self.prohibited_start
            .iter()
            .map(|s| s.as_ref())
            .collect::<Vec<&'a str>>()
    }

    fn prohibited_end<'a>(&'a self) -> Vec<&'a str> {
        self.prohibited_end
            .iter()
            .map(|s| s.as_ref())
            .collect::<Vec<&'a str>>()
    }

    /// Finds a line break in the given line and returns its byte index.
    #[allow(clippy::collapsible_if)]
    pub fn next_line_break(&self, line: &str) -> BreakPoint {
        test_log!("next_line_break() {:?}", line);

        let mut graphemes: Vec<&str> = Vec::with_capacity(128);
        let mut acc_width = 0u32;
        for (i, grapheme) in line.grapheme_indices(true) {
            // Stop if reached EOL.
            if grapheme == "\r" || grapheme == "\n" {
                test_log!("  {i:02} {:?} eol", grapheme);
                return BreakPoint::EndOfLine(i + 1);
            } else if grapheme == "\r\n" {
                test_log!("  {i:02} {:?} eol", grapheme);
                return BreakPoint::EndOfLine(i + 2);
            }

            // Test whether rendering this grapheme cluster will exceed the limit or not
            let width = if self.ambiguous_width == AmbiguousWidth::Narrow {
                grapheme.width()
            } else {
                grapheme.width_cjk()
            } as u32;
            if self.max_width < acc_width + width {
                test_log!(
                    "  {i:02} {:?} # max_width < acc_width + width ({} < {})",
                    grapheme,
                    self.max_width,
                    acc_width + width
                );
                if let Some(nbytes_seek_back) =
                    self.num_bytes_to_seek_back(graphemes.as_slice(), grapheme)
                {
                    test_log!(
                        "  split at {:02} --> {:?}",
                        i - nbytes_seek_back,
                        line.split_at_checked(i - nbytes_seek_back)
                            .expect("invalid split point")
                    );
                    return BreakPoint::WrapPoint {
                        overflow_pos: i,
                        adjustment: nbytes_seek_back,
                    };
                }
            }

            // Go to next grapheme cluster
            test_log!(
                "  {i:03} {grapheme:?} (acc_width+{width}: {})",
                acc_width + width
            );
            graphemes.push(grapheme);
            acc_width += width;
        }
        BreakPoint::EndOfText(line.len())
    }

    fn num_bytes_to_seek_back(
        &self,
        preceding_graphemes: &[&str],
        following_grapheme: &str,
    ) -> Option<usize> {
        debug_assert!(!preceding_graphemes.is_empty());

        let mut nbytes_to_rewind = 0;
        let mut following = following_grapheme;
        for grapheme in preceding_graphemes.iter().rev() {
            // Seek back if not breakable according to UAX#14
            if !is_breakable(grapheme, following) {
                let grapheme_len = grapheme.len();
                nbytes_to_rewind += grapheme_len;
                test_log!("    rewind {grapheme_len}: {grapheme:?} {following:?} (not breakable)",);
                following = grapheme;
                continue;
            }

            // Seek back if the preceding character is prohibited at line end
            if self.prohibited_end().contains(grapheme) {
                let grapheme_len = grapheme.len();
                nbytes_to_rewind += grapheme_len;
                test_log!("    rewind {grapheme_len}: {grapheme:?} {following:?} (prohibited_end)");
                following = grapheme;
                continue;
            }

            // Seek back if the following character is prohibited at line start
            if self.prohibited_start().contains(&following) {
                let grapheme_len = grapheme.len();
                nbytes_to_rewind += grapheme_len;
                test_log!(
                    "    rewind {grapheme_len}: {grapheme:?} {following:?} (prohibited_start)"
                );
                following = grapheme;
                continue;
            }

            test_log!("    break: {grapheme:?} {following:?}");
            return Some(nbytes_to_rewind);
        }
        test_log!("  cannot rewind anymore");
        None
    }
}

/// Check whether a line break is allowed between the given grapheme clusters.
///
/// This function is based on UAX#14 so kinsoku rules are not considered.
#[allow(clippy::let_and_return)]
fn is_breakable(preceding: &str, following: &str) -> bool {
    debug_assert!(!preceding.is_empty());
    debug_assert!(!following.is_empty());

    let preceding_break_property = preceding
        .chars()
        .last()
        .map(|c| break_property(c as u32))
        .expect("`preceding` must be non-empty");
    let following_break_property = following
        .chars()
        .next()
        .map(|c| break_property(c as u32))
        .expect("`following` must be non-empty");
    let breakable = match (preceding_break_property, following_break_property) {
        (BreakClass::After, _) => false,
        (_, BreakClass::Before) => false,
        (BreakClass::BeforeAndAfter, _) => false,
        (_, BreakClass::BeforeAndAfter) => false,
        (BreakClass::Alphabetic, BreakClass::Alphabetic) => false,
        (_, BreakClass::Space) => false,
        (_, _) => true,
    };
    // log!(
    //     "    {preceding:?}({:?}) {following:?}({:?}) --> {breakable}",
    //     preceding_break_property,
    //     following_break_property
    // );
    breakable
}

#[cfg(test)]
mod test {
    use super::*;
    use rstest::rstest;

    #[rstest]
    // not breakable between alphabetic characters
    #[case("a", "a", false)]
    #[case("a", "あ", true)]
    // not breakable before a space
    #[case("a", " ", false)]
    #[case(" ", "a", true)]
    fn is_breakable_normal(
        #[case] preceding: &str,
        #[case] following: &str,
        #[case] expected: bool,
    ) {
        assert_eq!(is_breakable(preceding, following), expected);
    }

    #[test]
    fn test_ambiguous_width() {
        for ambiguous_width in [AmbiguousWidth::Wide, AmbiguousWidth::Narrow] {
            let line_breaker = LineBreaker::builder()
                .ambiguous_width(ambiguous_width)
                .max_width(2)
                .build()
                .unwrap();

            assert_eq!(
                line_breaker.next_line_break("1a1a\n"),
                BreakPoint::WrapPoint {
                    overflow_pos: 2,
                    adjustment: 0
                },
            );
            assert_eq!(
                line_breaker.next_line_break("あa1a\n"),
                BreakPoint::WrapPoint {
                    overflow_pos: 3,
                    adjustment: 0
                },
            );
            assert_eq!(
                line_breaker.next_line_break("※a1a\n"),
                BreakPoint::WrapPoint {
                    overflow_pos: match ambiguous_width {
                        AmbiguousWidth::Narrow => 4,
                        AmbiguousWidth::Wide => 3,
                    },
                    adjustment: 0
                },
            );
        }
        assert!(LineBreaker::builder().max_width(1).build().is_err());
        assert!(LineBreaker::builder().max_width(2).build().is_ok());
        assert!(LineBreaker::builder().max_width(3).build().is_ok());
    }

    #[test]
    fn max_width() {
        assert!(LineBreaker::builder().max_width(0).build().is_err());
        assert!(LineBreaker::builder().max_width(1).build().is_err());
        assert!(LineBreaker::builder().max_width(2).build().is_ok());
        assert!(LineBreaker::builder().max_width(3).build().is_ok());
    }

    #[rstest]
    #[case(10, "あ「い」う", BreakPoint::EndOfText(15))]
    #[case(9, "あ「い」う", BreakPoint::WrapPoint { overflow_pos: 12, adjustment: 0 })]
    #[case(8, "あ「い」う", BreakPoint::WrapPoint { overflow_pos: 12, adjustment: 0 })]
    #[case(7, "あ「い」う", BreakPoint::WrapPoint { overflow_pos: 9, adjustment: 6 })]
    #[case(6, "あ「い」う", BreakPoint::WrapPoint { overflow_pos: 9, adjustment: 6 })]
    #[case(5, "あ「い」う", BreakPoint::WrapPoint { overflow_pos: 6, adjustment: 3 })]
    #[case(4, "あ「い」う", BreakPoint::WrapPoint { overflow_pos: 6, adjustment: 3 })]
    #[case(3, "あ「い」う", BreakPoint::WrapPoint { overflow_pos: 3, adjustment: 0 })]
    #[case(2, "あ「い」う", BreakPoint::WrapPoint { overflow_pos: 3, adjustment: 0 })]
    fn next_line_break(
        #[case] max_width: u32,
        #[case] line: &str,
        #[case] expected: BreakPoint,
    ) -> anyhow::Result<()> {
        let line_breaker = LineBreaker::builder().max_width(max_width).build()?;
        let actual = line_breaker.next_line_break(line);
        assert_eq!(expected, actual);
        Ok(())
    }

    #[rstest]
    #[case(2, "foo\rbar", BreakPoint::EndOfLine(4))]
    #[case(3, "foo\rbar", BreakPoint::EndOfLine(4))]
    #[case(4, "foo\rbar", BreakPoint::EndOfLine(4))]
    #[case(5, "foo\rbar", BreakPoint::EndOfLine(4))]
    #[case(5, "foo\nbar", BreakPoint::EndOfLine(4))]
    #[case(5, "foo\r\nbar", BreakPoint::EndOfLine(5))]
    fn next_line_break_eol(
        #[case] max_width: u32,
        #[case] line: &str,
        #[case] expected: BreakPoint,
    ) -> anyhow::Result<()> {
        let line_breaker = LineBreaker::builder().max_width(max_width).build()?;
        let actual = line_breaker.next_line_break(line);
        assert_eq!(expected, actual);
        Ok(())
    }

    // Cat + ZWJ + Black Large Square
    #[rstest]
    #[case(8, "あ「🐈‍⬛」う", BreakPoint::WrapPoint { overflow_pos: 19, adjustment: 0 })]
    #[case(7, "あ「🐈‍⬛」う", BreakPoint::WrapPoint { overflow_pos: 16, adjustment: 13 })]
    fn next_line_break_composite(
        #[case] max_width: u32,
        #[case] line: &str,
        #[case] expected: BreakPoint,
    ) -> anyhow::Result<()> {
        let line_breaker = LineBreaker::builder().max_width(max_width).build()?;
        let actual = line_breaker.next_line_break(line);
        assert_eq!(expected, actual);
        Ok(())
    }

    #[rstest]
    #[case(11, "あfoo barい", BreakPoint::EndOfText(13))]
    #[case(10, "あfoo barい", BreakPoint::WrapPoint { overflow_pos: 10, adjustment: 0 })]
    #[case(9, "あfoo barい", BreakPoint::WrapPoint { overflow_pos: 10, adjustment: 0 })]
    #[case(8, "あfoo barい", BreakPoint::WrapPoint { overflow_pos: 9, adjustment: 2 })]
    #[case(7, "あfoo barい", BreakPoint::WrapPoint { overflow_pos: 8, adjustment: 1 })]
    #[case(6, "あfoo barい", BreakPoint::WrapPoint { overflow_pos: 7, adjustment: 0 })]
    #[case(5, "あfoo barい", BreakPoint::WrapPoint { overflow_pos: 6, adjustment: 3 })]
    #[case(4, "あfoo barい", BreakPoint::WrapPoint { overflow_pos: 5, adjustment: 2 })]
    #[case(3, "あfoo barい", BreakPoint::WrapPoint { overflow_pos: 4, adjustment: 1 })]
    #[case(2, "あfoo barい", BreakPoint::WrapPoint { overflow_pos: 3, adjustment: 0 })]
    fn next_line_break_western_word_wrap(
        #[case] max_width: u32,
        #[case] line: &str,
        #[case] expected: BreakPoint,
    ) -> anyhow::Result<()> {
        let line_breaker = LineBreaker::builder().max_width(max_width).build()?;
        let actual = line_breaker.next_line_break(line);
        assert_eq!(expected, actual);
        Ok(())
    }

    #[rstest]
    #[case(8, "あ「い」", "う", Some(0))]
    #[case(6, "あ「い", "」", Some(6))]
    #[case(3, "あ「", "い", Some(3))]
    #[case(2, "あ", "「", Some(0))]
    #[case(2, "」", "「", Some(0))]
    #[case(2, "「", "「", None)]
    fn num_bytes_to_seek_back(
        #[case] max_width: u32,
        #[case] preceding_graphemes: &str,
        #[case] following_grapheme: &str,
        #[case] expected: Option<usize>,
    ) -> anyhow::Result<()> {
        let preceding_graphemes: Vec<&str> = preceding_graphemes.graphemes(true).collect();
        let line_breaker = LineBreaker::builder().max_width(max_width).build()?;

        let actual = line_breaker.num_bytes_to_seek_back(&preceding_graphemes, following_grapheme);
        assert_eq!(actual, expected);

        Ok(())
    }
}