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