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