Last active
August 29, 2015 14:02
-
-
Save danielepantaleone/daf5d3112b5cbf6c755a to your computer and use it in GitHub Desktop.
Possible implementation of getWrap function of B3 Parser class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def getWrap(self, text, length=80, sv_prefix_length=9): | |
""" | |
Returns a sequence of lines for text that fits within the limits | |
:param text: The text to be splitted | |
:param length: The maximum length of each line | |
:param sv_prefix_length: The length of the prefix added by the server to the message | |
""" | |
if not text: | |
return [] | |
length = int(length) | |
sv_prefix_length = int(sv_prefix_length) | |
first_line_length = length - len(self.msgPrefix) - sv_prefix_length | |
# if the message fits in the first line | |
if len(text) < first_line_length: | |
return [text] | |
lines = [] | |
start_index = 0 | |
end_index = length - 1 | |
while True: | |
# if it's the last line make sure | |
# we have a valid end index | |
if end_index >= len(text): | |
# rollback until index is valid | |
while end_index > len(text): | |
end_index -= 1 | |
lines.append(text[start_index:end_index]) | |
break | |
else: | |
if len(lines) > 0: | |
max_length = length | |
else: | |
max_length = first_line_length | |
# rollback until we find an empty | |
# char where to split our input string | |
while text[end_index - 1] != '': | |
end_index -= 1 | |
# this is to check whether the string we | |
# have to split is a char sequence without | |
# spaces: fi we skip this check we may have | |
# and infinite loop | |
if end_index <= start_index: | |
end_index += max_length - 1 | |
break | |
lines.append(text[start_index:end_index]) | |
start_index = end_index | |
end_index += max_length - 1 | |
return lines |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment