##// END OF EJS Templates
move Ansi related filters to ansi.py
jakobgager -
Show More
@@ -1,97 +1,138 b''
1 """Filters for processing ANSI colors within Jinja templates.
1 """Filters for processing ANSI colors within Jinja templates.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2013, the IPython Development Team.
4 # Copyright (c) 2013, the IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import re
15 import re
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Classes and functions
18 # Classes and functions
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 def remove_ansi(source):
21 def remove_ansi(source):
22 """
22 """
23 Remove ansi from text
23 Remove ansi from text
24
24
25 Parameters
25 Parameters
26 ----------
26 ----------
27 source : str
27 source : str
28 Source to remove the ansi from
28 Source to remove the ansi from
29 """
29 """
30
30
31 return re.sub(r'\033\[(0|\d;\d\d)m', '', source)
31 return re.sub(r'\033\[(0|\d;\d\d)m', '', source)
32
32
33
33
34 def ansi2html(text):
34 def ansi2html(text):
35 """
35 """
36 Conver ansi colors to html colors.
36 Conver ansi colors to html colors.
37
37
38 Parameters
38 Parameters
39 ----------
39 ----------
40 text : str
40 text : str
41 Text containing ansi colors to convert to html
41 Text containing ansi colors to convert to html
42 """
42 """
43
43
44 ansi_colormap = {
44 ansi_colormap = {
45 '30': 'ansiblack',
45 '30': 'ansiblack',
46 '31': 'ansired',
46 '31': 'ansired',
47 '32': 'ansigreen',
47 '32': 'ansigreen',
48 '33': 'ansiyellow',
48 '33': 'ansiyellow',
49 '34': 'ansiblue',
49 '34': 'ansiblue',
50 '35': 'ansipurple',
50 '35': 'ansipurple',
51 '36': 'ansicyan',
51 '36': 'ansicyan',
52 '37': 'ansigrey',
52 '37': 'ansigrey',
53 '01': 'ansibold',
53 '01': 'ansibold',
54 }
54 }
55
55
56 # do ampersand first
56 # do ampersand first
57 text = text.replace('&', '&')
57 text = text.replace('&', '&')
58 html_escapes = {
58 html_escapes = {
59 '<': '&lt;',
59 '<': '&lt;',
60 '>': '&gt;',
60 '>': '&gt;',
61 "'": '&apos;',
61 "'": '&apos;',
62 '"': '&quot;',
62 '"': '&quot;',
63 '`': '&#96;',
63 '`': '&#96;',
64 }
64 }
65
65
66 for c, escape in html_escapes.iteritems():
66 for c, escape in html_escapes.iteritems():
67 text = text.replace(c, escape)
67 text = text.replace(c, escape)
68
68
69 ansi_re = re.compile('\x1b' + r'\[([\dA-Fa-f;]*?)m')
69 ansi_re = re.compile('\x1b' + r'\[([\dA-Fa-f;]*?)m')
70 m = ansi_re.search(text)
70 m = ansi_re.search(text)
71 opened = False
71 opened = False
72 cmds = []
72 cmds = []
73 opener = ''
73 opener = ''
74 closer = ''
74 closer = ''
75 while m:
75 while m:
76 cmds = m.groups()[0].split(';')
76 cmds = m.groups()[0].split(';')
77 closer = '</span>' if opened else ''
77 closer = '</span>' if opened else ''
78
78
79 # True if there is there more than one element in cmds, *or*
79 # True if there is there more than one element in cmds, *or*
80 # if there is only one but it is not equal to a string of zeroes.
80 # if there is only one but it is not equal to a string of zeroes.
81 opened = len(cmds) > 1 or cmds[0] != '0' * len(cmds[0])
81 opened = len(cmds) > 1 or cmds[0] != '0' * len(cmds[0])
82 classes = []
82 classes = []
83 for cmd in cmds:
83 for cmd in cmds:
84 if cmd in ansi_colormap:
84 if cmd in ansi_colormap:
85 classes.append(ansi_colormap.get(cmd))
85 classes.append(ansi_colormap.get(cmd))
86
86
87 if classes:
87 if classes:
88 opener = '<span class="%s">' % (' '.join(classes))
88 opener = '<span class="%s">' % (' '.join(classes))
89 else:
89 else:
90 opener = ''
90 opener = ''
91 text = re.sub(ansi_re, closer + opener, text, 1)
91 text = re.sub(ansi_re, closer + opener, text, 1)
92
92
93 m = ansi_re.search(text)
93 m = ansi_re.search(text)
94
94
95 if opened:
95 if opened:
96 text += '</span>'
96 text += '</span>'
97 return text
97 return text
98
99
100 def single_ansi2latex(code):
101 """Converts single ansi markup to latex format
102
103 Return latex code and number of open brackets.
104 """
105 for color in coloransi.color_templates:
106 colcode = getattr(coloransi.TermColors,color[0])
107 # regular fonts
108 if code == colcode:
109 return '\\'+color[0].lower()+'{', 1
110 # bold fonts
111 if code == colcode[:3]+str(1)+colcode[3:]:
112 return '\\textbf{\\textcolor{'+color[0].lower()+'}{', 2
113 return '', 0
114
115 def ansi2latex(text):
116 """Converts ansi formated text to latex version
117
118 based on https://bitbucket.org/birkenfeld/sphinx-contrib/ansi.py
119 """
120 color_pattern = re.compile('\x1b\\[([^m]+)m')
121 last_end = 0
122 openbrack = 0
123 outstring = ''
124 for match in color_pattern.finditer(text):
125 head = text[last_end:match.start()]
126 formater = match.group()
127 outstring += head
128 if openbrack:
129 outstring += '}'*openbrack
130 openbrack = 0
131 if match.group() <> coloransi.TermColors.Normal and not openbrack:
132 texform, openbrack = single_ansi2latex(match.group())
133 outstring += texform
134 last_end = match.end()
135 if openbrack:
136 outstring += '}'*openbrack
137 outstring += text[last_end:]
138 return outstring.strip()
@@ -1,151 +1,105 b''
1 """String filters.
1 """String filters.
2
2
3 Contains a collection of useful string manipulation filters for use in Jinja
3 Contains a collection of useful string manipulation filters for use in Jinja
4 templates.
4 templates.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (c) 2013, the IPython Development Team.
7 # Copyright (c) 2013, the IPython Development Team.
8 #
8 #
9 # Distributed under the terms of the Modified BSD License.
9 # Distributed under the terms of the Modified BSD License.
10 #
10 #
11 # The full license is in the file COPYING.txt, distributed with this software.
11 # The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 import re
17 import re
18
18
19 # Our own imports
19 # Our own imports
20 import textwrap
20 import textwrap
21 from IPython.utils import coloransi
21 from IPython.utils import coloransi
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Functions
23 # Functions
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 def wrap(text, width=100):
26 def wrap(text, width=100):
27 """
27 """
28 Intelligently wrap text.
28 Intelligently wrap text.
29 Wrap text without breaking words if possible.
29 Wrap text without breaking words if possible.
30
30
31 Parameters
31 Parameters
32 ----------
32 ----------
33 text : str
33 text : str
34 Text to wrap.
34 Text to wrap.
35 width : int, optional
35 width : int, optional
36 Number of characters to wrap to, default 100.
36 Number of characters to wrap to, default 100.
37 """
37 """
38
38
39 split_text = text.split('\n')
39 split_text = text.split('\n')
40 wrp = map(lambda x:textwrap.wrap(x,width), split_text)
40 wrp = map(lambda x:textwrap.wrap(x,width), split_text)
41 wrpd = map('\n'.join, wrp)
41 wrpd = map('\n'.join, wrp)
42 return '\n'.join(wrpd)
42 return '\n'.join(wrpd)
43
43
44
44
45 def strip_dollars(text):
45 def strip_dollars(text):
46 """
46 """
47 Remove all dollar symbols from text
47 Remove all dollar symbols from text
48
48
49 Parameters
49 Parameters
50 ----------
50 ----------
51 text : str
51 text : str
52 Text to remove dollars from
52 Text to remove dollars from
53 """
53 """
54
54
55 return text.strip('$')
55 return text.strip('$')
56
56
57 def add_ansi_attr(ansistr, attr):
58 """Adds the attribute key to the ansi colors defined
59 with IPython.utils.ansicolors. Allows to boldface
60 the dark characters.
61 """
62 return ansistr[:3]+str(attr)+ansistr[3:]
63
64 def single_ansi2latex(code):
65 """Converts single ansi markup to latex format
66
67 Return latex code and number of open brackets.
68 """
69 for color in coloransi.color_templates:
70 colcode = getattr(coloransi.TermColors,color[0])
71 # regular fonts
72 if code == colcode:
73 return '\\'+color[0].lower()+'{', 1
74 # bold fonts
75 if code == add_ansi_attr(colcode,1):
76 return '\\textbf{\\textcolor{'+color[0].lower()+'}{', 2
77 return '', 0
78
79 def ansi2latex(text):
80 """Converts ansi formated text to latex version
81
82 based on https://bitbucket.org/birkenfeld/sphinx-contrib/ansi.py
83 """
84 color_pattern = re.compile('\x1b\\[([^m]+)m')
85 last_end = 0
86 openbrack = 0
87 outstring = ''
88 for match in color_pattern.finditer(text):
89 head = text[last_end:match.start()]
90 formater = match.group()
91 outstring += head
92 if openbrack:
93 outstring += '}'*openbrack
94 openbrack = 0
95 if match.group() <> coloransi.TermColors.Normal and not openbrack:
96 texform, openbrack = single_ansi2latex(match.group())
97 outstring += texform
98 last_end = match.end()
99 if openbrack:
100 outstring += '}'*openbrack
101 outstring += text[last_end:]
102 return outstring.strip()
103
57
104 def rm_fake(text):
58 def rm_fake(text):
105 """
59 """
106 Remove all occurrences of '/files/' from text
60 Remove all occurrences of '/files/' from text
107
61
108 Parameters
62 Parameters
109 ----------
63 ----------
110 text : str
64 text : str
111 Text to remove '/files/' from
65 Text to remove '/files/' from
112 """
66 """
113 return text.replace('/files/', '')
67 return text.replace('/files/', '')
114
68
115
69
116 def python_comment(text):
70 def python_comment(text):
117 """
71 """
118 Build a Python comment line from input text.
72 Build a Python comment line from input text.
119
73
120 Parameters
74 Parameters
121 ----------
75 ----------
122 text : str
76 text : str
123 Text to comment out.
77 Text to comment out.
124 """
78 """
125
79
126 #Replace line breaks with line breaks and comment symbols.
80 #Replace line breaks with line breaks and comment symbols.
127 #Also add a comment symbol at the beginning to comment out
81 #Also add a comment symbol at the beginning to comment out
128 #the first line.
82 #the first line.
129 return '# '+'\n# '.join(text.split('\n'))
83 return '# '+'\n# '.join(text.split('\n'))
130
84
131
85
132 def get_lines(text, start=None,end=None):
86 def get_lines(text, start=None,end=None):
133 """
87 """
134 Split the input text into separate lines and then return the
88 Split the input text into separate lines and then return the
135 lines that the caller is interested in.
89 lines that the caller is interested in.
136
90
137 Parameters
91 Parameters
138 ----------
92 ----------
139 text : str
93 text : str
140 Text to parse lines from.
94 Text to parse lines from.
141 start : int, optional
95 start : int, optional
142 First line to grab from.
96 First line to grab from.
143 end : int, optional
97 end : int, optional
144 Last line to grab from.
98 Last line to grab from.
145 """
99 """
146
100
147 # Split the input into lines.
101 # Split the input into lines.
148 lines = text.split("\n")
102 lines = text.split("\n")
149
103
150 # Return the right lines.
104 # Return the right lines.
151 return "\n".join(lines[start:end]) #re-join
105 return "\n".join(lines[start:end]) #re-join
General Comments 0
You need to be logged in to leave comments. Login now