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