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