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