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