2 * Copyright (c) 2017 The xterm.js authors. All rights reserved.
6 import { ISelectionRedrawRequestEvent } from 'browser/selection/Types';
7 import { IBuffer } from 'common/buffer/Types';
8 import { IBufferLine, IDisposable } from 'common/Types';
9 import * as Browser from 'common/Platform';
10 import { SelectionModel } from 'browser/selection/SelectionModel';
11 import { CellData } from 'common/buffer/CellData';
12 import { EventEmitter, IEvent } from 'common/EventEmitter';
13 import { ICharSizeService, IMouseService, ISelectionService } from 'browser/services/Services';
14 import { IBufferService, IOptionsService, ICoreService } from 'common/services/Services';
15 import { getCoordsRelativeToElement } from 'browser/input/Mouse';
16 import { moveToCellSequence } from 'browser/input/MoveToCell';
19 * The number of pixels the mouse needs to be above or below the viewport in
20 * order to scroll at the maximum speed.
22 const DRAG_SCROLL_MAX_THRESHOLD = 50;
25 * The maximum scrolling speed
27 const DRAG_SCROLL_MAX_SPEED = 15;
30 * The number of milliseconds between drag scroll updates.
32 const DRAG_SCROLL_INTERVAL = 50;
35 * The maximum amount of time that can have elapsed for an alt click to move the
38 const ALT_CLICK_MOVE_CURSOR_TIME = 500;
40 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
41 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
44 * Represents a position of a word on a line.
46 interface IWordPosition {
52 * A selection mode, this drives how the selection behaves on mouse move.
54 export const enum SelectionMode {
62 * A class that manages the selection of the terminal. With help from
63 * SelectionModel, SelectionService handles with all logic associated with
64 * dealing with the selection, including handling mouse interaction, wide
65 * characters and fetching the actual text within the selection. Rendering is
66 * not handled by the SelectionService but the onRedrawRequest event is fired
67 * when the selection is ready to be redrawn (on an animation frame).
69 export class SelectionService implements ISelectionService {
72 protected _model: SelectionModel;
75 * The amount to scroll every drag scroll update (depends on how far the mouse
76 * drag is above or below the terminal).
78 private _dragScrollAmount: number = 0;
81 * The current selection mode.
83 protected _activeSelectionMode: SelectionMode;
86 * A setInterval timer that is active while the mouse is down whose callback
87 * scrolls the viewport when necessary.
89 private _dragScrollIntervalTimer: number | undefined;
92 * The animation frame ID used for refreshing the selection.
94 private _refreshAnimationFrame: number | undefined;
97 * Whether selection is enabled.
99 private _enabled = true;
101 private _mouseMoveListener: EventListener;
102 private _mouseUpListener: EventListener;
103 private _trimListener: IDisposable;
104 private _workCell: CellData = new CellData();
106 private _mouseDownTimeStamp: number = 0;
108 private _onLinuxMouseSelection = new EventEmitter<string>();
109 public get onLinuxMouseSelection(): IEvent<string> { return this._onLinuxMouseSelection.event; }
110 private _onRedrawRequest = new EventEmitter<ISelectionRedrawRequestEvent>();
111 public get onRedrawRequest(): IEvent<ISelectionRedrawRequestEvent> { return this._onRedrawRequest.event; }
112 private _onSelectionChange = new EventEmitter<void>();
113 public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }
116 private readonly _scrollLines: (amount: number, suppressEvent: boolean) => void,
117 private readonly _element: HTMLElement,
118 private readonly _screenElement: HTMLElement,
119 @ICharSizeService private readonly _charSizeService: ICharSizeService,
120 @IBufferService private readonly _bufferService: IBufferService,
121 @ICoreService private readonly _coreService: ICoreService,
122 @IMouseService private readonly _mouseService: IMouseService,
123 @IOptionsService private readonly _optionsService: IOptionsService
126 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
127 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
128 this._coreService.onUserInput(() => {
129 if (this.hasSelection) {
130 this.clearSelection();
133 this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._onTrim(amount));
134 this._bufferService.buffers.onBufferActivate(e => this._onBufferActivate(e));
138 this._model = new SelectionModel(this._bufferService);
139 this._activeSelectionMode = SelectionMode.NORMAL;
142 public dispose(): void {
143 this._removeMouseDownListeners();
146 public reset(): void {
147 this.clearSelection();
151 * Disables the selection manager. This is useful for when terminal mouse
154 public disable(): void {
155 this.clearSelection();
156 this._enabled = false;
160 * Enable the selection manager.
162 public enable(): void {
163 this._enabled = true;
166 public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; }
167 public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; }
170 * Gets whether there is an active text selection.
172 public get hasSelection(): boolean {
173 const start = this._model.finalSelectionStart;
174 const end = this._model.finalSelectionEnd;
175 if (!start || !end) {
178 return start[0] !== end[0] || start[1] !== end[1];
182 * Gets the text currently selected.
184 public get selectionText(): string {
185 const start = this._model.finalSelectionStart;
186 const end = this._model.finalSelectionEnd;
187 if (!start || !end) {
191 const buffer = this._bufferService.buffer;
192 const result: string[] = [];
194 if (this._activeSelectionMode === SelectionMode.COLUMN) {
195 // Ignore zero width selections
196 if (start[0] === end[0]) {
200 for (let i = start[1]; i <= end[1]; i++) {
201 const lineText = buffer.translateBufferLineToString(i, true, start[0], end[0]);
202 result.push(lineText);
206 const startRowEndCol = start[1] === end[1] ? end[0] : undefined;
207 result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));
210 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
211 const bufferLine = buffer.lines.get(i);
212 const lineText = buffer.translateBufferLineToString(i, true);
213 if (bufferLine && bufferLine.isWrapped) {
214 result[result.length - 1] += lineText;
216 result.push(lineText);
221 if (start[1] !== end[1]) {
222 const bufferLine = buffer.lines.get(end[1]);
223 const lineText = buffer.translateBufferLineToString(end[1], true, 0, end[0]);
224 if (bufferLine && bufferLine!.isWrapped) {
225 result[result.length - 1] += lineText;
227 result.push(lineText);
232 // Format string by replacing non-breaking space chars with regular spaces
233 // and joining the array into a multi-line string.
234 const formattedResult = result.map(line => {
235 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
236 }).join(Browser.isWindows ? '\r\n' : '\n');
238 return formattedResult;
242 * Clears the current terminal selection.
244 public clearSelection(): void {
245 this._model.clearSelection();
246 this._removeMouseDownListeners();
248 this._onSelectionChange.fire();
252 * Queues a refresh, redrawing the selection on the next opportunity.
253 * @param isLinuxMouseSelection Whether the selection should be registered as a new
254 * selection on Linux.
256 public refresh(isLinuxMouseSelection?: boolean): void {
257 // Queue the refresh for the renderer
258 if (!this._refreshAnimationFrame) {
259 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
262 // If the platform is Linux and the refresh call comes from a mouse event,
263 // we need to update the selection for middle click to paste selection.
264 if (Browser.isLinux && isLinuxMouseSelection) {
265 const selectionText = this.selectionText;
266 if (selectionText.length) {
267 this._onLinuxMouseSelection.fire(this.selectionText);
273 * Fires the refresh event, causing consumers to pick it up and redraw the
276 private _refresh(): void {
277 this._refreshAnimationFrame = undefined;
278 this._onRedrawRequest.fire({
279 start: this._model.finalSelectionStart,
280 end: this._model.finalSelectionEnd,
281 columnSelectMode: this._activeSelectionMode === SelectionMode.COLUMN
286 * Checks if the current click was inside the current selection
287 * @param event The mouse event
289 public isClickInSelection(event: MouseEvent): boolean {
290 const coords = this._getMouseBufferCoords(event);
291 const start = this._model.finalSelectionStart;
292 const end = this._model.finalSelectionEnd;
294 if (!start || !end || !coords) {
298 return this._areCoordsInSelection(coords, start, end);
301 protected _areCoordsInSelection(coords: [number, number], start: [number, number], end: [number, number]): boolean {
302 return (coords[1] > start[1] && coords[1] < end[1]) ||
303 (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) ||
304 (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) ||
305 (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]);
309 * Selects word at the current mouse event coordinates.
310 * @param event The mouse event.
312 public selectWordAtCursor(event: MouseEvent): void {
313 const coords = this._getMouseBufferCoords(event);
315 this._selectWordAt(coords, false);
316 this._model.selectionEnd = undefined;
322 * Selects all text within the terminal.
324 public selectAll(): void {
325 this._model.isSelectAllActive = true;
327 this._onSelectionChange.fire();
330 public selectLines(start: number, end: number): void {
331 this._model.clearSelection();
332 start = Math.max(start, 0);
333 end = Math.min(end, this._bufferService.buffer.lines.length - 1);
334 this._model.selectionStart = [0, start];
335 this._model.selectionEnd = [this._bufferService.cols, end];
337 this._onSelectionChange.fire();
341 * Handle the buffer being trimmed, adjust the selection position.
342 * @param amount The amount the buffer is being trimmed.
344 private _onTrim(amount: number): void {
345 const needsRefresh = this._model.onTrim(amount);
352 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
353 * @param event The mouse event.
355 private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined {
356 const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);
361 // Convert to 0-based
365 // Convert viewport coords to buffer coords
366 coords[1] += this._bufferService.buffer.ydisp;
371 * Gets the amount the viewport should be scrolled based on how far out of the
372 * terminal the mouse is.
373 * @param event The mouse event.
375 private _getMouseEventScrollAmount(event: MouseEvent): number {
376 let offset = getCoordsRelativeToElement(event, this._screenElement)[1];
377 const terminalHeight = this._bufferService.rows * Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight);
378 if (offset >= 0 && offset <= terminalHeight) {
381 if (offset > terminalHeight) {
382 offset -= terminalHeight;
385 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
386 offset /= DRAG_SCROLL_MAX_THRESHOLD;
387 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
391 * Returns whether the selection manager should force selection, regardless of
392 * whether the terminal is in mouse events mode.
393 * @param event The mouse event.
395 public shouldForceSelection(event: MouseEvent): boolean {
397 return event.altKey && this._optionsService.options.macOptionClickForcesSelection;
400 return event.shiftKey;
404 * Handles te mousedown event, setting up for a new selection.
405 * @param event The mousedown event.
407 public onMouseDown(event: MouseEvent): void {
408 this._mouseDownTimeStamp = event.timeStamp;
409 // If we have selection, we want the context menu on right click even if the
410 // terminal is in mouse mode.
411 if (event.button === 2 && this.hasSelection) {
415 // Only action the primary button
416 if (event.button !== 0) {
420 // Allow selection when using a specific modifier key, even when disabled
421 if (!this._enabled) {
422 if (!this.shouldForceSelection(event)) {
426 // Don't send the mouse down event to the current process, we want to select
427 event.stopPropagation();
430 // Tell the browser not to start a regular selection
431 event.preventDefault();
433 // Reset drag scroll state
434 this._dragScrollAmount = 0;
436 if (this._enabled && event.shiftKey) {
437 this._onIncrementalClick(event);
439 if (event.detail === 1) {
440 this._onSingleClick(event);
441 } else if (event.detail === 2) {
442 this._onDoubleClick(event);
443 } else if (event.detail === 3) {
444 this._onTripleClick(event);
448 this._addMouseDownListeners();
453 * Adds listeners when mousedown is triggered.
455 private _addMouseDownListeners(): void {
456 // Listen on the document so that dragging outside of viewport works
457 if (this._screenElement.ownerDocument) {
458 this._screenElement.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
459 this._screenElement.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
461 this._dragScrollIntervalTimer = window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
465 * Removes the listeners that are registered when mousedown is triggered.
467 private _removeMouseDownListeners(): void {
468 if (this._screenElement.ownerDocument) {
469 this._screenElement.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
470 this._screenElement.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
472 clearInterval(this._dragScrollIntervalTimer);
473 this._dragScrollIntervalTimer = undefined;
477 * Performs an incremental click, setting the selection end position to the mouse
479 * @param event The mouse event.
481 private _onIncrementalClick(event: MouseEvent): void {
482 if (this._model.selectionStart) {
483 this._model.selectionEnd = this._getMouseBufferCoords(event);
488 * Performs a single click, resetting relevant state and setting the selection
490 * @param event The mouse event.
492 private _onSingleClick(event: MouseEvent): void {
493 this._model.selectionStartLength = 0;
494 this._model.isSelectAllActive = false;
495 this._activeSelectionMode = this.shouldColumnSelect(event) ? SelectionMode.COLUMN : SelectionMode.NORMAL;
497 // Initialize the new selection
498 this._model.selectionStart = this._getMouseBufferCoords(event);
499 if (!this._model.selectionStart) {
502 this._model.selectionEnd = undefined;
504 // Ensure the line exists
505 const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);
510 // Return early if the click event is not in the buffer (eg. in scroll bar)
511 if (line.length === this._model.selectionStart[0]) {
515 // If the mouse is over the second half of a wide character, adjust the
516 // selection to cover the whole character
517 if (line.hasWidth(this._model.selectionStart[0]) === 0) {
518 this._model.selectionStart[0]++;
523 * Performs a double click, selecting the current work.
524 * @param event The mouse event.
526 private _onDoubleClick(event: MouseEvent): void {
527 const coords = this._getMouseBufferCoords(event);
529 this._activeSelectionMode = SelectionMode.WORD;
530 this._selectWordAt(coords, true);
535 * Performs a triple click, selecting the current line and activating line
537 * @param event The mouse event.
539 private _onTripleClick(event: MouseEvent): void {
540 const coords = this._getMouseBufferCoords(event);
542 this._activeSelectionMode = SelectionMode.LINE;
543 this._selectLineAt(coords[1]);
548 * Returns whether the selection manager should operate in column select mode
549 * @param event the mouse or keyboard event
551 public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean {
552 return event.altKey && !(Browser.isMac && this._optionsService.options.macOptionClickForcesSelection);
556 * Handles the mousemove event when the mouse button is down, recording the
557 * end of the selection and refreshing the selection.
558 * @param event The mousemove event.
560 private _onMouseMove(event: MouseEvent): void {
561 // If the mousemove listener is active it means that a selection is
562 // currently being made, we should stop propagation to prevent mouse events
563 // to be sent to the pty.
564 event.stopImmediatePropagation();
566 // Do nothing if there is no selection start, this can happen if the first
567 // click in the terminal is an incremental click
568 if (!this._model.selectionStart) {
572 // Record the previous position so we know whether to redraw the selection
574 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
576 // Set the initial selection end based on the mouse coordinates
577 this._model.selectionEnd = this._getMouseBufferCoords(event);
578 if (!this._model.selectionEnd) {
583 // Select the entire line if line select mode is active.
584 if (this._activeSelectionMode === SelectionMode.LINE) {
585 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
586 this._model.selectionEnd[0] = 0;
588 this._model.selectionEnd[0] = this._bufferService.cols;
590 } else if (this._activeSelectionMode === SelectionMode.WORD) {
591 this._selectToWordAt(this._model.selectionEnd);
594 // Determine the amount of scrolling that will happen.
595 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
597 // If the cursor was above or below the viewport, make sure it's at the
598 // start or end of the viewport respectively. This should only happen when
599 // NOT in column select mode.
600 if (this._activeSelectionMode !== SelectionMode.COLUMN) {
601 if (this._dragScrollAmount > 0) {
602 this._model.selectionEnd[0] = this._bufferService.cols;
603 } else if (this._dragScrollAmount < 0) {
604 this._model.selectionEnd[0] = 0;
608 // If the character is a wide character include the cell to the right in the
609 // selection. Note that selections at the very end of the line will never
611 const buffer = this._bufferService.buffer;
612 if (this._model.selectionEnd[1] < buffer.lines.length) {
613 const line = buffer.lines.get(this._model.selectionEnd[1]);
614 if (line && line.hasWidth(this._model.selectionEnd[0]) === 0) {
615 this._model.selectionEnd[0]++;
619 // Only draw here if the selection changes.
620 if (!previousSelectionEnd ||
621 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
622 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
628 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
629 * scrolling of the viewport.
631 private _dragScroll(): void {
632 if (!this._model.selectionEnd || !this._model.selectionStart) {
635 if (this._dragScrollAmount) {
636 this._scrollLines(this._dragScrollAmount, false);
637 // Re-evaluate selection
638 // If the cursor was above or below the viewport, make sure it's at the
639 // start or end of the viewport respectively. This should only happen when
640 // NOT in column select mode.
641 const buffer = this._bufferService.buffer;
642 if (this._dragScrollAmount > 0) {
643 if (this._activeSelectionMode !== SelectionMode.COLUMN) {
644 this._model.selectionEnd[0] = this._bufferService.cols;
646 this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1);
648 if (this._activeSelectionMode !== SelectionMode.COLUMN) {
649 this._model.selectionEnd[0] = 0;
651 this._model.selectionEnd[1] = buffer.ydisp;
658 * Handles the mouseup event, removing the mousedown listeners.
659 * @param event The mouseup event.
661 private _onMouseUp(event: MouseEvent): void {
662 const timeElapsed = event.timeStamp - this._mouseDownTimeStamp;
664 this._removeMouseDownListeners();
666 if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME) {
667 if (event.altKey && this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) {
668 const coordinates = this._mouseService.getCoords(
671 this._bufferService.cols,
672 this._bufferService.rows,
675 if (coordinates && coordinates[0] !== undefined && coordinates[1] !== undefined) {
676 const sequence = moveToCellSequence(coordinates[0] - 1, coordinates[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys);
677 this._coreService.triggerDataEvent(sequence, true);
680 } else if (this.hasSelection) {
681 this._onSelectionChange.fire();
685 private _onBufferActivate(e: {activeBuffer: IBuffer, inactiveBuffer: IBuffer}): void {
686 this.clearSelection();
687 // Only adjust the selection on trim, shiftElements is rarely used (only in
688 // reverseIndex) and delete in a splice is only ever used when the same
689 // number of elements was just added. Given this is could actually be
690 // beneficial to leave the selection as is for these cases.
691 if (this._trimListener) {
692 this._trimListener.dispose();
694 this._trimListener = e.activeBuffer.lines.onTrim(amount => this._onTrim(amount));
698 * Converts a viewport column to the character index on the buffer line, the
699 * latter takes into account wide characters.
700 * @param coords The coordinates to find the 2 index for.
702 private _convertViewportColToCharacterIndex(bufferLine: IBufferLine, coords: [number, number]): number {
703 let charIndex = coords[0];
704 for (let i = 0; coords[0] >= i; i++) {
705 const length = bufferLine.loadCell(i, this._workCell).getChars().length;
706 if (this._workCell.getWidth() === 0) {
707 // Wide characters aren't included in the line string so decrement the
708 // index so the index is back on the wide character.
710 } else if (length > 1 && coords[0] !== i) {
711 // Emojis take up multiple characters, so adjust accordingly. For these
712 // we don't want ot include the character at the column as we're
713 // returning the start index in the string, not the end index.
714 charIndex += length - 1;
720 public setSelection(col: number, row: number, length: number): void {
721 this._model.clearSelection();
722 this._removeMouseDownListeners();
723 this._model.selectionStart = [col, row];
724 this._model.selectionStartLength = length;
729 * Gets positional information for the word at the coordinated specified.
730 * @param coords The coordinates to get the word at.
732 private _getWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean, followWrappedLinesAbove: boolean = true, followWrappedLinesBelow: boolean = true): IWordPosition | undefined {
733 // Ensure coords are within viewport (eg. not within scroll bar)
734 if (coords[0] >= this._bufferService.cols) {
738 const buffer = this._bufferService.buffer;
739 const bufferLine = buffer.lines.get(coords[1]);
744 const line = buffer.translateBufferLineToString(coords[1], false);
746 // Get actual index, taking into consideration wide characters
747 let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
748 let endIndex = startIndex;
750 // Record offset to be used later
751 const charOffset = coords[0] - startIndex;
752 let leftWideCharCount = 0;
753 let rightWideCharCount = 0;
754 let leftLongCharOffset = 0;
755 let rightLongCharOffset = 0;
757 if (line.charAt(startIndex) === ' ') {
758 // Expand until non-whitespace is hit
759 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
762 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
766 // Expand until whitespace is hit. This algorithm works by scanning left
767 // and right from the starting position, keeping both the index format
768 // (line) and the column format (bufferLine) in sync. When a wide
769 // character is hit, it is recorded and the column index is adjusted.
770 let startCol = coords[0];
771 let endCol = coords[0];
773 // Consider the initial position, skip it and increment the wide char
775 if (bufferLine.getWidth(startCol) === 0) {
779 if (bufferLine.getWidth(endCol) === 2) {
780 rightWideCharCount++;
784 // Adjust the end index for characters whose length are > 1 (emojis)
785 const length = bufferLine.getString(endCol).length;
787 rightLongCharOffset += length - 1;
788 endIndex += length - 1;
791 // Expand the string in both directions until a space is hit
792 while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.loadCell(startCol - 1, this._workCell))) {
793 bufferLine.loadCell(startCol - 1, this._workCell);
794 const length = this._workCell.getChars().length;
795 if (this._workCell.getWidth() === 0) {
796 // If the next character is a wide char, record it and skip the column
799 } else if (length > 1) {
800 // If the next character's string is longer than 1 char (eg. emoji),
802 leftLongCharOffset += length - 1;
803 startIndex -= length - 1;
808 while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.loadCell(endCol + 1, this._workCell))) {
809 bufferLine.loadCell(endCol + 1, this._workCell);
810 const length = this._workCell.getChars().length;
811 if (this._workCell.getWidth() === 2) {
812 // If the next character is a wide char, record it and skip the column
813 rightWideCharCount++;
815 } else if (length > 1) {
816 // If the next character's string is longer than 1 char (eg. emoji),
818 rightLongCharOffset += length - 1;
819 endIndex += length - 1;
826 // Incremenet the end index so it is at the start of the next character
829 // Calculate the start _column_, converting the the string indexes back to
830 // column coordinates.
832 startIndex // The index of the selection's start char in the line string
833 + charOffset // The difference between the initial char's column and index
834 - leftWideCharCount // The number of wide chars left of the initial char
835 + leftLongCharOffset; // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)
837 // Calculate the length in _columns_, converting the the string indexes back
838 // to column coordinates.
839 let length = Math.min(this._bufferService.cols, // Disallow lengths larger than the terminal cols
840 endIndex // The index of the selection's end char in the line string
841 - startIndex // The index of the selection's start char in the line string
842 + leftWideCharCount // The number of wide chars left of the initial char
843 + rightWideCharCount // The number of wide chars right of the initial char (inclusive)
844 - leftLongCharOffset // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)
845 - rightLongCharOffset); // The number of additional chars right of the initial char (inclusive) added by columns with strings longer than 1 (emojis)
847 if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {
851 // Recurse upwards if the line is wrapped and the word wraps to the above line
852 if (followWrappedLinesAbove) {
853 if (start === 0 && bufferLine.getCodePoint(0) !== 32 /*' '*/) {
854 const previousBufferLine = buffer.lines.get(coords[1] - 1);
855 if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {
856 const previousLineWordPosition = this._getWordAt([this._bufferService.cols - 1, coords[1] - 1], false, true, false);
857 if (previousLineWordPosition) {
858 const offset = this._bufferService.cols - previousLineWordPosition.start;
866 // Recurse downwards if the line is wrapped and the word wraps to the next line
867 if (followWrappedLinesBelow) {
868 if (start + length === this._bufferService.cols && bufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {
869 const nextBufferLine = buffer.lines.get(coords[1] + 1);
870 if (nextBufferLine && nextBufferLine.isWrapped && nextBufferLine.getCodePoint(0) !== 32 /*' '*/) {
871 const nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true);
872 if (nextLineWordPosition) {
873 length += nextLineWordPosition.length;
879 return { start, length };
883 * Selects the word at the coordinates specified.
884 * @param coords The coordinates to get the word at.
885 * @param allowWhitespaceOnlySelection If whitespace should be selected
887 protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void {
888 const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);
890 // Adjust negative start value
891 while (wordPosition.start < 0) {
892 wordPosition.start += this._bufferService.cols;
895 this._model.selectionStart = [wordPosition.start, coords[1]];
896 this._model.selectionStartLength = wordPosition.length;
901 * Sets the selection end to the word at the coordinated specified.
902 * @param coords The coordinates to get the word at.
904 private _selectToWordAt(coords: [number, number]): void {
905 const wordPosition = this._getWordAt(coords, true);
907 let endRow = coords[1];
909 // Adjust negative start value
910 while (wordPosition.start < 0) {
911 wordPosition.start += this._bufferService.cols;
915 // Adjust wrapped length value, this only needs to happen when values are reversed as in that
916 // case we're interested in the start of the word, not the end
917 if (!this._model.areSelectionValuesReversed()) {
918 while (wordPosition.start + wordPosition.length > this._bufferService.cols) {
919 wordPosition.length -= this._bufferService.cols;
924 this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow];
929 * Gets whether the character is considered a word separator by the select
931 * @param char The character to check.
933 private _isCharWordSeparator(cell: CellData): boolean {
934 // Zero width characters are never separators as they are always to the
935 // right of wide characters
936 if (cell.getWidth() === 0) {
939 return this._optionsService.options.wordSeparator.indexOf(cell.getChars()) >= 0;
943 * Selects the line specified.
944 * @param line The line index.
946 protected _selectLineAt(line: number): void {
947 const wrappedRange = this._bufferService.buffer.getWrappedRangeForLine(line);
948 this._model.selectionStart = [0, wrappedRange.first];
949 this._model.selectionEnd = [this._bufferService.cols, wrappedRange.last];
950 this._model.selectionStartLength = 0;