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