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