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