Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2Generates a dictionary of ANSI escape codes. 

3 

4http://en.wikipedia.org/wiki/ANSI_escape_code 

5 

6Uses colorama as an optional dependency to support color on Windows 

7""" 

8 

9try: 

10 import colorama 

11except ImportError: 

12 pass 

13else: 

14 colorama.init() 

15 

16__all__ = ('escape_codes', 'parse_colors') 

17 

18 

19# Returns escape codes from format codes 

20def esc(*x): 

21 return '\033[' + ';'.join(x) + 'm' 

22 

23 

24# The initial list of escape codes 

25escape_codes = { 

26 'reset': esc('0'), 

27 'bold': esc('01'), 

28 'thin': esc('02') 

29} 

30 

31# The color names 

32COLORS = [ 

33 'black', 

34 'red', 

35 'green', 

36 'yellow', 

37 'blue', 

38 'purple', 

39 'cyan', 

40 'white' 

41] 

42 

43PREFIXES = [ 

44 # Foreground without prefix 

45 ('3', ''), ('01;3', 'bold_'), ('02;3', 'thin_'), 

46 

47 # Foreground with fg_ prefix 

48 ('3', 'fg_'), ('01;3', 'fg_bold_'), ('02;3', 'fg_thin_'), 

49 

50 # Background with bg_ prefix - bold/light works differently 

51 ('4', 'bg_'), ('10', 'bg_bold_'), 

52] 

53 

54for prefix, prefix_name in PREFIXES: 

55 for code, name in enumerate(COLORS): 

56 escape_codes[prefix_name + name] = esc(prefix + str(code)) 

57 

58 

59def parse_colors(sequence): 

60 """Return escape codes from a color sequence.""" 

61 return ''.join(escape_codes[n] for n in sequence.split(',') if n)