xterm
[VSoRC/.git] / node_modules / xterm / src / browser / services / SelectionService.ts
1 /**
2  * Copyright (c) 2017 The xterm.js authors. All rights reserved.
3  * @license MIT
4  */
5
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';
17
18 /**
19  * The number of pixels the mouse needs to be above or below the viewport in
20  * order to scroll at the maximum speed.
21  */
22 const DRAG_SCROLL_MAX_THRESHOLD = 50;
23
24 /**
25  * The maximum scrolling speed
26  */
27 const DRAG_SCROLL_MAX_SPEED = 15;
28
29 /**
30  * The number of milliseconds between drag scroll updates.
31  */
32 const DRAG_SCROLL_INTERVAL = 50;
33
34 /**
35  * The maximum amount of time that can have elapsed for an alt click to move the
36  * cursor.
37  */
38 const ALT_CLICK_MOVE_CURSOR_TIME = 500;
39
40 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
41 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
42
43 /**
44  * Represents a position of a word on a line.
45  */
46 interface IWordPosition {
47   start: number;
48   length: number;
49 }
50
51 /**
52  * A selection mode, this drives how the selection behaves on mouse move.
53  */
54 export const enum SelectionMode {
55   NORMAL,
56   WORD,
57   LINE,
58   COLUMN
59 }
60
61 /**
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).
68  */
69 export class SelectionService implements ISelectionService {
70   serviceBrand: any;
71
72   protected _model: SelectionModel;
73
74   /**
75    * The amount to scroll every drag scroll update (depends on how far the mouse
76    * drag is above or below the terminal).
77    */
78   private _dragScrollAmount: number = 0;
79
80   /**
81    * The current selection mode.
82    */
83   protected _activeSelectionMode: SelectionMode;
84
85   /**
86    * A setInterval timer that is active while the mouse is down whose callback
87    * scrolls the viewport when necessary.
88    */
89   private _dragScrollIntervalTimer: number | undefined;
90
91   /**
92    * The animation frame ID used for refreshing the selection.
93    */
94   private _refreshAnimationFrame: number | undefined;
95
96   /**
97    * Whether selection is enabled.
98    */
99   private _enabled = true;
100
101   private _mouseMoveListener: EventListener;
102   private _mouseUpListener: EventListener;
103   private _trimListener: IDisposable;
104   private _workCell: CellData = new CellData();
105
106   private _mouseDownTimeStamp: number = 0;
107
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; }
114
115   constructor(
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
124   ) {
125     // Init listeners
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();
131       }
132     });
133     this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._onTrim(amount));
134     this._bufferService.buffers.onBufferActivate(e => this._onBufferActivate(e));
135
136     this.enable();
137
138     this._model = new SelectionModel(this._bufferService);
139     this._activeSelectionMode = SelectionMode.NORMAL;
140   }
141
142   public dispose(): void {
143     this._removeMouseDownListeners();
144   }
145
146   public reset(): void {
147     this.clearSelection();
148   }
149
150   /**
151    * Disables the selection manager. This is useful for when terminal mouse
152    * are enabled.
153    */
154   public disable(): void {
155     this.clearSelection();
156     this._enabled = false;
157   }
158
159   /**
160    * Enable the selection manager.
161    */
162   public enable(): void {
163     this._enabled = true;
164   }
165
166   public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; }
167   public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; }
168
169   /**
170    * Gets whether there is an active text selection.
171    */
172   public get hasSelection(): boolean {
173     const start = this._model.finalSelectionStart;
174     const end = this._model.finalSelectionEnd;
175     if (!start || !end) {
176       return false;
177     }
178     return start[0] !== end[0] || start[1] !== end[1];
179   }
180
181   /**
182    * Gets the text currently selected.
183    */
184   public get selectionText(): string {
185     const start = this._model.finalSelectionStart;
186     const end = this._model.finalSelectionEnd;
187     if (!start || !end) {
188       return '';
189     }
190
191     const buffer = this._bufferService.buffer;
192     const result: string[] = [];
193
194     if (this._activeSelectionMode === SelectionMode.COLUMN) {
195       // Ignore zero width selections
196       if (start[0] === end[0]) {
197         return '';
198       }
199
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);
203       }
204     } else {
205       // Get first row
206       const startRowEndCol = start[1] === end[1] ? end[0] : undefined;
207       result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));
208
209       // Get middle rows
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;
215         } else {
216           result.push(lineText);
217         }
218       }
219
220       // Get final row
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;
226         } else {
227           result.push(lineText);
228         }
229       }
230     }
231
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');
237
238     return formattedResult;
239   }
240
241   /**
242    * Clears the current terminal selection.
243    */
244   public clearSelection(): void {
245     this._model.clearSelection();
246     this._removeMouseDownListeners();
247     this.refresh();
248     this._onSelectionChange.fire();
249   }
250
251   /**
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.
255    */
256   public refresh(isLinuxMouseSelection?: boolean): void {
257     // Queue the refresh for the renderer
258     if (!this._refreshAnimationFrame) {
259       this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
260     }
261
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);
268       }
269     }
270   }
271
272   /**
273    * Fires the refresh event, causing consumers to pick it up and redraw the
274    * selection state.
275    */
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
282     });
283   }
284
285   /**
286    * Checks if the current click was inside the current selection
287    * @param event The mouse event
288    */
289   public isClickInSelection(event: MouseEvent): boolean {
290     const coords = this._getMouseBufferCoords(event);
291     const start = this._model.finalSelectionStart;
292     const end = this._model.finalSelectionEnd;
293
294     if (!start || !end || !coords) {
295       return false;
296     }
297
298     return this._areCoordsInSelection(coords, start, end);
299   }
300
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]);
306   }
307
308   /**
309    * Selects word at the current mouse event coordinates.
310    * @param event The mouse event.
311    */
312   public selectWordAtCursor(event: MouseEvent): void {
313     const coords = this._getMouseBufferCoords(event);
314     if (coords) {
315       this._selectWordAt(coords, false);
316       this._model.selectionEnd = undefined;
317       this.refresh(true);
318     }
319   }
320
321   /**
322    * Selects all text within the terminal.
323    */
324   public selectAll(): void {
325     this._model.isSelectAllActive = true;
326     this.refresh();
327     this._onSelectionChange.fire();
328   }
329
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];
336     this.refresh();
337     this._onSelectionChange.fire();
338   }
339
340   /**
341    * Handle the buffer being trimmed, adjust the selection position.
342    * @param amount The amount the buffer is being trimmed.
343    */
344   private _onTrim(amount: number): void {
345     const needsRefresh = this._model.onTrim(amount);
346     if (needsRefresh) {
347       this.refresh();
348     }
349   }
350
351   /**
352    * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
353    * @param event The mouse event.
354    */
355   private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined {
356     const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);
357     if (!coords) {
358       return undefined;
359     }
360
361     // Convert to 0-based
362     coords[0]--;
363     coords[1]--;
364
365     // Convert viewport coords to buffer coords
366     coords[1] += this._bufferService.buffer.ydisp;
367     return coords;
368   }
369
370   /**
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.
374    */
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) {
379       return 0;
380     }
381     if (offset > terminalHeight) {
382       offset -= terminalHeight;
383     }
384
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));
388   }
389
390   /**
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.
394    */
395   public shouldForceSelection(event: MouseEvent): boolean {
396     if (Browser.isMac) {
397       return event.altKey && this._optionsService.options.macOptionClickForcesSelection;
398     }
399
400     return event.shiftKey;
401   }
402
403   /**
404    * Handles te mousedown event, setting up for a new selection.
405    * @param event The mousedown event.
406    */
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) {
412       return;
413     }
414
415     // Only action the primary button
416     if (event.button !== 0) {
417       return;
418     }
419
420     // Allow selection when using a specific modifier key, even when disabled
421     if (!this._enabled) {
422       if (!this.shouldForceSelection(event)) {
423         return;
424       }
425
426       // Don't send the mouse down event to the current process, we want to select
427       event.stopPropagation();
428     }
429
430     // Tell the browser not to start a regular selection
431     event.preventDefault();
432
433     // Reset drag scroll state
434     this._dragScrollAmount = 0;
435
436     if (this._enabled && event.shiftKey) {
437       this._onIncrementalClick(event);
438     } else {
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);
445       }
446     }
447
448     this._addMouseDownListeners();
449     this.refresh(true);
450   }
451
452   /**
453    * Adds listeners when mousedown is triggered.
454    */
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);
460     }
461     this._dragScrollIntervalTimer = window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
462   }
463
464   /**
465    * Removes the listeners that are registered when mousedown is triggered.
466    */
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);
471     }
472     clearInterval(this._dragScrollIntervalTimer);
473     this._dragScrollIntervalTimer = undefined;
474   }
475
476   /**
477    * Performs an incremental click, setting the selection end position to the mouse
478    * position.
479    * @param event The mouse event.
480    */
481   private _onIncrementalClick(event: MouseEvent): void {
482     if (this._model.selectionStart) {
483       this._model.selectionEnd = this._getMouseBufferCoords(event);
484     }
485   }
486
487   /**
488    * Performs a single click, resetting relevant state and setting the selection
489    * start position.
490    * @param event The mouse event.
491    */
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;
496
497     // Initialize the new selection
498     this._model.selectionStart = this._getMouseBufferCoords(event);
499     if (!this._model.selectionStart) {
500       return;
501     }
502     this._model.selectionEnd = undefined;
503
504     // Ensure the line exists
505     const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);
506     if (!line) {
507       return;
508     }
509
510     // Return early if the click event is not in the buffer (eg. in scroll bar)
511     if (line.length === this._model.selectionStart[0]) {
512       return;
513     }
514
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]++;
519     }
520   }
521
522   /**
523    * Performs a double click, selecting the current work.
524    * @param event The mouse event.
525    */
526   private _onDoubleClick(event: MouseEvent): void {
527     const coords = this._getMouseBufferCoords(event);
528     if (coords) {
529       this._activeSelectionMode = SelectionMode.WORD;
530       this._selectWordAt(coords, true);
531     }
532   }
533
534   /**
535    * Performs a triple click, selecting the current line and activating line
536    * select mode.
537    * @param event The mouse event.
538    */
539   private _onTripleClick(event: MouseEvent): void {
540     const coords = this._getMouseBufferCoords(event);
541     if (coords) {
542       this._activeSelectionMode = SelectionMode.LINE;
543       this._selectLineAt(coords[1]);
544     }
545   }
546
547   /**
548    * Returns whether the selection manager should operate in column select mode
549    * @param event the mouse or keyboard event
550    */
551   public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean {
552     return event.altKey && !(Browser.isMac && this._optionsService.options.macOptionClickForcesSelection);
553   }
554
555   /**
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.
559    */
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();
565
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) {
569       return;
570     }
571
572     // Record the previous position so we know whether to redraw the selection
573     // at the end.
574     const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
575
576     // Set the initial selection end based on the mouse coordinates
577     this._model.selectionEnd = this._getMouseBufferCoords(event);
578     if (!this._model.selectionEnd) {
579       this.refresh(true);
580       return;
581     }
582
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;
587       } else {
588         this._model.selectionEnd[0] = this._bufferService.cols;
589       }
590     } else if (this._activeSelectionMode === SelectionMode.WORD) {
591       this._selectToWordAt(this._model.selectionEnd);
592     }
593
594     // Determine the amount of scrolling that will happen.
595     this._dragScrollAmount = this._getMouseEventScrollAmount(event);
596
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;
605       }
606     }
607
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
610     // have a character.
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]++;
616       }
617     }
618
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]) {
623       this.refresh(true);
624     }
625   }
626
627   /**
628    * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
629    * scrolling of the viewport.
630    */
631   private _dragScroll(): void {
632     if (!this._model.selectionEnd || !this._model.selectionStart) {
633       return;
634     }
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;
645         }
646         this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1);
647       } else {
648         if (this._activeSelectionMode !== SelectionMode.COLUMN) {
649           this._model.selectionEnd[0] = 0;
650         }
651         this._model.selectionEnd[1] = buffer.ydisp;
652       }
653       this.refresh();
654     }
655   }
656
657   /**
658    * Handles the mouseup event, removing the mousedown listeners.
659    * @param event The mouseup event.
660    */
661   private _onMouseUp(event: MouseEvent): void {
662     const timeElapsed = event.timeStamp - this._mouseDownTimeStamp;
663
664     this._removeMouseDownListeners();
665
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(
669           event,
670           this._element,
671           this._bufferService.cols,
672           this._bufferService.rows,
673           false
674         );
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);
678         }
679       }
680     } else if (this.hasSelection) {
681       this._onSelectionChange.fire();
682     }
683   }
684
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();
693     }
694     this._trimListener = e.activeBuffer.lines.onTrim(amount => this._onTrim(amount));
695   }
696
697   /**
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.
701    */
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.
709         charIndex--;
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;
715       }
716     }
717     return charIndex;
718   }
719
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;
725     this.refresh();
726   }
727
728   /**
729    * Gets positional information for the word at the coordinated specified.
730    * @param coords The coordinates to get the word at.
731    */
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) {
735       return undefined;
736     }
737
738     const buffer = this._bufferService.buffer;
739     const bufferLine = buffer.lines.get(coords[1]);
740     if (!bufferLine) {
741       return undefined;
742     }
743
744     const line = buffer.translateBufferLineToString(coords[1], false);
745
746     // Get actual index, taking into consideration wide characters
747     let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
748     let endIndex = startIndex;
749
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;
756
757     if (line.charAt(startIndex) === ' ') {
758       // Expand until non-whitespace is hit
759       while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
760         startIndex--;
761       }
762       while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
763         endIndex++;
764       }
765     } else {
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];
772
773       // Consider the initial position, skip it and increment the wide char
774       // variable
775       if (bufferLine.getWidth(startCol) === 0) {
776         leftWideCharCount++;
777         startCol--;
778       }
779       if (bufferLine.getWidth(endCol) === 2) {
780         rightWideCharCount++;
781         endCol++;
782       }
783
784       // Adjust the end index for characters whose length are > 1 (emojis)
785       const length = bufferLine.getString(endCol).length;
786       if (length > 1) {
787         rightLongCharOffset += length - 1;
788         endIndex += length - 1;
789       }
790
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
797           leftWideCharCount++;
798           startCol--;
799         } else if (length > 1) {
800           // If the next character's string is longer than 1 char (eg. emoji),
801           // adjust the index
802           leftLongCharOffset += length - 1;
803           startIndex -= length - 1;
804         }
805         startIndex--;
806         startCol--;
807       }
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++;
814           endCol++;
815         } else if (length > 1) {
816           // If the next character's string is longer than 1 char (eg. emoji),
817           // adjust the index
818           rightLongCharOffset += length - 1;
819           endIndex += length - 1;
820         }
821         endIndex++;
822         endCol++;
823       }
824     }
825
826     // Incremenet the end index so it is at the start of the next character
827     endIndex++;
828
829     // Calculate the start _column_, converting the the string indexes back to
830     // column coordinates.
831     let start =
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)
836
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)
846
847     if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {
848       return undefined;
849     }
850
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;
859             start -= offset;
860             length += offset;
861           }
862         }
863       }
864     }
865
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;
874           }
875         }
876       }
877     }
878
879     return { start, length };
880   }
881
882   /**
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
886    */
887   protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void {
888     const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);
889     if (wordPosition) {
890       // Adjust negative start value
891       while (wordPosition.start < 0) {
892         wordPosition.start += this._bufferService.cols;
893         coords[1]--;
894       }
895       this._model.selectionStart = [wordPosition.start, coords[1]];
896       this._model.selectionStartLength = wordPosition.length;
897     }
898   }
899
900   /**
901    * Sets the selection end to the word at the coordinated specified.
902    * @param coords The coordinates to get the word at.
903    */
904   private _selectToWordAt(coords: [number, number]): void {
905     const wordPosition = this._getWordAt(coords, true);
906     if (wordPosition) {
907       let endRow = coords[1];
908
909       // Adjust negative start value
910       while (wordPosition.start < 0) {
911         wordPosition.start += this._bufferService.cols;
912         endRow--;
913       }
914
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;
920           endRow++;
921         }
922       }
923
924       this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow];
925     }
926   }
927
928   /**
929    * Gets whether the character is considered a word separator by the select
930    * word logic.
931    * @param char The character to check.
932    */
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) {
937       return false;
938     }
939     return this._optionsService.options.wordSeparator.indexOf(cell.getChars()) >= 0;
940   }
941
942   /**
943    * Selects the line specified.
944    * @param line The line index.
945    */
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;
951   }
952 }