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