##// END OF EJS Templates
Strip non color related ANSI escape sequences from notebook output....
Jack Feser -
Show More
@@ -1,288 +1,294
1 1 //----------------------------------------------------------------------------
2 2 // Copyright (C) 2008-2012 The IPython Development Team
3 3 //
4 4 // Distributed under the terms of the BSD License. The full license is in
5 5 // the file COPYING, distributed as part of this software.
6 6 //----------------------------------------------------------------------------
7 7
8 8 //============================================================================
9 9 // Utilities
10 10 //============================================================================
11 11
12 12 IPython.namespace('IPython.utils');
13 13
14 14 IPython.utils = (function (IPython) {
15 15
16 16 //============================================================================
17 17 // Cross-browser RegEx Split
18 18 //============================================================================
19 19
20 20 // This code has been MODIFIED from the code licensed below to not replace the
21 21 // default browser split. The license is reproduced here.
22 22
23 23 // see http://blog.stevenlevithan.com/archives/cross-browser-split for more info:
24 24 /*!
25 25 * Cross-Browser Split 1.1.1
26 26 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
27 27 * Available under the MIT License
28 28 * ECMAScript compliant, uniform cross-browser split method
29 29 */
30 30
31 31 /**
32 32 * Splits a string into an array of strings using a regex or string
33 33 * separator. Matches of the separator are not included in the result array.
34 34 * However, if `separator` is a regex that contains capturing groups,
35 35 * backreferences are spliced into the result each time `separator` is
36 36 * matched. Fixes browser bugs compared to the native
37 37 * `String.prototype.split` and can be used reliably cross-browser.
38 38 * @param {String} str String to split.
39 39 * @param {RegExp|String} separator Regex or string to use for separating
40 40 * the string.
41 41 * @param {Number} [limit] Maximum number of items to include in the result
42 42 * array.
43 43 * @returns {Array} Array of substrings.
44 44 * @example
45 45 *
46 46 * // Basic use
47 47 * regex_split('a b c d', ' ');
48 48 * // -> ['a', 'b', 'c', 'd']
49 49 *
50 50 * // With limit
51 51 * regex_split('a b c d', ' ', 2);
52 52 * // -> ['a', 'b']
53 53 *
54 54 * // Backreferences in result array
55 55 * regex_split('..word1 word2..', /([a-z]+)(\d+)/i);
56 56 * // -> ['..', 'word', '1', ' ', 'word', '2', '..']
57 57 */
58 58 var regex_split = function (str, separator, limit) {
59 59 // If `separator` is not a regex, use `split`
60 60 if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
61 61 return split.call(str, separator, limit);
62 62 }
63 63 var output = [],
64 64 flags = (separator.ignoreCase ? "i" : "") +
65 65 (separator.multiline ? "m" : "") +
66 66 (separator.extended ? "x" : "") + // Proposed for ES6
67 67 (separator.sticky ? "y" : ""), // Firefox 3+
68 68 lastLastIndex = 0,
69 69 // Make `global` and avoid `lastIndex` issues by working with a copy
70 70 separator = new RegExp(separator.source, flags + "g"),
71 71 separator2, match, lastIndex, lastLength;
72 72 str += ""; // Type-convert
73 73
74 74 compliantExecNpcg = typeof(/()??/.exec("")[1]) === "undefined"
75 75 if (!compliantExecNpcg) {
76 76 // Doesn't need flags gy, but they don't hurt
77 77 separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
78 78 }
79 79 /* Values for `limit`, per the spec:
80 80 * If undefined: 4294967295 // Math.pow(2, 32) - 1
81 81 * If 0, Infinity, or NaN: 0
82 82 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
83 83 * If negative number: 4294967296 - Math.floor(Math.abs(limit))
84 84 * If other: Type-convert, then use the above rules
85 85 */
86 86 limit = typeof(limit) === "undefined" ?
87 87 -1 >>> 0 : // Math.pow(2, 32) - 1
88 88 limit >>> 0; // ToUint32(limit)
89 89 while (match = separator.exec(str)) {
90 90 // `separator.lastIndex` is not reliable cross-browser
91 91 lastIndex = match.index + match[0].length;
92 92 if (lastIndex > lastLastIndex) {
93 93 output.push(str.slice(lastLastIndex, match.index));
94 94 // Fix browsers whose `exec` methods don't consistently return `undefined` for
95 95 // nonparticipating capturing groups
96 96 if (!compliantExecNpcg && match.length > 1) {
97 97 match[0].replace(separator2, function () {
98 98 for (var i = 1; i < arguments.length - 2; i++) {
99 99 if (typeof(arguments[i]) === "undefined") {
100 100 match[i] = undefined;
101 101 }
102 102 }
103 103 });
104 104 }
105 105 if (match.length > 1 && match.index < str.length) {
106 106 Array.prototype.push.apply(output, match.slice(1));
107 107 }
108 108 lastLength = match[0].length;
109 109 lastLastIndex = lastIndex;
110 110 if (output.length >= limit) {
111 111 break;
112 112 }
113 113 }
114 114 if (separator.lastIndex === match.index) {
115 115 separator.lastIndex++; // Avoid an infinite loop
116 116 }
117 117 }
118 118 if (lastLastIndex === str.length) {
119 119 if (lastLength || !separator.test("")) {
120 120 output.push("");
121 121 }
122 122 } else {
123 123 output.push(str.slice(lastLastIndex));
124 124 }
125 125 return output.length > limit ? output.slice(0, limit) : output;
126 126 };
127 127
128 128 //============================================================================
129 129 // End contributed Cross-browser RegEx Split
130 130 //============================================================================
131 131
132 132
133 133 var uuid = function () {
134 134 // http://www.ietf.org/rfc/rfc4122.txt
135 135 var s = [];
136 136 var hexDigits = "0123456789ABCDEF";
137 137 for (var i = 0; i < 32; i++) {
138 138 s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
139 139 }
140 140 s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
141 141 s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
142 142
143 143 var uuid = s.join("");
144 144 return uuid;
145 145 };
146 146
147 147
148 148 //Fix raw text to parse correctly in crazy XML
149 149 function xmlencode(string) {
150 150 return string.replace(/\&/g,'&'+'amp;')
151 151 .replace(/</g,'&'+'lt;')
152 152 .replace(/>/g,'&'+'gt;')
153 153 .replace(/\'/g,'&'+'apos;')
154 154 .replace(/\"/g,'&'+'quot;')
155 155 .replace(/`/g,'&'+'#96;');
156 156 }
157 157
158 158
159 159 //Map from terminal commands to CSS classes
160 160 ansi_colormap = {
161 161 "30":"ansiblack", "31":"ansired",
162 162 "32":"ansigreen", "33":"ansiyellow",
163 163 "34":"ansiblue", "35":"ansipurple","36":"ansicyan",
164 164 "37":"ansigrey", "01":"ansibold"
165 165 };
166 166
167 167 // Transform ANSI color escape codes into HTML <span> tags with css
168 168 // classes listed in the above ansi_colormap object. The actual color used
169 169 // are set in the css file.
170 170 function fixConsole(txt) {
171 171 txt = xmlencode(txt);
172 172 var re = /\033\[([\dA-Fa-f;]*?)m/;
173 173 var opened = false;
174 174 var cmds = [];
175 175 var opener = "";
176 176 var closer = "";
177
178 // Strip all ANSI codes that are not color related. Matches
179 // all ANSI codes that do not end with "m".
180 var ignored_re = /(?=(\033\[[\d;=]*[a-ln-zA-Z]{1}))\1(?!m)/g;
181 txt = txt.replace(ignored_re, "");
182
177 183 while (re.test(txt)) {
178 184 var cmds = txt.match(re)[1].split(";");
179 185 closer = opened?"</span>":"";
180 186 opened = cmds.length > 1 || cmds[0] != 0;
181 187 var rep = [];
182 188 for (var i in cmds)
183 189 if (typeof(ansi_colormap[cmds[i]]) != "undefined")
184 190 rep.push(ansi_colormap[cmds[i]]);
185 191 opener = rep.length > 0?"<span class=\""+rep.join(" ")+"\">":"";
186 192 txt = txt.replace(re, closer + opener);
187 193 }
188 194 if (opened) txt += "</span>";
189 195 return txt;
190 196 }
191 197
192 198 // Remove chunks that should be overridden by the effect of
193 199 // carriage return characters
194 200 function fixCarriageReturn(txt) {
195 201 tmp = txt;
196 202 do {
197 203 txt = tmp;
198 204 tmp = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
199 205 tmp = tmp.replace(/^.*\r+/gm, ''); // Other \r --> clear line
200 206 } while (tmp.length < txt.length);
201 207 return txt;
202 208 }
203 209
204 210 // Locate URLs in plain text and wrap them in spaces so that they can be
205 211 // better picked out by autoLinkUrls even after the text has been
206 212 // converted to HTML
207 213 function wrapUrls(txt) {
208 214 // Note this regexp is a modified version of one from
209 215 // Markdown.Converter For now it only supports http(s) and ftp URLs,
210 216 // but could easily support others (though file:// should maybe be
211 217 // avoided)
212 218 var url_re = /(^|\W)(https?|ftp)(:\/\/[-A-Z0-9+&@#\/%?=~_|\[\]\(\)!:,\.;]*[-A-Z0-9+&@#\/%=~_|\[\]])($|\W)/gi;
213 219 return txt.replace(url_re, "$1 $2$3 $4");
214 220 }
215 221
216 222 // Locate a URL with spaces around it and convert that to a anchor tag
217 223 function autoLinkUrls(txt) {
218 224 return txt.replace(/ ((https?|ftp):[^'">\s]+) /gi,
219 225 "<a target=\"_blank\" href=\"$1\">$1</a>");
220 226 }
221 227
222 228 grow = function(element) {
223 229 // Grow the cell by hand. This is used upon reloading from JSON, when the
224 230 // autogrow handler is not called.
225 231 var dom = element.get(0);
226 232 var lines_count = 0;
227 233 // modified split rule from
228 234 // http://stackoverflow.com/questions/2035910/how-to-get-the-number-of-lines-in-a-textarea/2036424#2036424
229 235 var lines = dom.value.split(/\r|\r\n|\n/);
230 236 lines_count = lines.length;
231 237 if (lines_count >= 1) {
232 238 dom.rows = lines_count;
233 239 } else {
234 240 dom.rows = 1;
235 241 }
236 242 };
237 243
238 244 // some keycodes that seem to be platform/browser independant
239 245 var keycodes ={
240 246 BACKSPACE: 8,
241 247 TAB : 9,
242 248 ENTER : 13,
243 249 SHIFT : 16,
244 250 CTRL : 17,
245 251 CONTROL : 17,
246 252 ALT : 18,
247 253 ESC : 27,
248 254 SPACE : 32,
249 255 PGUP : 33,
250 256 PGDOWN : 34,
251 257 LEFT_ARROW: 37,
252 258 LEFTARROW: 37,
253 259 LEFT : 37,
254 260 UP_ARROW : 38,
255 261 UPARROW : 38,
256 262 UP : 38,
257 263 RIGHT_ARROW:39,
258 264 RIGHTARROW:39,
259 265 RIGHT : 39,
260 266 DOWN_ARROW: 40,
261 267 DOWNARROW: 40,
262 268 DOWN : 40,
263 269 };
264 270
265 271
266 272 points_to_pixels = function (points) {
267 273 // A reasonably good way of converting between points and pixels.
268 274 var test = $('<div style="display: none; width: 10000pt; padding:0; border:0;"></div>');
269 275 $(body).append(test);
270 276 var pixel_per_point = test.width()/10000;
271 277 test.remove();
272 278 return Math.floor(points*pixel_per_point);
273 279 }
274 280
275 281
276 282 return {
277 283 regex_split : regex_split,
278 284 uuid : uuid,
279 285 fixConsole : fixConsole,
280 286 keycodes : keycodes,
281 287 grow : grow,
282 288 fixCarriageReturn : fixCarriageReturn,
283 289 wrapUrls : wrapUrls,
284 290 autoLinkUrls : autoLinkUrls,
285 291 points_to_pixels : points_to_pixels
286 292 };
287 293
288 294 }(IPython));
General Comments 0
You need to be logged in to leave comments. Login now