]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Merge pull request #117 from Tyriar/86_protect_max_refresh
[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 (Terminal.focus !== this) 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 // Temporarily disabled:
1378 // this.refreshBlink();
1379 }
1380 };
1381
1382 Terminal.prototype.startBlink = function() {
1383 if (!this.cursorBlink) return;
1384 var self = this;
1385 this._blinker = function() {
1386 self._cursorBlink();
1387 };
1388 this._blink = setInterval(this._blinker, 500);
1389 };
1390
1391 Terminal.prototype.refreshBlink = function() {
1392 if (!this.cursorBlink) return;
1393 clearInterval(this._blink);
1394 this._blink = setInterval(this._blinker, 500);
1395 };
1396
1397 Terminal.prototype.scroll = function() {
1398 var row;
1399
1400 if (++this.ybase === this.scrollback) {
1401 this.ybase = this.ybase / 2 | 0;
1402 this.lines = this.lines.slice(-(this.ybase + this.rows) + 1);
1403 }
1404
1405 this.ydisp = this.ybase;
1406
1407 // last line
1408 row = this.ybase + this.rows - 1;
1409
1410 // subtract the bottom scroll region
1411 row -= this.rows - 1 - this.scrollBottom;
1412
1413 if (row === this.lines.length) {
1414 // potential optimization:
1415 // pushing is faster than splicing
1416 // when they amount to the same
1417 // behavior.
1418 this.lines.push(this.blankLine());
1419 } else {
1420 // add our new line
1421 this.lines.splice(row, 0, this.blankLine());
1422 }
1423
1424 if (this.scrollTop !== 0) {
1425 if (this.ybase !== 0) {
1426 this.ybase--;
1427 this.ydisp = this.ybase;
1428 }
1429 this.lines.splice(this.ybase + this.scrollTop, 1);
1430 }
1431
1432 // this.maxRange();
1433 this.updateRange(this.scrollTop);
1434 this.updateRange(this.scrollBottom);
1435 };
1436
1437 Terminal.prototype.scrollDisp = function(disp) {
1438 this.ydisp += disp;
1439
1440 if (this.ydisp > this.ybase) {
1441 this.ydisp = this.ybase;
1442 } else if (this.ydisp < 0) {
1443 this.ydisp = 0;
1444 }
1445
1446 this.refresh(0, this.rows - 1);
1447 };
1448
1449 /**
1450 * Writes text to the terminal.
1451 *
1452 * @param {string} text The text to write to the terminal.
1453 *
1454 * @public
1455 */
1456 Terminal.prototype.write = function(data) {
1457 var l = data.length, i = 0, j, cs, ch;
1458
1459 this.refreshStart = this.y;
1460 this.refreshEnd = this.y;
1461
1462 if (this.ybase !== this.ydisp) {
1463 this.ydisp = this.ybase;
1464 this.maxRange();
1465 }
1466
1467 for (; i < l; i++) {
1468 ch = data[i];
1469 switch (this.state) {
1470 case normal:
1471 switch (ch) {
1472 case '\x07':
1473 this.bell();
1474 break;
1475
1476 // '\n', '\v', '\f'
1477 case '\n':
1478 case '\x0b':
1479 case '\x0c':
1480 if (this.convertEol) {
1481 this.x = 0;
1482 }
1483 this.y++;
1484 if (this.y > this.scrollBottom) {
1485 this.y--;
1486 this.scroll();
1487 }
1488 break;
1489
1490 // '\r'
1491 case '\r':
1492 this.x = 0;
1493 break;
1494
1495 // '\b'
1496 case '\x08':
1497 if (this.x > 0) {
1498 this.x--;
1499 }
1500 break;
1501
1502 // '\t'
1503 case '\t':
1504 this.x = this.nextStop();
1505 break;
1506
1507 // shift out
1508 case '\x0e':
1509 this.setgLevel(1);
1510 break;
1511
1512 // shift in
1513 case '\x0f':
1514 this.setgLevel(0);
1515 break;
1516
1517 // '\e'
1518 case '\x1b':
1519 this.state = escaped;
1520 break;
1521
1522 default:
1523 // ' '
1524 if (ch >= ' ') {
1525 if (this.charset && this.charset[ch]) {
1526 ch = this.charset[ch];
1527 }
1528
1529 if (this.x >= this.cols) {
1530 this.x = 0;
1531 this.y++;
1532 if (this.y > this.scrollBottom) {
1533 this.y--;
1534 this.scroll();
1535 }
1536 }
1537
1538 this.lines[this.y + this.ybase][this.x] = [this.curAttr, ch];
1539 this.x++;
1540 this.updateRange(this.y);
1541
1542 if (isWide(ch)) {
1543 j = this.y + this.ybase;
1544 if (this.cols < 2 || this.x >= this.cols) {
1545 this.lines[j][this.x - 1] = [this.curAttr, ' '];
1546 break;
1547 }
1548 this.lines[j][this.x] = [this.curAttr, ' '];
1549 this.x++;
1550 }
1551 }
1552 break;
1553 }
1554 break;
1555 case escaped:
1556 switch (ch) {
1557 // ESC [ Control Sequence Introducer ( CSI is 0x9b).
1558 case '[':
1559 this.params = [];
1560 this.currentParam = 0;
1561 this.state = csi;
1562 break;
1563
1564 // ESC ] Operating System Command ( OSC is 0x9d).
1565 case ']':
1566 this.params = [];
1567 this.currentParam = 0;
1568 this.state = osc;
1569 break;
1570
1571 // ESC P Device Control String ( DCS is 0x90).
1572 case 'P':
1573 this.params = [];
1574 this.currentParam = 0;
1575 this.state = dcs;
1576 break;
1577
1578 // ESC _ Application Program Command ( APC is 0x9f).
1579 case '_':
1580 this.state = ignore;
1581 break;
1582
1583 // ESC ^ Privacy Message ( PM is 0x9e).
1584 case '^':
1585 this.state = ignore;
1586 break;
1587
1588 // ESC c Full Reset (RIS).
1589 case 'c':
1590 this.reset();
1591 break;
1592
1593 // ESC E Next Line ( NEL is 0x85).
1594 // ESC D Index ( IND is 0x84).
1595 case 'E':
1596 this.x = 0;
1597 ;
1598 case 'D':
1599 this.index();
1600 break;
1601
1602 // ESC M Reverse Index ( RI is 0x8d).
1603 case 'M':
1604 this.reverseIndex();
1605 break;
1606
1607 // ESC % Select default/utf-8 character set.
1608 // @ = default, G = utf-8
1609 case '%':
1610 //this.charset = null;
1611 this.setgLevel(0);
1612 this.setgCharset(0, Terminal.charsets.US);
1613 this.state = normal;
1614 i++;
1615 break;
1616
1617 // ESC (,),*,+,-,. Designate G0-G2 Character Set.
1618 case '(': // <-- this seems to get all the attention
1619 case ')':
1620 case '*':
1621 case '+':
1622 case '-':
1623 case '.':
1624 switch (ch) {
1625 case '(':
1626 this.gcharset = 0;
1627 break;
1628 case ')':
1629 this.gcharset = 1;
1630 break;
1631 case '*':
1632 this.gcharset = 2;
1633 break;
1634 case '+':
1635 this.gcharset = 3;
1636 break;
1637 case '-':
1638 this.gcharset = 1;
1639 break;
1640 case '.':
1641 this.gcharset = 2;
1642 break;
1643 }
1644 this.state = charset;
1645 break;
1646
1647 // Designate G3 Character Set (VT300).
1648 // A = ISO Latin-1 Supplemental.
1649 // Not implemented.
1650 case '/':
1651 this.gcharset = 3;
1652 this.state = charset;
1653 i--;
1654 break;
1655
1656 // ESC N
1657 // Single Shift Select of G2 Character Set
1658 // ( SS2 is 0x8e). This affects next character only.
1659 case 'N':
1660 break;
1661 // ESC O
1662 // Single Shift Select of G3 Character Set
1663 // ( SS3 is 0x8f). This affects next character only.
1664 case 'O':
1665 break;
1666 // ESC n
1667 // Invoke the G2 Character Set as GL (LS2).
1668 case 'n':
1669 this.setgLevel(2);
1670 break;
1671 // ESC o
1672 // Invoke the G3 Character Set as GL (LS3).
1673 case 'o':
1674 this.setgLevel(3);
1675 break;
1676 // ESC |
1677 // Invoke the G3 Character Set as GR (LS3R).
1678 case '|':
1679 this.setgLevel(3);
1680 break;
1681 // ESC }
1682 // Invoke the G2 Character Set as GR (LS2R).
1683 case '}':
1684 this.setgLevel(2);
1685 break;
1686 // ESC ~
1687 // Invoke the G1 Character Set as GR (LS1R).
1688 case '~':
1689 this.setgLevel(1);
1690 break;
1691
1692 // ESC 7 Save Cursor (DECSC).
1693 case '7':
1694 this.saveCursor();
1695 this.state = normal;
1696 break;
1697
1698 // ESC 8 Restore Cursor (DECRC).
1699 case '8':
1700 this.restoreCursor();
1701 this.state = normal;
1702 break;
1703
1704 // ESC # 3 DEC line height/width
1705 case '#':
1706 this.state = normal;
1707 i++;
1708 break;
1709
1710 // ESC H Tab Set (HTS is 0x88).
1711 case 'H':
1712 this.tabSet();
1713 break;
1714
1715 // ESC = Application Keypad (DECPAM).
1716 case '=':
1717 this.log('Serial port requested application keypad.');
1718 this.applicationKeypad = true;
1719 this.state = normal;
1720 break;
1721
1722 // ESC > Normal Keypad (DECPNM).
1723 case '>':
1724 this.log('Switching back to normal keypad.');
1725 this.applicationKeypad = false;
1726 this.state = normal;
1727 break;
1728
1729 default:
1730 this.state = normal;
1731 this.error('Unknown ESC control: %s.', ch);
1732 break;
1733 }
1734 break;
1735
1736 case charset:
1737 switch (ch) {
1738 case '0': // DEC Special Character and Line Drawing Set.
1739 cs = Terminal.charsets.SCLD;
1740 break;
1741 case 'A': // UK
1742 cs = Terminal.charsets.UK;
1743 break;
1744 case 'B': // United States (USASCII).
1745 cs = Terminal.charsets.US;
1746 break;
1747 case '4': // Dutch
1748 cs = Terminal.charsets.Dutch;
1749 break;
1750 case 'C': // Finnish
1751 case '5':
1752 cs = Terminal.charsets.Finnish;
1753 break;
1754 case 'R': // French
1755 cs = Terminal.charsets.French;
1756 break;
1757 case 'Q': // FrenchCanadian
1758 cs = Terminal.charsets.FrenchCanadian;
1759 break;
1760 case 'K': // German
1761 cs = Terminal.charsets.German;
1762 break;
1763 case 'Y': // Italian
1764 cs = Terminal.charsets.Italian;
1765 break;
1766 case 'E': // NorwegianDanish
1767 case '6':
1768 cs = Terminal.charsets.NorwegianDanish;
1769 break;
1770 case 'Z': // Spanish
1771 cs = Terminal.charsets.Spanish;
1772 break;
1773 case 'H': // Swedish
1774 case '7':
1775 cs = Terminal.charsets.Swedish;
1776 break;
1777 case '=': // Swiss
1778 cs = Terminal.charsets.Swiss;
1779 break;
1780 case '/': // ISOLatin (actually /A)
1781 cs = Terminal.charsets.ISOLatin;
1782 i++;
1783 break;
1784 default: // Default
1785 cs = Terminal.charsets.US;
1786 break;
1787 }
1788 this.setgCharset(this.gcharset, cs);
1789 this.gcharset = null;
1790 this.state = normal;
1791 break;
1792
1793 case osc:
1794 // OSC Ps ; Pt ST
1795 // OSC Ps ; Pt BEL
1796 // Set Text Parameters.
1797 if (ch === '\x1b' || ch === '\x07') {
1798 if (ch === '\x1b') i++;
1799
1800 this.params.push(this.currentParam);
1801
1802 switch (this.params[0]) {
1803 case 0:
1804 case 1:
1805 case 2:
1806 if (this.params[1]) {
1807 this.title = this.params[1];
1808 this.handleTitle(this.title);
1809 }
1810 break;
1811 case 3:
1812 // set X property
1813 break;
1814 case 4:
1815 case 5:
1816 // change dynamic colors
1817 break;
1818 case 10:
1819 case 11:
1820 case 12:
1821 case 13:
1822 case 14:
1823 case 15:
1824 case 16:
1825 case 17:
1826 case 18:
1827 case 19:
1828 // change dynamic ui colors
1829 break;
1830 case 46:
1831 // change log file
1832 break;
1833 case 50:
1834 // dynamic font
1835 break;
1836 case 51:
1837 // emacs shell
1838 break;
1839 case 52:
1840 // manipulate selection data
1841 break;
1842 case 104:
1843 case 105:
1844 case 110:
1845 case 111:
1846 case 112:
1847 case 113:
1848 case 114:
1849 case 115:
1850 case 116:
1851 case 117:
1852 case 118:
1853 // reset colors
1854 break;
1855 }
1856
1857 this.params = [];
1858 this.currentParam = 0;
1859 this.state = normal;
1860 } else {
1861 if (!this.params.length) {
1862 if (ch >= '0' && ch <= '9') {
1863 this.currentParam =
1864 this.currentParam * 10 + ch.charCodeAt(0) - 48;
1865 } else if (ch === ';') {
1866 this.params.push(this.currentParam);
1867 this.currentParam = '';
1868 }
1869 } else {
1870 this.currentParam += ch;
1871 }
1872 }
1873 break;
1874
1875 case csi:
1876 // '?', '>', '!'
1877 if (ch === '?' || ch === '>' || ch === '!') {
1878 this.prefix = ch;
1879 break;
1880 }
1881
1882 // 0 - 9
1883 if (ch >= '0' && ch <= '9') {
1884 this.currentParam = this.currentParam * 10 + ch.charCodeAt(0) - 48;
1885 break;
1886 }
1887
1888 // '$', '"', ' ', '\''
1889 if (ch === '$' || ch === '"' || ch === ' ' || ch === '\'') {
1890 this.postfix = ch;
1891 break;
1892 }
1893
1894 this.params.push(this.currentParam);
1895 this.currentParam = 0;
1896
1897 // ';'
1898 if (ch === ';') break;
1899
1900 this.state = normal;
1901
1902 switch (ch) {
1903 // CSI Ps A
1904 // Cursor Up Ps Times (default = 1) (CUU).
1905 case 'A':
1906 this.cursorUp(this.params);
1907 break;
1908
1909 // CSI Ps B
1910 // Cursor Down Ps Times (default = 1) (CUD).
1911 case 'B':
1912 this.cursorDown(this.params);
1913 break;
1914
1915 // CSI Ps C
1916 // Cursor Forward Ps Times (default = 1) (CUF).
1917 case 'C':
1918 this.cursorForward(this.params);
1919 break;
1920
1921 // CSI Ps D
1922 // Cursor Backward Ps Times (default = 1) (CUB).
1923 case 'D':
1924 this.cursorBackward(this.params);
1925 break;
1926
1927 // CSI Ps ; Ps H
1928 // Cursor Position [row;column] (default = [1,1]) (CUP).
1929 case 'H':
1930 this.cursorPos(this.params);
1931 break;
1932
1933 // CSI Ps J Erase in Display (ED).
1934 case 'J':
1935 this.eraseInDisplay(this.params);
1936 break;
1937
1938 // CSI Ps K Erase in Line (EL).
1939 case 'K':
1940 this.eraseInLine(this.params);
1941 break;
1942
1943 // CSI Pm m Character Attributes (SGR).
1944 case 'm':
1945 if (!this.prefix) {
1946 this.charAttributes(this.params);
1947 }
1948 break;
1949
1950 // CSI Ps n Device Status Report (DSR).
1951 case 'n':
1952 if (!this.prefix) {
1953 this.deviceStatus(this.params);
1954 }
1955 break;
1956
1957 /**
1958 * Additions
1959 */
1960
1961 // CSI Ps @
1962 // Insert Ps (Blank) Character(s) (default = 1) (ICH).
1963 case '@':
1964 this.insertChars(this.params);
1965 break;
1966
1967 // CSI Ps E
1968 // Cursor Next Line Ps Times (default = 1) (CNL).
1969 case 'E':
1970 this.cursorNextLine(this.params);
1971 break;
1972
1973 // CSI Ps F
1974 // Cursor Preceding Line Ps Times (default = 1) (CNL).
1975 case 'F':
1976 this.cursorPrecedingLine(this.params);
1977 break;
1978
1979 // CSI Ps G
1980 // Cursor Character Absolute [column] (default = [row,1]) (CHA).
1981 case 'G':
1982 this.cursorCharAbsolute(this.params);
1983 break;
1984
1985 // CSI Ps L
1986 // Insert Ps Line(s) (default = 1) (IL).
1987 case 'L':
1988 this.insertLines(this.params);
1989 break;
1990
1991 // CSI Ps M
1992 // Delete Ps Line(s) (default = 1) (DL).
1993 case 'M':
1994 this.deleteLines(this.params);
1995 break;
1996
1997 // CSI Ps P
1998 // Delete Ps Character(s) (default = 1) (DCH).
1999 case 'P':
2000 this.deleteChars(this.params);
2001 break;
2002
2003 // CSI Ps X
2004 // Erase Ps Character(s) (default = 1) (ECH).
2005 case 'X':
2006 this.eraseChars(this.params);
2007 break;
2008
2009 // CSI Pm ` Character Position Absolute
2010 // [column] (default = [row,1]) (HPA).
2011 case '`':
2012 this.charPosAbsolute(this.params);
2013 break;
2014
2015 // 141 61 a * HPR -
2016 // Horizontal Position Relative
2017 case 'a':
2018 this.HPositionRelative(this.params);
2019 break;
2020
2021 // CSI P s c
2022 // Send Device Attributes (Primary DA).
2023 // CSI > P s c
2024 // Send Device Attributes (Secondary DA)
2025 case 'c':
2026 this.sendDeviceAttributes(this.params);
2027 break;
2028
2029 // CSI Pm d
2030 // Line Position Absolute [row] (default = [1,column]) (VPA).
2031 case 'd':
2032 this.linePosAbsolute(this.params);
2033 break;
2034
2035 // 145 65 e * VPR - Vertical Position Relative
2036 case 'e':
2037 this.VPositionRelative(this.params);
2038 break;
2039
2040 // CSI Ps ; Ps f
2041 // Horizontal and Vertical Position [row;column] (default =
2042 // [1,1]) (HVP).
2043 case 'f':
2044 this.HVPosition(this.params);
2045 break;
2046
2047 // CSI Pm h Set Mode (SM).
2048 // CSI ? Pm h - mouse escape codes, cursor escape codes
2049 case 'h':
2050 this.setMode(this.params);
2051 break;
2052
2053 // CSI Pm l Reset Mode (RM).
2054 // CSI ? Pm l
2055 case 'l':
2056 this.resetMode(this.params);
2057 break;
2058
2059 // CSI Ps ; Ps r
2060 // Set Scrolling Region [top;bottom] (default = full size of win-
2061 // dow) (DECSTBM).
2062 // CSI ? Pm r
2063 case 'r':
2064 this.setScrollRegion(this.params);
2065 break;
2066
2067 // CSI s
2068 // Save cursor (ANSI.SYS).
2069 case 's':
2070 this.saveCursor(this.params);
2071 break;
2072
2073 // CSI u
2074 // Restore cursor (ANSI.SYS).
2075 case 'u':
2076 this.restoreCursor(this.params);
2077 break;
2078
2079 /**
2080 * Lesser Used
2081 */
2082
2083 // CSI Ps I
2084 // Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
2085 case 'I':
2086 this.cursorForwardTab(this.params);
2087 break;
2088
2089 // CSI Ps S Scroll up Ps lines (default = 1) (SU).
2090 case 'S':
2091 this.scrollUp(this.params);
2092 break;
2093
2094 // CSI Ps T Scroll down Ps lines (default = 1) (SD).
2095 // CSI Ps ; Ps ; Ps ; Ps ; Ps T
2096 // CSI > Ps; Ps T
2097 case 'T':
2098 // if (this.prefix === '>') {
2099 // this.resetTitleModes(this.params);
2100 // break;
2101 // }
2102 // if (this.params.length > 2) {
2103 // this.initMouseTracking(this.params);
2104 // break;
2105 // }
2106 if (this.params.length < 2 && !this.prefix) {
2107 this.scrollDown(this.params);
2108 }
2109 break;
2110
2111 // CSI Ps Z
2112 // Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
2113 case 'Z':
2114 this.cursorBackwardTab(this.params);
2115 break;
2116
2117 // CSI Ps b Repeat the preceding graphic character Ps times (REP).
2118 case 'b':
2119 this.repeatPrecedingCharacter(this.params);
2120 break;
2121
2122 // CSI Ps g Tab Clear (TBC).
2123 case 'g':
2124 this.tabClear(this.params);
2125 break;
2126
2127 // CSI Pm i Media Copy (MC).
2128 // CSI ? Pm i
2129 // case 'i':
2130 // this.mediaCopy(this.params);
2131 // break;
2132
2133 // CSI Pm m Character Attributes (SGR).
2134 // CSI > Ps; Ps m
2135 // case 'm': // duplicate
2136 // if (this.prefix === '>') {
2137 // this.setResources(this.params);
2138 // } else {
2139 // this.charAttributes(this.params);
2140 // }
2141 // break;
2142
2143 // CSI Ps n Device Status Report (DSR).
2144 // CSI > Ps n
2145 // case 'n': // duplicate
2146 // if (this.prefix === '>') {
2147 // this.disableModifiers(this.params);
2148 // } else {
2149 // this.deviceStatus(this.params);
2150 // }
2151 // break;
2152
2153 // CSI > Ps p Set pointer mode.
2154 // CSI ! p Soft terminal reset (DECSTR).
2155 // CSI Ps$ p
2156 // Request ANSI mode (DECRQM).
2157 // CSI ? Ps$ p
2158 // Request DEC private mode (DECRQM).
2159 // CSI Ps ; Ps " p
2160 case 'p':
2161 switch (this.prefix) {
2162 // case '>':
2163 // this.setPointerMode(this.params);
2164 // break;
2165 case '!':
2166 this.softReset(this.params);
2167 break;
2168 // case '?':
2169 // if (this.postfix === '$') {
2170 // this.requestPrivateMode(this.params);
2171 // }
2172 // break;
2173 // default:
2174 // if (this.postfix === '"') {
2175 // this.setConformanceLevel(this.params);
2176 // } else if (this.postfix === '$') {
2177 // this.requestAnsiMode(this.params);
2178 // }
2179 // break;
2180 }
2181 break;
2182
2183 // CSI Ps q Load LEDs (DECLL).
2184 // CSI Ps SP q
2185 // CSI Ps " q
2186 // case 'q':
2187 // if (this.postfix === ' ') {
2188 // this.setCursorStyle(this.params);
2189 // break;
2190 // }
2191 // if (this.postfix === '"') {
2192 // this.setCharProtectionAttr(this.params);
2193 // break;
2194 // }
2195 // this.loadLEDs(this.params);
2196 // break;
2197
2198 // CSI Ps ; Ps r
2199 // Set Scrolling Region [top;bottom] (default = full size of win-
2200 // dow) (DECSTBM).
2201 // CSI ? Pm r
2202 // CSI Pt; Pl; Pb; Pr; Ps$ r
2203 // case 'r': // duplicate
2204 // if (this.prefix === '?') {
2205 // this.restorePrivateValues(this.params);
2206 // } else if (this.postfix === '$') {
2207 // this.setAttrInRectangle(this.params);
2208 // } else {
2209 // this.setScrollRegion(this.params);
2210 // }
2211 // break;
2212
2213 // CSI s Save cursor (ANSI.SYS).
2214 // CSI ? Pm s
2215 // case 's': // duplicate
2216 // if (this.prefix === '?') {
2217 // this.savePrivateValues(this.params);
2218 // } else {
2219 // this.saveCursor(this.params);
2220 // }
2221 // break;
2222
2223 // CSI Ps ; Ps ; Ps t
2224 // CSI Pt; Pl; Pb; Pr; Ps$ t
2225 // CSI > Ps; Ps t
2226 // CSI Ps SP t
2227 // case 't':
2228 // if (this.postfix === '$') {
2229 // this.reverseAttrInRectangle(this.params);
2230 // } else if (this.postfix === ' ') {
2231 // this.setWarningBellVolume(this.params);
2232 // } else {
2233 // if (this.prefix === '>') {
2234 // this.setTitleModeFeature(this.params);
2235 // } else {
2236 // this.manipulateWindow(this.params);
2237 // }
2238 // }
2239 // break;
2240
2241 // CSI u Restore cursor (ANSI.SYS).
2242 // CSI Ps SP u
2243 // case 'u': // duplicate
2244 // if (this.postfix === ' ') {
2245 // this.setMarginBellVolume(this.params);
2246 // } else {
2247 // this.restoreCursor(this.params);
2248 // }
2249 // break;
2250
2251 // CSI Pt; Pl; Pb; Pr; Pp; Pt; Pl; Pp$ v
2252 // case 'v':
2253 // if (this.postfix === '$') {
2254 // this.copyRectagle(this.params);
2255 // }
2256 // break;
2257
2258 // CSI Pt ; Pl ; Pb ; Pr ' w
2259 // case 'w':
2260 // if (this.postfix === '\'') {
2261 // this.enableFilterRectangle(this.params);
2262 // }
2263 // break;
2264
2265 // CSI Ps x Request Terminal Parameters (DECREQTPARM).
2266 // CSI Ps x Select Attribute Change Extent (DECSACE).
2267 // CSI Pc; Pt; Pl; Pb; Pr$ x
2268 // case 'x':
2269 // if (this.postfix === '$') {
2270 // this.fillRectangle(this.params);
2271 // } else {
2272 // this.requestParameters(this.params);
2273 // //this.__(this.params);
2274 // }
2275 // break;
2276
2277 // CSI Ps ; Pu ' z
2278 // CSI Pt; Pl; Pb; Pr$ z
2279 // case 'z':
2280 // if (this.postfix === '\'') {
2281 // this.enableLocatorReporting(this.params);
2282 // } else if (this.postfix === '$') {
2283 // this.eraseRectangle(this.params);
2284 // }
2285 // break;
2286
2287 // CSI Pm ' {
2288 // CSI Pt; Pl; Pb; Pr$ {
2289 // case '{':
2290 // if (this.postfix === '\'') {
2291 // this.setLocatorEvents(this.params);
2292 // } else if (this.postfix === '$') {
2293 // this.selectiveEraseRectangle(this.params);
2294 // }
2295 // break;
2296
2297 // CSI Ps ' |
2298 // case '|':
2299 // if (this.postfix === '\'') {
2300 // this.requestLocatorPosition(this.params);
2301 // }
2302 // break;
2303
2304 // CSI P m SP }
2305 // Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
2306 // case '}':
2307 // if (this.postfix === ' ') {
2308 // this.insertColumns(this.params);
2309 // }
2310 // break;
2311
2312 // CSI P m SP ~
2313 // Delete P s Column(s) (default = 1) (DECDC), VT420 and up
2314 // case '~':
2315 // if (this.postfix === ' ') {
2316 // this.deleteColumns(this.params);
2317 // }
2318 // break;
2319
2320 default:
2321 this.error('Unknown CSI code: %s.', ch);
2322 break;
2323 }
2324
2325 this.prefix = '';
2326 this.postfix = '';
2327 break;
2328
2329 case dcs:
2330 if (ch === '\x1b' || ch === '\x07') {
2331 if (ch === '\x1b') i++;
2332
2333 switch (this.prefix) {
2334 // User-Defined Keys (DECUDK).
2335 case '':
2336 break;
2337
2338 // Request Status String (DECRQSS).
2339 // test: echo -e '\eP$q"p\e\\'
2340 case '$q':
2341 var pt = this.currentParam
2342 , valid = false;
2343
2344 switch (pt) {
2345 // DECSCA
2346 case '"q':
2347 pt = '0"q';
2348 break;
2349
2350 // DECSCL
2351 case '"p':
2352 pt = '61"p';
2353 break;
2354
2355 // DECSTBM
2356 case 'r':
2357 pt = ''
2358 + (this.scrollTop + 1)
2359 + ';'
2360 + (this.scrollBottom + 1)
2361 + 'r';
2362 break;
2363
2364 // SGR
2365 case 'm':
2366 pt = '0m';
2367 break;
2368
2369 default:
2370 this.error('Unknown DCS Pt: %s.', pt);
2371 pt = '';
2372 break;
2373 }
2374
2375 this.send('\x1bP' + +valid + '$r' + pt + '\x1b\\');
2376 break;
2377
2378 // Set Termcap/Terminfo Data (xterm, experimental).
2379 case '+p':
2380 break;
2381
2382 // Request Termcap/Terminfo String (xterm, experimental)
2383 // Regular xterm does not even respond to this sequence.
2384 // This can cause a small glitch in vim.
2385 // test: echo -ne '\eP+q6b64\e\\'
2386 case '+q':
2387 var pt = this.currentParam
2388 , valid = false;
2389
2390 this.send('\x1bP' + +valid + '+r' + pt + '\x1b\\');
2391 break;
2392
2393 default:
2394 this.error('Unknown DCS prefix: %s.', this.prefix);
2395 break;
2396 }
2397
2398 this.currentParam = 0;
2399 this.prefix = '';
2400 this.state = normal;
2401 } else if (!this.currentParam) {
2402 if (!this.prefix && ch !== '$' && ch !== '+') {
2403 this.currentParam = ch;
2404 } else if (this.prefix.length === 2) {
2405 this.currentParam = ch;
2406 } else {
2407 this.prefix += ch;
2408 }
2409 } else {
2410 this.currentParam += ch;
2411 }
2412 break;
2413
2414 case ignore:
2415 // For PM and APC.
2416 if (ch === '\x1b' || ch === '\x07') {
2417 if (ch === '\x1b') i++;
2418 this.state = normal;
2419 }
2420 break;
2421 }
2422 }
2423
2424 this.updateRange(this.y);
2425 this.refresh(this.refreshStart, this.refreshEnd);
2426 };
2427
2428 Terminal.prototype.writeln = function(data) {
2429 this.write(data + '\r\n');
2430 };
2431
2432 // Key Resources:
2433 // https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
2434 Terminal.prototype.keyDown = function(ev) {
2435 var self = this;
2436 var result = this.evaluateKeyEscapeSequence(ev);
2437
2438 if (result.scrollDisp) {
2439 this.scrollDisp(result.scrollDisp);
2440 return this.cancel(ev);
2441 }
2442
2443 if (isThirdLevelShift(this, ev)) {
2444 return true;
2445 }
2446
2447 if (result.cancel ) {
2448 // The event is canceled at the end already, is this necessary?
2449 this.cancel(ev, true);
2450 }
2451
2452 if (!result.key) {
2453 return true;
2454 }
2455
2456 this.emit('keydown', ev);
2457 this.emit('key', result.key, ev);
2458 this.showCursor();
2459 this.handler(result.key);
2460
2461 return this.cancel(ev, true);
2462 };
2463
2464 /**
2465 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
2466 * returned value is the new key code to pass to the PTY.
2467 *
2468 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
2469 */
2470 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
2471 var result = {
2472 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
2473 // canceled at the end of keyDown
2474 cancel: false,
2475 // The new key even to emit
2476 key: undefined,
2477 // The number of characters to scroll, if this is defined it will cancel the event
2478 scrollDisp: undefined
2479 };
2480 switch (ev.keyCode) {
2481 // backspace
2482 case 8:
2483 if (ev.shiftKey) {
2484 result.key = '\x08'; // ^H
2485 break;
2486 }
2487 result.key = '\x7f'; // ^?
2488 break;
2489 // tab
2490 case 9:
2491 if (ev.shiftKey) {
2492 result.key = '\x1b[Z';
2493 break;
2494 }
2495 result.key = '\t';
2496 result.cancel = true;
2497 break;
2498 // return/enter
2499 case 13:
2500 result.key = '\r';
2501 result.cancel = true;
2502 break;
2503 // escape
2504 case 27:
2505 result.key = '\x1b';
2506 result.cancel = true;
2507 break;
2508 // left-arrow
2509 case 37:
2510 if (ev.altKey) {
2511 result.key = '\x1bb' // Jump a word back
2512 result.cancel = true;
2513 break;
2514 }
2515 if (ev.ctrlKey) {
2516 result.key = '\x1b[5D'; // Jump a word back
2517 break;
2518 }
2519 if (this.applicationCursor) {
2520 result.key = '\x1bOD'; // SS3 as ^[O for 7-bit
2521 break;
2522 }
2523 result.key = '\x1b[D';
2524 break;
2525 // right-arrow
2526 case 39:
2527 if (ev.altKey) {
2528 result.key = '\x1bf' // Jump a word forward
2529 result.cancel = true;
2530 break;
2531 }
2532 if (ev.ctrlKey) {
2533 result.key = '\x1b[5C'; // Jump a word forward
2534 break;
2535 }
2536 if (this.applicationCursor) {
2537 result.key = '\x1bOC';
2538 break;
2539 }
2540 result.key = '\x1b[C';
2541 break;
2542 // up-arrow
2543 case 38:
2544 if (this.applicationCursor) {
2545 result.key = '\x1bOA';
2546 break;
2547 }
2548 if (ev.ctrlKey) {
2549 result.scrollDisp = -1;
2550 } else {
2551 result.key = '\x1b[A';
2552 }
2553 break;
2554 // down-arrow
2555 case 40:
2556 if (this.applicationCursor) {
2557 result.key = '\x1bOB';
2558 break;
2559 }
2560 if (ev.ctrlKey) {
2561 result.scrollDisp = 1;
2562 } else {
2563 result.key = '\x1b[B';
2564 }
2565 break;
2566 // insert
2567 case 45:
2568 if (!ev.shiftKey && !ev.ctrlKey) {
2569 // <Ctrl> or <Shift> + <Insert> are used to
2570 // copy-paste on some systems.
2571 result.key = '\x1b[2~';
2572 }
2573 break;
2574 // delete
2575 case 46: result.key = '\x1b[3~'; break;
2576 // home
2577 case 36:
2578 if (this.applicationKeypad) {
2579 result.key = '\x1bOH';
2580 break;
2581 }
2582 result.key = '\x1bOH';
2583 break;
2584 // end
2585 case 35:
2586 if (this.applicationKeypad) {
2587 result.key = '\x1bOF';
2588 break;
2589 }
2590 result.key = '\x1bOF';
2591 break;
2592 // page up
2593 case 33:
2594 if (ev.shiftKey) {
2595 result.scrollDisp = -(this.rows - 1);
2596 } else {
2597 result.key = '\x1b[5~';
2598 }
2599 break;
2600 // page down
2601 case 34:
2602 if (ev.shiftKey) {
2603 result.scrollDisp = this.rows - 1;
2604 } else {
2605 result.key = '\x1b[6~';
2606 }
2607 break;
2608 // F1-F12
2609 case 112: result.key = '\x1bOP'; break;
2610 case 113: result.key = '\x1bOQ'; break;
2611 case 114: result.key = '\x1bOR'; break;
2612 case 115: result.key = '\x1bOS'; break;
2613 case 116: result.key = '\x1b[15~'; break;
2614 case 117: result.key = '\x1b[17~'; break;
2615 case 118: result.key = '\x1b[18~'; break;
2616 case 119: result.key = '\x1b[19~'; break;
2617 case 120: result.key = '\x1b[20~'; break;
2618 case 121: result.key = '\x1b[21~'; break;
2619 case 122: result.key = '\x1b[23~'; break;
2620 case 123: result.key = '\x1b[24~'; break;
2621 default:
2622 // a-z and space
2623 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
2624 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
2625 result.key = String.fromCharCode(ev.keyCode - 64);
2626 } else if (ev.keyCode === 32) {
2627 // NUL
2628 result.key = String.fromCharCode(0);
2629 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
2630 // escape, file sep, group sep, record sep, unit sep
2631 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
2632 } else if (ev.keyCode === 56) {
2633 // delete
2634 result.key = String.fromCharCode(127);
2635 } else if (ev.keyCode === 219) {
2636 // ^[ - escape
2637 result.key = String.fromCharCode(27);
2638 } else if (ev.keyCode === 221) {
2639 // ^] - group sep
2640 result.key = String.fromCharCode(29);
2641 }
2642 } else if (!this.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
2643 // On Mac this is a third level shift. Use <Esc> instead.
2644 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
2645 result.key = '\x1b' + String.fromCharCode(ev.keyCode + 32);
2646 } else if (ev.keyCode === 192) {
2647 result.key = '\x1b`';
2648 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
2649 result.key = '\x1b' + (ev.keyCode - 48);
2650 }
2651 }
2652 break;
2653 }
2654 return result;
2655 };
2656
2657 Terminal.prototype.setgLevel = function(g) {
2658 this.glevel = g;
2659 this.charset = this.charsets[g];
2660 };
2661
2662 Terminal.prototype.setgCharset = function(g, charset) {
2663 this.charsets[g] = charset;
2664 if (this.glevel === g) {
2665 this.charset = charset;
2666 }
2667 };
2668
2669 Terminal.prototype.keyPress = function(ev) {
2670 var key;
2671
2672 if (ev.charCode) {
2673 key = ev.charCode;
2674 } else if (ev.which == null) {
2675 key = ev.keyCode;
2676 } else if (ev.which !== 0 && ev.charCode !== 0) {
2677 key = ev.which;
2678 } else {
2679 return false;
2680 }
2681
2682 if (!key || (
2683 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
2684 )) {
2685 return false;
2686 }
2687
2688 key = String.fromCharCode(key);
2689
2690 /**
2691 * When a key is pressed and a character is sent to the terminal, then clear any text
2692 * selected in the terminal.
2693 */
2694 if (key) {
2695 this.clearSelection();
2696 }
2697
2698 this.emit('keypress', key, ev);
2699 this.emit('key', key, ev);
2700 this.showCursor();
2701 this.handler(key);
2702
2703 this.cancel(ev, true);
2704
2705 return false;
2706 };
2707
2708 Terminal.prototype.send = function(data) {
2709 var self = this;
2710
2711 if (!this.queue) {
2712 setTimeout(function() {
2713 self.handler(self.queue);
2714 self.queue = '';
2715 }, 1);
2716 }
2717
2718 this.queue += data;
2719 };
2720
2721 Terminal.prototype.bell = function() {
2722 if (!this.visualBell) return;
2723 var self = this;
2724 this.element.style.borderColor = 'white';
2725 setTimeout(function() {
2726 self.element.style.borderColor = '';
2727 }, 10);
2728 if (this.popOnBell) this.focus();
2729 };
2730
2731 Terminal.prototype.log = function() {
2732 if (!this.debug) return;
2733 if (!this.context.console || !this.context.console.log) return;
2734 var args = Array.prototype.slice.call(arguments);
2735 this.context.console.log.apply(this.context.console, args);
2736 };
2737
2738 Terminal.prototype.error = function() {
2739 if (!this.debug) return;
2740 if (!this.context.console || !this.context.console.error) return;
2741 var args = Array.prototype.slice.call(arguments);
2742 this.context.console.error.apply(this.context.console, args);
2743 };
2744
2745 /**
2746 * Resizes the terminal.
2747 *
2748 * @param {number} x The number of columns to resize to.
2749 * @param {number} y The number of rows to resize to.
2750 *
2751 * @public
2752 */
2753 Terminal.prototype.resize = function(x, y) {
2754 var line
2755 , el
2756 , i
2757 , j
2758 , ch
2759 , addToY;
2760
2761 if (x === this.cols && y === this.rows) {
2762 return;
2763 }
2764
2765 if (x < 1) x = 1;
2766 if (y < 1) y = 1;
2767
2768 // resize cols
2769 j = this.cols;
2770 if (j < x) {
2771 ch = [this.defAttr, ' ']; // does xterm use the default attr?
2772 i = this.lines.length;
2773 while (i--) {
2774 while (this.lines[i].length < x) {
2775 this.lines[i].push(ch);
2776 }
2777 }
2778 } else { // (j > x)
2779 i = this.lines.length;
2780 while (i--) {
2781 while (this.lines[i].length > x) {
2782 this.lines[i].pop();
2783 }
2784 }
2785 }
2786 this.setupStops(j);
2787 this.cols = x;
2788
2789 // resize rows
2790 j = this.rows;
2791 addToY = 0;
2792 if (j < y) {
2793 el = this.element;
2794 while (j++ < y) {
2795 // y is rows, not this.y
2796 if (this.lines.length < y + this.ybase) {
2797 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
2798 // There is room above the buffer and there are no empty elements below the line,
2799 // scroll up
2800 this.ybase--;
2801 this.ydisp--;
2802 addToY++
2803 } else {
2804 // Add a blank line if there is no buffer left at the top to scroll to, or if there
2805 // are blank lines after the cursor
2806 this.lines.push(this.blankLine());
2807 }
2808 }
2809 if (this.children.length < y) {
2810 this.insertRow();
2811 }
2812 }
2813 } else { // (j > y)
2814 while (j-- > y) {
2815 if (this.lines.length > y + this.ybase) {
2816 if (this.lines.length > this.ybase + this.y + 1) {
2817 // The line is a blank line below the cursor, remove it
2818 this.lines.pop();
2819 } else {
2820 // The line is the cursor, scroll down
2821 this.ybase++;
2822 this.ydisp++;
2823 }
2824 }
2825 if (this.children.length > y) {
2826 el = this.children.shift();
2827 if (!el) continue;
2828 el.parentNode.removeChild(el);
2829 }
2830 }
2831 }
2832 this.rows = y;
2833
2834 /*
2835 * Make sure that the cursor stays on screen
2836 */
2837 if (this.y >= y) {
2838 this.y = y - 1;
2839 }
2840 if (addToY) {
2841 this.y += addToY;
2842 }
2843
2844 if (this.x >= x) {
2845 this.x = x - 1;
2846 }
2847
2848 this.scrollTop = 0;
2849 this.scrollBottom = y - 1;
2850
2851 this.refresh(0, this.rows - 1);
2852
2853 this.normal = null;
2854
2855 this.emit('resize', {terminal: this, cols: x, rows: y});
2856 };
2857
2858 Terminal.prototype.updateRange = function(y) {
2859 if (y < this.refreshStart) this.refreshStart = y;
2860 if (y > this.refreshEnd) this.refreshEnd = y;
2861 // if (y > this.refreshEnd) {
2862 // this.refreshEnd = y;
2863 // if (y > this.rows - 1) {
2864 // this.refreshEnd = this.rows - 1;
2865 // }
2866 // }
2867 };
2868
2869 Terminal.prototype.maxRange = function() {
2870 this.refreshStart = 0;
2871 this.refreshEnd = this.rows - 1;
2872 };
2873
2874 Terminal.prototype.setupStops = function(i) {
2875 if (i != null) {
2876 if (!this.tabs[i]) {
2877 i = this.prevStop(i);
2878 }
2879 } else {
2880 this.tabs = {};
2881 i = 0;
2882 }
2883
2884 for (; i < this.cols; i += 8) {
2885 this.tabs[i] = true;
2886 }
2887 };
2888
2889 Terminal.prototype.prevStop = function(x) {
2890 if (x == null) x = this.x;
2891 while (!this.tabs[--x] && x > 0);
2892 return x >= this.cols
2893 ? this.cols - 1
2894 : x < 0 ? 0 : x;
2895 };
2896
2897 Terminal.prototype.nextStop = function(x) {
2898 if (x == null) x = this.x;
2899 while (!this.tabs[++x] && x < this.cols);
2900 return x >= this.cols
2901 ? this.cols - 1
2902 : x < 0 ? 0 : x;
2903 };
2904
2905 Terminal.prototype.eraseRight = function(x, y) {
2906 var line = this.lines[this.ybase + y]
2907 , ch = [this.eraseAttr(), ' ']; // xterm
2908
2909
2910 for (; x < this.cols; x++) {
2911 line[x] = ch;
2912 }
2913
2914 this.updateRange(y);
2915 };
2916
2917 Terminal.prototype.eraseLeft = function(x, y) {
2918 var line = this.lines[this.ybase + y]
2919 , ch = [this.eraseAttr(), ' ']; // xterm
2920
2921 x++;
2922 while (x--) line[x] = ch;
2923
2924 this.updateRange(y);
2925 };
2926
2927 Terminal.prototype.eraseLine = function(y) {
2928 this.eraseRight(0, y);
2929 };
2930
2931 Terminal.prototype.blankLine = function(cur) {
2932 var attr = cur
2933 ? this.eraseAttr()
2934 : this.defAttr;
2935
2936 var ch = [attr, ' ']
2937 , line = []
2938 , i = 0;
2939
2940 for (; i < this.cols; i++) {
2941 line[i] = ch;
2942 }
2943
2944 return line;
2945 };
2946
2947 Terminal.prototype.ch = function(cur) {
2948 return cur
2949 ? [this.eraseAttr(), ' ']
2950 : [this.defAttr, ' '];
2951 };
2952
2953 Terminal.prototype.is = function(term) {
2954 var name = this.termName;
2955 return (name + '').indexOf(term) === 0;
2956 };
2957
2958 Terminal.prototype.handler = function(data) {
2959 this.emit('data', data);
2960 };
2961
2962 Terminal.prototype.handleTitle = function(title) {
2963 this.emit('title', title);
2964 };
2965
2966 /**
2967 * ESC
2968 */
2969
2970 // ESC D Index (IND is 0x84).
2971 Terminal.prototype.index = function() {
2972 this.y++;
2973 if (this.y > this.scrollBottom) {
2974 this.y--;
2975 this.scroll();
2976 }
2977 this.state = normal;
2978 };
2979
2980 // ESC M Reverse Index (RI is 0x8d).
2981 Terminal.prototype.reverseIndex = function() {
2982 var j;
2983 this.y--;
2984 if (this.y < this.scrollTop) {
2985 this.y++;
2986 // possibly move the code below to term.reverseScroll();
2987 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2988 // blankLine(true) is xterm/linux behavior
2989 this.lines.splice(this.y + this.ybase, 0, this.blankLine(true));
2990 j = this.rows - 1 - this.scrollBottom;
2991 this.lines.splice(this.rows - 1 + this.ybase - j + 1, 1);
2992 // this.maxRange();
2993 this.updateRange(this.scrollTop);
2994 this.updateRange(this.scrollBottom);
2995 }
2996 this.state = normal;
2997 };
2998
2999 // ESC c Full Reset (RIS).
3000 Terminal.prototype.reset = function() {
3001 this.options.rows = this.rows;
3002 this.options.cols = this.cols;
3003 Terminal.call(this, this.options);
3004 this.refresh(0, this.rows - 1);
3005 };
3006
3007 // ESC H Tab Set (HTS is 0x88).
3008 Terminal.prototype.tabSet = function() {
3009 this.tabs[this.x] = true;
3010 this.state = normal;
3011 };
3012
3013 /**
3014 * CSI
3015 */
3016
3017 // CSI Ps A
3018 // Cursor Up Ps Times (default = 1) (CUU).
3019 Terminal.prototype.cursorUp = function(params) {
3020 var param = params[0];
3021 if (param < 1) param = 1;
3022 this.y -= param;
3023 if (this.y < 0) this.y = 0;
3024 };
3025
3026 // CSI Ps B
3027 // Cursor Down Ps Times (default = 1) (CUD).
3028 Terminal.prototype.cursorDown = function(params) {
3029 var param = params[0];
3030 if (param < 1) param = 1;
3031 this.y += param;
3032 if (this.y >= this.rows) {
3033 this.y = this.rows - 1;
3034 }
3035 };
3036
3037 // CSI Ps C
3038 // Cursor Forward Ps Times (default = 1) (CUF).
3039 Terminal.prototype.cursorForward = function(params) {
3040 var param = params[0];
3041 if (param < 1) param = 1;
3042 this.x += param;
3043 if (this.x >= this.cols) {
3044 this.x = this.cols - 1;
3045 }
3046 };
3047
3048 // CSI Ps D
3049 // Cursor Backward Ps Times (default = 1) (CUB).
3050 Terminal.prototype.cursorBackward = function(params) {
3051 var param = params[0];
3052 if (param < 1) param = 1;
3053 this.x -= param;
3054 if (this.x < 0) this.x = 0;
3055 };
3056
3057 // CSI Ps ; Ps H
3058 // Cursor Position [row;column] (default = [1,1]) (CUP).
3059 Terminal.prototype.cursorPos = function(params) {
3060 var row, col;
3061
3062 row = params[0] - 1;
3063
3064 if (params.length >= 2) {
3065 col = params[1] - 1;
3066 } else {
3067 col = 0;
3068 }
3069
3070 if (row < 0) {
3071 row = 0;
3072 } else if (row >= this.rows) {
3073 row = this.rows - 1;
3074 }
3075
3076 if (col < 0) {
3077 col = 0;
3078 } else if (col >= this.cols) {
3079 col = this.cols - 1;
3080 }
3081
3082 this.x = col;
3083 this.y = row;
3084 };
3085
3086 // CSI Ps J Erase in Display (ED).
3087 // Ps = 0 -> Erase Below (default).
3088 // Ps = 1 -> Erase Above.
3089 // Ps = 2 -> Erase All.
3090 // Ps = 3 -> Erase Saved Lines (xterm).
3091 // CSI ? Ps J
3092 // Erase in Display (DECSED).
3093 // Ps = 0 -> Selective Erase Below (default).
3094 // Ps = 1 -> Selective Erase Above.
3095 // Ps = 2 -> Selective Erase All.
3096 Terminal.prototype.eraseInDisplay = function(params) {
3097 var j;
3098 switch (params[0]) {
3099 case 0:
3100 this.eraseRight(this.x, this.y);
3101 j = this.y + 1;
3102 for (; j < this.rows; j++) {
3103 this.eraseLine(j);
3104 }
3105 break;
3106 case 1:
3107 this.eraseLeft(this.x, this.y);
3108 j = this.y;
3109 while (j--) {
3110 this.eraseLine(j);
3111 }
3112 break;
3113 case 2:
3114 j = this.rows;
3115 while (j--) this.eraseLine(j);
3116 break;
3117 case 3:
3118 ; // no saved lines
3119 break;
3120 }
3121 };
3122
3123 // CSI Ps K Erase in Line (EL).
3124 // Ps = 0 -> Erase to Right (default).
3125 // Ps = 1 -> Erase to Left.
3126 // Ps = 2 -> Erase All.
3127 // CSI ? Ps K
3128 // Erase in Line (DECSEL).
3129 // Ps = 0 -> Selective Erase to Right (default).
3130 // Ps = 1 -> Selective Erase to Left.
3131 // Ps = 2 -> Selective Erase All.
3132 Terminal.prototype.eraseInLine = function(params) {
3133 switch (params[0]) {
3134 case 0:
3135 this.eraseRight(this.x, this.y);
3136 break;
3137 case 1:
3138 this.eraseLeft(this.x, this.y);
3139 break;
3140 case 2:
3141 this.eraseLine(this.y);
3142 break;
3143 }
3144 };
3145
3146 // CSI Pm m Character Attributes (SGR).
3147 // Ps = 0 -> Normal (default).
3148 // Ps = 1 -> Bold.
3149 // Ps = 4 -> Underlined.
3150 // Ps = 5 -> Blink (appears as Bold).
3151 // Ps = 7 -> Inverse.
3152 // Ps = 8 -> Invisible, i.e., hidden (VT300).
3153 // Ps = 2 2 -> Normal (neither bold nor faint).
3154 // Ps = 2 4 -> Not underlined.
3155 // Ps = 2 5 -> Steady (not blinking).
3156 // Ps = 2 7 -> Positive (not inverse).
3157 // Ps = 2 8 -> Visible, i.e., not hidden (VT300).
3158 // Ps = 3 0 -> Set foreground color to Black.
3159 // Ps = 3 1 -> Set foreground color to Red.
3160 // Ps = 3 2 -> Set foreground color to Green.
3161 // Ps = 3 3 -> Set foreground color to Yellow.
3162 // Ps = 3 4 -> Set foreground color to Blue.
3163 // Ps = 3 5 -> Set foreground color to Magenta.
3164 // Ps = 3 6 -> Set foreground color to Cyan.
3165 // Ps = 3 7 -> Set foreground color to White.
3166 // Ps = 3 9 -> Set foreground color to default (original).
3167 // Ps = 4 0 -> Set background color to Black.
3168 // Ps = 4 1 -> Set background color to Red.
3169 // Ps = 4 2 -> Set background color to Green.
3170 // Ps = 4 3 -> Set background color to Yellow.
3171 // Ps = 4 4 -> Set background color to Blue.
3172 // Ps = 4 5 -> Set background color to Magenta.
3173 // Ps = 4 6 -> Set background color to Cyan.
3174 // Ps = 4 7 -> Set background color to White.
3175 // Ps = 4 9 -> Set background color to default (original).
3176
3177 // If 16-color support is compiled, the following apply. Assume
3178 // that xterm's resources are set so that the ISO color codes are
3179 // the first 8 of a set of 16. Then the aixterm colors are the
3180 // bright versions of the ISO colors:
3181 // Ps = 9 0 -> Set foreground color to Black.
3182 // Ps = 9 1 -> Set foreground color to Red.
3183 // Ps = 9 2 -> Set foreground color to Green.
3184 // Ps = 9 3 -> Set foreground color to Yellow.
3185 // Ps = 9 4 -> Set foreground color to Blue.
3186 // Ps = 9 5 -> Set foreground color to Magenta.
3187 // Ps = 9 6 -> Set foreground color to Cyan.
3188 // Ps = 9 7 -> Set foreground color to White.
3189 // Ps = 1 0 0 -> Set background color to Black.
3190 // Ps = 1 0 1 -> Set background color to Red.
3191 // Ps = 1 0 2 -> Set background color to Green.
3192 // Ps = 1 0 3 -> Set background color to Yellow.
3193 // Ps = 1 0 4 -> Set background color to Blue.
3194 // Ps = 1 0 5 -> Set background color to Magenta.
3195 // Ps = 1 0 6 -> Set background color to Cyan.
3196 // Ps = 1 0 7 -> Set background color to White.
3197
3198 // If xterm is compiled with the 16-color support disabled, it
3199 // supports the following, from rxvt:
3200 // Ps = 1 0 0 -> Set foreground and background color to
3201 // default.
3202
3203 // If 88- or 256-color support is compiled, the following apply.
3204 // Ps = 3 8 ; 5 ; Ps -> Set foreground color to the second
3205 // Ps.
3206 // Ps = 4 8 ; 5 ; Ps -> Set background color to the second
3207 // Ps.
3208 Terminal.prototype.charAttributes = function(params) {
3209 // Optimize a single SGR0.
3210 if (params.length === 1 && params[0] === 0) {
3211 this.curAttr = this.defAttr;
3212 return;
3213 }
3214
3215 var l = params.length
3216 , i = 0
3217 , flags = this.curAttr >> 18
3218 , fg = (this.curAttr >> 9) & 0x1ff
3219 , bg = this.curAttr & 0x1ff
3220 , p;
3221
3222 for (; i < l; i++) {
3223 p = params[i];
3224 if (p >= 30 && p <= 37) {
3225 // fg color 8
3226 fg = p - 30;
3227 } else if (p >= 40 && p <= 47) {
3228 // bg color 8
3229 bg = p - 40;
3230 } else if (p >= 90 && p <= 97) {
3231 // fg color 16
3232 p += 8;
3233 fg = p - 90;
3234 } else if (p >= 100 && p <= 107) {
3235 // bg color 16
3236 p += 8;
3237 bg = p - 100;
3238 } else if (p === 0) {
3239 // default
3240 flags = this.defAttr >> 18;
3241 fg = (this.defAttr >> 9) & 0x1ff;
3242 bg = this.defAttr & 0x1ff;
3243 // flags = 0;
3244 // fg = 0x1ff;
3245 // bg = 0x1ff;
3246 } else if (p === 1) {
3247 // bold text
3248 flags |= 1;
3249 } else if (p === 4) {
3250 // underlined text
3251 flags |= 2;
3252 } else if (p === 5) {
3253 // blink
3254 flags |= 4;
3255 } else if (p === 7) {
3256 // inverse and positive
3257 // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m'
3258 flags |= 8;
3259 } else if (p === 8) {
3260 // invisible
3261 flags |= 16;
3262 } else if (p === 22) {
3263 // not bold
3264 flags &= ~1;
3265 } else if (p === 24) {
3266 // not underlined
3267 flags &= ~2;
3268 } else if (p === 25) {
3269 // not blink
3270 flags &= ~4;
3271 } else if (p === 27) {
3272 // not inverse
3273 flags &= ~8;
3274 } else if (p === 28) {
3275 // not invisible
3276 flags &= ~16;
3277 } else if (p === 39) {
3278 // reset fg
3279 fg = (this.defAttr >> 9) & 0x1ff;
3280 } else if (p === 49) {
3281 // reset bg
3282 bg = this.defAttr & 0x1ff;
3283 } else if (p === 38) {
3284 // fg color 256
3285 if (params[i + 1] === 2) {
3286 i += 2;
3287 fg = matchColor(
3288 params[i] & 0xff,
3289 params[i + 1] & 0xff,
3290 params[i + 2] & 0xff);
3291 if (fg === -1) fg = 0x1ff;
3292 i += 2;
3293 } else if (params[i + 1] === 5) {
3294 i += 2;
3295 p = params[i] & 0xff;
3296 fg = p;
3297 }
3298 } else if (p === 48) {
3299 // bg color 256
3300 if (params[i + 1] === 2) {
3301 i += 2;
3302 bg = matchColor(
3303 params[i] & 0xff,
3304 params[i + 1] & 0xff,
3305 params[i + 2] & 0xff);
3306 if (bg === -1) bg = 0x1ff;
3307 i += 2;
3308 } else if (params[i + 1] === 5) {
3309 i += 2;
3310 p = params[i] & 0xff;
3311 bg = p;
3312 }
3313 } else if (p === 100) {
3314 // reset fg/bg
3315 fg = (this.defAttr >> 9) & 0x1ff;
3316 bg = this.defAttr & 0x1ff;
3317 } else {
3318 this.error('Unknown SGR attribute: %d.', p);
3319 }
3320 }
3321
3322 this.curAttr = (flags << 18) | (fg << 9) | bg;
3323 };
3324
3325 // CSI Ps n Device Status Report (DSR).
3326 // Ps = 5 -> Status Report. Result (``OK'') is
3327 // CSI 0 n
3328 // Ps = 6 -> Report Cursor Position (CPR) [row;column].
3329 // Result is
3330 // CSI r ; c R
3331 // CSI ? Ps n
3332 // Device Status Report (DSR, DEC-specific).
3333 // Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI
3334 // ? r ; c R (assumes page is zero).
3335 // Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready).
3336 // or CSI ? 1 1 n (not ready).
3337 // Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked)
3338 // or CSI ? 2 1 n (locked).
3339 // Ps = 2 6 -> Report Keyboard status as
3340 // CSI ? 2 7 ; 1 ; 0 ; 0 n (North American).
3341 // The last two parameters apply to VT400 & up, and denote key-
3342 // board ready and LK01 respectively.
3343 // Ps = 5 3 -> Report Locator status as
3344 // CSI ? 5 3 n Locator available, if compiled-in, or
3345 // CSI ? 5 0 n No Locator, if not.
3346 Terminal.prototype.deviceStatus = function(params) {
3347 if (!this.prefix) {
3348 switch (params[0]) {
3349 case 5:
3350 // status report
3351 this.send('\x1b[0n');
3352 break;
3353 case 6:
3354 // cursor position
3355 this.send('\x1b['
3356 + (this.y + 1)
3357 + ';'
3358 + (this.x + 1)
3359 + 'R');
3360 break;
3361 }
3362 } else if (this.prefix === '?') {
3363 // modern xterm doesnt seem to
3364 // respond to any of these except ?6, 6, and 5
3365 switch (params[0]) {
3366 case 6:
3367 // cursor position
3368 this.send('\x1b[?'
3369 + (this.y + 1)
3370 + ';'
3371 + (this.x + 1)
3372 + 'R');
3373 break;
3374 case 15:
3375 // no printer
3376 // this.send('\x1b[?11n');
3377 break;
3378 case 25:
3379 // dont support user defined keys
3380 // this.send('\x1b[?21n');
3381 break;
3382 case 26:
3383 // north american keyboard
3384 // this.send('\x1b[?27;1;0;0n');
3385 break;
3386 case 53:
3387 // no dec locator/mouse
3388 // this.send('\x1b[?50n');
3389 break;
3390 }
3391 }
3392 };
3393
3394 /**
3395 * Additions
3396 */
3397
3398 // CSI Ps @
3399 // Insert Ps (Blank) Character(s) (default = 1) (ICH).
3400 Terminal.prototype.insertChars = function(params) {
3401 var param, row, j, ch;
3402
3403 param = params[0];
3404 if (param < 1) param = 1;
3405
3406 row = this.y + this.ybase;
3407 j = this.x;
3408 ch = [this.eraseAttr(), ' ']; // xterm
3409
3410 while (param-- && j < this.cols) {
3411 this.lines[row].splice(j++, 0, ch);
3412 this.lines[row].pop();
3413 }
3414 };
3415
3416 // CSI Ps E
3417 // Cursor Next Line Ps Times (default = 1) (CNL).
3418 // same as CSI Ps B ?
3419 Terminal.prototype.cursorNextLine = function(params) {
3420 var param = params[0];
3421 if (param < 1) param = 1;
3422 this.y += param;
3423 if (this.y >= this.rows) {
3424 this.y = this.rows - 1;
3425 }
3426 this.x = 0;
3427 };
3428
3429 // CSI Ps F
3430 // Cursor Preceding Line Ps Times (default = 1) (CNL).
3431 // reuse CSI Ps A ?
3432 Terminal.prototype.cursorPrecedingLine = function(params) {
3433 var param = params[0];
3434 if (param < 1) param = 1;
3435 this.y -= param;
3436 if (this.y < 0) this.y = 0;
3437 this.x = 0;
3438 };
3439
3440 // CSI Ps G
3441 // Cursor Character Absolute [column] (default = [row,1]) (CHA).
3442 Terminal.prototype.cursorCharAbsolute = function(params) {
3443 var param = params[0];
3444 if (param < 1) param = 1;
3445 this.x = param - 1;
3446 };
3447
3448 // CSI Ps L
3449 // Insert Ps Line(s) (default = 1) (IL).
3450 Terminal.prototype.insertLines = function(params) {
3451 var param, row, j;
3452
3453 param = params[0];
3454 if (param < 1) param = 1;
3455 row = this.y + this.ybase;
3456
3457 j = this.rows - 1 - this.scrollBottom;
3458 j = this.rows - 1 + this.ybase - j + 1;
3459
3460 while (param--) {
3461 // test: echo -e '\e[44m\e[1L\e[0m'
3462 // blankLine(true) - xterm/linux behavior
3463 this.lines.splice(row, 0, this.blankLine(true));
3464 this.lines.splice(j, 1);
3465 }
3466
3467 // this.maxRange();
3468 this.updateRange(this.y);
3469 this.updateRange(this.scrollBottom);
3470 };
3471
3472 // CSI Ps M
3473 // Delete Ps Line(s) (default = 1) (DL).
3474 Terminal.prototype.deleteLines = function(params) {
3475 var param, row, j;
3476
3477 param = params[0];
3478 if (param < 1) param = 1;
3479 row = this.y + this.ybase;
3480
3481 j = this.rows - 1 - this.scrollBottom;
3482 j = this.rows - 1 + this.ybase - j;
3483
3484 while (param--) {
3485 // test: echo -e '\e[44m\e[1M\e[0m'
3486 // blankLine(true) - xterm/linux behavior
3487 this.lines.splice(j + 1, 0, this.blankLine(true));
3488 this.lines.splice(row, 1);
3489 }
3490
3491 // this.maxRange();
3492 this.updateRange(this.y);
3493 this.updateRange(this.scrollBottom);
3494 };
3495
3496 // CSI Ps P
3497 // Delete Ps Character(s) (default = 1) (DCH).
3498 Terminal.prototype.deleteChars = function(params) {
3499 var param, row, ch;
3500
3501 param = params[0];
3502 if (param < 1) param = 1;
3503
3504 row = this.y + this.ybase;
3505 ch = [this.eraseAttr(), ' ']; // xterm
3506
3507 while (param--) {
3508 this.lines[row].splice(this.x, 1);
3509 this.lines[row].push(ch);
3510 }
3511 };
3512
3513 // CSI Ps X
3514 // Erase Ps Character(s) (default = 1) (ECH).
3515 Terminal.prototype.eraseChars = function(params) {
3516 var param, row, j, ch;
3517
3518 param = params[0];
3519 if (param < 1) param = 1;
3520
3521 row = this.y + this.ybase;
3522 j = this.x;
3523 ch = [this.eraseAttr(), ' ']; // xterm
3524
3525 while (param-- && j < this.cols) {
3526 this.lines[row][j++] = ch;
3527 }
3528 };
3529
3530 // CSI Pm ` Character Position Absolute
3531 // [column] (default = [row,1]) (HPA).
3532 Terminal.prototype.charPosAbsolute = function(params) {
3533 var param = params[0];
3534 if (param < 1) param = 1;
3535 this.x = param - 1;
3536 if (this.x >= this.cols) {
3537 this.x = this.cols - 1;
3538 }
3539 };
3540
3541 // 141 61 a * HPR -
3542 // Horizontal Position Relative
3543 // reuse CSI Ps C ?
3544 Terminal.prototype.HPositionRelative = function(params) {
3545 var param = params[0];
3546 if (param < 1) param = 1;
3547 this.x += param;
3548 if (this.x >= this.cols) {
3549 this.x = this.cols - 1;
3550 }
3551 };
3552
3553 // CSI Ps c Send Device Attributes (Primary DA).
3554 // Ps = 0 or omitted -> request attributes from terminal. The
3555 // response depends on the decTerminalID resource setting.
3556 // -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')
3557 // -> CSI ? 1 ; 0 c (``VT101 with No Options'')
3558 // -> CSI ? 6 c (``VT102'')
3559 // -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')
3560 // The VT100-style response parameters do not mean anything by
3561 // themselves. VT220 parameters do, telling the host what fea-
3562 // tures the terminal supports:
3563 // Ps = 1 -> 132-columns.
3564 // Ps = 2 -> Printer.
3565 // Ps = 6 -> Selective erase.
3566 // Ps = 8 -> User-defined keys.
3567 // Ps = 9 -> National replacement character sets.
3568 // Ps = 1 5 -> Technical characters.
3569 // Ps = 2 2 -> ANSI color, e.g., VT525.
3570 // Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).
3571 // CSI > Ps c
3572 // Send Device Attributes (Secondary DA).
3573 // Ps = 0 or omitted -> request the terminal's identification
3574 // code. The response depends on the decTerminalID resource set-
3575 // ting. It should apply only to VT220 and up, but xterm extends
3576 // this to VT100.
3577 // -> CSI > Pp ; Pv ; Pc c
3578 // where Pp denotes the terminal type
3579 // Pp = 0 -> ``VT100''.
3580 // Pp = 1 -> ``VT220''.
3581 // and Pv is the firmware version (for xterm, this was originally
3582 // the XFree86 patch number, starting with 95). In a DEC termi-
3583 // nal, Pc indicates the ROM cartridge registration number and is
3584 // always zero.
3585 // More information:
3586 // xterm/charproc.c - line 2012, for more information.
3587 // vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
3588 Terminal.prototype.sendDeviceAttributes = function(params) {
3589 if (params[0] > 0) return;
3590
3591 if (!this.prefix) {
3592 if (this.is('xterm')
3593 || this.is('rxvt-unicode')
3594 || this.is('screen')) {
3595 this.send('\x1b[?1;2c');
3596 } else if (this.is('linux')) {
3597 this.send('\x1b[?6c');
3598 }
3599 } else if (this.prefix === '>') {
3600 // xterm and urxvt
3601 // seem to spit this
3602 // out around ~370 times (?).
3603 if (this.is('xterm')) {
3604 this.send('\x1b[>0;276;0c');
3605 } else if (this.is('rxvt-unicode')) {
3606 this.send('\x1b[>85;95;0c');
3607 } else if (this.is('linux')) {
3608 // not supported by linux console.
3609 // linux console echoes parameters.
3610 this.send(params[0] + 'c');
3611 } else if (this.is('screen')) {
3612 this.send('\x1b[>83;40003;0c');
3613 }
3614 }
3615 };
3616
3617 // CSI Pm d
3618 // Line Position Absolute [row] (default = [1,column]) (VPA).
3619 Terminal.prototype.linePosAbsolute = function(params) {
3620 var param = params[0];
3621 if (param < 1) param = 1;
3622 this.y = param - 1;
3623 if (this.y >= this.rows) {
3624 this.y = this.rows - 1;
3625 }
3626 };
3627
3628 // 145 65 e * VPR - Vertical Position Relative
3629 // reuse CSI Ps B ?
3630 Terminal.prototype.VPositionRelative = function(params) {
3631 var param = params[0];
3632 if (param < 1) param = 1;
3633 this.y += param;
3634 if (this.y >= this.rows) {
3635 this.y = this.rows - 1;
3636 }
3637 };
3638
3639 // CSI Ps ; Ps f
3640 // Horizontal and Vertical Position [row;column] (default =
3641 // [1,1]) (HVP).
3642 Terminal.prototype.HVPosition = function(params) {
3643 if (params[0] < 1) params[0] = 1;
3644 if (params[1] < 1) params[1] = 1;
3645
3646 this.y = params[0] - 1;
3647 if (this.y >= this.rows) {
3648 this.y = this.rows - 1;
3649 }
3650
3651 this.x = params[1] - 1;
3652 if (this.x >= this.cols) {
3653 this.x = this.cols - 1;
3654 }
3655 };
3656
3657 // CSI Pm h Set Mode (SM).
3658 // Ps = 2 -> Keyboard Action Mode (AM).
3659 // Ps = 4 -> Insert Mode (IRM).
3660 // Ps = 1 2 -> Send/receive (SRM).
3661 // Ps = 2 0 -> Automatic Newline (LNM).
3662 // CSI ? Pm h
3663 // DEC Private Mode Set (DECSET).
3664 // Ps = 1 -> Application Cursor Keys (DECCKM).
3665 // Ps = 2 -> Designate USASCII for character sets G0-G3
3666 // (DECANM), and set VT100 mode.
3667 // Ps = 3 -> 132 Column Mode (DECCOLM).
3668 // Ps = 4 -> Smooth (Slow) Scroll (DECSCLM).
3669 // Ps = 5 -> Reverse Video (DECSCNM).
3670 // Ps = 6 -> Origin Mode (DECOM).
3671 // Ps = 7 -> Wraparound Mode (DECAWM).
3672 // Ps = 8 -> Auto-repeat Keys (DECARM).
3673 // Ps = 9 -> Send Mouse X & Y on button press. See the sec-
3674 // tion Mouse Tracking.
3675 // Ps = 1 0 -> Show toolbar (rxvt).
3676 // Ps = 1 2 -> Start Blinking Cursor (att610).
3677 // Ps = 1 8 -> Print form feed (DECPFF).
3678 // Ps = 1 9 -> Set print extent to full screen (DECPEX).
3679 // Ps = 2 5 -> Show Cursor (DECTCEM).
3680 // Ps = 3 0 -> Show scrollbar (rxvt).
3681 // Ps = 3 5 -> Enable font-shifting functions (rxvt).
3682 // Ps = 3 8 -> Enter Tektronix Mode (DECTEK).
3683 // Ps = 4 0 -> Allow 80 -> 132 Mode.
3684 // Ps = 4 1 -> more(1) fix (see curses resource).
3685 // Ps = 4 2 -> Enable Nation Replacement Character sets (DECN-
3686 // RCM).
3687 // Ps = 4 4 -> Turn On Margin Bell.
3688 // Ps = 4 5 -> Reverse-wraparound Mode.
3689 // Ps = 4 6 -> Start Logging. This is normally disabled by a
3690 // compile-time option.
3691 // Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis-
3692 // abled by the titeInhibit resource).
3693 // Ps = 6 6 -> Application keypad (DECNKM).
3694 // Ps = 6 7 -> Backarrow key sends backspace (DECBKM).
3695 // Ps = 1 0 0 0 -> Send Mouse X & Y on button press and
3696 // release. See the section Mouse Tracking.
3697 // Ps = 1 0 0 1 -> Use Hilite Mouse Tracking.
3698 // Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking.
3699 // Ps = 1 0 0 3 -> Use All Motion Mouse Tracking.
3700 // Ps = 1 0 0 4 -> Send FocusIn/FocusOut events.
3701 // Ps = 1 0 0 5 -> Enable Extended Mouse Mode.
3702 // Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt).
3703 // Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt).
3704 // Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit.
3705 // (enables the eightBitInput resource).
3706 // Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num-
3707 // Lock keys. (This enables the numLock resource).
3708 // Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This
3709 // enables the metaSendsEscape resource).
3710 // Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete
3711 // key.
3712 // Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This
3713 // enables the altSendsEscape resource).
3714 // Ps = 1 0 4 0 -> Keep selection even if not highlighted.
3715 // (This enables the keepSelection resource).
3716 // Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables
3717 // the selectToClipboard resource).
3718 // Ps = 1 0 4 2 -> Enable Urgency window manager hint when
3719 // Control-G is received. (This enables the bellIsUrgent
3720 // resource).
3721 // Ps = 1 0 4 3 -> Enable raising of the window when Control-G
3722 // is received. (enables the popOnBell resource).
3723 // Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be
3724 // disabled by the titeInhibit resource).
3725 // Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis-
3726 // abled by the titeInhibit resource).
3727 // Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate
3728 // Screen Buffer, clearing it first. (This may be disabled by
3729 // the titeInhibit resource). This combines the effects of the 1
3730 // 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based
3731 // applications rather than the 4 7 mode.
3732 // Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode.
3733 // Ps = 1 0 5 1 -> Set Sun function-key mode.
3734 // Ps = 1 0 5 2 -> Set HP function-key mode.
3735 // Ps = 1 0 5 3 -> Set SCO function-key mode.
3736 // Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6).
3737 // Ps = 1 0 6 1 -> Set VT220 keyboard emulation.
3738 // Ps = 2 0 0 4 -> Set bracketed paste mode.
3739 // Modes:
3740 // http://vt100.net/docs/vt220-rm/chapter4.html
3741 Terminal.prototype.setMode = function(params) {
3742 if (typeof params === 'object') {
3743 var l = params.length
3744 , i = 0;
3745
3746 for (; i < l; i++) {
3747 this.setMode(params[i]);
3748 }
3749
3750 return;
3751 }
3752
3753 if (!this.prefix) {
3754 switch (params) {
3755 case 4:
3756 this.insertMode = true;
3757 break;
3758 case 20:
3759 //this.convertEol = true;
3760 break;
3761 }
3762 } else if (this.prefix === '?') {
3763 switch (params) {
3764 case 1:
3765 this.applicationCursor = true;
3766 break;
3767 case 2:
3768 this.setgCharset(0, Terminal.charsets.US);
3769 this.setgCharset(1, Terminal.charsets.US);
3770 this.setgCharset(2, Terminal.charsets.US);
3771 this.setgCharset(3, Terminal.charsets.US);
3772 // set VT100 mode here
3773 break;
3774 case 3: // 132 col mode
3775 this.savedCols = this.cols;
3776 this.resize(132, this.rows);
3777 break;
3778 case 6:
3779 this.originMode = true;
3780 break;
3781 case 7:
3782 this.wraparoundMode = true;
3783 break;
3784 case 12:
3785 // this.cursorBlink = true;
3786 break;
3787 case 66:
3788 this.log('Serial port requested application keypad.');
3789 this.applicationKeypad = true;
3790 break;
3791 case 9: // X10 Mouse
3792 // no release, no motion, no wheel, no modifiers.
3793 case 1000: // vt200 mouse
3794 // no motion.
3795 // no modifiers, except control on the wheel.
3796 case 1002: // button event mouse
3797 case 1003: // any event mouse
3798 // any event - sends motion events,
3799 // even if there is no button held down.
3800 this.x10Mouse = params === 9;
3801 this.vt200Mouse = params === 1000;
3802 this.normalMouse = params > 1000;
3803 this.mouseEvents = true;
3804 this.element.style.cursor = 'default';
3805 this.log('Binding to mouse events.');
3806 break;
3807 case 1004: // send focusin/focusout events
3808 // focusin: ^[[I
3809 // focusout: ^[[O
3810 this.sendFocus = true;
3811 break;
3812 case 1005: // utf8 ext mode mouse
3813 this.utfMouse = true;
3814 // for wide terminals
3815 // simply encodes large values as utf8 characters
3816 break;
3817 case 1006: // sgr ext mode mouse
3818 this.sgrMouse = true;
3819 // for wide terminals
3820 // does not add 32 to fields
3821 // press: ^[[<b;x;yM
3822 // release: ^[[<b;x;ym
3823 break;
3824 case 1015: // urxvt ext mode mouse
3825 this.urxvtMouse = true;
3826 // for wide terminals
3827 // numbers for fields
3828 // press: ^[[b;x;yM
3829 // motion: ^[[b;x;yT
3830 break;
3831 case 25: // show cursor
3832 this.cursorHidden = false;
3833 break;
3834 case 1049: // alt screen buffer cursor
3835 //this.saveCursor();
3836 ; // FALL-THROUGH
3837 case 47: // alt screen buffer
3838 case 1047: // alt screen buffer
3839 if (!this.normal) {
3840 var normal = {
3841 lines: this.lines,
3842 ybase: this.ybase,
3843 ydisp: this.ydisp,
3844 x: this.x,
3845 y: this.y,
3846 scrollTop: this.scrollTop,
3847 scrollBottom: this.scrollBottom,
3848 tabs: this.tabs
3849 // XXX save charset(s) here?
3850 // charset: this.charset,
3851 // glevel: this.glevel,
3852 // charsets: this.charsets
3853 };
3854 this.reset();
3855 this.normal = normal;
3856 this.showCursor();
3857 }
3858 break;
3859 }
3860 }
3861 };
3862
3863 // CSI Pm l Reset Mode (RM).
3864 // Ps = 2 -> Keyboard Action Mode (AM).
3865 // Ps = 4 -> Replace Mode (IRM).
3866 // Ps = 1 2 -> Send/receive (SRM).
3867 // Ps = 2 0 -> Normal Linefeed (LNM).
3868 // CSI ? Pm l
3869 // DEC Private Mode Reset (DECRST).
3870 // Ps = 1 -> Normal Cursor Keys (DECCKM).
3871 // Ps = 2 -> Designate VT52 mode (DECANM).
3872 // Ps = 3 -> 80 Column Mode (DECCOLM).
3873 // Ps = 4 -> Jump (Fast) Scroll (DECSCLM).
3874 // Ps = 5 -> Normal Video (DECSCNM).
3875 // Ps = 6 -> Normal Cursor Mode (DECOM).
3876 // Ps = 7 -> No Wraparound Mode (DECAWM).
3877 // Ps = 8 -> No Auto-repeat Keys (DECARM).
3878 // Ps = 9 -> Don't send Mouse X & Y on button press.
3879 // Ps = 1 0 -> Hide toolbar (rxvt).
3880 // Ps = 1 2 -> Stop Blinking Cursor (att610).
3881 // Ps = 1 8 -> Don't print form feed (DECPFF).
3882 // Ps = 1 9 -> Limit print to scrolling region (DECPEX).
3883 // Ps = 2 5 -> Hide Cursor (DECTCEM).
3884 // Ps = 3 0 -> Don't show scrollbar (rxvt).
3885 // Ps = 3 5 -> Disable font-shifting functions (rxvt).
3886 // Ps = 4 0 -> Disallow 80 -> 132 Mode.
3887 // Ps = 4 1 -> No more(1) fix (see curses resource).
3888 // Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-
3889 // NRCM).
3890 // Ps = 4 4 -> Turn Off Margin Bell.
3891 // Ps = 4 5 -> No Reverse-wraparound Mode.
3892 // Ps = 4 6 -> Stop Logging. (This is normally disabled by a
3893 // compile-time option).
3894 // Ps = 4 7 -> Use Normal Screen Buffer.
3895 // Ps = 6 6 -> Numeric keypad (DECNKM).
3896 // Ps = 6 7 -> Backarrow key sends delete (DECBKM).
3897 // Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and
3898 // release. See the section Mouse Tracking.
3899 // Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.
3900 // Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.
3901 // Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.
3902 // Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.
3903 // Ps = 1 0 0 5 -> Disable Extended Mouse Mode.
3904 // Ps = 1 0 1 0 -> Don't scroll to bottom on tty output
3905 // (rxvt).
3906 // Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).
3907 // Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables
3908 // the eightBitInput resource).
3909 // Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-
3910 // Lock keys. (This disables the numLock resource).
3911 // Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.
3912 // (This disables the metaSendsEscape resource).
3913 // Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad
3914 // Delete key.
3915 // Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.
3916 // (This disables the altSendsEscape resource).
3917 // Ps = 1 0 4 0 -> Do not keep selection when not highlighted.
3918 // (This disables the keepSelection resource).
3919 // Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables
3920 // the selectToClipboard resource).
3921 // Ps = 1 0 4 2 -> Disable Urgency window manager hint when
3922 // Control-G is received. (This disables the bellIsUrgent
3923 // resource).
3924 // Ps = 1 0 4 3 -> Disable raising of the window when Control-
3925 // G is received. (This disables the popOnBell resource).
3926 // Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen
3927 // first if in the Alternate Screen. (This may be disabled by
3928 // the titeInhibit resource).
3929 // Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be
3930 // disabled by the titeInhibit resource).
3931 // Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor
3932 // as in DECRC. (This may be disabled by the titeInhibit
3933 // resource). This combines the effects of the 1 0 4 7 and 1 0
3934 // 4 8 modes. Use this with terminfo-based applications rather
3935 // than the 4 7 mode.
3936 // Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.
3937 // Ps = 1 0 5 1 -> Reset Sun function-key mode.
3938 // Ps = 1 0 5 2 -> Reset HP function-key mode.
3939 // Ps = 1 0 5 3 -> Reset SCO function-key mode.
3940 // Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).
3941 // Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.
3942 // Ps = 2 0 0 4 -> Reset bracketed paste mode.
3943 Terminal.prototype.resetMode = function(params) {
3944 if (typeof params === 'object') {
3945 var l = params.length
3946 , i = 0;
3947
3948 for (; i < l; i++) {
3949 this.resetMode(params[i]);
3950 }
3951
3952 return;
3953 }
3954
3955 if (!this.prefix) {
3956 switch (params) {
3957 case 4:
3958 this.insertMode = false;
3959 break;
3960 case 20:
3961 //this.convertEol = false;
3962 break;
3963 }
3964 } else if (this.prefix === '?') {
3965 switch (params) {
3966 case 1:
3967 this.applicationCursor = false;
3968 break;
3969 case 3:
3970 if (this.cols === 132 && this.savedCols) {
3971 this.resize(this.savedCols, this.rows);
3972 }
3973 delete this.savedCols;
3974 break;
3975 case 6:
3976 this.originMode = false;
3977 break;
3978 case 7:
3979 this.wraparoundMode = false;
3980 break;
3981 case 12:
3982 // this.cursorBlink = false;
3983 break;
3984 case 66:
3985 this.log('Switching back to normal keypad.');
3986 this.applicationKeypad = false;
3987 break;
3988 case 9: // X10 Mouse
3989 case 1000: // vt200 mouse
3990 case 1002: // button event mouse
3991 case 1003: // any event mouse
3992 this.x10Mouse = false;
3993 this.vt200Mouse = false;
3994 this.normalMouse = false;
3995 this.mouseEvents = false;
3996 this.element.style.cursor = '';
3997 break;
3998 case 1004: // send focusin/focusout events
3999 this.sendFocus = false;
4000 break;
4001 case 1005: // utf8 ext mode mouse
4002 this.utfMouse = false;
4003 break;
4004 case 1006: // sgr ext mode mouse
4005 this.sgrMouse = false;
4006 break;
4007 case 1015: // urxvt ext mode mouse
4008 this.urxvtMouse = false;
4009 break;
4010 case 25: // hide cursor
4011 this.cursorHidden = true;
4012 break;
4013 case 1049: // alt screen buffer cursor
4014 ; // FALL-THROUGH
4015 case 47: // normal screen buffer
4016 case 1047: // normal screen buffer - clearing it first
4017 if (this.normal) {
4018 this.lines = this.normal.lines;
4019 this.ybase = this.normal.ybase;
4020 this.ydisp = this.normal.ydisp;
4021 this.x = this.normal.x;
4022 this.y = this.normal.y;
4023 this.scrollTop = this.normal.scrollTop;
4024 this.scrollBottom = this.normal.scrollBottom;
4025 this.tabs = this.normal.tabs;
4026 this.normal = null;
4027 // if (params === 1049) {
4028 // this.x = this.savedX;
4029 // this.y = this.savedY;
4030 // }
4031 this.refresh(0, this.rows - 1);
4032 this.showCursor();
4033 }
4034 break;
4035 }
4036 }
4037 };
4038
4039 // CSI Ps ; Ps r
4040 // Set Scrolling Region [top;bottom] (default = full size of win-
4041 // dow) (DECSTBM).
4042 // CSI ? Pm r
4043 Terminal.prototype.setScrollRegion = function(params) {
4044 if (this.prefix) return;
4045 this.scrollTop = (params[0] || 1) - 1;
4046 this.scrollBottom = (params[1] || this.rows) - 1;
4047 this.x = 0;
4048 this.y = 0;
4049 };
4050
4051 // CSI s
4052 // Save cursor (ANSI.SYS).
4053 Terminal.prototype.saveCursor = function(params) {
4054 this.savedX = this.x;
4055 this.savedY = this.y;
4056 };
4057
4058 // CSI u
4059 // Restore cursor (ANSI.SYS).
4060 Terminal.prototype.restoreCursor = function(params) {
4061 this.x = this.savedX || 0;
4062 this.y = this.savedY || 0;
4063 };
4064
4065 /**
4066 * Lesser Used
4067 */
4068
4069 // CSI Ps I
4070 // Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
4071 Terminal.prototype.cursorForwardTab = function(params) {
4072 var param = params[0] || 1;
4073 while (param--) {
4074 this.x = this.nextStop();
4075 }
4076 };
4077
4078 // CSI Ps S Scroll up Ps lines (default = 1) (SU).
4079 Terminal.prototype.scrollUp = function(params) {
4080 var param = params[0] || 1;
4081 while (param--) {
4082 this.lines.splice(this.ybase + this.scrollTop, 1);
4083 this.lines.splice(this.ybase + this.scrollBottom, 0, this.blankLine());
4084 }
4085 // this.maxRange();
4086 this.updateRange(this.scrollTop);
4087 this.updateRange(this.scrollBottom);
4088 };
4089
4090 // CSI Ps T Scroll down Ps lines (default = 1) (SD).
4091 Terminal.prototype.scrollDown = function(params) {
4092 var param = params[0] || 1;
4093 while (param--) {
4094 this.lines.splice(this.ybase + this.scrollBottom, 1);
4095 this.lines.splice(this.ybase + this.scrollTop, 0, this.blankLine());
4096 }
4097 // this.maxRange();
4098 this.updateRange(this.scrollTop);
4099 this.updateRange(this.scrollBottom);
4100 };
4101
4102 // CSI Ps ; Ps ; Ps ; Ps ; Ps T
4103 // Initiate highlight mouse tracking. Parameters are
4104 // [func;startx;starty;firstrow;lastrow]. See the section Mouse
4105 // Tracking.
4106 Terminal.prototype.initMouseTracking = function(params) {
4107 // Relevant: DECSET 1001
4108 };
4109
4110 // CSI > Ps; Ps T
4111 // Reset one or more features of the title modes to the default
4112 // value. Normally, "reset" disables the feature. It is possi-
4113 // ble to disable the ability to reset features by compiling a
4114 // different default for the title modes into xterm.
4115 // Ps = 0 -> Do not set window/icon labels using hexadecimal.
4116 // Ps = 1 -> Do not query window/icon labels using hexadeci-
4117 // mal.
4118 // Ps = 2 -> Do not set window/icon labels using UTF-8.
4119 // Ps = 3 -> Do not query window/icon labels using UTF-8.
4120 // (See discussion of "Title Modes").
4121 Terminal.prototype.resetTitleModes = function(params) {
4122 ;
4123 };
4124
4125 // CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
4126 Terminal.prototype.cursorBackwardTab = function(params) {
4127 var param = params[0] || 1;
4128 while (param--) {
4129 this.x = this.prevStop();
4130 }
4131 };
4132
4133 // CSI Ps b Repeat the preceding graphic character Ps times (REP).
4134 Terminal.prototype.repeatPrecedingCharacter = function(params) {
4135 var param = params[0] || 1
4136 , line = this.lines[this.ybase + this.y]
4137 , ch = line[this.x - 1] || [this.defAttr, ' '];
4138
4139 while (param--) line[this.x++] = ch;
4140 };
4141
4142 // CSI Ps g Tab Clear (TBC).
4143 // Ps = 0 -> Clear Current Column (default).
4144 // Ps = 3 -> Clear All.
4145 // Potentially:
4146 // Ps = 2 -> Clear Stops on Line.
4147 // http://vt100.net/annarbor/aaa-ug/section6.html
4148 Terminal.prototype.tabClear = function(params) {
4149 var param = params[0];
4150 if (param <= 0) {
4151 delete this.tabs[this.x];
4152 } else if (param === 3) {
4153 this.tabs = {};
4154 }
4155 };
4156
4157 // CSI Pm i Media Copy (MC).
4158 // Ps = 0 -> Print screen (default).
4159 // Ps = 4 -> Turn off printer controller mode.
4160 // Ps = 5 -> Turn on printer controller mode.
4161 // CSI ? Pm i
4162 // Media Copy (MC, DEC-specific).
4163 // Ps = 1 -> Print line containing cursor.
4164 // Ps = 4 -> Turn off autoprint mode.
4165 // Ps = 5 -> Turn on autoprint mode.
4166 // Ps = 1 0 -> Print composed display, ignores DECPEX.
4167 // Ps = 1 1 -> Print all pages.
4168 Terminal.prototype.mediaCopy = function(params) {
4169 ;
4170 };
4171
4172 // CSI > Ps; Ps m
4173 // Set or reset resource-values used by xterm to decide whether
4174 // to construct escape sequences holding information about the
4175 // modifiers pressed with a given key. The first parameter iden-
4176 // tifies the resource to set/reset. The second parameter is the
4177 // value to assign to the resource. If the second parameter is
4178 // omitted, the resource is reset to its initial value.
4179 // Ps = 1 -> modifyCursorKeys.
4180 // Ps = 2 -> modifyFunctionKeys.
4181 // Ps = 4 -> modifyOtherKeys.
4182 // If no parameters are given, all resources are reset to their
4183 // initial values.
4184 Terminal.prototype.setResources = function(params) {
4185 ;
4186 };
4187
4188 // CSI > Ps n
4189 // Disable modifiers which may be enabled via the CSI > Ps; Ps m
4190 // sequence. This corresponds to a resource value of "-1", which
4191 // cannot be set with the other sequence. The parameter identi-
4192 // fies the resource to be disabled:
4193 // Ps = 1 -> modifyCursorKeys.
4194 // Ps = 2 -> modifyFunctionKeys.
4195 // Ps = 4 -> modifyOtherKeys.
4196 // If the parameter is omitted, modifyFunctionKeys is disabled.
4197 // When modifyFunctionKeys is disabled, xterm uses the modifier
4198 // keys to make an extended sequence of functions rather than
4199 // adding a parameter to each function key to denote the modi-
4200 // fiers.
4201 Terminal.prototype.disableModifiers = function(params) {
4202 ;
4203 };
4204
4205 // CSI > Ps p
4206 // Set resource value pointerMode. This is used by xterm to
4207 // decide whether to hide the pointer cursor as the user types.
4208 // Valid values for the parameter:
4209 // Ps = 0 -> never hide the pointer.
4210 // Ps = 1 -> hide if the mouse tracking mode is not enabled.
4211 // Ps = 2 -> always hide the pointer. If no parameter is
4212 // given, xterm uses the default, which is 1 .
4213 Terminal.prototype.setPointerMode = function(params) {
4214 ;
4215 };
4216
4217 // CSI ! p Soft terminal reset (DECSTR).
4218 // http://vt100.net/docs/vt220-rm/table4-10.html
4219 Terminal.prototype.softReset = function(params) {
4220 this.cursorHidden = false;
4221 this.insertMode = false;
4222 this.originMode = false;
4223 this.wraparoundMode = false; // autowrap
4224 this.applicationKeypad = false; // ?
4225 this.applicationCursor = false;
4226 this.scrollTop = 0;
4227 this.scrollBottom = this.rows - 1;
4228 this.curAttr = this.defAttr;
4229 this.x = this.y = 0; // ?
4230 this.charset = null;
4231 this.glevel = 0; // ??
4232 this.charsets = [null]; // ??
4233 };
4234
4235 // CSI Ps$ p
4236 // Request ANSI mode (DECRQM). For VT300 and up, reply is
4237 // CSI Ps; Pm$ y
4238 // where Ps is the mode number as in RM, and Pm is the mode
4239 // value:
4240 // 0 - not recognized
4241 // 1 - set
4242 // 2 - reset
4243 // 3 - permanently set
4244 // 4 - permanently reset
4245 Terminal.prototype.requestAnsiMode = function(params) {
4246 ;
4247 };
4248
4249 // CSI ? Ps$ p
4250 // Request DEC private mode (DECRQM). For VT300 and up, reply is
4251 // CSI ? Ps; Pm$ p
4252 // where Ps is the mode number as in DECSET, Pm is the mode value
4253 // as in the ANSI DECRQM.
4254 Terminal.prototype.requestPrivateMode = function(params) {
4255 ;
4256 };
4257
4258 // CSI Ps ; Ps " p
4259 // Set conformance level (DECSCL). Valid values for the first
4260 // parameter:
4261 // Ps = 6 1 -> VT100.
4262 // Ps = 6 2 -> VT200.
4263 // Ps = 6 3 -> VT300.
4264 // Valid values for the second parameter:
4265 // Ps = 0 -> 8-bit controls.
4266 // Ps = 1 -> 7-bit controls (always set for VT100).
4267 // Ps = 2 -> 8-bit controls.
4268 Terminal.prototype.setConformanceLevel = function(params) {
4269 ;
4270 };
4271
4272 // CSI Ps q Load LEDs (DECLL).
4273 // Ps = 0 -> Clear all LEDS (default).
4274 // Ps = 1 -> Light Num Lock.
4275 // Ps = 2 -> Light Caps Lock.
4276 // Ps = 3 -> Light Scroll Lock.
4277 // Ps = 2 1 -> Extinguish Num Lock.
4278 // Ps = 2 2 -> Extinguish Caps Lock.
4279 // Ps = 2 3 -> Extinguish Scroll Lock.
4280 Terminal.prototype.loadLEDs = function(params) {
4281 ;
4282 };
4283
4284 // CSI Ps SP q
4285 // Set cursor style (DECSCUSR, VT520).
4286 // Ps = 0 -> blinking block.
4287 // Ps = 1 -> blinking block (default).
4288 // Ps = 2 -> steady block.
4289 // Ps = 3 -> blinking underline.
4290 // Ps = 4 -> steady underline.
4291 Terminal.prototype.setCursorStyle = function(params) {
4292 ;
4293 };
4294
4295 // CSI Ps " q
4296 // Select character protection attribute (DECSCA). Valid values
4297 // for the parameter:
4298 // Ps = 0 -> DECSED and DECSEL can erase (default).
4299 // Ps = 1 -> DECSED and DECSEL cannot erase.
4300 // Ps = 2 -> DECSED and DECSEL can erase.
4301 Terminal.prototype.setCharProtectionAttr = function(params) {
4302 ;
4303 };
4304
4305 // CSI ? Pm r
4306 // Restore DEC Private Mode Values. The value of Ps previously
4307 // saved is restored. Ps values are the same as for DECSET.
4308 Terminal.prototype.restorePrivateValues = function(params) {
4309 ;
4310 };
4311
4312 // CSI Pt; Pl; Pb; Pr; Ps$ r
4313 // Change Attributes in Rectangular Area (DECCARA), VT400 and up.
4314 // Pt; Pl; Pb; Pr denotes the rectangle.
4315 // Ps denotes the SGR attributes to change: 0, 1, 4, 5, 7.
4316 // NOTE: xterm doesn't enable this code by default.
4317 Terminal.prototype.setAttrInRectangle = function(params) {
4318 var t = params[0]
4319 , l = params[1]
4320 , b = params[2]
4321 , r = params[3]
4322 , attr = params[4];
4323
4324 var line
4325 , i;
4326
4327 for (; t < b + 1; t++) {
4328 line = this.lines[this.ybase + t];
4329 for (i = l; i < r; i++) {
4330 line[i] = [attr, line[i][1]];
4331 }
4332 }
4333
4334 // this.maxRange();
4335 this.updateRange(params[0]);
4336 this.updateRange(params[2]);
4337 };
4338
4339
4340 // CSI Pc; Pt; Pl; Pb; Pr$ x
4341 // Fill Rectangular Area (DECFRA), VT420 and up.
4342 // Pc is the character to use.
4343 // Pt; Pl; Pb; Pr denotes the rectangle.
4344 // NOTE: xterm doesn't enable this code by default.
4345 Terminal.prototype.fillRectangle = function(params) {
4346 var ch = params[0]
4347 , t = params[1]
4348 , l = params[2]
4349 , b = params[3]
4350 , r = params[4];
4351
4352 var line
4353 , i;
4354
4355 for (; t < b + 1; t++) {
4356 line = this.lines[this.ybase + t];
4357 for (i = l; i < r; i++) {
4358 line[i] = [line[i][0], String.fromCharCode(ch)];
4359 }
4360 }
4361
4362 // this.maxRange();
4363 this.updateRange(params[1]);
4364 this.updateRange(params[3]);
4365 };
4366
4367 // CSI Ps ; Pu ' z
4368 // Enable Locator Reporting (DECELR).
4369 // Valid values for the first parameter:
4370 // Ps = 0 -> Locator disabled (default).
4371 // Ps = 1 -> Locator enabled.
4372 // Ps = 2 -> Locator enabled for one report, then disabled.
4373 // The second parameter specifies the coordinate unit for locator
4374 // reports.
4375 // Valid values for the second parameter:
4376 // Pu = 0 <- or omitted -> default to character cells.
4377 // Pu = 1 <- device physical pixels.
4378 // Pu = 2 <- character cells.
4379 Terminal.prototype.enableLocatorReporting = function(params) {
4380 var val = params[0] > 0;
4381 //this.mouseEvents = val;
4382 //this.decLocator = val;
4383 };
4384
4385 // CSI Pt; Pl; Pb; Pr$ z
4386 // Erase Rectangular Area (DECERA), VT400 and up.
4387 // Pt; Pl; Pb; Pr denotes the rectangle.
4388 // NOTE: xterm doesn't enable this code by default.
4389 Terminal.prototype.eraseRectangle = function(params) {
4390 var t = params[0]
4391 , l = params[1]
4392 , b = params[2]
4393 , r = params[3];
4394
4395 var line
4396 , i
4397 , ch;
4398
4399 ch = [this.eraseAttr(), ' ']; // xterm?
4400
4401 for (; t < b + 1; t++) {
4402 line = this.lines[this.ybase + t];
4403 for (i = l; i < r; i++) {
4404 line[i] = ch;
4405 }
4406 }
4407
4408 // this.maxRange();
4409 this.updateRange(params[0]);
4410 this.updateRange(params[2]);
4411 };
4412
4413
4414 // CSI P m SP }
4415 // Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
4416 // NOTE: xterm doesn't enable this code by default.
4417 Terminal.prototype.insertColumns = function() {
4418 var param = params[0]
4419 , l = this.ybase + this.rows
4420 , ch = [this.eraseAttr(), ' '] // xterm?
4421 , i;
4422
4423 while (param--) {
4424 for (i = this.ybase; i < l; i++) {
4425 this.lines[i].splice(this.x + 1, 0, ch);
4426 this.lines[i].pop();
4427 }
4428 }
4429
4430 this.maxRange();
4431 };
4432
4433
4434 // CSI P m SP ~
4435 // Delete P s Column(s) (default = 1) (DECDC), VT420 and up
4436 // NOTE: xterm doesn't enable this code by default.
4437 Terminal.prototype.deleteColumns = function() {
4438 var param = params[0]
4439 , l = this.ybase + this.rows
4440 , ch = [this.eraseAttr(), ' '] // xterm?
4441 , i;
4442
4443 while (param--) {
4444 for (i = this.ybase; i < l; i++) {
4445 this.lines[i].splice(this.x, 1);
4446 this.lines[i].push(ch);
4447 }
4448 }
4449
4450 this.maxRange();
4451 };
4452
4453 /**
4454 * Character Sets
4455 */
4456
4457 Terminal.charsets = {};
4458
4459 // DEC Special Character and Line Drawing Set.
4460 // http://vt100.net/docs/vt102-ug/table5-13.html
4461 // A lot of curses apps use this if they see TERM=xterm.
4462 // testing: echo -e '\e(0a\e(B'
4463 // The xterm output sometimes seems to conflict with the
4464 // reference above. xterm seems in line with the reference
4465 // when running vttest however.
4466 // The table below now uses xterm's output from vttest.
4467 Terminal.charsets.SCLD = { // (0
4468 '`': '\u25c6', // '◆'
4469 'a': '\u2592', // '▒'
4470 'b': '\u0009', // '\t'
4471 'c': '\u000c', // '\f'
4472 'd': '\u000d', // '\r'
4473 'e': '\u000a', // '\n'
4474 'f': '\u00b0', // '°'
4475 'g': '\u00b1', // '±'
4476 'h': '\u2424', // '\u2424' (NL)
4477 'i': '\u000b', // '\v'
4478 'j': '\u2518', // '┘'
4479 'k': '\u2510', // '┐'
4480 'l': '\u250c', // '┌'
4481 'm': '\u2514', // '└'
4482 'n': '\u253c', // '┼'
4483 'o': '\u23ba', // '⎺'
4484 'p': '\u23bb', // '⎻'
4485 'q': '\u2500', // '─'
4486 'r': '\u23bc', // '⎼'
4487 's': '\u23bd', // '⎽'
4488 't': '\u251c', // '├'
4489 'u': '\u2524', // '┤'
4490 'v': '\u2534', // '┴'
4491 'w': '\u252c', // '┬'
4492 'x': '\u2502', // '│'
4493 'y': '\u2264', // '≤'
4494 'z': '\u2265', // '≥'
4495 '{': '\u03c0', // 'π'
4496 '|': '\u2260', // '≠'
4497 '}': '\u00a3', // '£'
4498 '~': '\u00b7' // '·'
4499 };
4500
4501 Terminal.charsets.UK = null; // (A
4502 Terminal.charsets.US = null; // (B (USASCII)
4503 Terminal.charsets.Dutch = null; // (4
4504 Terminal.charsets.Finnish = null; // (C or (5
4505 Terminal.charsets.French = null; // (R
4506 Terminal.charsets.FrenchCanadian = null; // (Q
4507 Terminal.charsets.German = null; // (K
4508 Terminal.charsets.Italian = null; // (Y
4509 Terminal.charsets.NorwegianDanish = null; // (E or (6
4510 Terminal.charsets.Spanish = null; // (Z
4511 Terminal.charsets.Swedish = null; // (H or (7
4512 Terminal.charsets.Swiss = null; // (=
4513 Terminal.charsets.ISOLatin = null; // /A
4514
4515 /**
4516 * Helpers
4517 */
4518
4519 function contains(el, arr) {
4520 for (var i = 0; i < arr.length; i += 1) {
4521 if (el === arr[i]) {
4522 return true;
4523 }
4524 }
4525 return false;
4526 }
4527
4528 function on(el, type, handler, capture) {
4529 if (!Array.isArray(el)) {
4530 el = [el];
4531 }
4532 el.forEach(function (element) {
4533 element.addEventListener(type, handler, capture || false);
4534 });
4535 }
4536
4537 function off(el, type, handler, capture) {
4538 el.removeEventListener(type, handler, capture || false);
4539 }
4540
4541 function cancel(ev, force) {
4542 if (!this.cancelEvents && !force) {
4543 return;
4544 }
4545 ev.preventDefault();
4546 ev.stopPropagation();
4547 return false;
4548 }
4549
4550 function inherits(child, parent) {
4551 function f() {
4552 this.constructor = child;
4553 }
4554 f.prototype = parent.prototype;
4555 child.prototype = new f;
4556 }
4557
4558 // if bold is broken, we can't
4559 // use it in the terminal.
4560 function isBoldBroken(document) {
4561 var body = document.getElementsByTagName('body')[0];
4562 var el = document.createElement('span');
4563 el.innerHTML = 'hello world';
4564 body.appendChild(el);
4565 var w1 = el.scrollWidth;
4566 el.style.fontWeight = 'bold';
4567 var w2 = el.scrollWidth;
4568 body.removeChild(el);
4569 return w1 !== w2;
4570 }
4571
4572 var String = this.String;
4573 var setTimeout = this.setTimeout;
4574 var setInterval = this.setInterval;
4575
4576 function indexOf(obj, el) {
4577 var i = obj.length;
4578 while (i--) {
4579 if (obj[i] === el) return i;
4580 }
4581 return -1;
4582 }
4583
4584 function isThirdLevelShift(term, ev) {
4585 var thirdLevelKey =
4586 (term.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
4587 (term.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
4588
4589 // Don't invoke for arrows, pageDown, home, backspace, etc.
4590 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
4591 }
4592
4593 function isWide(ch) {
4594 if (ch <= '\uff00') return false;
4595 return (ch >= '\uff01' && ch <= '\uffbe')
4596 || (ch >= '\uffc2' && ch <= '\uffc7')
4597 || (ch >= '\uffca' && ch <= '\uffcf')
4598 || (ch >= '\uffd2' && ch <= '\uffd7')
4599 || (ch >= '\uffda' && ch <= '\uffdc')
4600 || (ch >= '\uffe0' && ch <= '\uffe6')
4601 || (ch >= '\uffe8' && ch <= '\uffee');
4602 }
4603
4604 function matchColor(r1, g1, b1) {
4605 var hash = (r1 << 16) | (g1 << 8) | b1;
4606
4607 if (matchColor._cache[hash] != null) {
4608 return matchColor._cache[hash];
4609 }
4610
4611 var ldiff = Infinity
4612 , li = -1
4613 , i = 0
4614 , c
4615 , r2
4616 , g2
4617 , b2
4618 , diff;
4619
4620 for (; i < Terminal.vcolors.length; i++) {
4621 c = Terminal.vcolors[i];
4622 r2 = c[0];
4623 g2 = c[1];
4624 b2 = c[2];
4625
4626 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
4627
4628 if (diff === 0) {
4629 li = i;
4630 break;
4631 }
4632
4633 if (diff < ldiff) {
4634 ldiff = diff;
4635 li = i;
4636 }
4637 }
4638
4639 return matchColor._cache[hash] = li;
4640 }
4641
4642 matchColor._cache = {};
4643
4644 // http://stackoverflow.com/questions/1633828
4645 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
4646 return Math.pow(30 * (r1 - r2), 2)
4647 + Math.pow(59 * (g1 - g2), 2)
4648 + Math.pow(11 * (b1 - b2), 2);
4649 };
4650
4651 function each(obj, iter, con) {
4652 if (obj.forEach) return obj.forEach(iter, con);
4653 for (var i = 0; i < obj.length; i++) {
4654 iter.call(con, obj[i], i, obj);
4655 }
4656 }
4657
4658 function keys(obj) {
4659 if (Object.keys) return Object.keys(obj);
4660 var key, keys = [];
4661 for (key in obj) {
4662 if (Object.prototype.hasOwnProperty.call(obj, key)) {
4663 keys.push(key);
4664 }
4665 }
4666 return keys;
4667 }
4668
4669 /**
4670 * Expose
4671 */
4672
4673 Terminal.EventEmitter = EventEmitter;
4674 Terminal.inherits = inherits;
4675
4676 /**
4677 * Adds an event listener to the terminal.
4678 *
4679 * @param {string} event The name of the event. TODO: Document all event types
4680 * @param {function} callback The function to call when the event is triggered.
4681 *
4682 * @public
4683 */
4684 Terminal.on = on;
4685 Terminal.off = off;
4686 Terminal.cancel = cancel;
4687
4688 return Terminal;
4689 });