]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Fix cursor blinking when enabled
[mirror_xterm.js.git] / src / xterm.js
1 /**
2 * xterm.js: xterm, in the browser
3 * Copyright (c) 2014, sourceLair Limited (www.sourcelair.com (MIT License)
4 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
5 * https://github.com/chjj/term.js
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 *
25 * Originally forked from (with the author's permission):
26 * Fabrice Bellard's javascript vt100 for jslinux:
27 * http://bellard.org/jslinux/
28 * Copyright (c) 2011 Fabrice Bellard
29 * The original design remains. The terminal itself
30 * has been extended to include xterm CSI codes, among
31 * other features.
32 */
33
34 (function (xterm) {
35 if (typeof exports === 'object' && typeof module === 'object') {
36 /*
37 * CommonJS environment
38 */
39 module.exports = xterm.call(this);
40 } else if (typeof define == 'function') {
41 /*
42 * Require.js is available
43 */
44 define([], xterm.bind(window));
45 } else {
46 /*
47 * Plain browser environment
48 */
49 this.Xterm = xterm.call(this);
50 this.Terminal = this.Xterm; /* Backwards compatibility with term.js */
51 }
52 })(function() {
53 /**
54 * Terminal Emulation References:
55 * http://vt100.net/
56 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
57 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
58 * http://invisible-island.net/vttest/
59 * http://www.inwap.com/pdp10/ansicode.txt
60 * http://linux.die.net/man/4/console_codes
61 * http://linux.die.net/man/7/urxvt
62 */
63
64 'use strict';
65
66 /**
67 * Shared
68 */
69
70 var window = this, document = this.document;
71
72 /**
73 * EventEmitter
74 */
75
76 function EventEmitter() {
77 this._events = this._events || {};
78 }
79
80 EventEmitter.prototype.addListener = function(type, listener) {
81 this._events[type] = this._events[type] || [];
82 this._events[type].push(listener);
83 };
84
85 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
86
87 EventEmitter.prototype.removeListener = function(type, listener) {
88 if (!this._events[type]) return;
89
90 var obj = this._events[type]
91 , i = obj.length;
92
93 while (i--) {
94 if (obj[i] === listener || obj[i].listener === listener) {
95 obj.splice(i, 1);
96 return;
97 }
98 }
99 };
100
101 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
102
103 EventEmitter.prototype.removeAllListeners = function(type) {
104 if (this._events[type]) delete this._events[type];
105 };
106
107 EventEmitter.prototype.once = function(type, listener) {
108 var self = this;
109 function on() {
110 var args = Array.prototype.slice.call(arguments);
111 self.removeListener(type, on);
112 return listener.apply(self, args);
113 }
114 on.listener = listener;
115 return this.on(type, on);
116 };
117
118 EventEmitter.prototype.emit = function(type) {
119 if (!this._events[type]) return;
120
121 var args = Array.prototype.slice.call(arguments, 1)
122 , obj = this._events[type]
123 , l = obj.length
124 , i = 0;
125
126 for (; i < l; i++) {
127 obj[i].apply(this, args);
128 }
129 };
130
131 EventEmitter.prototype.listeners = function(type) {
132 return this._events[type] = this._events[type] || [];
133 };
134
135
136 /**
137 * States
138 */
139 var normal = 0, escaped = 1, csi = 2, osc = 3, charset = 4, dcs = 5, ignore = 6;
140
141 /**
142 * Terminal
143 */
144
145 function Terminal(options) {
146 var self = this;
147
148 if (!(this instanceof Terminal)) {
149 return new Terminal(arguments[0], arguments[1], arguments[2]);
150 }
151
152 self.cancel = Terminal.cancel;
153
154 EventEmitter.call(this);
155
156 if (typeof options === 'number') {
157 options = {
158 cols: arguments[0],
159 rows: arguments[1],
160 handler: arguments[2]
161 };
162 }
163
164 options = options || {};
165
166
167 Object.keys(Terminal.defaults).forEach(function(key) {
168 if (options[key] == null) {
169 options[key] = Terminal.options[key];
170
171 if (Terminal[key] !== Terminal.defaults[key]) {
172 options[key] = Terminal[key];
173 }
174 }
175 self[key] = options[key];
176 });
177
178 if (options.colors.length === 8) {
179 options.colors = options.colors.concat(Terminal._colors.slice(8));
180 } else if (options.colors.length === 16) {
181 options.colors = options.colors.concat(Terminal._colors.slice(16));
182 } else if (options.colors.length === 10) {
183 options.colors = options.colors.slice(0, -2).concat(
184 Terminal._colors.slice(8, -2), options.colors.slice(-2));
185 } else if (options.colors.length === 18) {
186 options.colors = options.colors.concat(
187 Terminal._colors.slice(16, -2), options.colors.slice(-2));
188 }
189 this.colors = options.colors;
190
191 this.options = options;
192
193 // this.context = options.context || window;
194 // this.document = options.document || document;
195 this.parent = options.body || options.parent
196 || (document ? document.getElementsByTagName('body')[0] : null);
197
198 this.cols = options.cols || options.geometry[0];
199 this.rows = options.rows || options.geometry[1];
200
201 if (options.handler) {
202 this.on('data', options.handler);
203 }
204
205 /**
206 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
207 */
208 this.ybase = 0;
209
210 /**
211 * The scroll position of the viewport
212 */
213 this.ydisp = 0;
214
215 /**
216 * The cursor's x position after ybase
217 */
218 this.x = 0;
219
220 /**
221 * The cursor's y position after ybase
222 */
223 this.y = 0;
224
225 this.cursorState = 0;
226 this.cursorHidden = false;
227 this.convertEol;
228 this.state = 0;
229 this.queue = '';
230 this.scrollTop = 0;
231 this.scrollBottom = this.rows - 1;
232
233 // modes
234 this.applicationKeypad = false;
235 this.applicationCursor = false;
236 this.originMode = false;
237 this.insertMode = false;
238 this.wraparoundMode = false;
239 this.normal = null;
240
241 // charset
242 this.charset = null;
243 this.gcharset = null;
244 this.glevel = 0;
245 this.charsets = [null];
246
247 // mouse properties
248 this.decLocator;
249 this.x10Mouse;
250 this.vt200Mouse;
251 this.vt300Mouse;
252 this.normalMouse;
253 this.mouseEvents;
254 this.sendFocus;
255 this.utfMouse;
256 this.sgrMouse;
257 this.urxvtMouse;
258
259 // misc
260 this.element;
261 this.children;
262 this.refreshStart;
263 this.refreshEnd;
264 this.savedX;
265 this.savedY;
266 this.savedCols;
267
268 // stream
269 this.readable = true;
270 this.writable = true;
271
272 this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
273 this.curAttr = this.defAttr;
274
275 this.params = [];
276 this.currentParam = 0;
277 this.prefix = '';
278 this.postfix = '';
279
280 /**
281 * An array of all lines in the entire buffer, including the prompt. The lines are array of
282 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
283 */
284 this.lines = [];
285 var i = this.rows;
286 while (i--) {
287 this.lines.push(this.blankLine());
288 }
289
290 this.tabs;
291 this.setupStops();
292 }
293
294 inherits(Terminal, EventEmitter);
295
296 // back_color_erase feature for xterm.
297 Terminal.prototype.eraseAttr = function() {
298 // if (this.is('screen')) return this.defAttr;
299 return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
300 };
301
302 /**
303 * Colors
304 */
305
306 // Colors 0-15
307 Terminal.tangoColors = [
308 // dark:
309 '#2e3436',
310 '#cc0000',
311 '#4e9a06',
312 '#c4a000',
313 '#3465a4',
314 '#75507b',
315 '#06989a',
316 '#d3d7cf',
317 // bright:
318 '#555753',
319 '#ef2929',
320 '#8ae234',
321 '#fce94f',
322 '#729fcf',
323 '#ad7fa8',
324 '#34e2e2',
325 '#eeeeec'
326 ];
327
328 // Colors 0-15 + 16-255
329 // Much thanks to TooTallNate for writing this.
330 Terminal.colors = (function() {
331 var colors = Terminal.tangoColors.slice()
332 , r = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
333 , i;
334
335 // 16-231
336 i = 0;
337 for (; i < 216; i++) {
338 out(r[(i / 36) % 6 | 0], r[(i / 6) % 6 | 0], r[i % 6]);
339 }
340
341 // 232-255 (grey)
342 i = 0;
343 for (; i < 24; i++) {
344 r = 8 + i * 10;
345 out(r, r, r);
346 }
347
348 function out(r, g, b) {
349 colors.push('#' + hex(r) + hex(g) + hex(b));
350 }
351
352 function hex(c) {
353 c = c.toString(16);
354 return c.length < 2 ? '0' + c : c;
355 }
356
357 return colors;
358 })();
359
360 Terminal._colors = Terminal.colors.slice();
361
362 Terminal.vcolors = (function() {
363 var out = []
364 , colors = Terminal.colors
365 , i = 0
366 , color;
367
368 for (; i < 256; i++) {
369 color = parseInt(colors[i].substring(1), 16);
370 out.push([
371 (color >> 16) & 0xff,
372 (color >> 8) & 0xff,
373 color & 0xff
374 ]);
375 }
376
377 return out;
378 })();
379
380 /**
381 * Options
382 */
383
384 Terminal.defaults = {
385 colors: Terminal.colors,
386 theme: 'default',
387 convertEol: false,
388 termName: 'xterm',
389 geometry: [80, 24],
390 cursorBlink: false,
391 visualBell: false,
392 popOnBell: false,
393 scrollback: 1000,
394 screenKeys: false,
395 debug: false,
396 cancelEvents: false
397 // programFeatures: false,
398 // focusKeys: false,
399 };
400
401 Terminal.options = {};
402
403 Terminal.focus = null;
404
405 each(keys(Terminal.defaults), function(key) {
406 Terminal[key] = Terminal.defaults[key];
407 Terminal.options[key] = Terminal.defaults[key];
408 });
409
410 /**
411 * Focused Terminal
412 */
413 Terminal.prototype.focus = function() {
414 if (document.activeElement === this.element) {
415 return;
416 }
417
418 if (this.sendFocus) {
419 this.send('\x1b[I');
420 }
421
422 this.showCursor();
423 this.element.focus();
424 };
425
426 Terminal.prototype.blur = function() {
427 if (Terminal.focus !== this) {
428 return;
429 }
430
431 this.cursorState = 0;
432 this.refresh(this.y, this.y);
433 this.element.blur();
434
435 if (this.sendFocus) {
436 this.send('\x1b[O');
437 }
438 Terminal.focus = null;
439 };
440
441 /**
442 * Initialize default behavior
443 */
444 Terminal.prototype.initGlobal = function() {
445 Terminal.bindKeys(this);
446 Terminal.bindPaste(this);
447 Terminal.bindCopy(this);
448 Terminal.bindCut(this);
449 Terminal.bindDrop(this);
450 };
451
452 /**
453 * Clears all selected text, inside the terminal.
454 */
455 Terminal.prototype.clearSelection = function() {
456 var selectionBaseNode = window.getSelection().baseNode;
457
458 if (selectionBaseNode && (this.element.contains(selectionBaseNode.parentElement))) {
459 window.getSelection().removeAllRanges();
460 }
461 };
462
463 /**
464 * This function temporarily enables (leases) the contentEditable value of the terminal, which
465 * should be set back to false within 5 seconds at most.
466 */
467 Terminal.prototype.leaseContentEditable = function (ms, callback) {
468 var term = this;
469
470 term.element.contentEditable = true;
471 setTimeout(function () {
472 term.element.contentEditable = false;
473 if (typeof callback == 'function') {
474 callback.call(term);
475 }
476 }, ms || 5000);
477 };
478
479 /**
480 * Bind to paste event and allow both keyboard and right-click pasting, without having the
481 * contentEditable value set to true.
482 */
483 Terminal.bindPaste = function(term) {
484 on(term.element, 'paste', function(ev) {
485 if (ev.clipboardData) {
486 var text = ev.clipboardData.getData('text/plain');
487 term.emit('paste', text, ev);
488 term.handler(text);
489 /**
490 * Cancel the paste event, or else things will be pasted twice:
491 * 1. by the terminal handler
492 * 2. by the browser, because of the contentEditable value being true
493 */
494 term.cancel(ev, true);
495
496 /**
497 * After the paste event is completed, always set the contentEditable value to false.
498 */
499 term.element.contentEditable = false;
500 }
501 });
502
503 /**
504 * Hack pasting with keyboard, in order to make it work without contentEditable.
505 * When a user types Ctrl + Shift + V or Cmd + V on a Mac, lease the contentEditable value
506 * as true.
507 */
508 on(term.element, 'keydown', function (ev) {
509 /**
510 * If on a Mac, lease the contentEditable value temporarily, when the user presses
511 * the Cmd button, in order to cope with some sync issues on Safari.
512 */
513 if (term.isMac && ev.keyCode == 91) {
514 term.leaseContentEditable(1000);
515 }
516
517 if (ev.keyCode == 86) { // keyCode 96 corresponds to "v"
518 if (term.isMac && ev.metaKey) {
519 term.leaseContentEditable();
520 }
521 }
522
523 if (!term.isMac && ev.keyCode == 45 && ev.shiftKey && !ev.ctrlKey) {
524 // Shift + Insert pastes on windows and many linuxes
525 term.leaseContentEditable();
526 }
527 });
528
529 /**
530 * Hack pasting with right-click in order to allow right-click paste, by leasing the
531 * contentEditable value as true.
532 */
533 on(term.element, 'contextmenu', function (ev) {
534 term.leaseContentEditable();
535 });
536 };
537
538
539 /*
540 * Apply key handling to the terminal
541 */
542 Terminal.bindKeys = function(term) {
543 on(term.element, 'keydown', function(ev) {
544 term.keyDown(ev);
545 }, true);
546
547 on(term.element, 'keypress', function(ev) {
548 term.keyPress(ev);
549 }, true);
550 };
551
552 /**
553 * Prepares text copied from terminal selection, to be saved in the clipboard by:
554 * 1. stripping all trailing white spaces
555 * 2. converting all non-breaking spaces to regular spaces
556 * @param {string} text The copied text that needs processing for storing in clipboard
557 * @returns {string}
558 * @static
559 */
560 Terminal.prepareCopiedTextForClipboard = function (text) {
561 var space = String.fromCharCode(32),
562 nonBreakingSpace = String.fromCharCode(160),
563 allNonBreakingSpaces = new RegExp(nonBreakingSpace, 'g'),
564 processedText = text.split('\n').map(function (line) {
565 /**
566 * Strip all trailing white spaces and convert all non-breaking spaces to regular
567 * spaces.
568 */
569 var processedLine = line.replace(/\s+$/g, '').replace(allNonBreakingSpaces, space);
570
571 return processedLine;
572 }).join('\n');
573
574 return processedText;
575 };
576
577 /**
578 * Binds copy functionality to the given terminal.
579 * @static
580 */
581 Terminal.bindCopy = function(term) {
582 on(term.element, 'copy', function(ev) {
583 var copiedText = window.getSelection().toString(),
584 text = Terminal.prepareCopiedTextForClipboard(copiedText);
585
586 ev.clipboardData.setData('text/plain', text);
587 ev.preventDefault();
588 });
589 };
590
591 /**
592 * Cancel the cut event completely
593 */
594 Terminal.bindCut = function(term) {
595 on(term.element, 'cut', function (ev) {
596 ev.preventDefault();
597 });
598 };
599
600
601 Terminal.bindDrop = function (term) {
602 /*
603 * Do not perform the "drop" event. Altering the contents of the
604 * terminal with drag n drop is unwanted behavior.
605 */
606 on(term.element, 'drop', function (ev) {
607 term.cancel(ev, true);
608 });
609 };
610
611
612 Terminal.click = function (term) {
613 /*
614 * Do not perform the "drop" event. Altering the contents of the
615 * terminal with drag n drop is unwanted behavior.
616 */
617 on(term.element, 'click', function (ev) {
618 term.cancel(ev, true);
619 });
620 };
621
622
623 /*
624 * Insert the given row to the terminal or produce a new one
625 * if no row argument is passed. Return the inserted row.
626 */
627 Terminal.prototype.insertRow = function (row) {
628 if (typeof row != 'object') {
629 row = document.createElement('div');
630 }
631
632 this.rowContainer.appendChild(row);
633 this.children.push(row);
634
635 return row;
636 };
637
638
639 /*
640 * Open Terminal in the DOM
641 */
642 Terminal.prototype.open = function(parent) {
643 var self=this, i=0, div;
644
645 this.parent = parent || this.parent;
646
647 if (!this.parent) {
648 throw new Error('Terminal requires a parent element.');
649 }
650
651 /*
652 * Grab global elements
653 */
654 this.context = this.parent.ownerDocument.defaultView;
655 this.document = this.parent.ownerDocument;
656 this.body = this.document.getElementsByTagName('body')[0];
657
658 /*
659 * Parse User-Agent
660 */
661 if (this.context.navigator && this.context.navigator.userAgent) {
662 this.isMSIE = !!~this.context.navigator.userAgent.indexOf('MSIE');
663 }
664
665 /*
666 * Find the users platform. We use this to interpret the meta key
667 * and ISO third level shifts.
668 * http://stackoverflow.com/questions/19877924/what-is-the-list-of-possible-values-for-navigator-platform-as-of-today
669 */
670 if (this.context.navigator && this.context.navigator.platform) {
671 this.isMac = contains(
672 this.context.navigator.platform,
673 ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K']
674 );
675 this.isIpad = this.context.navigator.platform === 'iPad';
676 this.isIphone = this.context.navigator.platform === 'iPhone';
677 this.isMSWindows = contains(
678 this.context.navigator.platform,
679 ['Windows', 'Win16', 'Win32', 'WinCE']
680 );
681 }
682
683 /*
684 * Create main element container
685 */
686 this.element = this.document.createElement('div');
687 this.element.classList.add('terminal');
688 this.element.classList.add('xterm');
689 this.element.classList.add('xterm-theme-' + this.theme);
690 this.element.setAttribute('tabindex', 0);
691 this.element.spellcheck = 'false';
692 this.element.onfocus = function() {
693 self.emit('focus', {terminal: this});
694 };
695 this.element.onblur = function() {
696 self.emit('blur', {terminal: this});
697 };
698
699 /*
700 * Create the container that will hold the lines of the terminal and then
701 * produce the lines the lines.
702 */
703 this.rowContainer = document.createElement('div');
704 this.rowContainer.classList.add('xterm-rows');
705 this.element.appendChild(this.rowContainer);
706 this.children = [];
707
708 for (; i < this.rows; i++) {
709 this.insertRow();
710 }
711 this.parent.appendChild(this.element);
712
713 // Draw the screen.
714 this.refresh(0, this.rows - 1);
715
716 // Initialize global actions that
717 // need to be taken on the document.
718 this.initGlobal();
719
720 // Ensure there is a Terminal.focus.
721 this.focus();
722
723 // Start blinking the cursor.
724 this.startBlink();
725
726 on(this.element, 'mouseup', function() {
727 var selection = document.getSelection(),
728 collapsed = selection.isCollapsed,
729 isRange = typeof collapsed == 'boolean' ? !collapsed : selection.type == 'Range';
730 if (!isRange) {
731 self.focus();
732 }
733 });
734
735 // Listen for mouse events and translate
736 // them into terminal mouse protocols.
737 this.bindMouse();
738
739 // Figure out whether boldness affects
740 // the character width of monospace fonts.
741 if (Terminal.brokenBold == null) {
742 Terminal.brokenBold = isBoldBroken(this.document);
743 }
744
745 this.emit('open');
746 };
747
748 // XTerm mouse events
749 // http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
750 // To better understand these
751 // the xterm code is very helpful:
752 // Relevant files:
753 // button.c, charproc.c, misc.c
754 // Relevant functions in xterm/button.c:
755 // BtnCode, EmitButtonCode, EditorButton, SendMousePosition
756 Terminal.prototype.bindMouse = function() {
757 var el = this.element
758 , self = this
759 , pressed = 32;
760
761 var wheelEvent = 'onmousewheel' in this.context
762 ? 'mousewheel'
763 : 'DOMMouseScroll';
764
765 // mouseup, mousedown, mousewheel
766 // left click: ^[[M 3<^[[M#3<
767 // mousewheel up: ^[[M`3>
768 function sendButton(ev) {
769 var button
770 , pos;
771
772 // get the xterm-style button
773 button = getButton(ev);
774
775 // get mouse coordinates
776 pos = getCoords(ev);
777 if (!pos) return;
778
779 sendEvent(button, pos);
780
781 switch (ev.type) {
782 case 'mousedown':
783 pressed = button;
784 break;
785 case 'mouseup':
786 // keep it at the left
787 // button, just in case.
788 pressed = 32;
789 break;
790 case wheelEvent:
791 // nothing. don't
792 // interfere with
793 // `pressed`.
794 break;
795 }
796 }
797
798 // motion example of a left click:
799 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
800 function sendMove(ev) {
801 var button = pressed
802 , pos;
803
804 pos = getCoords(ev);
805 if (!pos) return;
806
807 // buttons marked as motions
808 // are incremented by 32
809 button += 32;
810
811 sendEvent(button, pos);
812 }
813
814 // encode button and
815 // position to characters
816 function encode(data, ch) {
817 if (!self.utfMouse) {
818 if (ch === 255) return data.push(0);
819 if (ch > 127) ch = 127;
820 data.push(ch);
821 } else {
822 if (ch === 2047) return data.push(0);
823 if (ch < 127) {
824 data.push(ch);
825 } else {
826 if (ch > 2047) ch = 2047;
827 data.push(0xC0 | (ch >> 6));
828 data.push(0x80 | (ch & 0x3F));
829 }
830 }
831 }
832
833 // send a mouse event:
834 // regular/utf8: ^[[M Cb Cx Cy
835 // urxvt: ^[[ Cb ; Cx ; Cy M
836 // sgr: ^[[ Cb ; Cx ; Cy M/m
837 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
838 // locator: CSI P e ; P b ; P r ; P c ; P p & w
839 function sendEvent(button, pos) {
840 // self.emit('mouse', {
841 // x: pos.x - 32,
842 // y: pos.x - 32,
843 // button: button
844 // });
845
846 if (self.vt300Mouse) {
847 // NOTE: Unstable.
848 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
849 button &= 3;
850 pos.x -= 32;
851 pos.y -= 32;
852 var data = '\x1b[24';
853 if (button === 0) data += '1';
854 else if (button === 1) data += '3';
855 else if (button === 2) data += '5';
856 else if (button === 3) return;
857 else data += '0';
858 data += '~[' + pos.x + ',' + pos.y + ']\r';
859 self.send(data);
860 return;
861 }
862
863 if (self.decLocator) {
864 // NOTE: Unstable.
865 button &= 3;
866 pos.x -= 32;
867 pos.y -= 32;
868 if (button === 0) button = 2;
869 else if (button === 1) button = 4;
870 else if (button === 2) button = 6;
871 else if (button === 3) button = 3;
872 self.send('\x1b['
873 + button
874 + ';'
875 + (button === 3 ? 4 : 0)
876 + ';'
877 + pos.y
878 + ';'
879 + pos.x
880 + ';'
881 + (pos.page || 0)
882 + '&w');
883 return;
884 }
885
886 if (self.urxvtMouse) {
887 pos.x -= 32;
888 pos.y -= 32;
889 pos.x++;
890 pos.y++;
891 self.send('\x1b[' + button + ';' + pos.x + ';' + pos.y + 'M');
892 return;
893 }
894
895 if (self.sgrMouse) {
896 pos.x -= 32;
897 pos.y -= 32;
898 self.send('\x1b[<'
899 + ((button & 3) === 3 ? button & ~3 : button)
900 + ';'
901 + pos.x
902 + ';'
903 + pos.y
904 + ((button & 3) === 3 ? 'm' : 'M'));
905 return;
906 }
907
908 var data = [];
909
910 encode(data, button);
911 encode(data, pos.x);
912 encode(data, pos.y);
913
914 self.send('\x1b[M' + String.fromCharCode.apply(String, data));
915 }
916
917 function getButton(ev) {
918 var button
919 , shift
920 , meta
921 , ctrl
922 , mod;
923
924 // two low bits:
925 // 0 = left
926 // 1 = middle
927 // 2 = right
928 // 3 = release
929 // wheel up/down:
930 // 1, and 2 - with 64 added
931 switch (ev.type) {
932 case 'mousedown':
933 button = ev.button != null
934 ? +ev.button
935 : ev.which != null
936 ? ev.which - 1
937 : null;
938
939 if (self.isMSIE) {
940 button = button === 1 ? 0 : button === 4 ? 1 : button;
941 }
942 break;
943 case 'mouseup':
944 button = 3;
945 break;
946 case 'DOMMouseScroll':
947 button = ev.detail < 0
948 ? 64
949 : 65;
950 break;
951 case 'mousewheel':
952 button = ev.wheelDeltaY > 0
953 ? 64
954 : 65;
955 break;
956 }
957
958 // next three bits are the modifiers:
959 // 4 = shift, 8 = meta, 16 = control
960 shift = ev.shiftKey ? 4 : 0;
961 meta = ev.metaKey ? 8 : 0;
962 ctrl = ev.ctrlKey ? 16 : 0;
963 mod = shift | meta | ctrl;
964
965 // no mods
966 if (self.vt200Mouse) {
967 // ctrl only
968 mod &= ctrl;
969 } else if (!self.normalMouse) {
970 mod = 0;
971 }
972
973 // increment to SP
974 button = (32 + (mod << 2)) + button;
975
976 return button;
977 }
978
979 // mouse coordinates measured in cols/rows
980 function getCoords(ev) {
981 var x, y, w, h, el;
982
983 // ignore browsers without pageX for now
984 if (ev.pageX == null) return;
985
986 x = ev.pageX;
987 y = ev.pageY;
988 el = self.element;
989
990 // should probably check offsetParent
991 // but this is more portable
992 while (el && el !== self.document.documentElement) {
993 x -= el.offsetLeft;
994 y -= el.offsetTop;
995 el = 'offsetParent' in el
996 ? el.offsetParent
997 : el.parentNode;
998 }
999
1000 // convert to cols/rows
1001 w = self.element.clientWidth;
1002 h = self.element.clientHeight;
1003 x = Math.round((x / w) * self.cols);
1004 y = Math.round((y / h) * self.rows);
1005
1006 // be sure to avoid sending
1007 // bad positions to the program
1008 if (x < 0) x = 0;
1009 if (x > self.cols) x = self.cols;
1010 if (y < 0) y = 0;
1011 if (y > self.rows) y = self.rows;
1012
1013 // xterm sends raw bytes and
1014 // starts at 32 (SP) for each.
1015 x += 32;
1016 y += 32;
1017
1018 return {
1019 x: x,
1020 y: y,
1021 type: ev.type === wheelEvent
1022 ? 'mousewheel'
1023 : ev.type
1024 };
1025 }
1026
1027 on(el, 'mousedown', function(ev) {
1028 if (!self.mouseEvents) return;
1029
1030 // send the button
1031 sendButton(ev);
1032
1033 // ensure focus
1034 self.focus();
1035
1036 // fix for odd bug
1037 //if (self.vt200Mouse && !self.normalMouse) {
1038 if (self.vt200Mouse) {
1039 sendButton({ __proto__: ev, type: 'mouseup' });
1040 return self.cancel(ev);
1041 }
1042
1043 // bind events
1044 if (self.normalMouse) on(self.document, 'mousemove', sendMove);
1045
1046 // x10 compatibility mode can't send button releases
1047 if (!self.x10Mouse) {
1048 on(self.document, 'mouseup', function up(ev) {
1049 sendButton(ev);
1050 if (self.normalMouse) off(self.document, 'mousemove', sendMove);
1051 off(self.document, 'mouseup', up);
1052 return self.cancel(ev);
1053 });
1054 }
1055
1056 return self.cancel(ev);
1057 });
1058
1059 //if (self.normalMouse) {
1060 // on(self.document, 'mousemove', sendMove);
1061 //}
1062
1063 on(el, wheelEvent, function(ev) {
1064 if (!self.mouseEvents) return;
1065 if (self.x10Mouse
1066 || self.vt300Mouse
1067 || self.decLocator) return;
1068 sendButton(ev);
1069 return self.cancel(ev);
1070 });
1071
1072 // allow mousewheel scrolling in
1073 // the shell for example
1074 on(el, wheelEvent, function(ev) {
1075 if (self.mouseEvents) return;
1076 if (self.applicationKeypad) return;
1077 if (ev.type === 'DOMMouseScroll') {
1078 self.scrollDisp(ev.detail < 0 ? -1 : 1);
1079 } else {
1080 self.scrollDisp(ev.wheelDeltaY > 0 ? -1 : 1);
1081 }
1082 return self.cancel(ev);
1083 });
1084 };
1085
1086 /**
1087 * Destroy Terminal
1088 */
1089
1090 Terminal.prototype.destroy = function() {
1091 this.readable = false;
1092 this.writable = false;
1093 this._events = {};
1094 this.handler = function() {};
1095 this.write = function() {};
1096 if (this.element.parentNode) {
1097 this.element.parentNode.removeChild(this.element);
1098 }
1099 //this.emit('close');
1100 };
1101
1102
1103 /**
1104 * Flags used to render terminal text properly
1105 */
1106 Terminal.flags = {
1107 BOLD: 1,
1108 UNDERLINE: 2,
1109 BLINK: 4,
1110 INVERSE: 8,
1111 INVISIBLE: 16
1112 }
1113
1114 /*
1115 * Rendering Engine
1116 *
1117 * In the screen buffer, each character
1118 * is stored as a an array with a character
1119 * and a 32-bit integer.
1120 * First value: a utf-16 character.
1121 * Second value:
1122 * Next 9 bits: background color (0-511).
1123 * Next 9 bits: foreground color (0-511).
1124 * Next 14 bits: a mask for misc. flags:
1125 * 1=bold, 2=underline, 4=blink, 8=inverse, 16=invisible
1126 */
1127 Terminal.prototype.refresh = function(start, end) {
1128 var x, y, i, line, out, ch, width, data, attr, bg, fg, flags, row, parent, focused = document.activeElement;
1129
1130 if (end - start >= this.rows / 2) {
1131 parent = this.element.parentNode;
1132 if (parent) parent.removeChild(this.element);
1133 }
1134
1135 width = this.cols;
1136 y = start;
1137
1138 if (end >= this.lines.length) {
1139 this.log('`end` is too large. Most likely a bad CSR.');
1140 end = this.lines.length - 1;
1141 }
1142
1143 for (; y <= end; y++) {
1144 row = y + this.ydisp;
1145
1146 line = this.lines[row];
1147 out = '';
1148
1149 if (this.y === y - (this.ybase - this.ydisp)
1150 && this.cursorState
1151 && !this.cursorHidden) {
1152 x = this.x;
1153 } else {
1154 x = -1;
1155 }
1156
1157 attr = this.defAttr;
1158 i = 0;
1159
1160 for (; i < width; i++) {
1161 data = line[i][0];
1162 ch = line[i][1];
1163
1164 if (i === x) data = -1;
1165
1166 if (data !== attr) {
1167 if (attr !== this.defAttr) {
1168 out += '</span>';
1169 }
1170 if (data !== this.defAttr) {
1171 if (data === -1) {
1172 out += '<span class="reverse-video terminal-cursor">';
1173 } else {
1174 var classNames = [];
1175
1176 bg = data & 0x1ff;
1177 fg = (data >> 9) & 0x1ff;
1178 flags = data >> 18;
1179
1180 if (flags & Terminal.flags.BOLD) {
1181 if (!Terminal.brokenBold) {
1182 classNames.push('xterm-bold');
1183 }
1184 // See: XTerm*boldColors
1185 if (fg < 8) fg += 8;
1186 }
1187
1188 if (flags & Terminal.flags.UNDERLINE) {
1189 classNames.push('xterm-underline');
1190 }
1191
1192 if (flags & Terminal.flags.BLINK) {
1193 classNames.push('xterm-blink');
1194 }
1195
1196 /**
1197 * If inverse flag is on, then swap the foreground and background variables.
1198 */
1199 if (flags & Terminal.flags.INVERSE) {
1200 /* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
1201 bg = [fg, fg = bg][0];
1202 // Should inverse just be before the
1203 // above boldColors effect instead?
1204 if ((flags & 1) && fg < 8) fg += 8;
1205 }
1206
1207 if (flags & Terminal.flags.INVISIBLE) {
1208 classNames.push('xterm-hidden');
1209 }
1210
1211 /**
1212 * Weird situation: Invert flag used black foreground and white background results
1213 * in invalid background color, positioned at the 256 index of the 256 terminal
1214 * color map. Pin the colors manually in such a case.
1215 *
1216 * Source: https://github.com/sourcelair/xterm.js/issues/57
1217 */
1218 if (flags & Terminal.flags.INVERSE) {
1219 if (bg == 257) {
1220 bg = 15;
1221 }
1222 if (fg == 256) {
1223 fg = 0;
1224 }
1225 }
1226
1227 if (bg < 256) {
1228 classNames.push('xterm-bg-color-' + bg);
1229 }
1230
1231 if (fg < 256) {
1232 classNames.push('xterm-color-' + fg);
1233 }
1234
1235 out += '<span';
1236 if (classNames.length) {
1237 out += ' class="' + classNames.join(' ') + '"';
1238 }
1239 out += '>';
1240 }
1241 }
1242 }
1243
1244 switch (ch) {
1245 case '&':
1246 out += '&amp;';
1247 break;
1248 case '<':
1249 out += '&lt;';
1250 break;
1251 case '>':
1252 out += '&gt;';
1253 break;
1254 default:
1255 if (ch <= ' ') {
1256 out += '&nbsp;';
1257 } else {
1258 if (isWide(ch)) i++;
1259 out += ch;
1260 }
1261 break;
1262 }
1263
1264 attr = data;
1265 }
1266
1267 if (attr !== this.defAttr) {
1268 out += '</span>';
1269 }
1270
1271 this.children[y].innerHTML = out;
1272 }
1273
1274 if (parent) {
1275 parent.appendChild(this.element);
1276 }
1277
1278 /*
1279 * Return focus to previously focused element
1280 */
1281 focused.focus();
1282 this.emit('refresh', {element: this.element, start: start, end: end});
1283 };
1284
1285 Terminal.prototype._cursorBlink = function() {
1286 if (document.activeElement !== this.element) return;
1287 this.cursorState ^= 1;
1288 this.refresh(this.y, this.y);
1289 };
1290
1291 Terminal.prototype.showCursor = function() {
1292 if (!this.cursorState) {
1293 this.cursorState = 1;
1294 this.refresh(this.y, this.y);
1295 } else {
1296 this.refreshBlink();
1297 }
1298 };
1299
1300 Terminal.prototype.startBlink = function() {
1301 if (!this.cursorBlink) return;
1302 var self = this;
1303 this._blinker = function() {
1304 self._cursorBlink();
1305 };
1306 this._blink = setInterval(this._blinker, 500);
1307 };
1308
1309 Terminal.prototype.refreshBlink = function() {
1310 if (!this.cursorBlink) return;
1311 clearInterval(this._blink);
1312 this._blink = setInterval(this._blinker, 500);
1313 };
1314
1315 Terminal.prototype.scroll = function() {
1316 var row;
1317
1318 if (++this.ybase === this.scrollback) {
1319 this.ybase = this.ybase / 2 | 0;
1320 this.lines = this.lines.slice(-(this.ybase + this.rows) + 1);
1321 }
1322
1323 this.ydisp = this.ybase;
1324
1325 // last line
1326 row = this.ybase + this.rows - 1;
1327
1328 // subtract the bottom scroll region
1329 row -= this.rows - 1 - this.scrollBottom;
1330
1331 if (row === this.lines.length) {
1332 // potential optimization:
1333 // pushing is faster than splicing
1334 // when they amount to the same
1335 // behavior.
1336 this.lines.push(this.blankLine());
1337 } else {
1338 // add our new line
1339 this.lines.splice(row, 0, this.blankLine());
1340 }
1341
1342 if (this.scrollTop !== 0) {
1343 if (this.ybase !== 0) {
1344 this.ybase--;
1345 this.ydisp = this.ybase;
1346 }
1347 this.lines.splice(this.ybase + this.scrollTop, 1);
1348 }
1349
1350 // this.maxRange();
1351 this.updateRange(this.scrollTop);
1352 this.updateRange(this.scrollBottom);
1353 };
1354
1355 Terminal.prototype.scrollDisp = function(disp) {
1356 this.ydisp += disp;
1357
1358 if (this.ydisp > this.ybase) {
1359 this.ydisp = this.ybase;
1360 } else if (this.ydisp < 0) {
1361 this.ydisp = 0;
1362 }
1363
1364 this.refresh(0, this.rows - 1);
1365 };
1366
1367 Terminal.prototype.write = function(data) {
1368 var l = data.length, i = 0, j, cs, ch;
1369
1370 this.refreshStart = this.y;
1371 this.refreshEnd = this.y;
1372
1373 if (this.ybase !== this.ydisp) {
1374 this.ydisp = this.ybase;
1375 this.maxRange();
1376 }
1377
1378 for (; i < l; i++) {
1379 ch = data[i];
1380 switch (this.state) {
1381 case normal:
1382 switch (ch) {
1383 case '\x07':
1384 this.bell();
1385 break;
1386
1387 // '\n', '\v', '\f'
1388 case '\n':
1389 case '\x0b':
1390 case '\x0c':
1391 if (this.convertEol) {
1392 this.x = 0;
1393 }
1394 this.y++;
1395 if (this.y > this.scrollBottom) {
1396 this.y--;
1397 this.scroll();
1398 }
1399 break;
1400
1401 // '\r'
1402 case '\r':
1403 this.x = 0;
1404 break;
1405
1406 // '\b'
1407 case '\x08':
1408 if (this.x > 0) {
1409 this.x--;
1410 }
1411 break;
1412
1413 // '\t'
1414 case '\t':
1415 this.x = this.nextStop();
1416 break;
1417
1418 // shift out
1419 case '\x0e':
1420 this.setgLevel(1);
1421 break;
1422
1423 // shift in
1424 case '\x0f':
1425 this.setgLevel(0);
1426 break;
1427
1428 // '\e'
1429 case '\x1b':
1430 this.state = escaped;
1431 break;
1432
1433 default:
1434 // ' '
1435 if (ch >= ' ') {
1436 if (this.charset && this.charset[ch]) {
1437 ch = this.charset[ch];
1438 }
1439
1440 if (this.x >= this.cols) {
1441 this.x = 0;
1442 this.y++;
1443 if (this.y > this.scrollBottom) {
1444 this.y--;
1445 this.scroll();
1446 }
1447 }
1448
1449 this.lines[this.y + this.ybase][this.x] = [this.curAttr, ch];
1450 this.x++;
1451 this.updateRange(this.y);
1452
1453 if (isWide(ch)) {
1454 j = this.y + this.ybase;
1455 if (this.cols < 2 || this.x >= this.cols) {
1456 this.lines[j][this.x - 1] = [this.curAttr, ' '];
1457 break;
1458 }
1459 this.lines[j][this.x] = [this.curAttr, ' '];
1460 this.x++;
1461 }
1462 }
1463 break;
1464 }
1465 break;
1466 case escaped:
1467 switch (ch) {
1468 // ESC [ Control Sequence Introducer ( CSI is 0x9b).
1469 case '[':
1470 this.params = [];
1471 this.currentParam = 0;
1472 this.state = csi;
1473 break;
1474
1475 // ESC ] Operating System Command ( OSC is 0x9d).
1476 case ']':
1477 this.params = [];
1478 this.currentParam = 0;
1479 this.state = osc;
1480 break;
1481
1482 // ESC P Device Control String ( DCS is 0x90).
1483 case 'P':
1484 this.params = [];
1485 this.currentParam = 0;
1486 this.state = dcs;
1487 break;
1488
1489 // ESC _ Application Program Command ( APC is 0x9f).
1490 case '_':
1491 this.state = ignore;
1492 break;
1493
1494 // ESC ^ Privacy Message ( PM is 0x9e).
1495 case '^':
1496 this.state = ignore;
1497 break;
1498
1499 // ESC c Full Reset (RIS).
1500 case 'c':
1501 this.reset();
1502 break;
1503
1504 // ESC E Next Line ( NEL is 0x85).
1505 // ESC D Index ( IND is 0x84).
1506 case 'E':
1507 this.x = 0;
1508 ;
1509 case 'D':
1510 this.index();
1511 break;
1512
1513 // ESC M Reverse Index ( RI is 0x8d).
1514 case 'M':
1515 this.reverseIndex();
1516 break;
1517
1518 // ESC % Select default/utf-8 character set.
1519 // @ = default, G = utf-8
1520 case '%':
1521 //this.charset = null;
1522 this.setgLevel(0);
1523 this.setgCharset(0, Terminal.charsets.US);
1524 this.state = normal;
1525 i++;
1526 break;
1527
1528 // ESC (,),*,+,-,. Designate G0-G2 Character Set.
1529 case '(': // <-- this seems to get all the attention
1530 case ')':
1531 case '*':
1532 case '+':
1533 case '-':
1534 case '.':
1535 switch (ch) {
1536 case '(':
1537 this.gcharset = 0;
1538 break;
1539 case ')':
1540 this.gcharset = 1;
1541 break;
1542 case '*':
1543 this.gcharset = 2;
1544 break;
1545 case '+':
1546 this.gcharset = 3;
1547 break;
1548 case '-':
1549 this.gcharset = 1;
1550 break;
1551 case '.':
1552 this.gcharset = 2;
1553 break;
1554 }
1555 this.state = charset;
1556 break;
1557
1558 // Designate G3 Character Set (VT300).
1559 // A = ISO Latin-1 Supplemental.
1560 // Not implemented.
1561 case '/':
1562 this.gcharset = 3;
1563 this.state = charset;
1564 i--;
1565 break;
1566
1567 // ESC N
1568 // Single Shift Select of G2 Character Set
1569 // ( SS2 is 0x8e). This affects next character only.
1570 case 'N':
1571 break;
1572 // ESC O
1573 // Single Shift Select of G3 Character Set
1574 // ( SS3 is 0x8f). This affects next character only.
1575 case 'O':
1576 break;
1577 // ESC n
1578 // Invoke the G2 Character Set as GL (LS2).
1579 case 'n':
1580 this.setgLevel(2);
1581 break;
1582 // ESC o
1583 // Invoke the G3 Character Set as GL (LS3).
1584 case 'o':
1585 this.setgLevel(3);
1586 break;
1587 // ESC |
1588 // Invoke the G3 Character Set as GR (LS3R).
1589 case '|':
1590 this.setgLevel(3);
1591 break;
1592 // ESC }
1593 // Invoke the G2 Character Set as GR (LS2R).
1594 case '}':
1595 this.setgLevel(2);
1596 break;
1597 // ESC ~
1598 // Invoke the G1 Character Set as GR (LS1R).
1599 case '~':
1600 this.setgLevel(1);
1601 break;
1602
1603 // ESC 7 Save Cursor (DECSC).
1604 case '7':
1605 this.saveCursor();
1606 this.state = normal;
1607 break;
1608
1609 // ESC 8 Restore Cursor (DECRC).
1610 case '8':
1611 this.restoreCursor();
1612 this.state = normal;
1613 break;
1614
1615 // ESC # 3 DEC line height/width
1616 case '#':
1617 this.state = normal;
1618 i++;
1619 break;
1620
1621 // ESC H Tab Set (HTS is 0x88).
1622 case 'H':
1623 this.tabSet();
1624 break;
1625
1626 // ESC = Application Keypad (DECPAM).
1627 case '=':
1628 this.log('Serial port requested application keypad.');
1629 this.applicationKeypad = true;
1630 this.state = normal;
1631 break;
1632
1633 // ESC > Normal Keypad (DECPNM).
1634 case '>':
1635 this.log('Switching back to normal keypad.');
1636 this.applicationKeypad = false;
1637 this.state = normal;
1638 break;
1639
1640 default:
1641 this.state = normal;
1642 this.error('Unknown ESC control: %s.', ch);
1643 break;
1644 }
1645 break;
1646
1647 case charset:
1648 switch (ch) {
1649 case '0': // DEC Special Character and Line Drawing Set.
1650 cs = Terminal.charsets.SCLD;
1651 break;
1652 case 'A': // UK
1653 cs = Terminal.charsets.UK;
1654 break;
1655 case 'B': // United States (USASCII).
1656 cs = Terminal.charsets.US;
1657 break;
1658 case '4': // Dutch
1659 cs = Terminal.charsets.Dutch;
1660 break;
1661 case 'C': // Finnish
1662 case '5':
1663 cs = Terminal.charsets.Finnish;
1664 break;
1665 case 'R': // French
1666 cs = Terminal.charsets.French;
1667 break;
1668 case 'Q': // FrenchCanadian
1669 cs = Terminal.charsets.FrenchCanadian;
1670 break;
1671 case 'K': // German
1672 cs = Terminal.charsets.German;
1673 break;
1674 case 'Y': // Italian
1675 cs = Terminal.charsets.Italian;
1676 break;
1677 case 'E': // NorwegianDanish
1678 case '6':
1679 cs = Terminal.charsets.NorwegianDanish;
1680 break;
1681 case 'Z': // Spanish
1682 cs = Terminal.charsets.Spanish;
1683 break;
1684 case 'H': // Swedish
1685 case '7':
1686 cs = Terminal.charsets.Swedish;
1687 break;
1688 case '=': // Swiss
1689 cs = Terminal.charsets.Swiss;
1690 break;
1691 case '/': // ISOLatin (actually /A)
1692 cs = Terminal.charsets.ISOLatin;
1693 i++;
1694 break;
1695 default: // Default
1696 cs = Terminal.charsets.US;
1697 break;
1698 }
1699 this.setgCharset(this.gcharset, cs);
1700 this.gcharset = null;
1701 this.state = normal;
1702 break;
1703
1704 case osc:
1705 // OSC Ps ; Pt ST
1706 // OSC Ps ; Pt BEL
1707 // Set Text Parameters.
1708 if (ch === '\x1b' || ch === '\x07') {
1709 if (ch === '\x1b') i++;
1710
1711 this.params.push(this.currentParam);
1712
1713 switch (this.params[0]) {
1714 case 0:
1715 case 1:
1716 case 2:
1717 if (this.params[1]) {
1718 this.title = this.params[1];
1719 this.handleTitle(this.title);
1720 }
1721 break;
1722 case 3:
1723 // set X property
1724 break;
1725 case 4:
1726 case 5:
1727 // change dynamic colors
1728 break;
1729 case 10:
1730 case 11:
1731 case 12:
1732 case 13:
1733 case 14:
1734 case 15:
1735 case 16:
1736 case 17:
1737 case 18:
1738 case 19:
1739 // change dynamic ui colors
1740 break;
1741 case 46:
1742 // change log file
1743 break;
1744 case 50:
1745 // dynamic font
1746 break;
1747 case 51:
1748 // emacs shell
1749 break;
1750 case 52:
1751 // manipulate selection data
1752 break;
1753 case 104:
1754 case 105:
1755 case 110:
1756 case 111:
1757 case 112:
1758 case 113:
1759 case 114:
1760 case 115:
1761 case 116:
1762 case 117:
1763 case 118:
1764 // reset colors
1765 break;
1766 }
1767
1768 this.params = [];
1769 this.currentParam = 0;
1770 this.state = normal;
1771 } else {
1772 if (!this.params.length) {
1773 if (ch >= '0' && ch <= '9') {
1774 this.currentParam =
1775 this.currentParam * 10 + ch.charCodeAt(0) - 48;
1776 } else if (ch === ';') {
1777 this.params.push(this.currentParam);
1778 this.currentParam = '';
1779 }
1780 } else {
1781 this.currentParam += ch;
1782 }
1783 }
1784 break;
1785
1786 case csi:
1787 // '?', '>', '!'
1788 if (ch === '?' || ch === '>' || ch === '!') {
1789 this.prefix = ch;
1790 break;
1791 }
1792
1793 // 0 - 9
1794 if (ch >= '0' && ch <= '9') {
1795 this.currentParam = this.currentParam * 10 + ch.charCodeAt(0) - 48;
1796 break;
1797 }
1798
1799 // '$', '"', ' ', '\''
1800 if (ch === '$' || ch === '"' || ch === ' ' || ch === '\'') {
1801 this.postfix = ch;
1802 break;
1803 }
1804
1805 this.params.push(this.currentParam);
1806 this.currentParam = 0;
1807
1808 // ';'
1809 if (ch === ';') break;
1810
1811 this.state = normal;
1812
1813 switch (ch) {
1814 // CSI Ps A
1815 // Cursor Up Ps Times (default = 1) (CUU).
1816 case 'A':
1817 this.cursorUp(this.params);
1818 break;
1819
1820 // CSI Ps B
1821 // Cursor Down Ps Times (default = 1) (CUD).
1822 case 'B':
1823 this.cursorDown(this.params);
1824 break;
1825
1826 // CSI Ps C
1827 // Cursor Forward Ps Times (default = 1) (CUF).
1828 case 'C':
1829 this.cursorForward(this.params);
1830 break;
1831
1832 // CSI Ps D
1833 // Cursor Backward Ps Times (default = 1) (CUB).
1834 case 'D':
1835 this.cursorBackward(this.params);
1836 break;
1837
1838 // CSI Ps ; Ps H
1839 // Cursor Position [row;column] (default = [1,1]) (CUP).
1840 case 'H':
1841 this.cursorPos(this.params);
1842 break;
1843
1844 // CSI Ps J Erase in Display (ED).
1845 case 'J':
1846 this.eraseInDisplay(this.params);
1847 break;
1848
1849 // CSI Ps K Erase in Line (EL).
1850 case 'K':
1851 this.eraseInLine(this.params);
1852 break;
1853
1854 // CSI Pm m Character Attributes (SGR).
1855 case 'm':
1856 if (!this.prefix) {
1857 this.charAttributes(this.params);
1858 }
1859 break;
1860
1861 // CSI Ps n Device Status Report (DSR).
1862 case 'n':
1863 if (!this.prefix) {
1864 this.deviceStatus(this.params);
1865 }
1866 break;
1867
1868 /**
1869 * Additions
1870 */
1871
1872 // CSI Ps @
1873 // Insert Ps (Blank) Character(s) (default = 1) (ICH).
1874 case '@':
1875 this.insertChars(this.params);
1876 break;
1877
1878 // CSI Ps E
1879 // Cursor Next Line Ps Times (default = 1) (CNL).
1880 case 'E':
1881 this.cursorNextLine(this.params);
1882 break;
1883
1884 // CSI Ps F
1885 // Cursor Preceding Line Ps Times (default = 1) (CNL).
1886 case 'F':
1887 this.cursorPrecedingLine(this.params);
1888 break;
1889
1890 // CSI Ps G
1891 // Cursor Character Absolute [column] (default = [row,1]) (CHA).
1892 case 'G':
1893 this.cursorCharAbsolute(this.params);
1894 break;
1895
1896 // CSI Ps L
1897 // Insert Ps Line(s) (default = 1) (IL).
1898 case 'L':
1899 this.insertLines(this.params);
1900 break;
1901
1902 // CSI Ps M
1903 // Delete Ps Line(s) (default = 1) (DL).
1904 case 'M':
1905 this.deleteLines(this.params);
1906 break;
1907
1908 // CSI Ps P
1909 // Delete Ps Character(s) (default = 1) (DCH).
1910 case 'P':
1911 this.deleteChars(this.params);
1912 break;
1913
1914 // CSI Ps X
1915 // Erase Ps Character(s) (default = 1) (ECH).
1916 case 'X':
1917 this.eraseChars(this.params);
1918 break;
1919
1920 // CSI Pm ` Character Position Absolute
1921 // [column] (default = [row,1]) (HPA).
1922 case '`':
1923 this.charPosAbsolute(this.params);
1924 break;
1925
1926 // 141 61 a * HPR -
1927 // Horizontal Position Relative
1928 case 'a':
1929 this.HPositionRelative(this.params);
1930 break;
1931
1932 // CSI P s c
1933 // Send Device Attributes (Primary DA).
1934 // CSI > P s c
1935 // Send Device Attributes (Secondary DA)
1936 case 'c':
1937 this.sendDeviceAttributes(this.params);
1938 break;
1939
1940 // CSI Pm d
1941 // Line Position Absolute [row] (default = [1,column]) (VPA).
1942 case 'd':
1943 this.linePosAbsolute(this.params);
1944 break;
1945
1946 // 145 65 e * VPR - Vertical Position Relative
1947 case 'e':
1948 this.VPositionRelative(this.params);
1949 break;
1950
1951 // CSI Ps ; Ps f
1952 // Horizontal and Vertical Position [row;column] (default =
1953 // [1,1]) (HVP).
1954 case 'f':
1955 this.HVPosition(this.params);
1956 break;
1957
1958 // CSI Pm h Set Mode (SM).
1959 // CSI ? Pm h - mouse escape codes, cursor escape codes
1960 case 'h':
1961 this.setMode(this.params);
1962 break;
1963
1964 // CSI Pm l Reset Mode (RM).
1965 // CSI ? Pm l
1966 case 'l':
1967 this.resetMode(this.params);
1968 break;
1969
1970 // CSI Ps ; Ps r
1971 // Set Scrolling Region [top;bottom] (default = full size of win-
1972 // dow) (DECSTBM).
1973 // CSI ? Pm r
1974 case 'r':
1975 this.setScrollRegion(this.params);
1976 break;
1977
1978 // CSI s
1979 // Save cursor (ANSI.SYS).
1980 case 's':
1981 this.saveCursor(this.params);
1982 break;
1983
1984 // CSI u
1985 // Restore cursor (ANSI.SYS).
1986 case 'u':
1987 this.restoreCursor(this.params);
1988 break;
1989
1990 /**
1991 * Lesser Used
1992 */
1993
1994 // CSI Ps I
1995 // Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
1996 case 'I':
1997 this.cursorForwardTab(this.params);
1998 break;
1999
2000 // CSI Ps S Scroll up Ps lines (default = 1) (SU).
2001 case 'S':
2002 this.scrollUp(this.params);
2003 break;
2004
2005 // CSI Ps T Scroll down Ps lines (default = 1) (SD).
2006 // CSI Ps ; Ps ; Ps ; Ps ; Ps T
2007 // CSI > Ps; Ps T
2008 case 'T':
2009 // if (this.prefix === '>') {
2010 // this.resetTitleModes(this.params);
2011 // break;
2012 // }
2013 // if (this.params.length > 2) {
2014 // this.initMouseTracking(this.params);
2015 // break;
2016 // }
2017 if (this.params.length < 2 && !this.prefix) {
2018 this.scrollDown(this.params);
2019 }
2020 break;
2021
2022 // CSI Ps Z
2023 // Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
2024 case 'Z':
2025 this.cursorBackwardTab(this.params);
2026 break;
2027
2028 // CSI Ps b Repeat the preceding graphic character Ps times (REP).
2029 case 'b':
2030 this.repeatPrecedingCharacter(this.params);
2031 break;
2032
2033 // CSI Ps g Tab Clear (TBC).
2034 case 'g':
2035 this.tabClear(this.params);
2036 break;
2037
2038 // CSI Pm i Media Copy (MC).
2039 // CSI ? Pm i
2040 // case 'i':
2041 // this.mediaCopy(this.params);
2042 // break;
2043
2044 // CSI Pm m Character Attributes (SGR).
2045 // CSI > Ps; Ps m
2046 // case 'm': // duplicate
2047 // if (this.prefix === '>') {
2048 // this.setResources(this.params);
2049 // } else {
2050 // this.charAttributes(this.params);
2051 // }
2052 // break;
2053
2054 // CSI Ps n Device Status Report (DSR).
2055 // CSI > Ps n
2056 // case 'n': // duplicate
2057 // if (this.prefix === '>') {
2058 // this.disableModifiers(this.params);
2059 // } else {
2060 // this.deviceStatus(this.params);
2061 // }
2062 // break;
2063
2064 // CSI > Ps p Set pointer mode.
2065 // CSI ! p Soft terminal reset (DECSTR).
2066 // CSI Ps$ p
2067 // Request ANSI mode (DECRQM).
2068 // CSI ? Ps$ p
2069 // Request DEC private mode (DECRQM).
2070 // CSI Ps ; Ps " p
2071 case 'p':
2072 switch (this.prefix) {
2073 // case '>':
2074 // this.setPointerMode(this.params);
2075 // break;
2076 case '!':
2077 this.softReset(this.params);
2078 break;
2079 // case '?':
2080 // if (this.postfix === '$') {
2081 // this.requestPrivateMode(this.params);
2082 // }
2083 // break;
2084 // default:
2085 // if (this.postfix === '"') {
2086 // this.setConformanceLevel(this.params);
2087 // } else if (this.postfix === '$') {
2088 // this.requestAnsiMode(this.params);
2089 // }
2090 // break;
2091 }
2092 break;
2093
2094 // CSI Ps q Load LEDs (DECLL).
2095 // CSI Ps SP q
2096 // CSI Ps " q
2097 // case 'q':
2098 // if (this.postfix === ' ') {
2099 // this.setCursorStyle(this.params);
2100 // break;
2101 // }
2102 // if (this.postfix === '"') {
2103 // this.setCharProtectionAttr(this.params);
2104 // break;
2105 // }
2106 // this.loadLEDs(this.params);
2107 // break;
2108
2109 // CSI Ps ; Ps r
2110 // Set Scrolling Region [top;bottom] (default = full size of win-
2111 // dow) (DECSTBM).
2112 // CSI ? Pm r
2113 // CSI Pt; Pl; Pb; Pr; Ps$ r
2114 // case 'r': // duplicate
2115 // if (this.prefix === '?') {
2116 // this.restorePrivateValues(this.params);
2117 // } else if (this.postfix === '$') {
2118 // this.setAttrInRectangle(this.params);
2119 // } else {
2120 // this.setScrollRegion(this.params);
2121 // }
2122 // break;
2123
2124 // CSI s Save cursor (ANSI.SYS).
2125 // CSI ? Pm s
2126 // case 's': // duplicate
2127 // if (this.prefix === '?') {
2128 // this.savePrivateValues(this.params);
2129 // } else {
2130 // this.saveCursor(this.params);
2131 // }
2132 // break;
2133
2134 // CSI Ps ; Ps ; Ps t
2135 // CSI Pt; Pl; Pb; Pr; Ps$ t
2136 // CSI > Ps; Ps t
2137 // CSI Ps SP t
2138 // case 't':
2139 // if (this.postfix === '$') {
2140 // this.reverseAttrInRectangle(this.params);
2141 // } else if (this.postfix === ' ') {
2142 // this.setWarningBellVolume(this.params);
2143 // } else {
2144 // if (this.prefix === '>') {
2145 // this.setTitleModeFeature(this.params);
2146 // } else {
2147 // this.manipulateWindow(this.params);
2148 // }
2149 // }
2150 // break;
2151
2152 // CSI u Restore cursor (ANSI.SYS).
2153 // CSI Ps SP u
2154 // case 'u': // duplicate
2155 // if (this.postfix === ' ') {
2156 // this.setMarginBellVolume(this.params);
2157 // } else {
2158 // this.restoreCursor(this.params);
2159 // }
2160 // break;
2161
2162 // CSI Pt; Pl; Pb; Pr; Pp; Pt; Pl; Pp$ v
2163 // case 'v':
2164 // if (this.postfix === '$') {
2165 // this.copyRectagle(this.params);
2166 // }
2167 // break;
2168
2169 // CSI Pt ; Pl ; Pb ; Pr ' w
2170 // case 'w':
2171 // if (this.postfix === '\'') {
2172 // this.enableFilterRectangle(this.params);
2173 // }
2174 // break;
2175
2176 // CSI Ps x Request Terminal Parameters (DECREQTPARM).
2177 // CSI Ps x Select Attribute Change Extent (DECSACE).
2178 // CSI Pc; Pt; Pl; Pb; Pr$ x
2179 // case 'x':
2180 // if (this.postfix === '$') {
2181 // this.fillRectangle(this.params);
2182 // } else {
2183 // this.requestParameters(this.params);
2184 // //this.__(this.params);
2185 // }
2186 // break;
2187
2188 // CSI Ps ; Pu ' z
2189 // CSI Pt; Pl; Pb; Pr$ z
2190 // case 'z':
2191 // if (this.postfix === '\'') {
2192 // this.enableLocatorReporting(this.params);
2193 // } else if (this.postfix === '$') {
2194 // this.eraseRectangle(this.params);
2195 // }
2196 // break;
2197
2198 // CSI Pm ' {
2199 // CSI Pt; Pl; Pb; Pr$ {
2200 // case '{':
2201 // if (this.postfix === '\'') {
2202 // this.setLocatorEvents(this.params);
2203 // } else if (this.postfix === '$') {
2204 // this.selectiveEraseRectangle(this.params);
2205 // }
2206 // break;
2207
2208 // CSI Ps ' |
2209 // case '|':
2210 // if (this.postfix === '\'') {
2211 // this.requestLocatorPosition(this.params);
2212 // }
2213 // break;
2214
2215 // CSI P m SP }
2216 // Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
2217 // case '}':
2218 // if (this.postfix === ' ') {
2219 // this.insertColumns(this.params);
2220 // }
2221 // break;
2222
2223 // CSI P m SP ~
2224 // Delete P s Column(s) (default = 1) (DECDC), VT420 and up
2225 // case '~':
2226 // if (this.postfix === ' ') {
2227 // this.deleteColumns(this.params);
2228 // }
2229 // break;
2230
2231 default:
2232 this.error('Unknown CSI code: %s.', ch);
2233 break;
2234 }
2235
2236 this.prefix = '';
2237 this.postfix = '';
2238 break;
2239
2240 case dcs:
2241 if (ch === '\x1b' || ch === '\x07') {
2242 if (ch === '\x1b') i++;
2243
2244 switch (this.prefix) {
2245 // User-Defined Keys (DECUDK).
2246 case '':
2247 break;
2248
2249 // Request Status String (DECRQSS).
2250 // test: echo -e '\eP$q"p\e\\'
2251 case '$q':
2252 var pt = this.currentParam
2253 , valid = false;
2254
2255 switch (pt) {
2256 // DECSCA
2257 case '"q':
2258 pt = '0"q';
2259 break;
2260
2261 // DECSCL
2262 case '"p':
2263 pt = '61"p';
2264 break;
2265
2266 // DECSTBM
2267 case 'r':
2268 pt = ''
2269 + (this.scrollTop + 1)
2270 + ';'
2271 + (this.scrollBottom + 1)
2272 + 'r';
2273 break;
2274
2275 // SGR
2276 case 'm':
2277 pt = '0m';
2278 break;
2279
2280 default:
2281 this.error('Unknown DCS Pt: %s.', pt);
2282 pt = '';
2283 break;
2284 }
2285
2286 this.send('\x1bP' + +valid + '$r' + pt + '\x1b\\');
2287 break;
2288
2289 // Set Termcap/Terminfo Data (xterm, experimental).
2290 case '+p':
2291 break;
2292
2293 // Request Termcap/Terminfo String (xterm, experimental)
2294 // Regular xterm does not even respond to this sequence.
2295 // This can cause a small glitch in vim.
2296 // test: echo -ne '\eP+q6b64\e\\'
2297 case '+q':
2298 var pt = this.currentParam
2299 , valid = false;
2300
2301 this.send('\x1bP' + +valid + '+r' + pt + '\x1b\\');
2302 break;
2303
2304 default:
2305 this.error('Unknown DCS prefix: %s.', this.prefix);
2306 break;
2307 }
2308
2309 this.currentParam = 0;
2310 this.prefix = '';
2311 this.state = normal;
2312 } else if (!this.currentParam) {
2313 if (!this.prefix && ch !== '$' && ch !== '+') {
2314 this.currentParam = ch;
2315 } else if (this.prefix.length === 2) {
2316 this.currentParam = ch;
2317 } else {
2318 this.prefix += ch;
2319 }
2320 } else {
2321 this.currentParam += ch;
2322 }
2323 break;
2324
2325 case ignore:
2326 // For PM and APC.
2327 if (ch === '\x1b' || ch === '\x07') {
2328 if (ch === '\x1b') i++;
2329 this.state = normal;
2330 }
2331 break;
2332 }
2333 }
2334
2335 this.updateRange(this.y);
2336 this.refresh(this.refreshStart, this.refreshEnd);
2337 };
2338
2339 Terminal.prototype.writeln = function(data) {
2340 this.write(data + '\r\n');
2341 };
2342
2343 // Key Resources:
2344 // https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
2345 Terminal.prototype.keyDown = function(ev) {
2346 var self = this;
2347 var result = this.evaluateKeyEscapeSequence(ev);
2348
2349 if (result.scrollDisp) {
2350 this.scrollDisp(result.scrollDisp);
2351 return this.cancel(ev);
2352 }
2353
2354 if (isThirdLevelShift(this, ev)) {
2355 return true;
2356 }
2357
2358 if (result.cancel ) {
2359 // The event is canceled at the end already, is this necessary?
2360 this.cancel(ev, true);
2361 }
2362
2363 if (!result.key) {
2364 return true;
2365 }
2366
2367 this.emit('keydown', ev);
2368 this.emit('key', result.key, ev);
2369 this.showCursor();
2370 this.handler(result.key);
2371
2372 return this.cancel(ev, true);
2373 };
2374
2375 /**
2376 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
2377 * returned value is the new key code to pass to the PTY.
2378 *
2379 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
2380 */
2381 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
2382 var result = {
2383 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
2384 // canceled at the end of keyDown
2385 cancel: false,
2386 // The new key even to emit
2387 key: undefined,
2388 // The number of characters to scroll, if this is defined it will cancel the event
2389 scrollDisp: undefined
2390 };
2391 switch (ev.keyCode) {
2392 // backspace
2393 case 8:
2394 if (ev.shiftKey) {
2395 result.key = '\x08'; // ^H
2396 break;
2397 }
2398 result.key = '\x7f'; // ^?
2399 break;
2400 // tab
2401 case 9:
2402 if (ev.shiftKey) {
2403 result.key = '\x1b[Z';
2404 break;
2405 }
2406 result.key = '\t';
2407 result.cancel = true;
2408 break;
2409 // return/enter
2410 case 13:
2411 result.key = '\r';
2412 result.cancel = true;
2413 break;
2414 // escape
2415 case 27:
2416 result.key = '\x1b';
2417 result.cancel = true;
2418 break;
2419 // left-arrow
2420 case 37:
2421 if (ev.altKey) {
2422 result.key = '\x1bb' // Jump a word back
2423 result.cancel = true;
2424 break;
2425 }
2426 if (ev.ctrlKey) {
2427 result.key = '\x1b[5D'; // Jump a word back
2428 break;
2429 }
2430 if (this.applicationCursor) {
2431 result.key = '\x1bOD'; // SS3 as ^[O for 7-bit
2432 break;
2433 }
2434 result.key = '\x1b[D';
2435 break;
2436 // right-arrow
2437 case 39:
2438 if (ev.altKey) {
2439 result.key = '\x1bf' // Jump a word forward
2440 result.cancel = true;
2441 break;
2442 }
2443 if (ev.ctrlKey) {
2444 result.key = '\x1b[5C'; // Jump a word forward
2445 break;
2446 }
2447 if (this.applicationCursor) {
2448 result.key = '\x1bOC';
2449 break;
2450 }
2451 result.key = '\x1b[C';
2452 break;
2453 // up-arrow
2454 case 38:
2455 if (this.applicationCursor) {
2456 result.key = '\x1bOA';
2457 break;
2458 }
2459 if (ev.ctrlKey) {
2460 result.scrollDisp = -1;
2461 } else {
2462 result.key = '\x1b[A';
2463 }
2464 break;
2465 // down-arrow
2466 case 40:
2467 if (this.applicationCursor) {
2468 result.key = '\x1bOB';
2469 break;
2470 }
2471 if (ev.ctrlKey) {
2472 result.scrollDisp = 1;
2473 } else {
2474 result.key = '\x1b[B';
2475 }
2476 break;
2477 // insert
2478 case 45:
2479 if (!ev.shiftKey && !ev.ctrlKey) {
2480 // <Ctrl> or <Shift> + <Insert> are used to
2481 // copy-paste on some systems.
2482 result.key = '\x1b[2~';
2483 }
2484 break;
2485 // delete
2486 case 46: result.key = '\x1b[3~'; break;
2487 // home
2488 case 36:
2489 if (this.applicationKeypad) {
2490 result.key = '\x1bOH';
2491 break;
2492 }
2493 result.key = '\x1bOH';
2494 break;
2495 // end
2496 case 35:
2497 if (this.applicationKeypad) {
2498 result.key = '\x1bOF';
2499 break;
2500 }
2501 result.key = '\x1bOF';
2502 break;
2503 // page up
2504 case 33:
2505 if (ev.shiftKey) {
2506 result.scrollDisp = -(this.rows - 1);
2507 } else {
2508 result.key = '\x1b[5~';
2509 }
2510 break;
2511 // page down
2512 case 34:
2513 if (ev.shiftKey) {
2514 result.scrollDisp = this.rows - 1;
2515 } else {
2516 result.key = '\x1b[6~';
2517 }
2518 break;
2519 // F1-F12
2520 case 112: result.key = '\x1bOP'; break;
2521 case 113: result.key = '\x1bOQ'; break;
2522 case 114: result.key = '\x1bOR'; break;
2523 case 115: result.key = '\x1bOS'; break;
2524 case 116: result.key = '\x1b[15~'; break;
2525 case 117: result.key = '\x1b[17~'; break;
2526 case 118: result.key = '\x1b[18~'; break;
2527 case 119: result.key = '\x1b[19~'; break;
2528 case 120: result.key = '\x1b[20~'; break;
2529 case 121: result.key = '\x1b[21~'; break;
2530 case 122: result.key = '\x1b[23~'; break;
2531 case 123: result.key = '\x1b[24~'; break;
2532 default:
2533 // a-z and space
2534 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
2535 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
2536 result.key = String.fromCharCode(ev.keyCode - 64);
2537 } else if (ev.keyCode === 32) {
2538 // NUL
2539 result.key = String.fromCharCode(0);
2540 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
2541 // escape, file sep, group sep, record sep, unit sep
2542 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
2543 } else if (ev.keyCode === 56) {
2544 // delete
2545 result.key = String.fromCharCode(127);
2546 } else if (ev.keyCode === 219) {
2547 // ^[ - escape
2548 result.key = String.fromCharCode(27);
2549 } else if (ev.keyCode === 221) {
2550 // ^] - group sep
2551 result.key = String.fromCharCode(29);
2552 }
2553 } else if (!this.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
2554 // On Mac this is a third level shift. Use <Esc> instead.
2555 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
2556 result.key = '\x1b' + String.fromCharCode(ev.keyCode + 32);
2557 } else if (ev.keyCode === 192) {
2558 result.key = '\x1b`';
2559 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
2560 result.key = '\x1b' + (ev.keyCode - 48);
2561 }
2562 }
2563 break;
2564 }
2565 return result;
2566 };
2567
2568 Terminal.prototype.setgLevel = function(g) {
2569 this.glevel = g;
2570 this.charset = this.charsets[g];
2571 };
2572
2573 Terminal.prototype.setgCharset = function(g, charset) {
2574 this.charsets[g] = charset;
2575 if (this.glevel === g) {
2576 this.charset = charset;
2577 }
2578 };
2579
2580 Terminal.prototype.keyPress = function(ev) {
2581 var key;
2582
2583 if (ev.charCode) {
2584 key = ev.charCode;
2585 } else if (ev.which == null) {
2586 key = ev.keyCode;
2587 } else if (ev.which !== 0 && ev.charCode !== 0) {
2588 key = ev.which;
2589 } else {
2590 return false;
2591 }
2592
2593 if (!key || (
2594 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
2595 )) {
2596 return false;
2597 }
2598
2599 key = String.fromCharCode(key);
2600
2601 /**
2602 * When a key is pressed and a character is sent to the terminal, then clear any text
2603 * selected in the terminal.
2604 */
2605 if (key) {
2606 this.clearSelection();
2607 }
2608
2609 this.emit('keypress', key, ev);
2610 this.emit('key', key, ev);
2611 this.showCursor();
2612 this.handler(key);
2613
2614 this.cancel(ev, true);
2615
2616 return false;
2617 };
2618
2619 Terminal.prototype.send = function(data) {
2620 var self = this;
2621
2622 if (!this.queue) {
2623 setTimeout(function() {
2624 self.handler(self.queue);
2625 self.queue = '';
2626 }, 1);
2627 }
2628
2629 this.queue += data;
2630 };
2631
2632 Terminal.prototype.bell = function() {
2633 if (!this.visualBell) return;
2634 var self = this;
2635 this.element.style.borderColor = 'white';
2636 setTimeout(function() {
2637 self.element.style.borderColor = '';
2638 }, 10);
2639 if (this.popOnBell) this.focus();
2640 };
2641
2642 Terminal.prototype.log = function() {
2643 if (!this.debug) return;
2644 if (!this.context.console || !this.context.console.log) return;
2645 var args = Array.prototype.slice.call(arguments);
2646 this.context.console.log.apply(this.context.console, args);
2647 };
2648
2649 Terminal.prototype.error = function() {
2650 if (!this.debug) return;
2651 if (!this.context.console || !this.context.console.error) return;
2652 var args = Array.prototype.slice.call(arguments);
2653 this.context.console.error.apply(this.context.console, args);
2654 };
2655
2656 Terminal.prototype.resize = function(x, y) {
2657 var line
2658 , el
2659 , i
2660 , j
2661 , ch
2662 , addToY;
2663
2664 if (x === this.cols && y === this.rows) {
2665 return;
2666 }
2667
2668 if (x < 1) x = 1;
2669 if (y < 1) y = 1;
2670
2671 // resize cols
2672 j = this.cols;
2673 if (j < x) {
2674 ch = [this.defAttr, ' ']; // does xterm use the default attr?
2675 i = this.lines.length;
2676 while (i--) {
2677 while (this.lines[i].length < x) {
2678 this.lines[i].push(ch);
2679 }
2680 }
2681 } else { // (j > x)
2682 i = this.lines.length;
2683 while (i--) {
2684 while (this.lines[i].length > x) {
2685 this.lines[i].pop();
2686 }
2687 }
2688 }
2689 this.setupStops(j);
2690 this.cols = x;
2691
2692 // resize rows
2693 j = this.rows;
2694 addToY = 0;
2695 if (j < y) {
2696 el = this.element;
2697 while (j++ < y) {
2698 // y is rows, not this.y
2699 if (this.lines.length < y + this.ybase) {
2700 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
2701 // There is room above the buffer and there are no empty elements below the line,
2702 // scroll up
2703 this.ybase--;
2704 this.ydisp--;
2705 addToY++
2706 } else {
2707 // Add a blank line if there is no buffer left at the top to scroll to, or if there
2708 // are blank lines after the cursor
2709 this.lines.push(this.blankLine());
2710 }
2711 }
2712 if (this.children.length < y) {
2713 this.insertRow();
2714 }
2715 }
2716 } else { // (j > y)
2717 while (j-- > y) {
2718 if (this.lines.length > y + this.ybase) {
2719 if (this.lines.length > this.ybase + this.y + 1) {
2720 // The line is a blank line below the cursor, remove it
2721 this.lines.pop();
2722 } else {
2723 // The line is the cursor, scroll down
2724 this.ybase++;
2725 this.ydisp++;
2726 }
2727 }
2728 if (this.children.length > y) {
2729 el = this.children.shift();
2730 if (!el) continue;
2731 el.parentNode.removeChild(el);
2732 }
2733 }
2734 }
2735 this.rows = y;
2736
2737 /*
2738 * Make sure that the cursor stays on screen
2739 */
2740 if (this.y >= y) {
2741 this.y = y - 1;
2742 }
2743 if (addToY) {
2744 this.y += addToY;
2745 }
2746
2747 if (this.x >= x) {
2748 this.x = x - 1;
2749 }
2750
2751 this.scrollTop = 0;
2752 this.scrollBottom = y - 1;
2753
2754 this.refresh(0, this.rows - 1);
2755
2756 this.normal = null;
2757
2758 this.emit('resize', {terminal: this, cols: x, rows: y});
2759 };
2760
2761 Terminal.prototype.updateRange = function(y) {
2762 if (y < this.refreshStart) this.refreshStart = y;
2763 if (y > this.refreshEnd) this.refreshEnd = y;
2764 // if (y > this.refreshEnd) {
2765 // this.refreshEnd = y;
2766 // if (y > this.rows - 1) {
2767 // this.refreshEnd = this.rows - 1;
2768 // }
2769 // }
2770 };
2771
2772 Terminal.prototype.maxRange = function() {
2773 this.refreshStart = 0;
2774 this.refreshEnd = this.rows - 1;
2775 };
2776
2777 Terminal.prototype.setupStops = function(i) {
2778 if (i != null) {
2779 if (!this.tabs[i]) {
2780 i = this.prevStop(i);
2781 }
2782 } else {
2783 this.tabs = {};
2784 i = 0;
2785 }
2786
2787 for (; i < this.cols; i += 8) {
2788 this.tabs[i] = true;
2789 }
2790 };
2791
2792 Terminal.prototype.prevStop = function(x) {
2793 if (x == null) x = this.x;
2794 while (!this.tabs[--x] && x > 0);
2795 return x >= this.cols
2796 ? this.cols - 1
2797 : x < 0 ? 0 : x;
2798 };
2799
2800 Terminal.prototype.nextStop = function(x) {
2801 if (x == null) x = this.x;
2802 while (!this.tabs[++x] && x < this.cols);
2803 return x >= this.cols
2804 ? this.cols - 1
2805 : x < 0 ? 0 : x;
2806 };
2807
2808 Terminal.prototype.eraseRight = function(x, y) {
2809 var line = this.lines[this.ybase + y]
2810 , ch = [this.eraseAttr(), ' ']; // xterm
2811
2812
2813 for (; x < this.cols; x++) {
2814 line[x] = ch;
2815 }
2816
2817 this.updateRange(y);
2818 };
2819
2820 Terminal.prototype.eraseLeft = function(x, y) {
2821 var line = this.lines[this.ybase + y]
2822 , ch = [this.eraseAttr(), ' ']; // xterm
2823
2824 x++;
2825 while (x--) line[x] = ch;
2826
2827 this.updateRange(y);
2828 };
2829
2830 Terminal.prototype.eraseLine = function(y) {
2831 this.eraseRight(0, y);
2832 };
2833
2834 Terminal.prototype.blankLine = function(cur) {
2835 var attr = cur
2836 ? this.eraseAttr()
2837 : this.defAttr;
2838
2839 var ch = [attr, ' ']
2840 , line = []
2841 , i = 0;
2842
2843 for (; i < this.cols; i++) {
2844 line[i] = ch;
2845 }
2846
2847 return line;
2848 };
2849
2850 Terminal.prototype.ch = function(cur) {
2851 return cur
2852 ? [this.eraseAttr(), ' ']
2853 : [this.defAttr, ' '];
2854 };
2855
2856 Terminal.prototype.is = function(term) {
2857 var name = this.termName;
2858 return (name + '').indexOf(term) === 0;
2859 };
2860
2861 Terminal.prototype.handler = function(data) {
2862 this.emit('data', data);
2863 };
2864
2865 Terminal.prototype.handleTitle = function(title) {
2866 this.emit('title', title);
2867 };
2868
2869 /**
2870 * ESC
2871 */
2872
2873 // ESC D Index (IND is 0x84).
2874 Terminal.prototype.index = function() {
2875 this.y++;
2876 if (this.y > this.scrollBottom) {
2877 this.y--;
2878 this.scroll();
2879 }
2880 this.state = normal;
2881 };
2882
2883 // ESC M Reverse Index (RI is 0x8d).
2884 Terminal.prototype.reverseIndex = function() {
2885 var j;
2886 this.y--;
2887 if (this.y < this.scrollTop) {
2888 this.y++;
2889 // possibly move the code below to term.reverseScroll();
2890 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2891 // blankLine(true) is xterm/linux behavior
2892 this.lines.splice(this.y + this.ybase, 0, this.blankLine(true));
2893 j = this.rows - 1 - this.scrollBottom;
2894 this.lines.splice(this.rows - 1 + this.ybase - j + 1, 1);
2895 // this.maxRange();
2896 this.updateRange(this.scrollTop);
2897 this.updateRange(this.scrollBottom);
2898 }
2899 this.state = normal;
2900 };
2901
2902 // ESC c Full Reset (RIS).
2903 Terminal.prototype.reset = function() {
2904 this.options.rows = this.rows;
2905 this.options.cols = this.cols;
2906 Terminal.call(this, this.options);
2907 this.refresh(0, this.rows - 1);
2908 };
2909
2910 // ESC H Tab Set (HTS is 0x88).
2911 Terminal.prototype.tabSet = function() {
2912 this.tabs[this.x] = true;
2913 this.state = normal;
2914 };
2915
2916 /**
2917 * CSI
2918 */
2919
2920 // CSI Ps A
2921 // Cursor Up Ps Times (default = 1) (CUU).
2922 Terminal.prototype.cursorUp = function(params) {
2923 var param = params[0];
2924 if (param < 1) param = 1;
2925 this.y -= param;
2926 if (this.y < 0) this.y = 0;
2927 };
2928
2929 // CSI Ps B
2930 // Cursor Down Ps Times (default = 1) (CUD).
2931 Terminal.prototype.cursorDown = function(params) {
2932 var param = params[0];
2933 if (param < 1) param = 1;
2934 this.y += param;
2935 if (this.y >= this.rows) {
2936 this.y = this.rows - 1;
2937 }
2938 };
2939
2940 // CSI Ps C
2941 // Cursor Forward Ps Times (default = 1) (CUF).
2942 Terminal.prototype.cursorForward = function(params) {
2943 var param = params[0];
2944 if (param < 1) param = 1;
2945 this.x += param;
2946 if (this.x >= this.cols) {
2947 this.x = this.cols - 1;
2948 }
2949 };
2950
2951 // CSI Ps D
2952 // Cursor Backward Ps Times (default = 1) (CUB).
2953 Terminal.prototype.cursorBackward = function(params) {
2954 var param = params[0];
2955 if (param < 1) param = 1;
2956 this.x -= param;
2957 if (this.x < 0) this.x = 0;
2958 };
2959
2960 // CSI Ps ; Ps H
2961 // Cursor Position [row;column] (default = [1,1]) (CUP).
2962 Terminal.prototype.cursorPos = function(params) {
2963 var row, col;
2964
2965 row = params[0] - 1;
2966
2967 if (params.length >= 2) {
2968 col = params[1] - 1;
2969 } else {
2970 col = 0;
2971 }
2972
2973 if (row < 0) {
2974 row = 0;
2975 } else if (row >= this.rows) {
2976 row = this.rows - 1;
2977 }
2978
2979 if (col < 0) {
2980 col = 0;
2981 } else if (col >= this.cols) {
2982 col = this.cols - 1;
2983 }
2984
2985 this.x = col;
2986 this.y = row;
2987 };
2988
2989 // CSI Ps J Erase in Display (ED).
2990 // Ps = 0 -> Erase Below (default).
2991 // Ps = 1 -> Erase Above.
2992 // Ps = 2 -> Erase All.
2993 // Ps = 3 -> Erase Saved Lines (xterm).
2994 // CSI ? Ps J
2995 // Erase in Display (DECSED).
2996 // Ps = 0 -> Selective Erase Below (default).
2997 // Ps = 1 -> Selective Erase Above.
2998 // Ps = 2 -> Selective Erase All.
2999 Terminal.prototype.eraseInDisplay = function(params) {
3000 var j;
3001 switch (params[0]) {
3002 case 0:
3003 this.eraseRight(this.x, this.y);
3004 j = this.y + 1;
3005 for (; j < this.rows; j++) {
3006 this.eraseLine(j);
3007 }
3008 break;
3009 case 1:
3010 this.eraseLeft(this.x, this.y);
3011 j = this.y;
3012 while (j--) {
3013 this.eraseLine(j);
3014 }
3015 break;
3016 case 2:
3017 j = this.rows;
3018 while (j--) this.eraseLine(j);
3019 break;
3020 case 3:
3021 ; // no saved lines
3022 break;
3023 }
3024 };
3025
3026 // CSI Ps K Erase in Line (EL).
3027 // Ps = 0 -> Erase to Right (default).
3028 // Ps = 1 -> Erase to Left.
3029 // Ps = 2 -> Erase All.
3030 // CSI ? Ps K
3031 // Erase in Line (DECSEL).
3032 // Ps = 0 -> Selective Erase to Right (default).
3033 // Ps = 1 -> Selective Erase to Left.
3034 // Ps = 2 -> Selective Erase All.
3035 Terminal.prototype.eraseInLine = function(params) {
3036 switch (params[0]) {
3037 case 0:
3038 this.eraseRight(this.x, this.y);
3039 break;
3040 case 1:
3041 this.eraseLeft(this.x, this.y);
3042 break;
3043 case 2:
3044 this.eraseLine(this.y);
3045 break;
3046 }
3047 };
3048
3049 // CSI Pm m Character Attributes (SGR).
3050 // Ps = 0 -> Normal (default).
3051 // Ps = 1 -> Bold.
3052 // Ps = 4 -> Underlined.
3053 // Ps = 5 -> Blink (appears as Bold).
3054 // Ps = 7 -> Inverse.
3055 // Ps = 8 -> Invisible, i.e., hidden (VT300).
3056 // Ps = 2 2 -> Normal (neither bold nor faint).
3057 // Ps = 2 4 -> Not underlined.
3058 // Ps = 2 5 -> Steady (not blinking).
3059 // Ps = 2 7 -> Positive (not inverse).
3060 // Ps = 2 8 -> Visible, i.e., not hidden (VT300).
3061 // Ps = 3 0 -> Set foreground color to Black.
3062 // Ps = 3 1 -> Set foreground color to Red.
3063 // Ps = 3 2 -> Set foreground color to Green.
3064 // Ps = 3 3 -> Set foreground color to Yellow.
3065 // Ps = 3 4 -> Set foreground color to Blue.
3066 // Ps = 3 5 -> Set foreground color to Magenta.
3067 // Ps = 3 6 -> Set foreground color to Cyan.
3068 // Ps = 3 7 -> Set foreground color to White.
3069 // Ps = 3 9 -> Set foreground color to default (original).
3070 // Ps = 4 0 -> Set background color to Black.
3071 // Ps = 4 1 -> Set background color to Red.
3072 // Ps = 4 2 -> Set background color to Green.
3073 // Ps = 4 3 -> Set background color to Yellow.
3074 // Ps = 4 4 -> Set background color to Blue.
3075 // Ps = 4 5 -> Set background color to Magenta.
3076 // Ps = 4 6 -> Set background color to Cyan.
3077 // Ps = 4 7 -> Set background color to White.
3078 // Ps = 4 9 -> Set background color to default (original).
3079
3080 // If 16-color support is compiled, the following apply. Assume
3081 // that xterm's resources are set so that the ISO color codes are
3082 // the first 8 of a set of 16. Then the aixterm colors are the
3083 // bright versions of the ISO colors:
3084 // Ps = 9 0 -> Set foreground color to Black.
3085 // Ps = 9 1 -> Set foreground color to Red.
3086 // Ps = 9 2 -> Set foreground color to Green.
3087 // Ps = 9 3 -> Set foreground color to Yellow.
3088 // Ps = 9 4 -> Set foreground color to Blue.
3089 // Ps = 9 5 -> Set foreground color to Magenta.
3090 // Ps = 9 6 -> Set foreground color to Cyan.
3091 // Ps = 9 7 -> Set foreground color to White.
3092 // Ps = 1 0 0 -> Set background color to Black.
3093 // Ps = 1 0 1 -> Set background color to Red.
3094 // Ps = 1 0 2 -> Set background color to Green.
3095 // Ps = 1 0 3 -> Set background color to Yellow.
3096 // Ps = 1 0 4 -> Set background color to Blue.
3097 // Ps = 1 0 5 -> Set background color to Magenta.
3098 // Ps = 1 0 6 -> Set background color to Cyan.
3099 // Ps = 1 0 7 -> Set background color to White.
3100
3101 // If xterm is compiled with the 16-color support disabled, it
3102 // supports the following, from rxvt:
3103 // Ps = 1 0 0 -> Set foreground and background color to
3104 // default.
3105
3106 // If 88- or 256-color support is compiled, the following apply.
3107 // Ps = 3 8 ; 5 ; Ps -> Set foreground color to the second
3108 // Ps.
3109 // Ps = 4 8 ; 5 ; Ps -> Set background color to the second
3110 // Ps.
3111 Terminal.prototype.charAttributes = function(params) {
3112 // Optimize a single SGR0.
3113 if (params.length === 1 && params[0] === 0) {
3114 this.curAttr = this.defAttr;
3115 return;
3116 }
3117
3118 var l = params.length
3119 , i = 0
3120 , flags = this.curAttr >> 18
3121 , fg = (this.curAttr >> 9) & 0x1ff
3122 , bg = this.curAttr & 0x1ff
3123 , p;
3124
3125 for (; i < l; i++) {
3126 p = params[i];
3127 if (p >= 30 && p <= 37) {
3128 // fg color 8
3129 fg = p - 30;
3130 } else if (p >= 40 && p <= 47) {
3131 // bg color 8
3132 bg = p - 40;
3133 } else if (p >= 90 && p <= 97) {
3134 // fg color 16
3135 p += 8;
3136 fg = p - 90;
3137 } else if (p >= 100 && p <= 107) {
3138 // bg color 16
3139 p += 8;
3140 bg = p - 100;
3141 } else if (p === 0) {
3142 // default
3143 flags = this.defAttr >> 18;
3144 fg = (this.defAttr >> 9) & 0x1ff;
3145 bg = this.defAttr & 0x1ff;
3146 // flags = 0;
3147 // fg = 0x1ff;
3148 // bg = 0x1ff;
3149 } else if (p === 1) {
3150 // bold text
3151 flags |= 1;
3152 } else if (p === 4) {
3153 // underlined text
3154 flags |= 2;
3155 } else if (p === 5) {
3156 // blink
3157 flags |= 4;
3158 } else if (p === 7) {
3159 // inverse and positive
3160 // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m'
3161 flags |= 8;
3162 } else if (p === 8) {
3163 // invisible
3164 flags |= 16;
3165 } else if (p === 22) {
3166 // not bold
3167 flags &= ~1;
3168 } else if (p === 24) {
3169 // not underlined
3170 flags &= ~2;
3171 } else if (p === 25) {
3172 // not blink
3173 flags &= ~4;
3174 } else if (p === 27) {
3175 // not inverse
3176 flags &= ~8;
3177 } else if (p === 28) {
3178 // not invisible
3179 flags &= ~16;
3180 } else if (p === 39) {
3181 // reset fg
3182 fg = (this.defAttr >> 9) & 0x1ff;
3183 } else if (p === 49) {
3184 // reset bg
3185 bg = this.defAttr & 0x1ff;
3186 } else if (p === 38) {
3187 // fg color 256
3188 if (params[i + 1] === 2) {
3189 i += 2;
3190 fg = matchColor(
3191 params[i] & 0xff,
3192 params[i + 1] & 0xff,
3193 params[i + 2] & 0xff);
3194 if (fg === -1) fg = 0x1ff;
3195 i += 2;
3196 } else if (params[i + 1] === 5) {
3197 i += 2;
3198 p = params[i] & 0xff;
3199 fg = p;
3200 }
3201 } else if (p === 48) {
3202 // bg color 256
3203 if (params[i + 1] === 2) {
3204 i += 2;
3205 bg = matchColor(
3206 params[i] & 0xff,
3207 params[i + 1] & 0xff,
3208 params[i + 2] & 0xff);
3209 if (bg === -1) bg = 0x1ff;
3210 i += 2;
3211 } else if (params[i + 1] === 5) {
3212 i += 2;
3213 p = params[i] & 0xff;
3214 bg = p;
3215 }
3216 } else if (p === 100) {
3217 // reset fg/bg
3218 fg = (this.defAttr >> 9) & 0x1ff;
3219 bg = this.defAttr & 0x1ff;
3220 } else {
3221 this.error('Unknown SGR attribute: %d.', p);
3222 }
3223 }
3224
3225 this.curAttr = (flags << 18) | (fg << 9) | bg;
3226 };
3227
3228 // CSI Ps n Device Status Report (DSR).
3229 // Ps = 5 -> Status Report. Result (``OK'') is
3230 // CSI 0 n
3231 // Ps = 6 -> Report Cursor Position (CPR) [row;column].
3232 // Result is
3233 // CSI r ; c R
3234 // CSI ? Ps n
3235 // Device Status Report (DSR, DEC-specific).
3236 // Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI
3237 // ? r ; c R (assumes page is zero).
3238 // Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready).
3239 // or CSI ? 1 1 n (not ready).
3240 // Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked)
3241 // or CSI ? 2 1 n (locked).
3242 // Ps = 2 6 -> Report Keyboard status as
3243 // CSI ? 2 7 ; 1 ; 0 ; 0 n (North American).
3244 // The last two parameters apply to VT400 & up, and denote key-
3245 // board ready and LK01 respectively.
3246 // Ps = 5 3 -> Report Locator status as
3247 // CSI ? 5 3 n Locator available, if compiled-in, or
3248 // CSI ? 5 0 n No Locator, if not.
3249 Terminal.prototype.deviceStatus = function(params) {
3250 if (!this.prefix) {
3251 switch (params[0]) {
3252 case 5:
3253 // status report
3254 this.send('\x1b[0n');
3255 break;
3256 case 6:
3257 // cursor position
3258 this.send('\x1b['
3259 + (this.y + 1)
3260 + ';'
3261 + (this.x + 1)
3262 + 'R');
3263 break;
3264 }
3265 } else if (this.prefix === '?') {
3266 // modern xterm doesnt seem to
3267 // respond to any of these except ?6, 6, and 5
3268 switch (params[0]) {
3269 case 6:
3270 // cursor position
3271 this.send('\x1b[?'
3272 + (this.y + 1)
3273 + ';'
3274 + (this.x + 1)
3275 + 'R');
3276 break;
3277 case 15:
3278 // no printer
3279 // this.send('\x1b[?11n');
3280 break;
3281 case 25:
3282 // dont support user defined keys
3283 // this.send('\x1b[?21n');
3284 break;
3285 case 26:
3286 // north american keyboard
3287 // this.send('\x1b[?27;1;0;0n');
3288 break;
3289 case 53:
3290 // no dec locator/mouse
3291 // this.send('\x1b[?50n');
3292 break;
3293 }
3294 }
3295 };
3296
3297 /**
3298 * Additions
3299 */
3300
3301 // CSI Ps @
3302 // Insert Ps (Blank) Character(s) (default = 1) (ICH).
3303 Terminal.prototype.insertChars = function(params) {
3304 var param, row, j, ch;
3305
3306 param = params[0];
3307 if (param < 1) param = 1;
3308
3309 row = this.y + this.ybase;
3310 j = this.x;
3311 ch = [this.eraseAttr(), ' ']; // xterm
3312
3313 while (param-- && j < this.cols) {
3314 this.lines[row].splice(j++, 0, ch);
3315 this.lines[row].pop();
3316 }
3317 };
3318
3319 // CSI Ps E
3320 // Cursor Next Line Ps Times (default = 1) (CNL).
3321 // same as CSI Ps B ?
3322 Terminal.prototype.cursorNextLine = function(params) {
3323 var param = params[0];
3324 if (param < 1) param = 1;
3325 this.y += param;
3326 if (this.y >= this.rows) {
3327 this.y = this.rows - 1;
3328 }
3329 this.x = 0;
3330 };
3331
3332 // CSI Ps F
3333 // Cursor Preceding Line Ps Times (default = 1) (CNL).
3334 // reuse CSI Ps A ?
3335 Terminal.prototype.cursorPrecedingLine = function(params) {
3336 var param = params[0];
3337 if (param < 1) param = 1;
3338 this.y -= param;
3339 if (this.y < 0) this.y = 0;
3340 this.x = 0;
3341 };
3342
3343 // CSI Ps G
3344 // Cursor Character Absolute [column] (default = [row,1]) (CHA).
3345 Terminal.prototype.cursorCharAbsolute = function(params) {
3346 var param = params[0];
3347 if (param < 1) param = 1;
3348 this.x = param - 1;
3349 };
3350
3351 // CSI Ps L
3352 // Insert Ps Line(s) (default = 1) (IL).
3353 Terminal.prototype.insertLines = function(params) {
3354 var param, row, j;
3355
3356 param = params[0];
3357 if (param < 1) param = 1;
3358 row = this.y + this.ybase;
3359
3360 j = this.rows - 1 - this.scrollBottom;
3361 j = this.rows - 1 + this.ybase - j + 1;
3362
3363 while (param--) {
3364 // test: echo -e '\e[44m\e[1L\e[0m'
3365 // blankLine(true) - xterm/linux behavior
3366 this.lines.splice(row, 0, this.blankLine(true));
3367 this.lines.splice(j, 1);
3368 }
3369
3370 // this.maxRange();
3371 this.updateRange(this.y);
3372 this.updateRange(this.scrollBottom);
3373 };
3374
3375 // CSI Ps M
3376 // Delete Ps Line(s) (default = 1) (DL).
3377 Terminal.prototype.deleteLines = function(params) {
3378 var param, row, j;
3379
3380 param = params[0];
3381 if (param < 1) param = 1;
3382 row = this.y + this.ybase;
3383
3384 j = this.rows - 1 - this.scrollBottom;
3385 j = this.rows - 1 + this.ybase - j;
3386
3387 while (param--) {
3388 // test: echo -e '\e[44m\e[1M\e[0m'
3389 // blankLine(true) - xterm/linux behavior
3390 this.lines.splice(j + 1, 0, this.blankLine(true));
3391 this.lines.splice(row, 1);
3392 }
3393
3394 // this.maxRange();
3395 this.updateRange(this.y);
3396 this.updateRange(this.scrollBottom);
3397 };
3398
3399 // CSI Ps P
3400 // Delete Ps Character(s) (default = 1) (DCH).
3401 Terminal.prototype.deleteChars = function(params) {
3402 var param, row, ch;
3403
3404 param = params[0];
3405 if (param < 1) param = 1;
3406
3407 row = this.y + this.ybase;
3408 ch = [this.eraseAttr(), ' ']; // xterm
3409
3410 while (param--) {
3411 this.lines[row].splice(this.x, 1);
3412 this.lines[row].push(ch);
3413 }
3414 };
3415
3416 // CSI Ps X
3417 // Erase Ps Character(s) (default = 1) (ECH).
3418 Terminal.prototype.eraseChars = function(params) {
3419 var param, row, j, ch;
3420
3421 param = params[0];
3422 if (param < 1) param = 1;
3423
3424 row = this.y + this.ybase;
3425 j = this.x;
3426 ch = [this.eraseAttr(), ' ']; // xterm
3427
3428 while (param-- && j < this.cols) {
3429 this.lines[row][j++] = ch;
3430 }
3431 };
3432
3433 // CSI Pm ` Character Position Absolute
3434 // [column] (default = [row,1]) (HPA).
3435 Terminal.prototype.charPosAbsolute = function(params) {
3436 var param = params[0];
3437 if (param < 1) param = 1;
3438 this.x = param - 1;
3439 if (this.x >= this.cols) {
3440 this.x = this.cols - 1;
3441 }
3442 };
3443
3444 // 141 61 a * HPR -
3445 // Horizontal Position Relative
3446 // reuse CSI Ps C ?
3447 Terminal.prototype.HPositionRelative = function(params) {
3448 var param = params[0];
3449 if (param < 1) param = 1;
3450 this.x += param;
3451 if (this.x >= this.cols) {
3452 this.x = this.cols - 1;
3453 }
3454 };
3455
3456 // CSI Ps c Send Device Attributes (Primary DA).
3457 // Ps = 0 or omitted -> request attributes from terminal. The
3458 // response depends on the decTerminalID resource setting.
3459 // -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')
3460 // -> CSI ? 1 ; 0 c (``VT101 with No Options'')
3461 // -> CSI ? 6 c (``VT102'')
3462 // -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')
3463 // The VT100-style response parameters do not mean anything by
3464 // themselves. VT220 parameters do, telling the host what fea-
3465 // tures the terminal supports:
3466 // Ps = 1 -> 132-columns.
3467 // Ps = 2 -> Printer.
3468 // Ps = 6 -> Selective erase.
3469 // Ps = 8 -> User-defined keys.
3470 // Ps = 9 -> National replacement character sets.
3471 // Ps = 1 5 -> Technical characters.
3472 // Ps = 2 2 -> ANSI color, e.g., VT525.
3473 // Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).
3474 // CSI > Ps c
3475 // Send Device Attributes (Secondary DA).
3476 // Ps = 0 or omitted -> request the terminal's identification
3477 // code. The response depends on the decTerminalID resource set-
3478 // ting. It should apply only to VT220 and up, but xterm extends
3479 // this to VT100.
3480 // -> CSI > Pp ; Pv ; Pc c
3481 // where Pp denotes the terminal type
3482 // Pp = 0 -> ``VT100''.
3483 // Pp = 1 -> ``VT220''.
3484 // and Pv is the firmware version (for xterm, this was originally
3485 // the XFree86 patch number, starting with 95). In a DEC termi-
3486 // nal, Pc indicates the ROM cartridge registration number and is
3487 // always zero.
3488 // More information:
3489 // xterm/charproc.c - line 2012, for more information.
3490 // vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
3491 Terminal.prototype.sendDeviceAttributes = function(params) {
3492 if (params[0] > 0) return;
3493
3494 if (!this.prefix) {
3495 if (this.is('xterm')
3496 || this.is('rxvt-unicode')
3497 || this.is('screen')) {
3498 this.send('\x1b[?1;2c');
3499 } else if (this.is('linux')) {
3500 this.send('\x1b[?6c');
3501 }
3502 } else if (this.prefix === '>') {
3503 // xterm and urxvt
3504 // seem to spit this
3505 // out around ~370 times (?).
3506 if (this.is('xterm')) {
3507 this.send('\x1b[>0;276;0c');
3508 } else if (this.is('rxvt-unicode')) {
3509 this.send('\x1b[>85;95;0c');
3510 } else if (this.is('linux')) {
3511 // not supported by linux console.
3512 // linux console echoes parameters.
3513 this.send(params[0] + 'c');
3514 } else if (this.is('screen')) {
3515 this.send('\x1b[>83;40003;0c');
3516 }
3517 }
3518 };
3519
3520 // CSI Pm d
3521 // Line Position Absolute [row] (default = [1,column]) (VPA).
3522 Terminal.prototype.linePosAbsolute = function(params) {
3523 var param = params[0];
3524 if (param < 1) param = 1;
3525 this.y = param - 1;
3526 if (this.y >= this.rows) {
3527 this.y = this.rows - 1;
3528 }
3529 };
3530
3531 // 145 65 e * VPR - Vertical Position Relative
3532 // reuse CSI Ps B ?
3533 Terminal.prototype.VPositionRelative = function(params) {
3534 var param = params[0];
3535 if (param < 1) param = 1;
3536 this.y += param;
3537 if (this.y >= this.rows) {
3538 this.y = this.rows - 1;
3539 }
3540 };
3541
3542 // CSI Ps ; Ps f
3543 // Horizontal and Vertical Position [row;column] (default =
3544 // [1,1]) (HVP).
3545 Terminal.prototype.HVPosition = function(params) {
3546 if (params[0] < 1) params[0] = 1;
3547 if (params[1] < 1) params[1] = 1;
3548
3549 this.y = params[0] - 1;
3550 if (this.y >= this.rows) {
3551 this.y = this.rows - 1;
3552 }
3553
3554 this.x = params[1] - 1;
3555 if (this.x >= this.cols) {
3556 this.x = this.cols - 1;
3557 }
3558 };
3559
3560 // CSI Pm h Set Mode (SM).
3561 // Ps = 2 -> Keyboard Action Mode (AM).
3562 // Ps = 4 -> Insert Mode (IRM).
3563 // Ps = 1 2 -> Send/receive (SRM).
3564 // Ps = 2 0 -> Automatic Newline (LNM).
3565 // CSI ? Pm h
3566 // DEC Private Mode Set (DECSET).
3567 // Ps = 1 -> Application Cursor Keys (DECCKM).
3568 // Ps = 2 -> Designate USASCII for character sets G0-G3
3569 // (DECANM), and set VT100 mode.
3570 // Ps = 3 -> 132 Column Mode (DECCOLM).
3571 // Ps = 4 -> Smooth (Slow) Scroll (DECSCLM).
3572 // Ps = 5 -> Reverse Video (DECSCNM).
3573 // Ps = 6 -> Origin Mode (DECOM).
3574 // Ps = 7 -> Wraparound Mode (DECAWM).
3575 // Ps = 8 -> Auto-repeat Keys (DECARM).
3576 // Ps = 9 -> Send Mouse X & Y on button press. See the sec-
3577 // tion Mouse Tracking.
3578 // Ps = 1 0 -> Show toolbar (rxvt).
3579 // Ps = 1 2 -> Start Blinking Cursor (att610).
3580 // Ps = 1 8 -> Print form feed (DECPFF).
3581 // Ps = 1 9 -> Set print extent to full screen (DECPEX).
3582 // Ps = 2 5 -> Show Cursor (DECTCEM).
3583 // Ps = 3 0 -> Show scrollbar (rxvt).
3584 // Ps = 3 5 -> Enable font-shifting functions (rxvt).
3585 // Ps = 3 8 -> Enter Tektronix Mode (DECTEK).
3586 // Ps = 4 0 -> Allow 80 -> 132 Mode.
3587 // Ps = 4 1 -> more(1) fix (see curses resource).
3588 // Ps = 4 2 -> Enable Nation Replacement Character sets (DECN-
3589 // RCM).
3590 // Ps = 4 4 -> Turn On Margin Bell.
3591 // Ps = 4 5 -> Reverse-wraparound Mode.
3592 // Ps = 4 6 -> Start Logging. This is normally disabled by a
3593 // compile-time option.
3594 // Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis-
3595 // abled by the titeInhibit resource).
3596 // Ps = 6 6 -> Application keypad (DECNKM).
3597 // Ps = 6 7 -> Backarrow key sends backspace (DECBKM).
3598 // Ps = 1 0 0 0 -> Send Mouse X & Y on button press and
3599 // release. See the section Mouse Tracking.
3600 // Ps = 1 0 0 1 -> Use Hilite Mouse Tracking.
3601 // Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking.
3602 // Ps = 1 0 0 3 -> Use All Motion Mouse Tracking.
3603 // Ps = 1 0 0 4 -> Send FocusIn/FocusOut events.
3604 // Ps = 1 0 0 5 -> Enable Extended Mouse Mode.
3605 // Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt).
3606 // Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt).
3607 // Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit.
3608 // (enables the eightBitInput resource).
3609 // Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num-
3610 // Lock keys. (This enables the numLock resource).
3611 // Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This
3612 // enables the metaSendsEscape resource).
3613 // Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete
3614 // key.
3615 // Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This
3616 // enables the altSendsEscape resource).
3617 // Ps = 1 0 4 0 -> Keep selection even if not highlighted.
3618 // (This enables the keepSelection resource).
3619 // Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables
3620 // the selectToClipboard resource).
3621 // Ps = 1 0 4 2 -> Enable Urgency window manager hint when
3622 // Control-G is received. (This enables the bellIsUrgent
3623 // resource).
3624 // Ps = 1 0 4 3 -> Enable raising of the window when Control-G
3625 // is received. (enables the popOnBell resource).
3626 // Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be
3627 // disabled by the titeInhibit resource).
3628 // Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis-
3629 // abled by the titeInhibit resource).
3630 // Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate
3631 // Screen Buffer, clearing it first. (This may be disabled by
3632 // the titeInhibit resource). This combines the effects of the 1
3633 // 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based
3634 // applications rather than the 4 7 mode.
3635 // Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode.
3636 // Ps = 1 0 5 1 -> Set Sun function-key mode.
3637 // Ps = 1 0 5 2 -> Set HP function-key mode.
3638 // Ps = 1 0 5 3 -> Set SCO function-key mode.
3639 // Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6).
3640 // Ps = 1 0 6 1 -> Set VT220 keyboard emulation.
3641 // Ps = 2 0 0 4 -> Set bracketed paste mode.
3642 // Modes:
3643 // http://vt100.net/docs/vt220-rm/chapter4.html
3644 Terminal.prototype.setMode = function(params) {
3645 if (typeof params === 'object') {
3646 var l = params.length
3647 , i = 0;
3648
3649 for (; i < l; i++) {
3650 this.setMode(params[i]);
3651 }
3652
3653 return;
3654 }
3655
3656 if (!this.prefix) {
3657 switch (params) {
3658 case 4:
3659 this.insertMode = true;
3660 break;
3661 case 20:
3662 //this.convertEol = true;
3663 break;
3664 }
3665 } else if (this.prefix === '?') {
3666 switch (params) {
3667 case 1:
3668 this.applicationCursor = true;
3669 break;
3670 case 2:
3671 this.setgCharset(0, Terminal.charsets.US);
3672 this.setgCharset(1, Terminal.charsets.US);
3673 this.setgCharset(2, Terminal.charsets.US);
3674 this.setgCharset(3, Terminal.charsets.US);
3675 // set VT100 mode here
3676 break;
3677 case 3: // 132 col mode
3678 this.savedCols = this.cols;
3679 this.resize(132, this.rows);
3680 break;
3681 case 6:
3682 this.originMode = true;
3683 break;
3684 case 7:
3685 this.wraparoundMode = true;
3686 break;
3687 case 12:
3688 // this.cursorBlink = true;
3689 break;
3690 case 66:
3691 this.log('Serial port requested application keypad.');
3692 this.applicationKeypad = true;
3693 break;
3694 case 9: // X10 Mouse
3695 // no release, no motion, no wheel, no modifiers.
3696 case 1000: // vt200 mouse
3697 // no motion.
3698 // no modifiers, except control on the wheel.
3699 case 1002: // button event mouse
3700 case 1003: // any event mouse
3701 // any event - sends motion events,
3702 // even if there is no button held down.
3703 this.x10Mouse = params === 9;
3704 this.vt200Mouse = params === 1000;
3705 this.normalMouse = params > 1000;
3706 this.mouseEvents = true;
3707 this.element.style.cursor = 'default';
3708 this.log('Binding to mouse events.');
3709 break;
3710 case 1004: // send focusin/focusout events
3711 // focusin: ^[[I
3712 // focusout: ^[[O
3713 this.sendFocus = true;
3714 break;
3715 case 1005: // utf8 ext mode mouse
3716 this.utfMouse = true;
3717 // for wide terminals
3718 // simply encodes large values as utf8 characters
3719 break;
3720 case 1006: // sgr ext mode mouse
3721 this.sgrMouse = true;
3722 // for wide terminals
3723 // does not add 32 to fields
3724 // press: ^[[<b;x;yM
3725 // release: ^[[<b;x;ym
3726 break;
3727 case 1015: // urxvt ext mode mouse
3728 this.urxvtMouse = true;
3729 // for wide terminals
3730 // numbers for fields
3731 // press: ^[[b;x;yM
3732 // motion: ^[[b;x;yT
3733 break;
3734 case 25: // show cursor
3735 this.cursorHidden = false;
3736 break;
3737 case 1049: // alt screen buffer cursor
3738 //this.saveCursor();
3739 ; // FALL-THROUGH
3740 case 47: // alt screen buffer
3741 case 1047: // alt screen buffer
3742 if (!this.normal) {
3743 var normal = {
3744 lines: this.lines,
3745 ybase: this.ybase,
3746 ydisp: this.ydisp,
3747 x: this.x,
3748 y: this.y,
3749 scrollTop: this.scrollTop,
3750 scrollBottom: this.scrollBottom,
3751 tabs: this.tabs
3752 // XXX save charset(s) here?
3753 // charset: this.charset,
3754 // glevel: this.glevel,
3755 // charsets: this.charsets
3756 };
3757 this.reset();
3758 this.normal = normal;
3759 this.showCursor();
3760 }
3761 break;
3762 }
3763 }
3764 };
3765
3766 // CSI Pm l Reset Mode (RM).
3767 // Ps = 2 -> Keyboard Action Mode (AM).
3768 // Ps = 4 -> Replace Mode (IRM).
3769 // Ps = 1 2 -> Send/receive (SRM).
3770 // Ps = 2 0 -> Normal Linefeed (LNM).
3771 // CSI ? Pm l
3772 // DEC Private Mode Reset (DECRST).
3773 // Ps = 1 -> Normal Cursor Keys (DECCKM).
3774 // Ps = 2 -> Designate VT52 mode (DECANM).
3775 // Ps = 3 -> 80 Column Mode (DECCOLM).
3776 // Ps = 4 -> Jump (Fast) Scroll (DECSCLM).
3777 // Ps = 5 -> Normal Video (DECSCNM).
3778 // Ps = 6 -> Normal Cursor Mode (DECOM).
3779 // Ps = 7 -> No Wraparound Mode (DECAWM).
3780 // Ps = 8 -> No Auto-repeat Keys (DECARM).
3781 // Ps = 9 -> Don't send Mouse X & Y on button press.
3782 // Ps = 1 0 -> Hide toolbar (rxvt).
3783 // Ps = 1 2 -> Stop Blinking Cursor (att610).
3784 // Ps = 1 8 -> Don't print form feed (DECPFF).
3785 // Ps = 1 9 -> Limit print to scrolling region (DECPEX).
3786 // Ps = 2 5 -> Hide Cursor (DECTCEM).
3787 // Ps = 3 0 -> Don't show scrollbar (rxvt).
3788 // Ps = 3 5 -> Disable font-shifting functions (rxvt).
3789 // Ps = 4 0 -> Disallow 80 -> 132 Mode.
3790 // Ps = 4 1 -> No more(1) fix (see curses resource).
3791 // Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-
3792 // NRCM).
3793 // Ps = 4 4 -> Turn Off Margin Bell.
3794 // Ps = 4 5 -> No Reverse-wraparound Mode.
3795 // Ps = 4 6 -> Stop Logging. (This is normally disabled by a
3796 // compile-time option).
3797 // Ps = 4 7 -> Use Normal Screen Buffer.
3798 // Ps = 6 6 -> Numeric keypad (DECNKM).
3799 // Ps = 6 7 -> Backarrow key sends delete (DECBKM).
3800 // Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and
3801 // release. See the section Mouse Tracking.
3802 // Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.
3803 // Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.
3804 // Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.
3805 // Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.
3806 // Ps = 1 0 0 5 -> Disable Extended Mouse Mode.
3807 // Ps = 1 0 1 0 -> Don't scroll to bottom on tty output
3808 // (rxvt).
3809 // Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).
3810 // Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables
3811 // the eightBitInput resource).
3812 // Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-
3813 // Lock keys. (This disables the numLock resource).
3814 // Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.
3815 // (This disables the metaSendsEscape resource).
3816 // Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad
3817 // Delete key.
3818 // Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.
3819 // (This disables the altSendsEscape resource).
3820 // Ps = 1 0 4 0 -> Do not keep selection when not highlighted.
3821 // (This disables the keepSelection resource).
3822 // Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables
3823 // the selectToClipboard resource).
3824 // Ps = 1 0 4 2 -> Disable Urgency window manager hint when
3825 // Control-G is received. (This disables the bellIsUrgent
3826 // resource).
3827 // Ps = 1 0 4 3 -> Disable raising of the window when Control-
3828 // G is received. (This disables the popOnBell resource).
3829 // Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen
3830 // first if in the Alternate Screen. (This may be disabled by
3831 // the titeInhibit resource).
3832 // Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be
3833 // disabled by the titeInhibit resource).
3834 // Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor
3835 // as in DECRC. (This may be disabled by the titeInhibit
3836 // resource). This combines the effects of the 1 0 4 7 and 1 0
3837 // 4 8 modes. Use this with terminfo-based applications rather
3838 // than the 4 7 mode.
3839 // Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.
3840 // Ps = 1 0 5 1 -> Reset Sun function-key mode.
3841 // Ps = 1 0 5 2 -> Reset HP function-key mode.
3842 // Ps = 1 0 5 3 -> Reset SCO function-key mode.
3843 // Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).
3844 // Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.
3845 // Ps = 2 0 0 4 -> Reset bracketed paste mode.
3846 Terminal.prototype.resetMode = function(params) {
3847 if (typeof params === 'object') {
3848 var l = params.length
3849 , i = 0;
3850
3851 for (; i < l; i++) {
3852 this.resetMode(params[i]);
3853 }
3854
3855 return;
3856 }
3857
3858 if (!this.prefix) {
3859 switch (params) {
3860 case 4:
3861 this.insertMode = false;
3862 break;
3863 case 20:
3864 //this.convertEol = false;
3865 break;
3866 }
3867 } else if (this.prefix === '?') {
3868 switch (params) {
3869 case 1:
3870 this.applicationCursor = false;
3871 break;
3872 case 3:
3873 if (this.cols === 132 && this.savedCols) {
3874 this.resize(this.savedCols, this.rows);
3875 }
3876 delete this.savedCols;
3877 break;
3878 case 6:
3879 this.originMode = false;
3880 break;
3881 case 7:
3882 this.wraparoundMode = false;
3883 break;
3884 case 12:
3885 // this.cursorBlink = false;
3886 break;
3887 case 66:
3888 this.log('Switching back to normal keypad.');
3889 this.applicationKeypad = false;
3890 break;
3891 case 9: // X10 Mouse
3892 case 1000: // vt200 mouse
3893 case 1002: // button event mouse
3894 case 1003: // any event mouse
3895 this.x10Mouse = false;
3896 this.vt200Mouse = false;
3897 this.normalMouse = false;
3898 this.mouseEvents = false;
3899 this.element.style.cursor = '';
3900 break;
3901 case 1004: // send focusin/focusout events
3902 this.sendFocus = false;
3903 break;
3904 case 1005: // utf8 ext mode mouse
3905 this.utfMouse = false;
3906 break;
3907 case 1006: // sgr ext mode mouse
3908 this.sgrMouse = false;
3909 break;
3910 case 1015: // urxvt ext mode mouse
3911 this.urxvtMouse = false;
3912 break;
3913 case 25: // hide cursor
3914 this.cursorHidden = true;
3915 break;
3916 case 1049: // alt screen buffer cursor
3917 ; // FALL-THROUGH
3918 case 47: // normal screen buffer
3919 case 1047: // normal screen buffer - clearing it first
3920 if (this.normal) {
3921 this.lines = this.normal.lines;
3922 this.ybase = this.normal.ybase;
3923 this.ydisp = this.normal.ydisp;
3924 this.x = this.normal.x;
3925 this.y = this.normal.y;
3926 this.scrollTop = this.normal.scrollTop;
3927 this.scrollBottom = this.normal.scrollBottom;
3928 this.tabs = this.normal.tabs;
3929 this.normal = null;
3930 // if (params === 1049) {
3931 // this.x = this.savedX;
3932 // this.y = this.savedY;
3933 // }
3934 this.refresh(0, this.rows - 1);
3935 this.showCursor();
3936 }
3937 break;
3938 }
3939 }
3940 };
3941
3942 // CSI Ps ; Ps r
3943 // Set Scrolling Region [top;bottom] (default = full size of win-
3944 // dow) (DECSTBM).
3945 // CSI ? Pm r
3946 Terminal.prototype.setScrollRegion = function(params) {
3947 if (this.prefix) return;
3948 this.scrollTop = (params[0] || 1) - 1;
3949 this.scrollBottom = (params[1] || this.rows) - 1;
3950 this.x = 0;
3951 this.y = 0;
3952 };
3953
3954 // CSI s
3955 // Save cursor (ANSI.SYS).
3956 Terminal.prototype.saveCursor = function(params) {
3957 this.savedX = this.x;
3958 this.savedY = this.y;
3959 };
3960
3961 // CSI u
3962 // Restore cursor (ANSI.SYS).
3963 Terminal.prototype.restoreCursor = function(params) {
3964 this.x = this.savedX || 0;
3965 this.y = this.savedY || 0;
3966 };
3967
3968 /**
3969 * Lesser Used
3970 */
3971
3972 // CSI Ps I
3973 // Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
3974 Terminal.prototype.cursorForwardTab = function(params) {
3975 var param = params[0] || 1;
3976 while (param--) {
3977 this.x = this.nextStop();
3978 }
3979 };
3980
3981 // CSI Ps S Scroll up Ps lines (default = 1) (SU).
3982 Terminal.prototype.scrollUp = function(params) {
3983 var param = params[0] || 1;
3984 while (param--) {
3985 this.lines.splice(this.ybase + this.scrollTop, 1);
3986 this.lines.splice(this.ybase + this.scrollBottom, 0, this.blankLine());
3987 }
3988 // this.maxRange();
3989 this.updateRange(this.scrollTop);
3990 this.updateRange(this.scrollBottom);
3991 };
3992
3993 // CSI Ps T Scroll down Ps lines (default = 1) (SD).
3994 Terminal.prototype.scrollDown = function(params) {
3995 var param = params[0] || 1;
3996 while (param--) {
3997 this.lines.splice(this.ybase + this.scrollBottom, 1);
3998 this.lines.splice(this.ybase + this.scrollTop, 0, this.blankLine());
3999 }
4000 // this.maxRange();
4001 this.updateRange(this.scrollTop);
4002 this.updateRange(this.scrollBottom);
4003 };
4004
4005 // CSI Ps ; Ps ; Ps ; Ps ; Ps T
4006 // Initiate highlight mouse tracking. Parameters are
4007 // [func;startx;starty;firstrow;lastrow]. See the section Mouse
4008 // Tracking.
4009 Terminal.prototype.initMouseTracking = function(params) {
4010 // Relevant: DECSET 1001
4011 };
4012
4013 // CSI > Ps; Ps T
4014 // Reset one or more features of the title modes to the default
4015 // value. Normally, "reset" disables the feature. It is possi-
4016 // ble to disable the ability to reset features by compiling a
4017 // different default for the title modes into xterm.
4018 // Ps = 0 -> Do not set window/icon labels using hexadecimal.
4019 // Ps = 1 -> Do not query window/icon labels using hexadeci-
4020 // mal.
4021 // Ps = 2 -> Do not set window/icon labels using UTF-8.
4022 // Ps = 3 -> Do not query window/icon labels using UTF-8.
4023 // (See discussion of "Title Modes").
4024 Terminal.prototype.resetTitleModes = function(params) {
4025 ;
4026 };
4027
4028 // CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
4029 Terminal.prototype.cursorBackwardTab = function(params) {
4030 var param = params[0] || 1;
4031 while (param--) {
4032 this.x = this.prevStop();
4033 }
4034 };
4035
4036 // CSI Ps b Repeat the preceding graphic character Ps times (REP).
4037 Terminal.prototype.repeatPrecedingCharacter = function(params) {
4038 var param = params[0] || 1
4039 , line = this.lines[this.ybase + this.y]
4040 , ch = line[this.x - 1] || [this.defAttr, ' '];
4041
4042 while (param--) line[this.x++] = ch;
4043 };
4044
4045 // CSI Ps g Tab Clear (TBC).
4046 // Ps = 0 -> Clear Current Column (default).
4047 // Ps = 3 -> Clear All.
4048 // Potentially:
4049 // Ps = 2 -> Clear Stops on Line.
4050 // http://vt100.net/annarbor/aaa-ug/section6.html
4051 Terminal.prototype.tabClear = function(params) {
4052 var param = params[0];
4053 if (param <= 0) {
4054 delete this.tabs[this.x];
4055 } else if (param === 3) {
4056 this.tabs = {};
4057 }
4058 };
4059
4060 // CSI Pm i Media Copy (MC).
4061 // Ps = 0 -> Print screen (default).
4062 // Ps = 4 -> Turn off printer controller mode.
4063 // Ps = 5 -> Turn on printer controller mode.
4064 // CSI ? Pm i
4065 // Media Copy (MC, DEC-specific).
4066 // Ps = 1 -> Print line containing cursor.
4067 // Ps = 4 -> Turn off autoprint mode.
4068 // Ps = 5 -> Turn on autoprint mode.
4069 // Ps = 1 0 -> Print composed display, ignores DECPEX.
4070 // Ps = 1 1 -> Print all pages.
4071 Terminal.prototype.mediaCopy = function(params) {
4072 ;
4073 };
4074
4075 // CSI > Ps; Ps m
4076 // Set or reset resource-values used by xterm to decide whether
4077 // to construct escape sequences holding information about the
4078 // modifiers pressed with a given key. The first parameter iden-
4079 // tifies the resource to set/reset. The second parameter is the
4080 // value to assign to the resource. If the second parameter is
4081 // omitted, the resource is reset to its initial value.
4082 // Ps = 1 -> modifyCursorKeys.
4083 // Ps = 2 -> modifyFunctionKeys.
4084 // Ps = 4 -> modifyOtherKeys.
4085 // If no parameters are given, all resources are reset to their
4086 // initial values.
4087 Terminal.prototype.setResources = function(params) {
4088 ;
4089 };
4090
4091 // CSI > Ps n
4092 // Disable modifiers which may be enabled via the CSI > Ps; Ps m
4093 // sequence. This corresponds to a resource value of "-1", which
4094 // cannot be set with the other sequence. The parameter identi-
4095 // fies the resource to be disabled:
4096 // Ps = 1 -> modifyCursorKeys.
4097 // Ps = 2 -> modifyFunctionKeys.
4098 // Ps = 4 -> modifyOtherKeys.
4099 // If the parameter is omitted, modifyFunctionKeys is disabled.
4100 // When modifyFunctionKeys is disabled, xterm uses the modifier
4101 // keys to make an extended sequence of functions rather than
4102 // adding a parameter to each function key to denote the modi-
4103 // fiers.
4104 Terminal.prototype.disableModifiers = function(params) {
4105 ;
4106 };
4107
4108 // CSI > Ps p
4109 // Set resource value pointerMode. This is used by xterm to
4110 // decide whether to hide the pointer cursor as the user types.
4111 // Valid values for the parameter:
4112 // Ps = 0 -> never hide the pointer.
4113 // Ps = 1 -> hide if the mouse tracking mode is not enabled.
4114 // Ps = 2 -> always hide the pointer. If no parameter is
4115 // given, xterm uses the default, which is 1 .
4116 Terminal.prototype.setPointerMode = function(params) {
4117 ;
4118 };
4119
4120 // CSI ! p Soft terminal reset (DECSTR).
4121 // http://vt100.net/docs/vt220-rm/table4-10.html
4122 Terminal.prototype.softReset = function(params) {
4123 this.cursorHidden = false;
4124 this.insertMode = false;
4125 this.originMode = false;
4126 this.wraparoundMode = false; // autowrap
4127 this.applicationKeypad = false; // ?
4128 this.applicationCursor = false;
4129 this.scrollTop = 0;
4130 this.scrollBottom = this.rows - 1;
4131 this.curAttr = this.defAttr;
4132 this.x = this.y = 0; // ?
4133 this.charset = null;
4134 this.glevel = 0; // ??
4135 this.charsets = [null]; // ??
4136 };
4137
4138 // CSI Ps$ p
4139 // Request ANSI mode (DECRQM). For VT300 and up, reply is
4140 // CSI Ps; Pm$ y
4141 // where Ps is the mode number as in RM, and Pm is the mode
4142 // value:
4143 // 0 - not recognized
4144 // 1 - set
4145 // 2 - reset
4146 // 3 - permanently set
4147 // 4 - permanently reset
4148 Terminal.prototype.requestAnsiMode = function(params) {
4149 ;
4150 };
4151
4152 // CSI ? Ps$ p
4153 // Request DEC private mode (DECRQM). For VT300 and up, reply is
4154 // CSI ? Ps; Pm$ p
4155 // where Ps is the mode number as in DECSET, Pm is the mode value
4156 // as in the ANSI DECRQM.
4157 Terminal.prototype.requestPrivateMode = function(params) {
4158 ;
4159 };
4160
4161 // CSI Ps ; Ps " p
4162 // Set conformance level (DECSCL). Valid values for the first
4163 // parameter:
4164 // Ps = 6 1 -> VT100.
4165 // Ps = 6 2 -> VT200.
4166 // Ps = 6 3 -> VT300.
4167 // Valid values for the second parameter:
4168 // Ps = 0 -> 8-bit controls.
4169 // Ps = 1 -> 7-bit controls (always set for VT100).
4170 // Ps = 2 -> 8-bit controls.
4171 Terminal.prototype.setConformanceLevel = function(params) {
4172 ;
4173 };
4174
4175 // CSI Ps q Load LEDs (DECLL).
4176 // Ps = 0 -> Clear all LEDS (default).
4177 // Ps = 1 -> Light Num Lock.
4178 // Ps = 2 -> Light Caps Lock.
4179 // Ps = 3 -> Light Scroll Lock.
4180 // Ps = 2 1 -> Extinguish Num Lock.
4181 // Ps = 2 2 -> Extinguish Caps Lock.
4182 // Ps = 2 3 -> Extinguish Scroll Lock.
4183 Terminal.prototype.loadLEDs = function(params) {
4184 ;
4185 };
4186
4187 // CSI Ps SP q
4188 // Set cursor style (DECSCUSR, VT520).
4189 // Ps = 0 -> blinking block.
4190 // Ps = 1 -> blinking block (default).
4191 // Ps = 2 -> steady block.
4192 // Ps = 3 -> blinking underline.
4193 // Ps = 4 -> steady underline.
4194 Terminal.prototype.setCursorStyle = function(params) {
4195 ;
4196 };
4197
4198 // CSI Ps " q
4199 // Select character protection attribute (DECSCA). Valid values
4200 // for the parameter:
4201 // Ps = 0 -> DECSED and DECSEL can erase (default).
4202 // Ps = 1 -> DECSED and DECSEL cannot erase.
4203 // Ps = 2 -> DECSED and DECSEL can erase.
4204 Terminal.prototype.setCharProtectionAttr = function(params) {
4205 ;
4206 };
4207
4208 // CSI ? Pm r
4209 // Restore DEC Private Mode Values. The value of Ps previously
4210 // saved is restored. Ps values are the same as for DECSET.
4211 Terminal.prototype.restorePrivateValues = function(params) {
4212 ;
4213 };
4214
4215 // CSI Pt; Pl; Pb; Pr; Ps$ r
4216 // Change Attributes in Rectangular Area (DECCARA), VT400 and up.
4217 // Pt; Pl; Pb; Pr denotes the rectangle.
4218 // Ps denotes the SGR attributes to change: 0, 1, 4, 5, 7.
4219 // NOTE: xterm doesn't enable this code by default.
4220 Terminal.prototype.setAttrInRectangle = function(params) {
4221 var t = params[0]
4222 , l = params[1]
4223 , b = params[2]
4224 , r = params[3]
4225 , attr = params[4];
4226
4227 var line
4228 , i;
4229
4230 for (; t < b + 1; t++) {
4231 line = this.lines[this.ybase + t];
4232 for (i = l; i < r; i++) {
4233 line[i] = [attr, line[i][1]];
4234 }
4235 }
4236
4237 // this.maxRange();
4238 this.updateRange(params[0]);
4239 this.updateRange(params[2]);
4240 };
4241
4242
4243 // CSI Pc; Pt; Pl; Pb; Pr$ x
4244 // Fill Rectangular Area (DECFRA), VT420 and up.
4245 // Pc is the character to use.
4246 // Pt; Pl; Pb; Pr denotes the rectangle.
4247 // NOTE: xterm doesn't enable this code by default.
4248 Terminal.prototype.fillRectangle = function(params) {
4249 var ch = params[0]
4250 , t = params[1]
4251 , l = params[2]
4252 , b = params[3]
4253 , r = params[4];
4254
4255 var line
4256 , i;
4257
4258 for (; t < b + 1; t++) {
4259 line = this.lines[this.ybase + t];
4260 for (i = l; i < r; i++) {
4261 line[i] = [line[i][0], String.fromCharCode(ch)];
4262 }
4263 }
4264
4265 // this.maxRange();
4266 this.updateRange(params[1]);
4267 this.updateRange(params[3]);
4268 };
4269
4270 // CSI Ps ; Pu ' z
4271 // Enable Locator Reporting (DECELR).
4272 // Valid values for the first parameter:
4273 // Ps = 0 -> Locator disabled (default).
4274 // Ps = 1 -> Locator enabled.
4275 // Ps = 2 -> Locator enabled for one report, then disabled.
4276 // The second parameter specifies the coordinate unit for locator
4277 // reports.
4278 // Valid values for the second parameter:
4279 // Pu = 0 <- or omitted -> default to character cells.
4280 // Pu = 1 <- device physical pixels.
4281 // Pu = 2 <- character cells.
4282 Terminal.prototype.enableLocatorReporting = function(params) {
4283 var val = params[0] > 0;
4284 //this.mouseEvents = val;
4285 //this.decLocator = val;
4286 };
4287
4288 // CSI Pt; Pl; Pb; Pr$ z
4289 // Erase Rectangular Area (DECERA), VT400 and up.
4290 // Pt; Pl; Pb; Pr denotes the rectangle.
4291 // NOTE: xterm doesn't enable this code by default.
4292 Terminal.prototype.eraseRectangle = function(params) {
4293 var t = params[0]
4294 , l = params[1]
4295 , b = params[2]
4296 , r = params[3];
4297
4298 var line
4299 , i
4300 , ch;
4301
4302 ch = [this.eraseAttr(), ' ']; // xterm?
4303
4304 for (; t < b + 1; t++) {
4305 line = this.lines[this.ybase + t];
4306 for (i = l; i < r; i++) {
4307 line[i] = ch;
4308 }
4309 }
4310
4311 // this.maxRange();
4312 this.updateRange(params[0]);
4313 this.updateRange(params[2]);
4314 };
4315
4316
4317 // CSI P m SP }
4318 // Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
4319 // NOTE: xterm doesn't enable this code by default.
4320 Terminal.prototype.insertColumns = function() {
4321 var param = params[0]
4322 , l = this.ybase + this.rows
4323 , ch = [this.eraseAttr(), ' '] // xterm?
4324 , i;
4325
4326 while (param--) {
4327 for (i = this.ybase; i < l; i++) {
4328 this.lines[i].splice(this.x + 1, 0, ch);
4329 this.lines[i].pop();
4330 }
4331 }
4332
4333 this.maxRange();
4334 };
4335
4336
4337 // CSI P m SP ~
4338 // Delete P s Column(s) (default = 1) (DECDC), VT420 and up
4339 // NOTE: xterm doesn't enable this code by default.
4340 Terminal.prototype.deleteColumns = function() {
4341 var param = params[0]
4342 , l = this.ybase + this.rows
4343 , ch = [this.eraseAttr(), ' '] // xterm?
4344 , i;
4345
4346 while (param--) {
4347 for (i = this.ybase; i < l; i++) {
4348 this.lines[i].splice(this.x, 1);
4349 this.lines[i].push(ch);
4350 }
4351 }
4352
4353 this.maxRange();
4354 };
4355
4356 /**
4357 * Character Sets
4358 */
4359
4360 Terminal.charsets = {};
4361
4362 // DEC Special Character and Line Drawing Set.
4363 // http://vt100.net/docs/vt102-ug/table5-13.html
4364 // A lot of curses apps use this if they see TERM=xterm.
4365 // testing: echo -e '\e(0a\e(B'
4366 // The xterm output sometimes seems to conflict with the
4367 // reference above. xterm seems in line with the reference
4368 // when running vttest however.
4369 // The table below now uses xterm's output from vttest.
4370 Terminal.charsets.SCLD = { // (0
4371 '`': '\u25c6', // '◆'
4372 'a': '\u2592', // '▒'
4373 'b': '\u0009', // '\t'
4374 'c': '\u000c', // '\f'
4375 'd': '\u000d', // '\r'
4376 'e': '\u000a', // '\n'
4377 'f': '\u00b0', // '°'
4378 'g': '\u00b1', // '±'
4379 'h': '\u2424', // '\u2424' (NL)
4380 'i': '\u000b', // '\v'
4381 'j': '\u2518', // '┘'
4382 'k': '\u2510', // '┐'
4383 'l': '\u250c', // '┌'
4384 'm': '\u2514', // '└'
4385 'n': '\u253c', // '┼'
4386 'o': '\u23ba', // '⎺'
4387 'p': '\u23bb', // '⎻'
4388 'q': '\u2500', // '─'
4389 'r': '\u23bc', // '⎼'
4390 's': '\u23bd', // '⎽'
4391 't': '\u251c', // '├'
4392 'u': '\u2524', // '┤'
4393 'v': '\u2534', // '┴'
4394 'w': '\u252c', // '┬'
4395 'x': '\u2502', // '│'
4396 'y': '\u2264', // '≤'
4397 'z': '\u2265', // '≥'
4398 '{': '\u03c0', // 'π'
4399 '|': '\u2260', // '≠'
4400 '}': '\u00a3', // '£'
4401 '~': '\u00b7' // '·'
4402 };
4403
4404 Terminal.charsets.UK = null; // (A
4405 Terminal.charsets.US = null; // (B (USASCII)
4406 Terminal.charsets.Dutch = null; // (4
4407 Terminal.charsets.Finnish = null; // (C or (5
4408 Terminal.charsets.French = null; // (R
4409 Terminal.charsets.FrenchCanadian = null; // (Q
4410 Terminal.charsets.German = null; // (K
4411 Terminal.charsets.Italian = null; // (Y
4412 Terminal.charsets.NorwegianDanish = null; // (E or (6
4413 Terminal.charsets.Spanish = null; // (Z
4414 Terminal.charsets.Swedish = null; // (H or (7
4415 Terminal.charsets.Swiss = null; // (=
4416 Terminal.charsets.ISOLatin = null; // /A
4417
4418 /**
4419 * Helpers
4420 */
4421
4422 function contains(el, arr) {
4423 for (var i = 0; i < arr.length; i += 1) {
4424 if (el === arr[i]) {
4425 return true;
4426 }
4427 }
4428 return false;
4429 }
4430
4431 function on(el, type, handler, capture) {
4432 if (!Array.isArray(el)) {
4433 el = [el];
4434 }
4435 el.forEach(function (element) {
4436 element.addEventListener(type, handler, capture || false);
4437 });
4438 }
4439
4440 function off(el, type, handler, capture) {
4441 el.removeEventListener(type, handler, capture || false);
4442 }
4443
4444 function cancel(ev, force) {
4445 if (!this.cancelEvents && !force) {
4446 return;
4447 }
4448 ev.preventDefault();
4449 ev.stopPropagation();
4450 return false;
4451 }
4452
4453 function inherits(child, parent) {
4454 function f() {
4455 this.constructor = child;
4456 }
4457 f.prototype = parent.prototype;
4458 child.prototype = new f;
4459 }
4460
4461 // if bold is broken, we can't
4462 // use it in the terminal.
4463 function isBoldBroken(document) {
4464 var body = document.getElementsByTagName('body')[0];
4465 var el = document.createElement('span');
4466 el.innerHTML = 'hello world';
4467 body.appendChild(el);
4468 var w1 = el.scrollWidth;
4469 el.style.fontWeight = 'bold';
4470 var w2 = el.scrollWidth;
4471 body.removeChild(el);
4472 return w1 !== w2;
4473 }
4474
4475 var String = this.String;
4476 var setTimeout = this.setTimeout;
4477 var setInterval = this.setInterval;
4478
4479 function indexOf(obj, el) {
4480 var i = obj.length;
4481 while (i--) {
4482 if (obj[i] === el) return i;
4483 }
4484 return -1;
4485 }
4486
4487 function isThirdLevelShift(term, ev) {
4488 var thirdLevelKey =
4489 (term.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
4490 (term.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
4491
4492 // Don't invoke for arrows, pageDown, home, backspace, etc.
4493 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
4494 }
4495
4496 function isWide(ch) {
4497 if (ch <= '\uff00') return false;
4498 return (ch >= '\uff01' && ch <= '\uffbe')
4499 || (ch >= '\uffc2' && ch <= '\uffc7')
4500 || (ch >= '\uffca' && ch <= '\uffcf')
4501 || (ch >= '\uffd2' && ch <= '\uffd7')
4502 || (ch >= '\uffda' && ch <= '\uffdc')
4503 || (ch >= '\uffe0' && ch <= '\uffe6')
4504 || (ch >= '\uffe8' && ch <= '\uffee');
4505 }
4506
4507 function matchColor(r1, g1, b1) {
4508 var hash = (r1 << 16) | (g1 << 8) | b1;
4509
4510 if (matchColor._cache[hash] != null) {
4511 return matchColor._cache[hash];
4512 }
4513
4514 var ldiff = Infinity
4515 , li = -1
4516 , i = 0
4517 , c
4518 , r2
4519 , g2
4520 , b2
4521 , diff;
4522
4523 for (; i < Terminal.vcolors.length; i++) {
4524 c = Terminal.vcolors[i];
4525 r2 = c[0];
4526 g2 = c[1];
4527 b2 = c[2];
4528
4529 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
4530
4531 if (diff === 0) {
4532 li = i;
4533 break;
4534 }
4535
4536 if (diff < ldiff) {
4537 ldiff = diff;
4538 li = i;
4539 }
4540 }
4541
4542 return matchColor._cache[hash] = li;
4543 }
4544
4545 matchColor._cache = {};
4546
4547 // http://stackoverflow.com/questions/1633828
4548 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
4549 return Math.pow(30 * (r1 - r2), 2)
4550 + Math.pow(59 * (g1 - g2), 2)
4551 + Math.pow(11 * (b1 - b2), 2);
4552 };
4553
4554 function each(obj, iter, con) {
4555 if (obj.forEach) return obj.forEach(iter, con);
4556 for (var i = 0; i < obj.length; i++) {
4557 iter.call(con, obj[i], i, obj);
4558 }
4559 }
4560
4561 function keys(obj) {
4562 if (Object.keys) return Object.keys(obj);
4563 var key, keys = [];
4564 for (key in obj) {
4565 if (Object.prototype.hasOwnProperty.call(obj, key)) {
4566 keys.push(key);
4567 }
4568 }
4569 return keys;
4570 }
4571
4572 /**
4573 * Expose
4574 */
4575
4576 Terminal.EventEmitter = EventEmitter;
4577 Terminal.inherits = inherits;
4578 Terminal.on = on;
4579 Terminal.off = off;
4580 Terminal.cancel = cancel;
4581
4582 return Terminal;
4583 });