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