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