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