]> git.proxmox.com Git - mirror_xterm.js.git/blame - src/SelectionManager.ts
Add a comment
[mirror_xterm.js.git] / src / SelectionManager.ts
CommitLineData
70fda994
DI
1/**
2 * @license MIT
3 */
4
dc165175
DI
5import * as Mouse from './utils/Mouse';
6import * as Browser from './utils/Browser';
70fda994
DI
7import { CharMeasure } from './utils/CharMeasure';
8import { CircularList } from './utils/CircularList';
b594407c 9import { EventEmitter } from './EventEmitter';
ad3ae67e 10import { ITerminal } from './Interfaces';
f7d6ab5f 11import { SelectionModel } from './SelectionModel';
70fda994 12
0dc3dd03
DI
13/**
14 * The number of pixels the mouse needs to be above or below the viewport in
15 * order to scroll at the maximum speed.
16 */
b8129910 17const DRAG_SCROLL_MAX_THRESHOLD = 50;
0dc3dd03
DI
18
19/**
20 * The maximum scrolling speed
21 */
b8129910 22const DRAG_SCROLL_MAX_SPEED = 15;
0dc3dd03
DI
23
24/**
25 * The number of milliseconds between drag scroll updates.
26 */
b8129910 27const DRAG_SCROLL_INTERVAL = 50;
0dc3dd03 28
9f271de8 29/**
f380153f
DI
30 * The amount of time before mousedown events are no longer stacked to create
31 * double/triple click events.
9f271de8
DI
32 */
33const CLEAR_MOUSE_DOWN_TIME = 400;
34
f380153f
DI
35/**
36 * The number of pixels in each direction that the mouse must move before
37 * mousedown events are no longer stacked to create double/triple click events.
38 */
39const CLEAR_MOUSE_DISTANCE = 10;
40
7f2e94c3
DI
41/**
42 * A string containing all characters that are considered word separated by the
43 * double click to select work logic.
44 */
07882c42 45const WORD_SEPARATORS = ' ()[]{}:\'"';
7f2e94c3 46
2621be81
DI
47// TODO: Move these constants elsewhere, they belong in a buffer or buffer
48// data/line class.
54e7f65d
DI
49const LINE_DATA_CHAR_INDEX = 1;
50const LINE_DATA_WIDTH_INDEX = 2;
51
2012c8c9
DI
52const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
53const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
54
320fb55d
DI
55/**
56 * Represents a position of a word on a line.
57 */
4b170ca4
DI
58interface IWordPosition {
59 start: number;
60 length: number;
61}
62
320fb55d
DI
63/**
64 * A selection mode, this drives how the selection behaves on mouse move.
65 */
66enum SelectionMode {
67 NORMAL,
68 WORD,
69 LINE
70}
71
6075498c
DI
72/**
73 * A class that manages the selection of the terminal. With help from
74 * SelectionModel, SelectionManager handles with all logic associated with
75 * dealing with the selection, including handling mouse interaction, wide
76 * characters and fetching the actual text within the selection. Rendering is
77 * not handled by the SelectionManager but a 'refresh' event is fired when the
78 * selection is ready to be redrawn.
79 */
b594407c 80export class SelectionManager extends EventEmitter {
fd91c5e1 81 protected _model: SelectionModel;
9f271de8
DI
82
83 /**
84 * The amount to scroll every drag scroll update (depends on how far the mouse
85 * drag is above or below the terminal).
86 */
0dc3dd03 87 private _dragScrollAmount: number;
70fda994 88
9f271de8
DI
89 /**
90 * The last time the mousedown event fired, this is used to track double and
91 * triple clicks.
92 */
93 private _lastMouseDownTime: number;
94
f380153f
DI
95 /**
96 * The last position the mouse was clicked [x, y].
97 */
98 private _lastMousePosition: [number, number];
99
2621be81
DI
100 /**
101 * The number of clicks of the mousedown event. This is used to keep track of
102 * double and triple clicks.
103 */
9f271de8
DI
104 private _clickCount: number;
105
2621be81 106 /**
320fb55d 107 * The current selection mode.
2621be81 108 */
320fb55d 109 private _activeSelectionMode: SelectionMode;
4b170ca4 110
d0b603d0
DI
111 /**
112 * A setInterval timer that is active while the mouse is down whose callback
113 * scrolls the viewport when necessary.
114 */
115 private _dragScrollIntervalTimer: NodeJS.Timer;
116
b81c165b
DI
117 /**
118 * The animation frame ID used for refreshing the selection.
119 */
13c401cb
DI
120 private _refreshAnimationFrame: number;
121
ab40908f 122 private _bufferTrimListener: any;
70fda994 123 private _mouseMoveListener: EventListener;
ab40908f
DI
124 private _mouseDownListener: EventListener;
125 private _mouseUpListener: EventListener;
70fda994 126
ad3ae67e
DI
127 constructor(
128 private _terminal: ITerminal,
129 private _buffer: CircularList<any>,
130 private _rowContainer: HTMLElement,
ad3ae67e
DI
131 private _charMeasure: CharMeasure
132 ) {
b594407c 133 super();
ab40908f
DI
134 this._initListeners();
135 this.enable();
9f271de8 136
f7d6ab5f 137 this._model = new SelectionModel(_terminal);
9f271de8 138 this._lastMouseDownTime = 0;
320fb55d 139 this._activeSelectionMode = SelectionMode.NORMAL;
70fda994
DI
140 }
141
d0b603d0
DI
142 /**
143 * Initializes listener variables.
144 */
ab40908f
DI
145 private _initListeners() {
146 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
70fda994 147 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
ab40908f
DI
148 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
149 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
ab40908f 150 }
70fda994 151
ab40908f
DI
152 /**
153 * Disables the selection manager. This is useful for when terminal mouse
154 * are enabled.
155 */
156 public disable() {
4405f5e1 157 this.clearSelection();
ab40908f
DI
158 this._buffer.off('trim', this._bufferTrimListener);
159 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
ab40908f
DI
160 }
161
162 /**
163 * Enable the selection manager.
164 */
165 public enable() {
f380153f
DI
166 // Only adjust the selection on trim, shiftElements is rarely used (only in
167 // reverseIndex) and delete in a splice is only ever used when the same
168 // number of elements was just added. Given this is could actually be
169 // beneficial to leave the selection as is for these cases.
ab40908f
DI
170 this._buffer.on('trim', this._bufferTrimListener);
171 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
70fda994
DI
172 }
173
9a86eeb3
DI
174 /**
175 * Sets the active buffer, this should be called when the alt buffer is
176 * switched in or out.
177 * @param buffer The active buffer.
178 */
179 public setBuffer(buffer: CircularList<any>): void {
180 this._buffer = buffer;
181 }
182
1343b83f
DI
183 /**
184 * Gets whether there is an active text selection.
185 */
186 public get hasSelection(): boolean {
187 return !!this._model.finalSelectionStart && !!this._model.finalSelectionEnd;
188 }
189
9f271de8
DI
190 /**
191 * Gets the text currently selected.
192 */
70fda994 193 public get selectionText(): string {
f7d6ab5f
DI
194 const start = this._model.finalSelectionStart;
195 const end = this._model.finalSelectionEnd;
e29ab294 196 if (!start || !end) {
293ae18a 197 return '';
70fda994 198 }
43c796a7 199
43c796a7 200 // Get first row
293ae18a 201 const startRowEndCol = start[1] === end[1] ? end[0] : null;
32b34cbe 202 let result: string[] = [];
ec61f3ac 203 result.push(this._translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
43c796a7
DI
204
205 // Get middle rows
293ae18a 206 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
346b5177
DI
207 const bufferLine = this._buffer.get(i);
208 const lineText = this._translateBufferLineToString(bufferLine, true);
209 if (bufferLine.isWrapped) {
210 result[result.length - 1] += lineText;
211 } else {
212 result.push(lineText);
213 }
32b34cbe 214 }
43c796a7
DI
215
216 // Get final row
293ae18a 217 if (start[1] !== end[1]) {
346b5177
DI
218 const bufferLine = this._buffer.get(end[1]);
219 const lineText = this._translateBufferLineToString(bufferLine, true, 0, end[0]);
220 if (bufferLine.isWrapped) {
221 result[result.length - 1] += lineText;
222 } else {
223 result.push(lineText);
224 }
32b34cbe 225 }
2b243182 226
2012c8c9
DI
227 // Format string by replacing non-breaking space chars with regular spaces
228 // and joining the array into a multi-line string.
229 const formattedResult = result.map(line => {
230 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
231 }).join('\n');
232
233 return formattedResult;
32b34cbe
DI
234 }
235
5d33727a
DI
236 /**
237 * Clears the current terminal selection.
238 */
239 public clearSelection(): void {
4405f5e1 240 this._model.clearSelection();
5d33727a
DI
241 this._removeMouseDownListeners();
242 this.refresh();
243 }
244
d0b603d0
DI
245 /**
246 * Translates a buffer line to a string, with optional start and end columns.
247 * Wide characters will count as two columns in the resulting string. This
248 * function is useful for getting the actual text underneath the raw selection
249 * position.
250 * @param line The line being translated.
251 * @param trimRight Whether to trim whitespace to the right.
252 * @param startCol The column to start at.
253 * @param endCol The column to end at.
254 */
ec61f3ac 255 private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
32b34cbe 256 // TODO: This function should live in a buffer or buffer line class
ec61f3ac
DI
257
258 // Get full line
259 let lineString = '';
54e7f65d
DI
260 let widthAdjustedStartCol = startCol;
261 let widthAdjustedEndCol = endCol;
ec61f3ac 262 for (let i = 0; i < line.length; i++) {
54e7f65d
DI
263 const char = line[i];
264 lineString += char[LINE_DATA_CHAR_INDEX];
265 // Adjust start and end cols for wide characters if they affect their
266 // column indexes
267 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
268 if (startCol >= i) {
269 widthAdjustedStartCol--;
270 }
271 if (endCol >= i) {
272 widthAdjustedEndCol--;
273 }
274 }
ec61f3ac
DI
275 }
276
54e7f65d
DI
277 // Calculate the final end col by trimming whitespace on the right of the
278 // line if needed.
d3865ad2 279 let finalEndCol = widthAdjustedEndCol || line.length;
ec61f3ac
DI
280 if (trimRight) {
281 const rightWhitespaceIndex = lineString.search(/\s+$/);
a53a0acd
DI
282 if (rightWhitespaceIndex !== -1) {
283 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
284 }
ec61f3ac 285 // Return the empty string if only trimmed whitespace is selected
54e7f65d 286 if (finalEndCol <= widthAdjustedStartCol) {
ec61f3ac
DI
287 return '';
288 }
289 }
290
54e7f65d 291 return lineString.substring(widthAdjustedStartCol, finalEndCol);
70fda994
DI
292 }
293
207c4cf9 294 /**
13c401cb 295 * Queues a refresh, redrawing the selection on the next opportunity.
207c4cf9 296 */
8811d96a
DI
297 public refresh(fromMouseEvent?: boolean): void {
298 // Queue the refresh for the renderer
13c401cb
DI
299 if (!this._refreshAnimationFrame) {
300 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
301 }
8811d96a 302
dc165175
DI
303 // If the platform is Linux and the refresh call comes from a mouse event,
304 // we need to update the selection for middle click to paste selection.
305 if (Browser.isLinux && fromMouseEvent) {
306 const selectionText = this.selectionText;
307 if (selectionText.length) {
308 this.emit('newselection', this.selectionText);
309 }
8811d96a 310 }
13c401cb
DI
311 }
312
313 /**
314 * Fires the refresh event, causing consumers to pick it up and redraw the
315 * selection state.
316 */
317 private _refresh(): void {
318 this._refreshAnimationFrame = null;
f7d6ab5f 319 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
25152e44
DI
320 }
321
322 /**
323 * Selects all text within the terminal.
324 */
325 public selectAll(): void {
f7d6ab5f 326 this._model.isSelectAllActive = true;
25152e44 327 this.refresh();
207c4cf9
DI
328 }
329
330 /**
331 * Handle the buffer being trimmed, adjust the selection position.
332 * @param amount The amount the buffer is being trimmed.
333 */
70fda994 334 private _onTrim(amount: number) {
f7d6ab5f
DI
335 const needsRefresh = this._model.onTrim(amount);
336 if (needsRefresh) {
207c4cf9 337 this.refresh();
207c4cf9 338 }
70fda994
DI
339 }
340
d0b603d0
DI
341 /**
342 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
343 * @param event The mouse event.
344 */
0dc3dd03 345 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
b05814e6 346 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows, true);
ad3ae67e
DI
347 // Convert to 0-based
348 coords[0]--;
349 coords[1]--;
350 // Convert viewport coords to buffer coords
351 coords[1] += this._terminal.ydisp;
352 return coords;
b36d8780
DI
353 }
354
d0b603d0
DI
355 /**
356 * Gets the amount the viewport should be scrolled based on how far out of the
357 * terminal the mouse is.
358 * @param event The mouse event.
359 */
0dc3dd03
DI
360 private _getMouseEventScrollAmount(event: MouseEvent): number {
361 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
362 const terminalHeight = this._terminal.rows * this._charMeasure.height;
363 if (offset >= 0 && offset <= terminalHeight) {
364 return 0;
365 }
366 if (offset > terminalHeight) {
367 offset -= terminalHeight;
368 }
369
370 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
371 offset /= DRAG_SCROLL_MAX_THRESHOLD;
372 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
373 }
374
e63fdf58
DI
375 /**
376 * Handles te mousedown event, setting up for a new selection.
377 * @param event The mousedown event.
378 */
70fda994 379 private _onMouseDown(event: MouseEvent) {
0dc3dd03
DI
380 // Only action the primary button
381 if (event.button !== 0) {
382 return;
383 }
384
2a0f44b0
DI
385 // Tell the browser not to start a regular selection
386 event.preventDefault();
387
b8129910
DI
388 // Reset drag scroll state
389 this._dragScrollAmount = 0;
390
f380153f 391 this._setMouseClickCount(event);
9f271de8 392
db8ded2a
DI
393 if (event.shiftKey) {
394 this._onShiftClick(event);
395 } else {
396 if (this._clickCount === 1) {
397 this._onSingleClick(event);
398 } else if (this._clickCount === 2) {
399 this._onDoubleClick(event);
400 } else if (this._clickCount === 3) {
401 this._onTripleClick(event);
402 }
9f271de8 403 }
e29ab294 404
b8129910 405 this._addMouseDownListeners();
8811d96a 406 this.refresh(true);
b8129910
DI
407 }
408
409 /**
410 * Adds listeners when mousedown is triggered.
411 */
412 private _addMouseDownListeners(): void {
e29ab294
DI
413 // Listen on the document so that dragging outside of viewport works
414 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
415 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
2621be81 416 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
b8129910
DI
417 }
418
419 /**
420 * Removes the listeners that are registered when mousedown is triggered.
421 */
422 private _removeMouseDownListeners(): void {
423 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
424 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
425 clearInterval(this._dragScrollIntervalTimer);
426 this._dragScrollIntervalTimer = null;
9f271de8
DI
427 }
428
d0b603d0
DI
429 /**
430 * Performs a shift click, setting the selection end position to the mouse
431 * position.
432 * @param event The mouse event.
433 */
db8ded2a
DI
434 private _onShiftClick(event: MouseEvent): void {
435 if (this._model.selectionStart) {
436 this._model.selectionEnd = this._getMouseBufferCoords(event);
437 }
438 }
439
d0b603d0
DI
440 /**
441 * Performs a single click, resetting relevant state and setting the selection
442 * start position.
443 * @param event The mouse event.
444 */
9f271de8 445 private _onSingleClick(event: MouseEvent): void {
f7d6ab5f
DI
446 this._model.selectionStartLength = 0;
447 this._model.isSelectAllActive = false;
320fb55d 448 this._activeSelectionMode = SelectionMode.NORMAL;
f7d6ab5f
DI
449 this._model.selectionStart = this._getMouseBufferCoords(event);
450 if (this._model.selectionStart) {
451 this._model.selectionEnd = null;
54e7f65d
DI
452 // If the mouse is over the second half of a wide character, adjust the
453 // selection to cover the whole character
454 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
455 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
456 this._model.selectionStart[0]++;
457 }
70fda994
DI
458 }
459 }
460
d0b603d0
DI
461 /**
462 * Performs a double click, selecting the current work.
463 * @param event The mouse event.
464 */
9f271de8
DI
465 private _onDoubleClick(event: MouseEvent): void {
466 const coords = this._getMouseBufferCoords(event);
467 if (coords) {
320fb55d 468 this._activeSelectionMode = SelectionMode.WORD;
9f271de8
DI
469 this._selectWordAt(coords);
470 }
471 }
472
d0b603d0
DI
473 /**
474 * Performs a triple click, selecting the current line and activating line
475 * select mode.
476 * @param event The mouse event.
477 */
9f271de8
DI
478 private _onTripleClick(event: MouseEvent): void {
479 const coords = this._getMouseBufferCoords(event);
480 if (coords) {
320fb55d 481 this._activeSelectionMode = SelectionMode.LINE;
9f271de8
DI
482 this._selectLineAt(coords[1]);
483 }
484 }
485
d0b603d0
DI
486 /**
487 * Sets the number of clicks for the current mousedown event based on the time
488 * and position of the last mousedown event.
489 * @param event The mouse event.
490 */
f380153f 491 private _setMouseClickCount(event: MouseEvent): void {
9f271de8 492 let currentTime = (new Date()).getTime();
f380153f 493 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
9f271de8 494 this._clickCount = 0;
d3865ad2
DI
495 }
496 this._lastMouseDownTime = currentTime;
f380153f 497 this._lastMousePosition = [event.pageX, event.pageY];
9f271de8 498 this._clickCount++;
f380153f 499 }
9f271de8 500
d0b603d0
DI
501 /**
502 * Gets the maximum number of pixels in each direction the mouse has moved.
503 * @param event The mouse event.
504 */
f380153f
DI
505 private _distanceFromLastMousePosition(event: MouseEvent): number {
506 const result = Math.max(
507 Math.abs(this._lastMousePosition[0] - event.pageX),
508 Math.abs(this._lastMousePosition[1] - event.pageY));
509 return result;
9f271de8
DI
510 }
511
e63fdf58
DI
512 /**
513 * Handles the mousemove event when the mouse button is down, recording the
514 * end of the selection and refreshing the selection.
515 * @param event The mousemove event.
516 */
70fda994 517 private _onMouseMove(event: MouseEvent) {
2621be81
DI
518 // Record the previous position so we know whether to redraw the selection
519 // at the end.
520 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
521
522 // Set the initial selection end based on the mouse coordinates
523 this._model.selectionEnd = this._getMouseBufferCoords(event);
524
525 // Select the entire line if line select mode is active.
320fb55d 526 if (this._activeSelectionMode === SelectionMode.LINE) {
5bc11121
DI
527 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
528 this._model.selectionEnd[0] = 0;
529 } else {
530 this._model.selectionEnd[0] = this._terminal.cols;
531 }
320fb55d 532 } else if (this._activeSelectionMode === SelectionMode.WORD) {
4b170ca4
DI
533 this._selectToWordAt(this._model.selectionEnd);
534 }
535
2621be81 536 // Determine the amount of scrolling that will happen.
0dc3dd03 537 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
2621be81 538
0dc3dd03 539 // If the cursor was above or below the viewport, make sure it's at the
2621be81 540 // start or end of the viewport respectively.
0dc3dd03 541 if (this._dragScrollAmount > 0) {
f7d6ab5f 542 this._model.selectionEnd[0] = this._terminal.cols - 1;
0dc3dd03 543 } else if (this._dragScrollAmount < 0) {
f7d6ab5f 544 this._model.selectionEnd[0] = 0;
0dc3dd03 545 }
54e7f65d
DI
546
547 // If the character is a wide character include the cell to the right in the
5bc11121
DI
548 // selection. Note that selections at the very end of the line will never
549 // have a character.
71477874
DI
550 if (this._model.selectionEnd[1] < this._buffer.length) {
551 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
552 if (char && char[2] === 0) {
553 this._model.selectionEnd[0]++;
554 }
54e7f65d
DI
555 }
556
2621be81
DI
557 // Only draw here if the selection changes.
558 if (!previousSelectionEnd ||
559 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
560 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
dc165175 561 this.refresh(true);
2621be81 562 }
70fda994
DI
563 }
564
d0b603d0
DI
565 /**
566 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
567 * scrolling of the viewport.
568 */
0dc3dd03
DI
569 private _dragScroll() {
570 if (this._dragScrollAmount) {
571 this._terminal.scrollDisp(this._dragScrollAmount, false);
572 // Re-evaluate selection
573 if (this._dragScrollAmount > 0) {
f7d6ab5f 574 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
0dc3dd03 575 } else {
f7d6ab5f 576 this._model.selectionEnd = [0, this._terminal.ydisp];
0dc3dd03
DI
577 }
578 this.refresh();
579 }
580 }
581
e63fdf58 582 /**
b8129910 583 * Handles the mouseup event, removing the mousedown listeners.
e63fdf58
DI
584 * @param event The mouseup event.
585 */
70fda994 586 private _onMouseUp(event: MouseEvent) {
b8129910 587 this._removeMouseDownListeners();
70fda994 588 }
597c6939 589
cb6533f3
DI
590 /**
591 * Converts a viewport column to the character index on the buffer line, the
592 * latter takes into account wide characters.
d3865ad2 593 * @param coords The coordinates to find the 2 index for.
cb6533f3 594 */
11cec31d 595 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
cb6533f3 596 let charIndex = coords[0];
d9991b25 597 for (let i = 0; coords[0] >= i; i++) {
11cec31d 598 const char = bufferLine[i];
cb6533f3
DI
599 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
600 charIndex--;
601 }
602 }
603 return charIndex;
604 }
605
597c6939 606 /**
4b170ca4 607 * Gets positional information for the word at the coordinated specified.
597c6939
DI
608 * @param coords The coordinates to get the word at.
609 */
4b170ca4 610 private _getWordAt(coords: [number, number]): IWordPosition {
11cec31d
DI
611 const bufferLine = this._buffer.get(coords[1]);
612 const line = this._translateBufferLineToString(bufferLine, false);
cb6533f3
DI
613
614 // Get actual index, taking into consideration wide characters
11cec31d 615 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
cb6533f3 616 let startIndex = endIndex;
cb6533f3
DI
617
618 // Record offset to be used later
619 const charOffset = coords[0] - startIndex;
11cec31d
DI
620 let leftWideCharCount = 0;
621 let rightWideCharCount = 0;
cb6533f3 622
cb6533f3 623 if (line.charAt(startIndex) === ' ') {
11cec31d 624 // Expand until non-whitespace is hit
cb6533f3
DI
625 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
626 startIndex--;
627 }
628 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
629 endIndex++;
630 }
cb6533f3 631 } else {
11cec31d
DI
632 // Expand until whitespace is hit. This algorithm works by scanning left
633 // and right from the starting position, keeping both the index format
634 // (line) and the column format (bufferLine) in sync. When a wide
635 // character is hit, it is recorded and the column index is adjusted.
d9991b25
DI
636 let startCol = coords[0];
637 let endCol = coords[0];
638 // Consider the initial position, skip it and increment the wide char
639 // variable
11cec31d 640 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
d9991b25
DI
641 leftWideCharCount++;
642 startCol--;
643 }
11cec31d 644 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
d9991b25
DI
645 rightWideCharCount++;
646 endCol++;
647 }
cb6533f3 648 // Expand the string in both directions until a space is hit
7f2e94c3 649 while (startIndex > 0 && !this._isCharWordSeparator(line.charAt(startIndex - 1))) {
11cec31d
DI
650 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
651 // If the next character is a wide char, record it and skip the column
d9991b25
DI
652 leftWideCharCount++;
653 startCol--;
cb6533f3
DI
654 }
655 startIndex--;
d9991b25 656 startCol--;
cb6533f3 657 }
7f2e94c3 658 while (endIndex + 1 < line.length && !this._isCharWordSeparator(line.charAt(endIndex + 1))) {
11cec31d
DI
659 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
660 // If the next character is a wide char, record it and skip the column
d9991b25
DI
661 rightWideCharCount++;
662 endCol++;
cb6533f3
DI
663 }
664 endIndex++;
d9991b25 665 endCol++;
cb6533f3 666 }
597c6939 667 }
11cec31d 668
4b170ca4
DI
669 const start = startIndex + charOffset - leftWideCharCount;
670 const length = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
671 return {start, length};
672 }
673
674 /**
675 * Selects the word at the coordinates specified.
676 * @param coords The coordinates to get the word at.
677 */
678 protected _selectWordAt(coords: [number, number]): void {
679 const wordPosition = this._getWordAt(coords);
680 this._model.selectionStart = [wordPosition.start, coords[1]];
681 this._model.selectionStartLength = wordPosition.length;
682 }
683
684 /**
685 * Sets the selection end to the word at the coordinated specified.
686 * @param coords The coordinates to get the word at.
687 */
688 private _selectToWordAt(coords: [number, number]): void {
689 const wordPosition = this._getWordAt(coords);
690 this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
597c6939 691 }
9f271de8 692
7f2e94c3
DI
693 /**
694 * Gets whether the character is considered a word separator by the select
695 * word logic.
696 * @param char The character to check.
697 */
698 private _isCharWordSeparator(char: string): boolean {
699 return WORD_SEPARATORS.indexOf(char) >= 0;
700 }
701
d0b603d0
DI
702 /**
703 * Selects the line specified.
704 * @param line The line index.
705 */
fd91c5e1 706 protected _selectLineAt(line: number): void {
f7d6ab5f
DI
707 this._model.selectionStart = [0, line];
708 this._model.selectionStartLength = this._terminal.cols;
9f271de8 709 }
70fda994 710}