summaryrefslogtreecommitdiff
path: root/bzrlib/utextwrap.py
blob: 14cb0f9af99e85ed5ed9e55cdd8efd29154a1d4f (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
# Copyright (C) 2011 Canonical Ltd
#
# UTextWrapper._handle_long_word, UTextWrapper._wrap_chunks,
# UTextWrapper._fix_sentence_endings, wrap and fill is copied from Python's
# textwrap module (under PSF license) and modified for support CJK.
# Original Copyright for these functions:
#
# Copyright (C) 1999-2001 Gregory P. Ward.
# Copyright (C) 2002, 2003 Python Software Foundation.
#
# Written by Greg Ward <gward@python.net>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

from __future__ import absolute_import

import sys
import textwrap
from unicodedata import east_asian_width as _eawidth

from bzrlib import osutils

__all__ = ["UTextWrapper", "fill", "wrap"]

class UTextWrapper(textwrap.TextWrapper):
    """
    Extend TextWrapper for Unicode.

    This textwrapper handles east asian double width and split word
    even if !break_long_words when word contains double width
    characters.

    :param ambiguous_width: (keyword argument) width for character when
                            unicodedata.east_asian_width(c) == 'A'
                            (default: 1)

    Limitations:
    * expand_tabs doesn't fixed. It uses len() for calculating width
      of string on left of TAB.
    * Handles one codeunit as a single character having 1 or 2 width.
      This is not correct when there are surrogate pairs, combined
      characters or zero-width characters.
    * Treats all asian character are line breakable. But it is not
      true because line breaking is prohibited around some characters.
      (For example, breaking before punctation mark is prohibited.)
      See UAX # 14 "UNICODE LINE BREAKING ALGORITHM"
    """

    def __init__(self, width=None, **kwargs):
        if width is None:
            width = (osutils.terminal_width() or
                        osutils.default_terminal_width) - 1

        ambi_width = kwargs.pop('ambiguous_width', 1)
        if ambi_width == 1:
            self._east_asian_doublewidth = 'FW'
        elif ambi_width == 2:
            self._east_asian_doublewidth = 'FWA'
        else:
            raise ValueError("ambiguous_width should be 1 or 2")

        # No drop_whitespace param before Python 2.6 it was always dropped
        if sys.version_info < (2, 6):
            self.drop_whitespace = kwargs.pop("drop_whitespace", True)
            if not self.drop_whitespace:
                raise ValueError("TextWrapper version must drop whitespace")
        textwrap.TextWrapper.__init__(self, width, **kwargs)

    def _unicode_char_width(self, uc):
        """Return width of character `uc`.

        :param:     uc      Single unicode character.
        """
        # 'A' means width of the character is not be able to determine.
        # We assume that it's width is 2 because longer wrap may over
        # terminal width but shorter wrap may be acceptable.
        return (_eawidth(uc) in self._east_asian_doublewidth and 2) or 1

    def _width(self, s):
        """Returns width for s.

        When s is unicode, take care of east asian width.
        When s is bytes, treat all byte is single width character.
        """
        charwidth = self._unicode_char_width
        return sum(charwidth(c) for c in s)

    def _cut(self, s, width):
        """Returns head and rest of s. (head+rest == s)

        Head is large as long as _width(head) <= width.
        """
        w = 0
        charwidth = self._unicode_char_width
        for pos, c in enumerate(s):
            w += charwidth(c)
            if w > width:
                return s[:pos], s[pos:]
        return s, u''

    def _fix_sentence_endings(self, chunks):
        """_fix_sentence_endings(chunks : [string])

        Correct for sentence endings buried in 'chunks'.  Eg. when the
        original text contains "... foo.\nBar ...", munge_whitespace()
        and split() will convert that to [..., "foo.", " ", "Bar", ...]
        which has one too few spaces; this method simply changes the one
        space to two.

        Note: This function is copied from textwrap.TextWrap and modified
        to use unicode always.
        """
        i = 0
        L = len(chunks)-1
        patsearch = self.sentence_end_re.search
        while i < L:
            if chunks[i+1] == u" " and patsearch(chunks[i]):
                chunks[i+1] = u"  "
                i += 2
            else:
                i += 1

    def _handle_long_word(self, chunks, cur_line, cur_len, width):
        # Figure out when indent is larger than the specified width, and make
        # sure at least one character is stripped off on every pass
        if width < 2:
            space_left = chunks[-1] and self._width(chunks[-1][0]) or 1
        else:
            space_left = width - cur_len

        # If we're allowed to break long words, then do so: put as much
        # of the next chunk onto the current line as will fit.
        if self.break_long_words:
            head, rest = self._cut(chunks[-1], space_left)
            cur_line.append(head)
            if rest:
                chunks[-1] = rest
            else:
                del chunks[-1]

        # Otherwise, we have to preserve the long word intact.  Only add
        # it to the current line if there's nothing already there --
        # that minimizes how much we violate the width constraint.
        elif not cur_line:
            cur_line.append(chunks.pop())

        # If we're not allowed to break long words, and there's already
        # text on the current line, do nothing.  Next time through the
        # main loop of _wrap_chunks(), we'll wind up here again, but
        # cur_len will be zero, so the next line will be entirely
        # devoted to the long word that we can't handle right now.

    def _wrap_chunks(self, chunks):
        lines = []
        if self.width <= 0:
            raise ValueError("invalid width %r (must be > 0)" % self.width)

        # Arrange in reverse order so items can be efficiently popped
        # from a stack of chucks.
        chunks.reverse()

        while chunks:

            # Start the list of chunks that will make up the current line.
            # cur_len is just the length of all the chunks in cur_line.
            cur_line = []
            cur_len = 0

            # Figure out which static string will prefix this line.
            if lines:
                indent = self.subsequent_indent
            else:
                indent = self.initial_indent

            # Maximum width for this line.
            width = self.width - len(indent)

            # First chunk on line is whitespace -- drop it, unless this
            # is the very beginning of the text (ie. no lines started yet).
            if self.drop_whitespace and chunks[-1].strip() == '' and lines:
                del chunks[-1]

            while chunks:
                # Use _width instead of len for east asian width
                l = self._width(chunks[-1])

                # Can at least squeeze this chunk onto the current line.
                if cur_len + l <= width:
                    cur_line.append(chunks.pop())
                    cur_len += l

                # Nope, this line is full.
                else:
                    break

            # The current line is full, and the next chunk is too big to
            # fit on *any* line (not just this one).
            if chunks and self._width(chunks[-1]) > width:
                self._handle_long_word(chunks, cur_line, cur_len, width)

            # If the last chunk on this line is all whitespace, drop it.
            if self.drop_whitespace and cur_line and not cur_line[-1].strip():
                del cur_line[-1]

            # Convert current line back to a string and store it in list
            # of all lines (return value).
            if cur_line:
                lines.append(indent + u''.join(cur_line))

        return lines

    def _split(self, text):
        chunks = textwrap.TextWrapper._split(self, unicode(text))
        cjk_split_chunks = []
        for chunk in chunks:
            prev_pos = 0
            for pos, char in enumerate(chunk):
                if self._unicode_char_width(char) == 2:
                    if prev_pos < pos:
                        cjk_split_chunks.append(chunk[prev_pos:pos])
                    cjk_split_chunks.append(char)
                    prev_pos = pos+1
            if prev_pos < len(chunk):
                cjk_split_chunks.append(chunk[prev_pos:])
        return cjk_split_chunks

    def wrap(self, text):
        # ensure text is unicode
        return textwrap.TextWrapper.wrap(self, unicode(text))

# -- Convenience interface ---------------------------------------------

def wrap(text, width=None, **kwargs):
    """Wrap a single paragraph of text, returning a list of wrapped lines.

    Reformat the single paragraph in 'text' so it fits in lines of no
    more than 'width' columns, and return a list of wrapped lines.  By
    default, tabs in 'text' are expanded with string.expandtabs(), and
    all other whitespace characters (including newline) are converted to
    space.  See TextWrapper class for available keyword args to customize
    wrapping behaviour.
    """
    return UTextWrapper(width=width, **kwargs).wrap(text)

def fill(text, width=None, **kwargs):
    """Fill a single paragraph of text, returning a new string.

    Reformat the single paragraph in 'text' to fit in lines of no more
    than 'width' columns, and return a new string containing the entire
    wrapped paragraph.  As with wrap(), tabs are expanded and other
    whitespace characters converted to space.  See TextWrapper class for
    available keyword args to customize wrapping behaviour.
    """
    return UTextWrapper(width=width, **kwargs).fill(text)