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