-
Notifications
You must be signed in to change notification settings - Fork 1
/
text_output.py
77 lines (55 loc) · 2.26 KB
/
text_output.py
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
#!/usr/bin/python
#
# This file is part of lava-hacks. lava-hacks 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, version 2.
#
# 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.
#
# Copyright Anders Roxell 2015
def get_sub_str(text, from_pos, num_chars, break_chars):
sub_str = text[from_pos:from_pos+num_chars]
for index, ch in enumerate(sub_str):
if ch in break_chars:
return (sub_str[:index], from_pos+index+1)
return (sub_str, from_pos+len(sub_str))
class TextBlock(object):
def __init__(self, text="", width=0):
self.text = str(text)
self.width = width
self.block = list()
def set_width(self, width, reflow=True):
self.width = width
if reflow: self.reflow()
def set_text(self, text, reflow=True):
self.text = str(text)
if reflow: self.reflow()
def append_text(self, new_text, reflow=True):
self.text += str(text)
if reflow: self.reflow()
def get_block(self, start_line, num_lines):
block_len = len(self.block)
if start_line < 0:
start_line = block_len-start_line-num_lines
if start_line+num_lines > block_len:
num_lines = block_len-start_line
return self.block[start_line:start_line+num_lines]
def reflow(self, width=0):
if not self.width:
raise Exception("Cannot reflow to windows of width %d" % self.width)
del self.block[:]
self.width = width or self.width
text_len = len(self.text)
cur_pos = 0
while cur_pos < text_len:
cur_line, next_pos = get_sub_str(self.text, cur_pos, self.width, ('\n',))
self.block.append(cur_line)
cur_pos = next_pos
# vim: set sw=4 sts=4 et fileencoding=utf-8 :