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