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