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