Merge lp:~songofacandy/bzr/i18n-utextwrap into lp:bzr

Proposed by methane
Status: Merged
Approved by: Martin Packman
Approved revision: no longer in the source branch.
Merged at revision: 5874
Proposed branch: lp:~songofacandy/bzr/i18n-utextwrap
Merge into: lp:bzr
Diff against target: 492 lines (+472/-0)
3 files modified
bzrlib/tests/__init__.py (+1/-0)
bzrlib/tests/test_utextwrap.py (+207/-0)
bzrlib/utextwrap.py (+264/-0)
To merge this branch: bzr merge lp:~songofacandy/bzr/i18n-utextwrap
Reviewer Review Type Date Requested Status
Martin Packman (community) Approve
Vincent Ladeuil Approve
Review via email: mp+59950@code.launchpad.net

Commit message

Add support for double width characters to textwrap.

Description of the change

I18n part 1
textwrap supports double width characters.

To post a comment you must log in.
Revision history for this message
Vincent Ladeuil (vila) wrote :

Haaa, far better :) Thanks a lot !

The tests are a good start but wrap probably deserve more of them given its internal complexity and fill should probably receive some too. Finally one test demonstrating that the width is correctly handled would help (the idea is to make it easier later to debug specific areas of the code by having tests that already exercise it. That makes far easier to debug the code when you didn't write it yourself).

  ./bzr selftest -s bt.test_utext --coverage utext

will help you ensuring a minimal coverage (look into utext/bzrlib.utextwrap.cover).

I just did, so if indeed 'fill' is not tested, there is only a few spots that aren't in 'wrap' so you're really close already. (Forgive my ignorance, but is 'Good Morning' already on multiple lines in Japanese ?).

I'll put the review into 'work in progress', don't forget to set it back to 'NeedsReview' when needed.

review: Needs Fixing
Revision history for this message
Alexander Belchenko (bialix) wrote :

On Windows osutils.terminal_width() returns the real terminal width, but
we need (osutils.terminal_width()-1) otherwise user will see extra blank
line when line filled up to that limit.

Revision history for this message
Vincent Ladeuil (vila) wrote :

> On Windows osutils.terminal_width() returns the real terminal width, but
> we need (osutils.terminal_width()-1) otherwise user will see extra blank
> line when line filled up to that limit.

Right. We need tests for that or we'll keep having this discussion. In any case, the windows implementation of osutils.terminal_width should take that into account so this proposal should have to care about it.

Do we have a bug filed for that ?

Revision history for this message
methane (songofacandy) wrote :

Thank you for your review, Vincent.

> Haaa, far better :) Thanks a lot !
>
> The tests are a good start but wrap probably deserve more of them given its
> internal complexity and fill should probably receive some too. Finally one
> test demonstrating that the width is correctly handled would help (the idea is
> to make it easier later to debug specific areas of the code by having tests
> that already exercise it. That makes far easier to debug the code when you
> didn't write it yourself).
>
> ./bzr selftest -s bt.test_utext --coverage utext
> will help you ensuring a minimal coverage (look into
> utext/bzrlib.utextwrap.cover).
>
> I just did, so if indeed 'fill' is not tested, there is only a few spots that
> aren't in 'wrap' so you're really close already.

Okey, I've added many tests and fixed minor bug found by the test.
I make UTextWrap's private methods compatible to TextWrap and
run test_textwrap on UTextWrap to ensure no regression with
single byte texts.

> (Forgive my ignorance, but is
> 'Good Morning' already on multiple lines in Japanese ?).

No, it is 4 grams word. O-HA-YO-U and usually on one line.
But we don't use word separator like whiteespace and
can split any place. (There are some exception but handling
these exception is bit hard.)

> I'll put the review into 'work in progress', don't forget to set it back to
> 'NeedsReview' when needed.

I've got ready.

Revision history for this message
Alexander Belchenko (bialix) wrote :

Vincent Ladeuil пишет:
>> On Windows osutils.terminal_width() returns the real terminal width, but
>> we need (osutils.terminal_width()-1) otherwise user will see extra blank
>> line when line filled up to that limit.
>
> Right. We need tests for that or we'll keep having this discussion. In any case, the windows implementation of osutils.terminal_width should take that into account so this proposal should have to care about it.
>
> Do we have a bug filed for that ?

I don't think so but sometimes we talked about this issue with you in
IRC, cause it affects selftest output.

--
All the dude wanted was his rug back

Revision history for this message
Vincent Ladeuil (vila) wrote :

> I don't think so but sometimes we talked about this issue with you in
> IRC, cause it affects selftest output.

Yeah I remember the discussions, but as I have never been able to reproduce the issue myself, filing a bug with a recipe will help (hint, hint, nudge, nudge ;)

Revision history for this message
Alexander Belchenko (bialix) wrote :

> > I don't think so but sometimes we talked about this issue with you in
> > IRC, cause it affects selftest output.
>
> Yeah I remember the discussions, but as I have never been able to reproduce
> the issue myself, filing a bug with a recipe will help (hint, hint, nudge,
> nudge ;)

Well, if you're asking then I'm doing :-)

Revision history for this message
Vincent Ladeuil (vila) wrote :

> Okey, I've added many tests and fixed minor bug found by the test.

Thanks and yeah for tests finding bugs \o/

> I make UTextWrap's private methods compatible to TextWrap and
> run test_textwrap on UTextWrap to ensure no regression with
> single byte texts.

Excellent, also I just noticed a couple of issues with the way you write your tests.

The rule is that we do assert(expected, actual). While this may not be true for every test, that's what we aim for.

We also aim at making tests as focused as possible, so some tests are worth splitting.

Finally, overriding symbols as you do while reusing the python tests leave them overriden after the tests are run, not a big deal here but just in case, it's better to use overrideAttr to ensure they are restored.

I've made those changes in lp:~vila/bzr/i18n-utextwrap , you may merge that if you agree with them and put the proposal into 'NeedsReview' again for final approval.

>
> > (Forgive my ignorance, but is
> > 'Good Morning' already on multiple lines in Japanese ?).
>
> No, it is 4 grams word. O-HA-YO-U and usually on one line.
> But we don't use word separator like whiteespace

Doh ! Of course ! I never thought about that...

> and
> can split any place. (There are some exception but handling
> these exception is bit hard.)

Ok, we can deal with that later if needed.

review: Needs Fixing
Revision history for this message
methane (songofacandy) wrote :

I've seen your fixes and merged it. Thank you.

Revision history for this message
Vincent Ladeuil (vila) wrote :

mgz said he'll do a second review, I'm fine with the proposal myself.

review: Approve
Revision history for this message
Martin Packman (gz) wrote :
Download full text (4.7 KiB)

Good work tackling this, reading TR14 again reminds me how not-fun all the details are. I think your overall approach of trying extend the existing stdlib functionality just enough for bzr is sensible. We currently have en, es, ja, and ru docs so there isn't any need to deal with esoteric rules for other languages yet.

Various notes and nitpicks on the diff follow. The main thing that needs fixing is that wrapping for Russian (and Greek) will follow east asian style with this change rather than western, and width measurement will be wrong in those cases. The easiest way to fix this is debatable, I'd be tempted to try and use the language as an input to change the text wrapping behaviour, and possibly the codepage for the width measurement.

general
=======

I find the tests a little hard to follow, but they look like a realy good start. Currently only hiragana and basic latin are covered, which is why the cyrillic and greek problems aren't apparent.

+# Copyright (C) 2011 Canonical Ltd

For bzrlib.utextwrap this line possibly wants the dates and names from textwrap.py as you note later that some code comes from that module.

+ if self.drop_whitespace and chunks[-1].strip() == '' and lines:

The `drop_whitespace` param is 2.6 or later only:

<http://docs.python.org/library/textwrap.html#textwrap.TextWrapper.drop_whitespace>

This is likely a feature bzr doesn't need, but it's not hard to add a little version check, pull <lp:~gz/bzr/tweak_utextwrap> for a fix.

It looks like the `expand_tabs` param won't work correctly for ideographic text as the `_munge_whitespace` method isn't overridden and it uses `unicode.expandtabs` which does the wrong measurement for tab stops. This probably also a feature bzr doesn't need, but the limitation should be documented.

str vs. unicode
===============

Is there any reason to support non-unicode strings in this class? Is is a requirement for your neat trick of running the Python textwrap tests against this module too?

+ if isinstance(s, str):
+ return len(s)
+ assert isinstance(s, unicode)

The two blocks like this in the private `_width` and `_cut` functions would ideally not be needed, the public entrance points should ensure the string is unicode. Currently, they look like they'll just silently do the wrong thing for non-ascii byte strings.

+ def _split(self, text):
+ chunks = textwrap.TextWrapper._split(self, unicode(text))

This is also a private method so shouldn't need to convert the argument, the callers should just use the right object.

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

In the public interface this is a reasonable way to support ascii-only byte strings and a convenience for callers, other parts of bzrlib do a similar thing. The main issue is that it's easy for callers to get away with doing the wrong thing, but that's not much of a concern here as it should be obvious when non-english text is passed.

east_asian_width
================

The main problem comes from this logic:

+ w += (c in 'FWA' and 2) or 1
...
+ w += (_eawidth(c) in 'FWA' and 2) or 1
...
+ ...

Read more...

Revision history for this message
Martin Packman (gz) :
review: Needs Fixing
Revision history for this message
John A Meinel (jameinel) wrote :

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 5/7/2011 11:28 PM, Martin [gz] wrote:
> Review: Needs Fixing
>

I just want us to remember the rules for reviewing:

 Is it better than what we have, and doesn't reduce test coverage.

Nowhere in there is "Is it perfect".

I don't understand enough here to be able to say where things are at.
But if the current code is an improvement over our existing logic, it
can be landed into core, *and improved from there*, rather than stalling
the work at the review stage.

John
=:->
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAk3GS7oACgkQJdeBCYSNAAP75ACeL6TyvVYtwsfo8cc6CACpPFya
t4oAoKZo3y3voqNyjWsd3PcwqZkCtVSC
=Rs3O
-----END PGP SIGNATURE-----

Revision history for this message
methane (songofacandy) wrote :
Download full text (4.9 KiB)

> +# Copyright (C) 2011 Canonical Ltd
>
> For bzrlib.utextwrap this line possibly wants the dates and names from
> textwrap.py as you note later that some code comes from that module.

I've copied Copyright lines from textwrap.

> + if self.drop_whitespace and chunks[-1].strip() == '' and lines:
>
> The `drop_whitespace` param is 2.6 or later only:
>
> <http://docs.python.org/library/textwrap.html#textwrap.TextWrapper.drop_whites
> pace>
>
> This is likely a feature bzr doesn't need, but it's not hard to add a little
> version check, pull <lp:~gz/bzr/tweak_utextwrap> for a fix.

Thank you. I've merged it.

> It looks like the `expand_tabs` param won't work correctly for ideographic
> text as the `_munge_whitespace` method isn't overridden and it uses
> `unicode.expandtabs` which does the wrong measurement for tab stops. This
> probably also a feature bzr doesn't need, but the limitation should be
> documented.

Could you tell me what is the problem of `unicode.expandtabs`?
I haven't heard about that.

> str vs. unicode
> ===============
>
> Is there any reason to support non-unicode strings in this class? Is is a
> requirement for your neat trick of running the Python textwrap tests against
> this module too?
>
> + if isinstance(s, str):
> + return len(s)
> + assert isinstance(s, unicode)
>
> The two blocks like this in the private `_width` and `_cut` functions would
> ideally not be needed, the public entrance points should ensure the string is
> unicode. Currently, they look like they'll just silently do the wrong thing
> for non-ascii byte strings.

I've removed `if isinstance(...`.

>
> + def _split(self, text):
> + chunks = textwrap.TextWrapper._split(self, unicode(text))
>
> This is also a private method so shouldn't need to convert the argument, the
> callers should just use the right object.

This private method is tested by test_textwrap and it passes byte string.
`unicode(text)` uses default encoding that is 'ascii' on most platform and
raises UnicodeDecodeError when we passes non-ascii string.

>
> + def wrap(self, text):
> + # ensure text is unicode
> + return textwrap.TextWrapper.wrap(self, unicode(text))
>
> In the public interface this is a reasonable way to support ascii-only byte
> strings and a convenience for callers, other parts of bzrlib do a similar
> thing. The main issue is that it's easy for callers to get away with doing the
> wrong thing, but that's not much of a concern here as it should be obvious
> when non-english text is passed.
>
>
> east_asian_width
> ================
>
> The main problem comes from this logic:
>
> + w += (c in 'FWA' and 2) or 1
> ...
> + w += (_eawidth(c) in 'FWA' and 2) or 1
> ...
> + if _eawidth(char) in 'FWA':
>
> Firstly, it's a bad thing that a similar-but different line appears three
> times. That's a sign a helper is needed.

I've split it.

>
> For width measurement, `in 'FWA'` isn't a bad check in an ideographic context,
> I have nearly the same logic in a script I use to work out indents in EUC-JP
> text with a `eawidth_map = {"F":2,"H":1,"W":2,"Na":1,"A":2,"N":1}` mapping.
>
> However...

Read more...

Revision history for this message
Martin Packman (gz) wrote :

> Nowhere in there is "Is it perfect".

Yes, there's a conflict between "writing everything I think of when I read through the code" and "being clear about what changes are needed so the code can land".

Avoiding a regression in how Russian is handled versus the default TextWrapper class is the main thing, but until there's some Russian help text written that's not actually fatal.

Revision history for this message
Martin Packman (gz) wrote :

Thanks for following up on this!

> Could you tell me what is the problem of `unicode.expandtabs`?
> I haven't heard about that.

It gets the tabulation wrong in this context, eg:

>>> s = u"English\ten\n日本語\tja"
>>> print s
English en
日本語 ja
>>> print s.expandtabs()
English en
日本語 ja

The help text we're dealing with doesn't use tabs for tables, so just noting the `expand_tabs` param may give surprising results is fine.

> > + if isinstance(s, str):
> > + return len(s)
> > + assert isinstance(s, unicode)
...
>
> I've removed `if isinstance(...`.

One thing I forgot to mention is that we can't use `assert` either, try `bzr selftest -s bt.test_source`, in these two cases just removing that statement should be fine.

> This private method is tested by test_textwrap and it passes byte string.
> `unicode(text)` uses default encoding that is 'ascii' on most platform and
> raises UnicodeDecodeError when we passes non-ascii string.

This is fine then.

> I think we can use i18n for it. For example, i18n module may be able to
> provide a
> function like:
>
> def get_ambiguous_width():
> if _installed_language in ('cn', 'ja', 'kr'):
> return 2
> else:
> return 1
>
> For now, I've stopped using utextwrap in bzrlib.help module.

That's the kind of thing I was thinking of, I'm not sure if gettext really makes it easy to do this. Passing the actual language to UTextWrapper would also allow it do vary the wrapping behaviour in other language-specific contexts. This isn't something that needs doing in this merge proposal.

> Splitting between combined character or surrogate pair may cause a problem.
> I'll try to make more clever line breaking if the problem happens.
> But if the problem happen, users can show English help (we shoud provide
> that way) so nothing goes worse than now.

Yes, this was just some extra thoughts and not any changes that needed doing now.

Revision history for this message
methane (songofacandy) wrote :

Thank you for teaching me.

I've added some docstring about limitations.
But I'm not good English writer. I hope someone rewrites docs written by me.

Revision history for this message
John C Barstow (jbowtie) wrote :

On Sun, May 8, 2011 at 9:24 AM, Martin [gz] <email address hidden> wrote:
> We currently have en, es, ja, and ru docs so there isn't any need to deal with esoteric rules for other languages yet.

In general i18n terms, the only thing really missing to round out our
sample is a bidirectional language like Arabic (ar), which would
expose any major weaknesses left in the logic. But I'm more than happy
to see this land.

Revision history for this message
Martin Packman (gz) wrote :

> One thing I forgot to mention is that we can't use `assert` either, try `bzr
> selftest -s bt.test_source`, in these two cases just removing that statement
> should be fine.

The asserts need removing before PQM will let this branch land.

Revision history for this message
methane (songofacandy) wrote :

> > One thing I forgot to mention is that we can't use `assert` either, try `bzr
> > selftest -s bt.test_source`, in these two cases just removing that statement
> > should be fine.
>
> The asserts need removing before PQM will let this branch land.

I've removed the asserts.

Revision history for this message
Vincent Ladeuil (vila) wrote :

@gz: Are you ok to land this now ?

Revision history for this message
Martin Packman (gz) wrote :

+ assert chunk # TextWrapper._split removes empty chunk

Need to remove that one too. Run `./bzr selftest -s bt.test_source` to make sure you've got them all.

With that done this should be fine to land, need to try it with some real translations to improve further probably.

Revision history for this message
methane (songofacandy) wrote :

> + assert chunk # TextWrapper._split removes empty chunk
>
> Need to remove that one too. Run `./bzr selftest -s bt.test_source` to make
> sure you've got them all.
>

Sorry, I removed last assert.
And run test_source then fix minor issue reported by the test.

Revision history for this message
Martin Packman (gz) wrote :

Okay, nearly there. Two tests from textwrapper that use `fix_sentence_endings=True` fail because of this code in the textwrap module which puts bytestrings in the chunks list:

    if chunks[i+1] == " " and pat.search(chunks[i]):
        chunks[i+1] = " "

Resulting in errors like:

Traceback (most recent call last):
  ...
  File "...\lib\test\test_textwrap.py", line 102, in test_fix_sentence_endings
    self.check(wrapper.wrap(text), expect)
  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 216, in wrap
    return textwrap.TextWrapper.wrap(self, unicode(text))
  File "...\lib\textwrap.py", line 321, in wrap
    return self._wrap_chunks(chunks)
  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 172, in _wrap_chunks
    l = self._width(chunks[-1])
  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 95, in _width
    return sum(charwidth(c) for c in s)
  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 95, in <genexpr>
    return sum(charwidth(c) for c in s)
  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 86, in _unicode_char_width
    return (_eawidth(uc) in self._east_asian_doublewidth and 2) or 1
TypeError: must be unicode, not str

Annoying. That option is pretty bogus anyway, I'd not mind just not supporting it. Otherwise _fix_sentence_endings needs overriding so it doesn't mix up types in the chunks list.

Revision history for this message
methane (songofacandy) wrote :

On Sat, May 14, 2011 at 10:04 PM, Martin [gz] <email address hidden> wrote:
> Okay, nearly there. Two tests from textwrapper that use `fix_sentence_endings=True` fail because of this code in the textwrap module which puts bytestrings in the chunks list:
>
>    if chunks[i+1] == " " and pat.search(chunks[i]):
>        chunks[i+1] = "  "
>
> Resulting in errors like:
>
> Traceback (most recent call last):
>  ...
>  File "...\lib\test\test_textwrap.py", line 102, in test_fix_sentence_endings
>    self.check(wrapper.wrap(text), expect)
>  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 216, in wrap
>    return textwrap.TextWrapper.wrap(self, unicode(text))
>  File "...\lib\textwrap.py", line 321, in wrap
>    return self._wrap_chunks(chunks)
>  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 172, in _wrap_chunks
>    l = self._width(chunks[-1])
>  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 95, in _width
>    return sum(charwidth(c) for c in s)
>  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 95, in <genexpr>
>    return sum(charwidth(c) for c in s)
>  File "...\i18n-utextwrap\bzrlib\utextwrap.py", line 86, in _unicode_char_width
>    return (_eawidth(uc) in self._east_asian_doublewidth and 2) or 1
> TypeError: must be unicode, not str
>
> Annoying. That option is pretty bogus anyway, I'd not mind just not supporting it. Otherwise _fix_sentence_endings needs overriding so it doesn't mix up types in the chunks list.

I've overrided the _fix_sentence_endings.

Why I miss the error is I used another Python environment when
removing cast to unicode.
To avoid this, I've added empty test case that raises TestSkipped when
test.test_textwrap
is unavailable.

> --
> https://code.launchpad.net/~songofacandy/bzr/i18n-utextwrap/+merge/59950
> You are the owner of lp:~songofacandy/bzr/i18n-utextwrap.
>

--
INADA Naoki  <email address hidden>

Revision history for this message
Martin Packman (gz) wrote :

Tests pass, looks time to try it out for real.

review: Approve
Revision history for this message
Vincent Ladeuil (vila) wrote :

sent to pqm by email

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'bzrlib/tests/__init__.py'
--- bzrlib/tests/__init__.py 2011-05-13 12:51:05 +0000
+++ bzrlib/tests/__init__.py 2011-05-14 15:01:51 +0000
@@ -3899,6 +3899,7 @@
3899 'bzrlib.tests.test_upgrade',3899 'bzrlib.tests.test_upgrade',
3900 'bzrlib.tests.test_upgrade_stacked',3900 'bzrlib.tests.test_upgrade_stacked',
3901 'bzrlib.tests.test_urlutils',3901 'bzrlib.tests.test_urlutils',
3902 'bzrlib.tests.test_utextwrap',
3902 'bzrlib.tests.test_version',3903 'bzrlib.tests.test_version',
3903 'bzrlib.tests.test_version_info',3904 'bzrlib.tests.test_version_info',
3904 'bzrlib.tests.test_versionedfile',3905 'bzrlib.tests.test_versionedfile',
39053906
=== added file 'bzrlib/tests/test_utextwrap.py'
--- bzrlib/tests/test_utextwrap.py 1970-01-01 00:00:00 +0000
+++ bzrlib/tests/test_utextwrap.py 2011-05-14 15:01:51 +0000
@@ -0,0 +1,207 @@
1# Copyright (C) 2011 Canonical Ltd
2#
3# This program is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation; either version 2 of the License, or
6# (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program; if not, write to the Free Software
15# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16#
17
18"""Tests of the bzrlib.utextwrap."""
19
20from bzrlib import tests, utextwrap
21from bzrlib.tests import TestSkipped
22
23# Japanese "Good morning".
24# Each character have double width. So total 8 width on console.
25_str_D = u'\u304a\u306f\u3088\u3046'
26
27_str_S = u"hello"
28
29# Combine single width characters and double width characters.
30_str_SD = _str_S + _str_D
31_str_DS = _str_D + _str_S
32
33class TestUTextWrap(tests.TestCase):
34
35 def check_width(self, text, expected_width):
36 w = utextwrap.UTextWrapper()
37 self.assertEqual(
38 w._width(text),
39 expected_width,
40 "Width of %r should be %d" % (text, expected_width))
41
42 def test_width(self):
43 self.check_width(_str_D, 8)
44 self.check_width(_str_SD, 13)
45
46 def check_cut(self, text, width, pos):
47 w = utextwrap.UTextWrapper()
48 self.assertEqual((text[:pos], text[pos:]), w._cut(text, width))
49
50 def test_cut(self):
51 s = _str_SD
52 self.check_cut(s, 0, 0)
53 self.check_cut(s, 1, 1)
54 self.check_cut(s, 5, 5)
55 self.check_cut(s, 6, 5)
56 self.check_cut(s, 7, 6)
57 self.check_cut(s, 12, 8)
58 self.check_cut(s, 13, 9)
59 self.check_cut(s, 14, 9)
60 self.check_cut(u'A'*5, 3, 3)
61
62 def test_split(self):
63 w = utextwrap.UTextWrapper()
64 self.assertEqual(list(_str_D), w._split(_str_D))
65 self.assertEqual([_str_S]+list(_str_D), w._split(_str_SD))
66 self.assertEqual(list(_str_D)+[_str_S], w._split(_str_DS))
67
68 def test_wrap(self):
69 self.assertEqual(list(_str_D), utextwrap.wrap(_str_D, 1))
70 self.assertEqual(list(_str_D), utextwrap.wrap(_str_D, 2))
71 self.assertEqual(list(_str_D), utextwrap.wrap(_str_D, 3))
72 self.assertEqual(list(_str_D),
73 utextwrap.wrap(_str_D, 3, break_long_words=False))
74
75class TestUTextFill(tests.TestCase):
76
77 def test_fill_simple(self):
78 # Test only can call fill() because it's just '\n'.join(wrap(text)).
79 self.assertEqual("%s\n%s" % (_str_D[:2], _str_D[2:]),
80 utextwrap.fill(_str_D, 4))
81
82 def test_fill_with_breaks(self):
83 # Demonstrate complicated case.
84 text = u"spam ham egg spamhamegg" + _str_D + u" spam" + _str_D*2
85 self.assertEqual(u'\n'.join(["spam ham",
86 "egg spam",
87 "hamegg" + _str_D[0],
88 _str_D[1:],
89 "spam" + _str_D[:2],
90 _str_D[2:]+_str_D[:2],
91 _str_D[2:]]),
92 utextwrap.fill(text, 8))
93
94 def test_fill_without_breaks(self):
95 text = u"spam ham egg spamhamegg" + _str_D + u" spam" + _str_D*2
96 self.assertEqual(u'\n'.join(["spam ham",
97 "egg",
98 "spamhamegg",
99 # border between single width and double
100 # width.
101 _str_D,
102 "spam" + _str_D[:2],
103 _str_D[2:]+_str_D[:2],
104 _str_D[2:]]),
105 utextwrap.fill(text, 8, break_long_words=False))
106
107 def test_fill_indent_with_breaks(self):
108 w = utextwrap.UTextWrapper(8, initial_indent=' '*4,
109 subsequent_indent=' '*4)
110 self.assertEqual(u'\n'.join([" hell",
111 " o" + _str_D[0],
112 " " + _str_D[1:3],
113 " " + _str_D[3]
114 ]),
115 w.fill(_str_SD))
116
117 def test_fill_indent_without_breaks(self):
118 w = utextwrap.UTextWrapper(8, initial_indent=' '*4,
119 subsequent_indent=' '*4)
120 w.break_long_words = False
121 self.assertEqual(u'\n'.join([" hello",
122 " " + _str_D[:2],
123 " " + _str_D[2:],
124 ]),
125 w.fill(_str_SD))
126
127 def test_fill_indent_without_breaks_with_fixed_width(self):
128 w = utextwrap.UTextWrapper(8, initial_indent=' '*4,
129 subsequent_indent=' '*4)
130 w.break_long_words = False
131 w.width = 3
132 self.assertEqual(u'\n'.join([" hello",
133 " " + _str_D[0],
134 " " + _str_D[1],
135 " " + _str_D[2],
136 " " + _str_D[3],
137 ]),
138 w.fill(_str_SD))
139
140class TestUTextWrapAmbiWidth(tests.TestCase):
141 _cyrill_char = u"\u0410" # east_asian_width() == 'A'
142
143 def test_ambiwidth1(self):
144 w = utextwrap.UTextWrapper(4, ambiguous_width=1)
145 s = self._cyrill_char*8
146 self.assertEqual([self._cyrill_char*4]*2, w.wrap(s))
147
148 def test_ambiwidth2(self):
149 w = utextwrap.UTextWrapper(4, ambiguous_width=2)
150 s = self._cyrill_char*8
151 self.assertEqual([self._cyrill_char*2]*4, w.wrap(s))
152
153
154# Regression test with Python's test_textwrap
155# Note that some distribution including Ubuntu doesn't install
156# Python's test suite.
157try:
158 from test import test_textwrap
159
160 def override_textwrap_symbols(testcase):
161 # Override the symbols imported by test_textwrap so it uses our own
162 # replacements.
163 testcase.overrideAttr(test_textwrap, 'TextWrapper',
164 utextwrap.UTextWrapper)
165 testcase.overrideAttr(test_textwrap, 'wrap', utextwrap.wrap)
166 testcase.overrideAttr(test_textwrap, 'fill', utextwrap.fill)
167
168
169 def setup_both(testcase, base_class, reused_class):
170 super(base_class, testcase).setUp()
171 override_textwrap_symbols(testcase)
172 reused_class.setUp(testcase)
173
174
175 class TestWrap(tests.TestCase, test_textwrap.WrapTestCase):
176
177 def setUp(self):
178 setup_both(self, TestWrap, test_textwrap.WrapTestCase)
179
180
181 class TestLongWord(tests.TestCase, test_textwrap.LongWordTestCase):
182
183 def setUp(self):
184 setup_both(self, TestLongWord, test_textwrap.LongWordTestCase)
185
186
187 class TestIndent(tests.TestCase, test_textwrap.IndentTestCases):
188
189 def setUp(self):
190 setup_both(self, TestIndent, test_textwrap.IndentTestCases)
191
192except ImportError:
193
194 class TestWrap(tests.TestCase):
195
196 def test_wrap(self):
197 raise TestSkipped("test.test_textwrap is not avialable.")
198
199 class TestLongWord(tests.TestCase):
200
201 def test_longword(self):
202 raise TestSkipped("test.test_textwrap is not avialable.")
203
204 class TestIndent(tests.TestCase):
205
206 def test_indent(self):
207 raise TestSkipped("test.test_textwrap is not avialable.")
0208
=== added file 'bzrlib/utextwrap.py'
--- bzrlib/utextwrap.py 1970-01-01 00:00:00 +0000
+++ bzrlib/utextwrap.py 2011-05-14 15:01:51 +0000
@@ -0,0 +1,264 @@
1# Copyright (C) 2011 Canonical Ltd
2#
3# UTextWrapper._handle_long_word, UTextWrapper._wrap_chunks,
4# UTextWrapper._fix_sentence_endings, wrap and fill is copied from Python's
5# textwrap module (under PSF license) and modified for support CJK.
6# Original Copyright for these functions:
7#
8# Copyright (C) 1999-2001 Gregory P. Ward.
9# Copyright (C) 2002, 2003 Python Software Foundation.
10#
11# Written by Greg Ward <gward@python.net>
12# This program is free software; you can redistribute it and/or modify
13# it under the terms of the GNU General Public License as published by
14# the Free Software Foundation; either version 2 of the License, or
15# (at your option) any later version.
16#
17# This program is distributed in the hope that it will be useful,
18# but WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20# GNU General Public License for more details.
21#
22# You should have received a copy of the GNU General Public License
23# along with this program; if not, write to the Free Software
24# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25
26import sys
27import textwrap
28from unicodedata import east_asian_width as _eawidth
29
30from bzrlib import osutils
31
32__all__ = ["UTextWrapper", "fill", "wrap"]
33
34class UTextWrapper(textwrap.TextWrapper):
35 """
36 Extend TextWrapper for Unicode.
37
38 This textwrapper handles east asian double width and split word
39 even if !break_long_words when word contains double width
40 characters.
41
42 :param ambiguous_width: (keyword argument) width for character when
43 unicodedata.east_asian_width(c) == 'A'
44 (default: 1)
45
46 Limitations:
47 * expand_tabs doesn't fixed. It uses len() for calculating width
48 of string on left of TAB.
49 * Handles one codeunit as a single character having 1 or 2 width.
50 This is not correct when there are surrogate pairs, combined
51 characters or zero-width characters.
52 * Treats all asian character are line breakable. But it is not
53 true because line breaking is prohibited around some characters.
54 (For example, breaking before punctation mark is prohibited.)
55 See UAX # 14 "UNICODE LINE BREAKING ALGORITHM"
56 """
57
58 def __init__(self, width=None, **kwargs):
59 if width is None:
60 width = (osutils.terminal_width() or
61 osutils.default_terminal_width) - 1
62
63 ambi_width = kwargs.pop('ambiguous_width', 1)
64 if ambi_width == 1:
65 self._east_asian_doublewidth = 'FW'
66 elif ambi_width == 2:
67 self._east_asian_doublewidth = 'FWA'
68 else:
69 raise ValueError("ambiguous_width should be 1 or 2")
70
71 # No drop_whitespace param before Python 2.6 it was always dropped
72 if sys.version_info < (2, 6):
73 self.drop_whitespace = kwargs.pop("drop_whitespace", True)
74 if not self.drop_whitespace:
75 raise ValueError("TextWrapper version must drop whitespace")
76 textwrap.TextWrapper.__init__(self, width, **kwargs)
77
78 def _unicode_char_width(self, uc):
79 """Return width of character `uc`.
80
81 :param: uc Single unicode character.
82 """
83 # 'A' means width of the character is not be able to determine.
84 # We assume that it's width is 2 because longer wrap may over
85 # terminal width but shorter wrap may be acceptable.
86 return (_eawidth(uc) in self._east_asian_doublewidth and 2) or 1
87
88 def _width(self, s):
89 """Returns width for s.
90
91 When s is unicode, take care of east asian width.
92 When s is bytes, treat all byte is single width character.
93 """
94 charwidth = self._unicode_char_width
95 return sum(charwidth(c) for c in s)
96
97 def _cut(self, s, width):
98 """Returns head and rest of s. (head+rest == s)
99
100 Head is large as long as _width(head) <= width.
101 """
102 w = 0
103 charwidth = self._unicode_char_width
104 for pos, c in enumerate(s):
105 w += charwidth(c)
106 if w > width:
107 return s[:pos], s[pos:]
108 return s, u''
109
110 def _fix_sentence_endings(self, chunks):
111 """_fix_sentence_endings(chunks : [string])
112
113 Correct for sentence endings buried in 'chunks'. Eg. when the
114 original text contains "... foo.\nBar ...", munge_whitespace()
115 and split() will convert that to [..., "foo.", " ", "Bar", ...]
116 which has one too few spaces; this method simply changes the one
117 space to two.
118
119 Note: This function is copied from textwrap.TextWrap and modified
120 to use unicode always.
121 """
122 i = 0
123 L = len(chunks)-1
124 patsearch = self.sentence_end_re.search
125 while i < L:
126 if chunks[i+1] == u" " and patsearch(chunks[i]):
127 chunks[i+1] = u" "
128 i += 2
129 else:
130 i += 1
131
132 def _handle_long_word(self, chunks, cur_line, cur_len, width):
133 # Figure out when indent is larger than the specified width, and make
134 # sure at least one character is stripped off on every pass
135 if width < 2:
136 space_left = chunks[-1] and self._width(chunks[-1][0]) or 1
137 else:
138 space_left = width - cur_len
139
140 # If we're allowed to break long words, then do so: put as much
141 # of the next chunk onto the current line as will fit.
142 if self.break_long_words:
143 head, rest = self._cut(chunks[-1], space_left)
144 cur_line.append(head)
145 if rest:
146 chunks[-1] = rest
147 else:
148 del chunks[-1]
149
150 # Otherwise, we have to preserve the long word intact. Only add
151 # it to the current line if there's nothing already there --
152 # that minimizes how much we violate the width constraint.
153 elif not cur_line:
154 cur_line.append(chunks.pop())
155
156 # If we're not allowed to break long words, and there's already
157 # text on the current line, do nothing. Next time through the
158 # main loop of _wrap_chunks(), we'll wind up here again, but
159 # cur_len will be zero, so the next line will be entirely
160 # devoted to the long word that we can't handle right now.
161
162 def _wrap_chunks(self, chunks):
163 lines = []
164 if self.width <= 0:
165 raise ValueError("invalid width %r (must be > 0)" % self.width)
166
167 # Arrange in reverse order so items can be efficiently popped
168 # from a stack of chucks.
169 chunks.reverse()
170
171 while chunks:
172
173 # Start the list of chunks that will make up the current line.
174 # cur_len is just the length of all the chunks in cur_line.
175 cur_line = []
176 cur_len = 0
177
178 # Figure out which static string will prefix this line.
179 if lines:
180 indent = self.subsequent_indent
181 else:
182 indent = self.initial_indent
183
184 # Maximum width for this line.
185 width = self.width - len(indent)
186
187 # First chunk on line is whitespace -- drop it, unless this
188 # is the very beginning of the text (ie. no lines started yet).
189 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
190 del chunks[-1]
191
192 while chunks:
193 # Use _width instead of len for east asian width
194 l = self._width(chunks[-1])
195
196 # Can at least squeeze this chunk onto the current line.
197 if cur_len + l <= width:
198 cur_line.append(chunks.pop())
199 cur_len += l
200
201 # Nope, this line is full.
202 else:
203 break
204
205 # The current line is full, and the next chunk is too big to
206 # fit on *any* line (not just this one).
207 if chunks and self._width(chunks[-1]) > width:
208 self._handle_long_word(chunks, cur_line, cur_len, width)
209
210 # If the last chunk on this line is all whitespace, drop it.
211 if self.drop_whitespace and cur_line and not cur_line[-1].strip():
212 del cur_line[-1]
213
214 # Convert current line back to a string and store it in list
215 # of all lines (return value).
216 if cur_line:
217 lines.append(indent + u''.join(cur_line))
218
219 return lines
220
221 def _split(self, text):
222 chunks = textwrap.TextWrapper._split(self, unicode(text))
223 cjk_split_chunks = []
224 for chunk in chunks:
225 prev_pos = 0
226 for pos, char in enumerate(chunk):
227 if self._unicode_char_width(char) == 2:
228 if prev_pos < pos:
229 cjk_split_chunks.append(chunk[prev_pos:pos])
230 cjk_split_chunks.append(char)
231 prev_pos = pos+1
232 if prev_pos < len(chunk):
233 cjk_split_chunks.append(chunk[prev_pos:])
234 return cjk_split_chunks
235
236 def wrap(self, text):
237 # ensure text is unicode
238 return textwrap.TextWrapper.wrap(self, unicode(text))
239
240# -- Convenience interface ---------------------------------------------
241
242def wrap(text, width=None, **kwargs):
243 """Wrap a single paragraph of text, returning a list of wrapped lines.
244
245 Reformat the single paragraph in 'text' so it fits in lines of no
246 more than 'width' columns, and return a list of wrapped lines. By
247 default, tabs in 'text' are expanded with string.expandtabs(), and
248 all other whitespace characters (including newline) are converted to
249 space. See TextWrapper class for available keyword args to customize
250 wrapping behaviour.
251 """
252 return UTextWrapper(width=width, **kwargs).wrap(text)
253
254def fill(text, width=None, **kwargs):
255 """Fill a single paragraph of text, returning a new string.
256
257 Reformat the single paragraph in 'text' to fit in lines of no more
258 than 'width' columns, and return a new string containing the entire
259 wrapped paragraph. As with wrap(), tabs are expanded and other
260 whitespace characters converted to space. See TextWrapper class for
261 available keyword args to customize wrapping behaviour.
262 """
263 return UTextWrapper(width=width, **kwargs).fill(text)
264