def reflow(text):
    """
    Reformat CJK text according to its punctuation.

    Given a string, this function will reformat ("reflow") the text so that
    words and terms are not broken apart between lines. The function first
    strips out any leading margins as used by CBETA texts. It then adds an
    extra space following any short lines that might stand alone. Then it
    reformats the text according to horizontal spacing and punctuation.

    CBETA margin format: X01n0020_p0404a01(00)║

    """
    starters = '「『\u3000\t'
    enders = '：，；。？！」』.;:?!'
    specials = starters + enders + '\x1f'
    new_str = ''
    prev_c = '\x1f'
    for line in text.split('\n'):
        if '║' in line:
            line = line.split('║', 1)[-1]
        if line.startswith('\u3000') and len(line) < 17:
            line += '\u3000'
        for cur_c in line:
            if prev_c in enders and cur_c not in enders:
                new_str += '\n'
            elif cur_c in starters and prev_c not in specials:
                new_str += '\n'
            new_str += cur_c
            prev_c = cur_c
    if len(new_str) > 0 and new_str[-1] != '\n':
        new_str += '\n'
    return new_str
