2 # -*- coding: utf-8 -*-
4 Copyright (c) 2015-2016, René Tanczos <gravmatt@gmail.com> (Twitter @gravmatt)
7 pyterm helps positioning the cursor and styling output inside the terminal.
9 Project on github https://github.com/gravmatt/py-term
12 __author__ = 'Rene Tanczos'
19 from subprocess import Popen, PIPE
22 off = '\033[0m\033[27m'
25 underscore = '\033[4m'
44 bgmagenta = '\033[45m'
54 def pos(line, column):
55 send('\033[%s;%sf' % (line, column))
63 send('\033[%sA' % value)
67 send('\033[%sB' % value)
71 send('\033[%sC' % value)
75 send('\033[%sD' % value)
92 def clearLineFromPos():
104 def write(text='', *style):
105 send(format(text, *style))
108 def writeLine(text='', *style):
109 write(str(text) + '\n', *style)
113 send('\033]2;%s\007' % name)
121 send('\033]1;%s\007' % name)
129 return re.sub('\x1b\[[0-9]{1,2}m', '', text)
133 return ' ' * (int(getSize()[1] / 2) - int(len(strip(text)) / 2)) + text
137 return ' ' * (getSize()[1] - len(strip(text))) + text
142 os_sys = platform.system()
143 if(os_sys in ['Linux', 'Darwin'] or os_sys.startswith('CYGWIN')):
145 def __get_unix_terminal_size(fd):
146 import fcntl, termios, struct
147 return struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, 'rene'))
148 cr = __get_unix_terminal_size(0) or __get_unix_terminal_size(1) or __get_unix_terminal_size(2)
150 fd = os.open(os.ctermid(), os.O_RDONLY)
151 cr = __get_unix_terminal_size(fd)
157 raise Exception('operating system not supported')
160 def format(text, *style):
162 return '%s%s%s' % (''.join(style), text, off)
167 def highlight(pattern, text, func):
170 matches = [(m.start(), m.end()) for m in re.finditer(pattern, text)]
172 output += text[idx:p[0]]
173 output += func(text[p[0]:p[1]])
176 return (output, len(matches), matches)