From 55a3d61139e7d8f9cd2b362d26e0369d09f72be0 Mon Sep 17 00:00:00 2001 From: Rolux Date: Sun, 6 Jul 2008 11:43:06 +0200 Subject: [PATCH] wrapString --- oxlib/str.py | 32 -------------------------------- oxlib/text.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 32 deletions(-) delete mode 100644 oxlib/str.py diff --git a/oxlib/str.py b/oxlib/str.py deleted file mode 100644 index d5e7575..0000000 --- a/oxlib/str.py +++ /dev/null @@ -1,32 +0,0 @@ -# -*- coding: utf-8 -*- -# vi:si:et:sw=4:sts=4:ts=4 - -def wrap(string, length, separator, balance): - if balance: - # balance lines: test if same number of lines - # can be achieved with a shorter line length - lines = wrap(string, length, separator, False).split(separator) - if len(lines) > 1: - while length > max(map(lambda x : len(x), string.split(' '))): - length -= 1 - if len(wrap(string, length, separator, False).split(separator)) > len(lines): - length += 1 - break - words = string.split(' ') - lines = [''] - for word in words: - if len(lines[len(lines) - 1] + word + ' ') <= length + 1: - # word fits in current line - lines[len(lines) - 1] += word + ' '; - else: - if len(word) <= length: - # word fits in next line - lines.append(word + ' ') - else: - # word is longer than line - position = length - len(lines[len(lines) - 1]) + 1 - lines[len(lines) - 1] += word[0:position] - for i in range(position, len(word), length): - lines.append(word[i:i+length]); - lines[len(lines) - 1] += ' ' - return separator.join(lines).strip() diff --git a/oxlib/text.py b/oxlib/text.py index 8870ffd..1ae2ebd 100644 --- a/oxlib/text.py +++ b/oxlib/text.py @@ -65,6 +65,37 @@ def wrap(text, width): text.split(' ') ) +def wrapString(string, length, separator, balance): + if balance: + # balance lines: test if same number of lines + # can be achieved with a shorter line length + lines = wrapString(string, length, separator, False).split(separator) + if len(lines) > 1: + while length > max(map(lambda x : len(x), string.split(' '))): + length -= 1 + if len(wrapString(string, length, separator, False).split(separator)) > len(lines): + length += 1 + break + words = string.split(' ') + lines = [''] + for word in words: + if len(lines[len(lines) - 1] + word + ' ') <= length + 1: + # word fits in current line + lines[len(lines) - 1] += word + ' '; + else: + if len(word) <= length: + # word fits in next line + lines.append(word + ' ') + else: + # word is longer than line + position = length - len(lines[len(lines) - 1]) + 1 + lines[len(lines) - 1] += word[0:position] + for i in range(position, len(word), length): + lines.append(word[i:i+length]); + lines[len(lines) - 1] += ' ' + return separator.join(lines).strip() + + def truncateString(s, num): """Truncates a string after a certain number of chacters, but ends with a word