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