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