##// END OF EJS Templates
add indexed-color in 256-color support
MinRK -
Show More
@@ -1,380 +1,390
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 IPython.namespace('IPython.utils');
12 12
13 13 IPython.utils = (function (IPython) {
14 14
15 15 //============================================================================
16 16 // Cross-browser RegEx Split
17 17 //============================================================================
18 18
19 19 // This code has been MODIFIED from the code licensed below to not replace the
20 20 // default browser split. The license is reproduced here.
21 21
22 22 // see http://blog.stevenlevithan.com/archives/cross-browser-split for more info:
23 23 /*!
24 24 * Cross-Browser Split 1.1.1
25 25 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
26 26 * Available under the MIT License
27 27 * ECMAScript compliant, uniform cross-browser split method
28 28 */
29 29
30 30 /**
31 31 * Splits a string into an array of strings using a regex or string
32 32 * separator. Matches of the separator are not included in the result array.
33 33 * However, if `separator` is a regex that contains capturing groups,
34 34 * backreferences are spliced into the result each time `separator` is
35 35 * matched. Fixes browser bugs compared to the native
36 36 * `String.prototype.split` and can be used reliably cross-browser.
37 37 * @param {String} str String to split.
38 38 * @param {RegExp|String} separator Regex or string to use for separating
39 39 * the string.
40 40 * @param {Number} [limit] Maximum number of items to include in the result
41 41 * array.
42 42 * @returns {Array} Array of substrings.
43 43 * @example
44 44 *
45 45 * // Basic use
46 46 * regex_split('a b c d', ' ');
47 47 * // -> ['a', 'b', 'c', 'd']
48 48 *
49 49 * // With limit
50 50 * regex_split('a b c d', ' ', 2);
51 51 * // -> ['a', 'b']
52 52 *
53 53 * // Backreferences in result array
54 54 * regex_split('..word1 word2..', /([a-z]+)(\d+)/i);
55 55 * // -> ['..', 'word', '1', ' ', 'word', '2', '..']
56 56 */
57 57 var regex_split = function (str, separator, limit) {
58 58 // If `separator` is not a regex, use `split`
59 59 if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
60 60 return split.call(str, separator, limit);
61 61 }
62 62 var output = [],
63 63 flags = (separator.ignoreCase ? "i" : "") +
64 64 (separator.multiline ? "m" : "") +
65 65 (separator.extended ? "x" : "") + // Proposed for ES6
66 66 (separator.sticky ? "y" : ""), // Firefox 3+
67 67 lastLastIndex = 0,
68 68 // Make `global` and avoid `lastIndex` issues by working with a copy
69 69 separator = new RegExp(separator.source, flags + "g"),
70 70 separator2, match, lastIndex, lastLength;
71 71 str += ""; // Type-convert
72 72
73 73 var compliantExecNpcg = typeof(/()??/.exec("")[1]) === "undefined";
74 74 if (!compliantExecNpcg) {
75 75 // Doesn't need flags gy, but they don't hurt
76 76 separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
77 77 }
78 78 /* Values for `limit`, per the spec:
79 79 * If undefined: 4294967295 // Math.pow(2, 32) - 1
80 80 * If 0, Infinity, or NaN: 0
81 81 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
82 82 * If negative number: 4294967296 - Math.floor(Math.abs(limit))
83 83 * If other: Type-convert, then use the above rules
84 84 */
85 85 limit = typeof(limit) === "undefined" ?
86 86 -1 >>> 0 : // Math.pow(2, 32) - 1
87 87 limit >>> 0; // ToUint32(limit)
88 88 while (match = separator.exec(str)) {
89 89 // `separator.lastIndex` is not reliable cross-browser
90 90 lastIndex = match.index + match[0].length;
91 91 if (lastIndex > lastLastIndex) {
92 92 output.push(str.slice(lastLastIndex, match.index));
93 93 // Fix browsers whose `exec` methods don't consistently return `undefined` for
94 94 // nonparticipating capturing groups
95 95 if (!compliantExecNpcg && match.length > 1) {
96 96 match[0].replace(separator2, function () {
97 97 for (var i = 1; i < arguments.length - 2; i++) {
98 98 if (typeof(arguments[i]) === "undefined") {
99 99 match[i] = undefined;
100 100 }
101 101 }
102 102 });
103 103 }
104 104 if (match.length > 1 && match.index < str.length) {
105 105 Array.prototype.push.apply(output, match.slice(1));
106 106 }
107 107 lastLength = match[0].length;
108 108 lastLastIndex = lastIndex;
109 109 if (output.length >= limit) {
110 110 break;
111 111 }
112 112 }
113 113 if (separator.lastIndex === match.index) {
114 114 separator.lastIndex++; // Avoid an infinite loop
115 115 }
116 116 }
117 117 if (lastLastIndex === str.length) {
118 118 if (lastLength || !separator.test("")) {
119 119 output.push("");
120 120 }
121 121 } else {
122 122 output.push(str.slice(lastLastIndex));
123 123 }
124 124 return output.length > limit ? output.slice(0, limit) : output;
125 125 };
126 126
127 127 //============================================================================
128 128 // End contributed Cross-browser RegEx Split
129 129 //============================================================================
130 130
131 131
132 132 var uuid = function () {
133 133 // http://www.ietf.org/rfc/rfc4122.txt
134 134 var s = [];
135 135 var hexDigits = "0123456789ABCDEF";
136 136 for (var i = 0; i < 32; i++) {
137 137 s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
138 138 }
139 139 s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
140 140 s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
141 141
142 142 var uuid = s.join("");
143 143 return uuid;
144 144 };
145 145
146 146
147 147 //Fix raw text to parse correctly in crazy XML
148 148 function xmlencode(string) {
149 149 return string.replace(/\&/g,'&'+'amp;')
150 150 .replace(/</g,'&'+'lt;')
151 151 .replace(/>/g,'&'+'gt;')
152 152 .replace(/\'/g,'&'+'apos;')
153 153 .replace(/\"/g,'&'+'quot;')
154 154 .replace(/`/g,'&'+'#96;');
155 155 }
156 156
157 157
158 158 //Map from terminal commands to CSS classes
159 159 var ansi_colormap = {
160 160 "01":"ansibold",
161
161
162 162 "30":"ansiblack",
163 163 "31":"ansired",
164 164 "32":"ansigreen",
165 165 "33":"ansiyellow",
166 166 "34":"ansiblue",
167 167 "35":"ansipurple",
168 168 "36":"ansicyan",
169 169 "37":"ansigray",
170
170
171 171 "40":"ansibgblack",
172 172 "41":"ansibgred",
173 173 "42":"ansibggreen",
174 174 "44":"ansibgyellow",
175 175 "44":"ansibgblue",
176 176 "45":"ansibgpurple",
177 177 "46":"ansibgcyan",
178 178 "47":"ansibggray"
179 179 };
180 180
181 181 function _process_numbers(attrs, numbers) {
182 182 // process ansi escapes
183 183 var n = numbers.shift();
184 184 if (ansi_colormap[n]) {
185 185 if ( ! attrs["class"] ) {
186 186 attrs["class"] = ansi_colormap[n];
187 187 } else {
188 188 attrs["class"] += " " + ansi_colormap[n];
189 189 }
190 190 } else if (n == "38" || n == "48") {
191 191 // 256-color
192 192 if (numbers.length < 2) {
193 193 console.log("Not enough fields for 256-color escapes", numbers);
194 194 return;
195 195 }
196 196
197 197 var index_or_rgb = numbers.shift();
198 198 var r,g,b;
199 199 if (index_or_rgb == "5") {
200 // indexed 256 color
200 201 var idx = parseInt(numbers.shift());
201 202 if (idx < 16) {
202 // indexed color, not supported
203 // indexed ANSI
204 // ignore bright / non-bright distinction
205 idx = idx % 8;
206 var ansiclass = ansi_colormap[n[0] + (idx % 8).toString()];
207 if ( ! attrs["class"] ) {
208 attrs["class"] = ansiclass;
209 } else {
210 attrs["class"] += " " + ansiclass;
211 }
212 return;
203 213 } else if (idx < 232) {
204 // 216 color 6x6x6
214 // 216 color 6x6x6 RGB
205 215 idx = idx - 16;
206 216 b = idx % 6;
207 217 g = Math.floor(idx / 6) % 6;
208 218 r = Math.floor(idx / 36) % 6;
209 219 // convert to rgb
210 220 r = (r * 51);
211 221 g = (g * 51);
212 222 b = (b * 51);
213 223 } else {
214 224 // grayscale
215 225 idx = idx - 231;
216 226 // it's 1-24 and should *not* include black or white,
217 227 // so a 26 point scale
218 r = g = b = idx * 256 / 26;
228 r = g = b = Math.floor(idx * 256 / 26);
219 229 }
220 230 } else if (index_or_rgb == "2") {
231 // Simple 24 bit RGB
221 232 if (numbers.length > 3) {
222 233 console.log("Not enough fields for RGB", numbers);
223 234 return;
224 235 }
225 // simple rgb
226 236 r = numbers.shift();
227 237 g = numbers.shift();
228 238 b = numbers.shift();
229 239 } else {
230 240 console.log("unrecognized control", numbers);
231 241 return;
232 242 }
233 243 if (r !== undefined) {
234 244 // apply the rgb color
235 245 var line;
236 246 if (n == "38") {
237 247 line = "color: ";
238 248 } else {
239 249 line = "background-color: ";
240 250 }
241 251 line = line + "rgb(" + r + "," + g + "," + b + ");"
242 252 if ( !attrs["style"] ) {
243 253 attrs["style"] = line;
244 254 } else {
245 255 attrs["style"] += " " + line;
246 256 }
247 257 }
248 258 }
249 259 }
250 260
251 261 function ansispan(str) {
252 262 // ansispan function adapted from github.com/mmalecki/ansispan (MIT License)
253 263 // regular ansi escapes (using the table above)
254 264 return str.replace(/\033\[(0?[01]|22|39)?([;\d]+)?m/g, function(match, prefix, pattern) {
255 265 if (!pattern) {
256 266 // [(01|22|39|)m close spans
257 267 return "</span>";
258 268 }
259 269 // consume sequence of color escapes
260 270 var numbers = pattern.match(/\d+/g);
261 271 var attrs = {};
262 272 while (numbers.length > 0) {
263 273 _process_numbers(attrs, numbers);
264 274 }
265 275
266 276 var span = "<span ";
267 277 for (var attr in attrs) {
268 278 var value = attrs[attr];
269 279 span = span + " " + attr + '="' + attrs[attr] + '"';
270 280 }
271 281 return span + ">";
272 282 });
273 283 };
274 284
275 285 // Transform ANSI color escape codes into HTML <span> tags with css
276 286 // classes listed in the above ansi_colormap object. The actual color used
277 287 // are set in the css file.
278 288 function fixConsole(txt) {
279 289 txt = xmlencode(txt);
280 290 var re = /\033\[([\dA-Fa-f;]*?)m/;
281 291 var opened = false;
282 292 var cmds = [];
283 293 var opener = "";
284 294 var closer = "";
285 295
286 296 // Strip all ANSI codes that are not color related. Matches
287 297 // all ANSI codes that do not end with "m".
288 298 var ignored_re = /(?=(\033\[[\d;=]*[a-ln-zA-Z]{1}))\1(?!m)/g;
289 299 txt = txt.replace(ignored_re, "");
290 300
291 301 // color ansi codes
292 302 txt = ansispan(txt);
293 303 return txt;
294 304 }
295 305
296 306 // Remove chunks that should be overridden by the effect of
297 307 // carriage return characters
298 308 function fixCarriageReturn(txt) {
299 309 var tmp = txt;
300 310 do {
301 311 txt = tmp;
302 312 tmp = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
303 313 tmp = tmp.replace(/^.*\r+/gm, ''); // Other \r --> clear line
304 314 } while (tmp.length < txt.length);
305 315 return txt;
306 316 }
307 317
308 318 // Locate any URLs and convert them to a anchor tag
309 319 function autoLinkUrls(txt) {
310 320 return txt.replace(/(^|\s)(https?|ftp)(:[^'">\s]+)/gi,
311 321 "$1<a target=\"_blank\" href=\"$2$3\">$2$3</a>");
312 322 }
313 323
314 324 // some keycodes that seem to be platform/browser independent
315 325 var keycodes = {
316 326 BACKSPACE: 8,
317 327 TAB : 9,
318 328 ENTER : 13,
319 329 SHIFT : 16,
320 330 CTRL : 17,
321 331 CONTROL : 17,
322 332 ALT : 18,
323 333 CAPS_LOCK: 20,
324 334 ESC : 27,
325 335 SPACE : 32,
326 336 PGUP : 33,
327 337 PGDOWN : 34,
328 338 END : 35,
329 339 HOME : 36,
330 340 LEFT_ARROW: 37,
331 341 LEFTARROW: 37,
332 342 LEFT : 37,
333 343 UP_ARROW : 38,
334 344 UPARROW : 38,
335 345 UP : 38,
336 346 RIGHT_ARROW:39,
337 347 RIGHTARROW:39,
338 348 RIGHT : 39,
339 349 DOWN_ARROW: 40,
340 350 DOWNARROW: 40,
341 351 DOWN : 40,
342 352 // all three of these keys may be COMMAND on OS X:
343 353 LEFT_SUPER : 91,
344 354 RIGHT_SUPER : 92,
345 355 COMMAND : 93,
346 356 };
347 357
348 358
349 359 var points_to_pixels = function (points) {
350 360 // A reasonably good way of converting between points and pixels.
351 361 var test = $('<div style="display: none; width: 10000pt; padding:0; border:0;"></div>');
352 362 $(body).append(test);
353 363 var pixel_per_point = test.width()/10000;
354 364 test.remove();
355 365 return Math.floor(points*pixel_per_point);
356 366 };
357 367
358 368 // http://stackoverflow.com/questions/2400935/browser-detection-in-javascript
359 369 browser = (function() {
360 370 var N= navigator.appName, ua= navigator.userAgent, tem;
361 371 var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
362 372 if (M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
363 373 M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
364 374 return M;
365 375 })();
366 376
367 377
368 378 return {
369 379 regex_split : regex_split,
370 380 uuid : uuid,
371 381 fixConsole : fixConsole,
372 382 keycodes : keycodes,
373 383 fixCarriageReturn : fixCarriageReturn,
374 384 autoLinkUrls : autoLinkUrls,
375 385 points_to_pixels : points_to_pixels,
376 386 browser : browser
377 387 };
378 388
379 389 }(IPython));
380 390
General Comments 0
You need to be logged in to leave comments. Login now