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