Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/editor/browser/controller/editContext/textArea/textAreaEditContext.ts
3296 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import './textAreaEditContext.css';
7
import * as nls from '../../../../../nls.js';
8
import * as browser from '../../../../../base/browser/browser.js';
9
import { FastDomNode, createFastDomNode } from '../../../../../base/browser/fastDomNode.js';
10
import { IKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js';
11
import * as platform from '../../../../../base/common/platform.js';
12
import * as strings from '../../../../../base/common/strings.js';
13
import { applyFontInfo } from '../../../config/domFontInfo.js';
14
import { ViewController } from '../../../view/viewController.js';
15
import { PartFingerprint, PartFingerprints } from '../../../view/viewPart.js';
16
import { LineNumbersOverlay } from '../../../viewParts/lineNumbers/lineNumbers.js';
17
import { Margin } from '../../../viewParts/margin/margin.js';
18
import { RenderLineNumbersType, EditorOption, IComputedEditorOptions, EditorOptions } from '../../../../common/config/editorOptions.js';
19
import { FontInfo } from '../../../../common/config/fontInfo.js';
20
import { Position } from '../../../../common/core/position.js';
21
import { Range } from '../../../../common/core/range.js';
22
import { Selection } from '../../../../common/core/selection.js';
23
import { ScrollType } from '../../../../common/editorCommon.js';
24
import { EndOfLinePreference } from '../../../../common/model.js';
25
import { RenderingContext, RestrictedRenderingContext, HorizontalPosition, LineVisibleRanges } from '../../../view/renderingContext.js';
26
import { ViewContext } from '../../../../common/viewModel/viewContext.js';
27
import * as viewEvents from '../../../../common/viewEvents.js';
28
import { AccessibilitySupport } from '../../../../../platform/accessibility/common/accessibility.js';
29
import { IEditorAriaOptions } from '../../../editorBrowser.js';
30
import { MOUSE_CURSOR_TEXT_CSS_CLASS_NAME } from '../../../../../base/browser/ui/mouseCursor/mouseCursor.js';
31
import { TokenizationRegistry } from '../../../../common/languages.js';
32
import { ColorId, ITokenPresentation } from '../../../../common/encodedTokenAttributes.js';
33
import { Color } from '../../../../../base/common/color.js';
34
import { IME } from '../../../../../base/common/ime.js';
35
import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js';
36
import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js';
37
import { AbstractEditContext } from '../editContext.js';
38
import { ICompositionData, IPasteData, ITextAreaInputHost, TextAreaInput, TextAreaWrapper } from './textAreaEditContextInput.js';
39
import { ariaLabelForScreenReaderContent, newlinecount, SimplePagedScreenReaderStrategy } from '../screenReaderUtils.js';
40
import { ClipboardDataToCopy, getDataToCopy } from '../clipboardUtils.js';
41
import { _debugComposition, ITypeData, TextAreaState } from './textAreaEditContextState.js';
42
import { getMapForWordSeparators, WordCharacterClass } from '../../../../common/core/wordCharacterClassifier.js';
43
44
export interface IVisibleRangeProvider {
45
visibleRangeForPosition(position: Position): HorizontalPosition | null;
46
linesVisibleRangesForRange(range: Range, includeNewLines: boolean): LineVisibleRanges[] | null;
47
}
48
49
class VisibleTextAreaData {
50
_visibleTextAreaBrand: void = undefined;
51
52
public startPosition: Position | null = null;
53
public endPosition: Position | null = null;
54
55
public visibleTextareaStart: HorizontalPosition | null = null;
56
public visibleTextareaEnd: HorizontalPosition | null = null;
57
58
/**
59
* When doing composition, the currently composed text might be split up into
60
* multiple tokens, then merged again into a single token, etc. Here we attempt
61
* to keep the presentation of the <textarea> stable by using the previous used
62
* style if multiple tokens come into play. This avoids flickering.
63
*/
64
private _previousPresentation: ITokenPresentation | null = null;
65
66
constructor(
67
private readonly _context: ViewContext,
68
public readonly modelLineNumber: number,
69
public readonly distanceToModelLineStart: number,
70
public readonly widthOfHiddenLineTextBefore: number,
71
public readonly distanceToModelLineEnd: number,
72
) {
73
}
74
75
prepareRender(visibleRangeProvider: IVisibleRangeProvider): void {
76
const startModelPosition = new Position(this.modelLineNumber, this.distanceToModelLineStart + 1);
77
const endModelPosition = new Position(this.modelLineNumber, this._context.viewModel.model.getLineMaxColumn(this.modelLineNumber) - this.distanceToModelLineEnd);
78
79
this.startPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(startModelPosition);
80
this.endPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(endModelPosition);
81
82
if (this.startPosition.lineNumber === this.endPosition.lineNumber) {
83
this.visibleTextareaStart = visibleRangeProvider.visibleRangeForPosition(this.startPosition);
84
this.visibleTextareaEnd = visibleRangeProvider.visibleRangeForPosition(this.endPosition);
85
} else {
86
// TODO: what if the view positions are not on the same line?
87
this.visibleTextareaStart = null;
88
this.visibleTextareaEnd = null;
89
}
90
}
91
92
definePresentation(tokenPresentation: ITokenPresentation | null): ITokenPresentation {
93
if (!this._previousPresentation) {
94
// To avoid flickering, once set, always reuse a presentation throughout the entire IME session
95
if (tokenPresentation) {
96
this._previousPresentation = tokenPresentation;
97
} else {
98
this._previousPresentation = {
99
foreground: ColorId.DefaultForeground,
100
italic: false,
101
bold: false,
102
underline: false,
103
strikethrough: false,
104
};
105
}
106
}
107
return this._previousPresentation;
108
}
109
}
110
111
const canUseZeroSizeTextarea = (browser.isFirefox);
112
113
export class TextAreaEditContext extends AbstractEditContext {
114
115
private readonly _viewController: ViewController;
116
private readonly _visibleRangeProvider: IVisibleRangeProvider;
117
private _scrollLeft: number;
118
private _scrollTop: number;
119
120
private _accessibilitySupport!: AccessibilitySupport;
121
private _accessibilityPageSize!: number;
122
private _textAreaWrapping!: boolean;
123
private _textAreaWidth!: number;
124
private _contentLeft: number;
125
private _contentWidth: number;
126
private _contentHeight: number;
127
private _fontInfo: FontInfo;
128
private _emptySelectionClipboard: boolean;
129
private _copyWithSyntaxHighlighting: boolean;
130
131
/**
132
* Defined only when the text area is visible (composition case).
133
*/
134
private _visibleTextArea: VisibleTextAreaData | null;
135
private _selections: Selection[];
136
private _modelSelections: Selection[];
137
138
/**
139
* The position at which the textarea was rendered.
140
* This is useful for hit-testing and determining the mouse position.
141
*/
142
private _lastRenderPosition: Position | null;
143
144
public readonly textArea: FastDomNode<HTMLTextAreaElement>;
145
public readonly textAreaCover: FastDomNode<HTMLElement>;
146
private readonly _textAreaInput: TextAreaInput;
147
148
constructor(
149
context: ViewContext,
150
overflowGuardContainer: FastDomNode<HTMLElement>,
151
viewController: ViewController,
152
visibleRangeProvider: IVisibleRangeProvider,
153
@IKeybindingService private readonly _keybindingService: IKeybindingService,
154
@IInstantiationService private readonly _instantiationService: IInstantiationService
155
) {
156
super(context);
157
158
this._viewController = viewController;
159
this._visibleRangeProvider = visibleRangeProvider;
160
this._scrollLeft = 0;
161
this._scrollTop = 0;
162
163
const options = this._context.configuration.options;
164
const layoutInfo = options.get(EditorOption.layoutInfo);
165
166
this._setAccessibilityOptions(options);
167
this._contentLeft = layoutInfo.contentLeft;
168
this._contentWidth = layoutInfo.contentWidth;
169
this._contentHeight = layoutInfo.height;
170
this._fontInfo = options.get(EditorOption.fontInfo);
171
this._emptySelectionClipboard = options.get(EditorOption.emptySelectionClipboard);
172
this._copyWithSyntaxHighlighting = options.get(EditorOption.copyWithSyntaxHighlighting);
173
174
this._visibleTextArea = null;
175
this._selections = [new Selection(1, 1, 1, 1)];
176
this._modelSelections = [new Selection(1, 1, 1, 1)];
177
this._lastRenderPosition = null;
178
179
// Text Area (The focus will always be in the textarea when the cursor is blinking)
180
this.textArea = createFastDomNode(document.createElement('textarea'));
181
PartFingerprints.write(this.textArea, PartFingerprint.TextArea);
182
this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
183
this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');
184
const { tabSize } = this._context.viewModel.model.getOptions();
185
this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;
186
this.textArea.setAttribute('autocorrect', 'off');
187
this.textArea.setAttribute('autocapitalize', 'off');
188
this.textArea.setAttribute('autocomplete', 'off');
189
this.textArea.setAttribute('spellcheck', 'false');
190
this.textArea.setAttribute('aria-label', ariaLabelForScreenReaderContent(options, this._keybindingService));
191
this.textArea.setAttribute('aria-required', options.get(EditorOption.ariaRequired) ? 'true' : 'false');
192
this.textArea.setAttribute('tabindex', String(options.get(EditorOption.tabIndex)));
193
this.textArea.setAttribute('role', 'textbox');
194
this.textArea.setAttribute('aria-roledescription', nls.localize('editor', "editor"));
195
this.textArea.setAttribute('aria-multiline', 'true');
196
this.textArea.setAttribute('aria-autocomplete', options.get(EditorOption.readOnly) ? 'none' : 'both');
197
198
this._ensureReadOnlyAttribute();
199
200
this.textAreaCover = createFastDomNode(document.createElement('div'));
201
this.textAreaCover.setPosition('absolute');
202
203
overflowGuardContainer.appendChild(this.textArea);
204
overflowGuardContainer.appendChild(this.textAreaCover);
205
206
const simplePagedScreenReaderStrategy = new SimplePagedScreenReaderStrategy();
207
const textAreaInputHost: ITextAreaInputHost = {
208
getDataToCopy: (): ClipboardDataToCopy => {
209
return getDataToCopy(this._context.viewModel, this._modelSelections, this._emptySelectionClipboard, this._copyWithSyntaxHighlighting);
210
},
211
getScreenReaderContent: (): TextAreaState => {
212
if (this._accessibilitySupport === AccessibilitySupport.Disabled) {
213
// We know for a fact that a screen reader is not attached
214
// On OSX, we write the character before the cursor to allow for "long-press" composition
215
// Also on OSX, we write the word before the cursor to allow for the Accessibility Keyboard to give good hints
216
const selection = this._selections[0];
217
if (platform.isMacintosh && selection.isEmpty()) {
218
const position = selection.getStartPosition();
219
220
let textBefore = this._getWordBeforePosition(position);
221
if (textBefore.length === 0) {
222
textBefore = this._getCharacterBeforePosition(position);
223
}
224
225
if (textBefore.length > 0) {
226
return new TextAreaState(textBefore, textBefore.length, textBefore.length, Range.fromPositions(position), 0);
227
}
228
}
229
// on macOS, write current selection into textarea will allow system text services pick selected text,
230
// but we still want to limit the amount of text given Chromium handles very poorly text even of a few
231
// thousand chars
232
// (https://github.com/microsoft/vscode/issues/27799)
233
const LIMIT_CHARS = 500;
234
if (platform.isMacintosh && !selection.isEmpty() && this._context.viewModel.getValueLengthInRange(selection, EndOfLinePreference.TextDefined) < LIMIT_CHARS) {
235
const text = this._context.viewModel.getValueInRange(selection, EndOfLinePreference.TextDefined);
236
return new TextAreaState(text, 0, text.length, selection, 0);
237
}
238
239
// on Safari, document.execCommand('cut') and document.execCommand('copy') will just not work
240
// if the textarea has no content selected. So if there is an editor selection, ensure something
241
// is selected in the textarea.
242
if (browser.isSafari && !selection.isEmpty()) {
243
const placeholderText = 'vscode-placeholder';
244
return new TextAreaState(placeholderText, 0, placeholderText.length, null, undefined);
245
}
246
247
return TextAreaState.EMPTY;
248
}
249
250
if (browser.isAndroid) {
251
// when tapping in the editor on a word, Android enters composition mode.
252
// in the `compositionstart` event we cannot clear the textarea, because
253
// it then forgets to ever send a `compositionend`.
254
// we therefore only write the current word in the textarea
255
const selection = this._selections[0];
256
if (selection.isEmpty()) {
257
const position = selection.getStartPosition();
258
const [wordAtPosition, positionOffsetInWord] = this._getAndroidWordAtPosition(position);
259
if (wordAtPosition.length > 0) {
260
return new TextAreaState(wordAtPosition, positionOffsetInWord, positionOffsetInWord, Range.fromPositions(position), 0);
261
}
262
}
263
return TextAreaState.EMPTY;
264
}
265
266
const screenReaderContentState = simplePagedScreenReaderStrategy.fromEditorSelection(this._context.viewModel, this._selections[0], this._accessibilityPageSize, this._accessibilitySupport === AccessibilitySupport.Unknown);
267
return TextAreaState.fromScreenReaderContentState(screenReaderContentState);
268
},
269
270
deduceModelPosition: (viewAnchorPosition: Position, deltaOffset: number, lineFeedCnt: number): Position => {
271
return this._context.viewModel.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);
272
}
273
};
274
275
const textAreaWrapper = this._register(new TextAreaWrapper(this.textArea.domNode));
276
this._textAreaInput = this._register(this._instantiationService.createInstance(TextAreaInput, textAreaInputHost, textAreaWrapper, platform.OS, {
277
isAndroid: browser.isAndroid,
278
isChrome: browser.isChrome,
279
isFirefox: browser.isFirefox,
280
isSafari: browser.isSafari,
281
}));
282
283
this._register(this._textAreaInput.onKeyDown((e: IKeyboardEvent) => {
284
this._viewController.emitKeyDown(e);
285
}));
286
287
this._register(this._textAreaInput.onKeyUp((e: IKeyboardEvent) => {
288
this._viewController.emitKeyUp(e);
289
}));
290
291
this._register(this._textAreaInput.onPaste((e: IPasteData) => {
292
let pasteOnNewLine = false;
293
let multicursorText: string[] | null = null;
294
let mode: string | null = null;
295
if (e.metadata) {
296
pasteOnNewLine = (this._emptySelectionClipboard && !!e.metadata.isFromEmptySelection);
297
multicursorText = (typeof e.metadata.multicursorText !== 'undefined' ? e.metadata.multicursorText : null);
298
mode = e.metadata.mode;
299
}
300
this._viewController.paste(e.text, pasteOnNewLine, multicursorText, mode);
301
}));
302
303
this._register(this._textAreaInput.onCut(() => {
304
this._viewController.cut();
305
}));
306
307
this._register(this._textAreaInput.onType((e: ITypeData) => {
308
if (e.replacePrevCharCnt || e.replaceNextCharCnt || e.positionDelta) {
309
// must be handled through the new command
310
if (_debugComposition) {
311
console.log(` => compositionType: <<${e.text}>>, ${e.replacePrevCharCnt}, ${e.replaceNextCharCnt}, ${e.positionDelta}`);
312
}
313
this._viewController.compositionType(e.text, e.replacePrevCharCnt, e.replaceNextCharCnt, e.positionDelta);
314
} else {
315
if (_debugComposition) {
316
console.log(` => type: <<${e.text}>>`);
317
}
318
this._viewController.type(e.text);
319
}
320
}));
321
322
this._register(this._textAreaInput.onSelectionChangeRequest((modelSelection: Selection) => {
323
this._viewController.setSelection(modelSelection);
324
}));
325
326
this._register(this._textAreaInput.onCompositionStart((e) => {
327
328
// The textarea might contain some content when composition starts.
329
//
330
// When we make the textarea visible, it always has a height of 1 line,
331
// so we don't need to worry too much about content on lines above or below
332
// the selection.
333
//
334
// However, the text on the current line needs to be made visible because
335
// some IME methods allow to move to other glyphs on the current line
336
// (by pressing arrow keys).
337
//
338
// (1) The textarea might contain only some parts of the current line,
339
// like the word before the selection. Also, the content inside the textarea
340
// can grow or shrink as composition occurs. We therefore anchor the textarea
341
// in terms of distance to a certain line start and line end.
342
//
343
// (2) Also, we should not make \t characters visible, because their rendering
344
// inside the <textarea> will not align nicely with our rendering. We therefore
345
// will hide (if necessary) some of the leading text on the current line.
346
347
const ta = this.textArea.domNode;
348
const modelSelection = this._modelSelections[0];
349
350
const { distanceToModelLineStart, widthOfHiddenTextBefore } = (() => {
351
// Find the text that is on the current line before the selection
352
const textBeforeSelection = ta.value.substring(0, Math.min(ta.selectionStart, ta.selectionEnd));
353
const lineFeedOffset1 = textBeforeSelection.lastIndexOf('\n');
354
const lineTextBeforeSelection = textBeforeSelection.substring(lineFeedOffset1 + 1);
355
356
// We now search to see if we should hide some part of it (if it contains \t)
357
const tabOffset1 = lineTextBeforeSelection.lastIndexOf('\t');
358
const desiredVisibleBeforeCharCount = lineTextBeforeSelection.length - tabOffset1 - 1;
359
const startModelPosition = modelSelection.getStartPosition();
360
const visibleBeforeCharCount = Math.min(startModelPosition.column - 1, desiredVisibleBeforeCharCount);
361
const distanceToModelLineStart = startModelPosition.column - 1 - visibleBeforeCharCount;
362
const hiddenLineTextBefore = lineTextBeforeSelection.substring(0, lineTextBeforeSelection.length - visibleBeforeCharCount);
363
const { tabSize } = this._context.viewModel.model.getOptions();
364
const widthOfHiddenTextBefore = measureText(this.textArea.domNode.ownerDocument, hiddenLineTextBefore, this._fontInfo, tabSize);
365
366
return { distanceToModelLineStart, widthOfHiddenTextBefore };
367
})();
368
369
const { distanceToModelLineEnd } = (() => {
370
// Find the text that is on the current line after the selection
371
const textAfterSelection = ta.value.substring(Math.max(ta.selectionStart, ta.selectionEnd));
372
const lineFeedOffset2 = textAfterSelection.indexOf('\n');
373
const lineTextAfterSelection = lineFeedOffset2 === -1 ? textAfterSelection : textAfterSelection.substring(0, lineFeedOffset2);
374
375
const tabOffset2 = lineTextAfterSelection.indexOf('\t');
376
const desiredVisibleAfterCharCount = (tabOffset2 === -1 ? lineTextAfterSelection.length : lineTextAfterSelection.length - tabOffset2 - 1);
377
const endModelPosition = modelSelection.getEndPosition();
378
const visibleAfterCharCount = Math.min(this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column, desiredVisibleAfterCharCount);
379
const distanceToModelLineEnd = this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column - visibleAfterCharCount;
380
381
return { distanceToModelLineEnd };
382
})();
383
384
// Scroll to reveal the location in the editor where composition occurs
385
this._context.viewModel.revealRange(
386
'keyboard',
387
true,
388
Range.fromPositions(this._selections[0].getStartPosition()),
389
viewEvents.VerticalRevealType.Simple,
390
ScrollType.Immediate
391
);
392
393
this._visibleTextArea = new VisibleTextAreaData(
394
this._context,
395
modelSelection.startLineNumber,
396
distanceToModelLineStart,
397
widthOfHiddenTextBefore,
398
distanceToModelLineEnd,
399
);
400
401
// We turn off wrapping if the <textarea> becomes visible for composition
402
this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');
403
404
this._visibleTextArea.prepareRender(this._visibleRangeProvider);
405
this._render();
406
407
// Show the textarea
408
this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ime-input`);
409
410
this._viewController.compositionStart();
411
this._context.viewModel.onCompositionStart();
412
}));
413
414
this._register(this._textAreaInput.onCompositionUpdate((e: ICompositionData) => {
415
if (!this._visibleTextArea) {
416
return;
417
}
418
419
this._visibleTextArea.prepareRender(this._visibleRangeProvider);
420
this._render();
421
}));
422
423
this._register(this._textAreaInput.onCompositionEnd(() => {
424
425
this._visibleTextArea = null;
426
427
// We turn on wrapping as necessary if the <textarea> hides after composition
428
this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');
429
430
this._render();
431
432
this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
433
this._viewController.compositionEnd();
434
this._context.viewModel.onCompositionEnd();
435
}));
436
437
this._register(this._textAreaInput.onFocus(() => {
438
this._context.viewModel.setHasFocus(true);
439
}));
440
441
this._register(this._textAreaInput.onBlur(() => {
442
this._context.viewModel.setHasFocus(false);
443
}));
444
445
this._register(IME.onDidChange(() => {
446
this._ensureReadOnlyAttribute();
447
}));
448
}
449
450
public get domNode() {
451
return this.textArea;
452
}
453
454
public writeScreenReaderContent(reason: string): void {
455
this._textAreaInput.writeNativeTextAreaContent(reason);
456
}
457
458
public getTextAreaDomNode(): HTMLTextAreaElement {
459
return this.textArea.domNode;
460
}
461
462
public override dispose(): void {
463
super.dispose();
464
this.textArea.domNode.remove();
465
this.textAreaCover.domNode.remove();
466
}
467
468
private _getAndroidWordAtPosition(position: Position): [string, number] {
469
const ANDROID_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:",.<>/?';
470
const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
471
const wordSeparators = getMapForWordSeparators(ANDROID_WORD_SEPARATORS, []);
472
473
let goingLeft = true;
474
let startColumn = position.column;
475
let goingRight = true;
476
let endColumn = position.column;
477
let distance = 0;
478
while (distance < 50 && (goingLeft || goingRight)) {
479
if (goingLeft && startColumn <= 1) {
480
goingLeft = false;
481
}
482
if (goingLeft) {
483
const charCode = lineContent.charCodeAt(startColumn - 2);
484
const charClass = wordSeparators.get(charCode);
485
if (charClass !== WordCharacterClass.Regular) {
486
goingLeft = false;
487
} else {
488
startColumn--;
489
}
490
}
491
if (goingRight && endColumn > lineContent.length) {
492
goingRight = false;
493
}
494
if (goingRight) {
495
const charCode = lineContent.charCodeAt(endColumn - 1);
496
const charClass = wordSeparators.get(charCode);
497
if (charClass !== WordCharacterClass.Regular) {
498
goingRight = false;
499
} else {
500
endColumn++;
501
}
502
}
503
distance++;
504
}
505
506
return [lineContent.substring(startColumn - 1, endColumn - 1), position.column - startColumn];
507
}
508
509
private _getWordBeforePosition(position: Position): string {
510
const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
511
const wordSeparators = getMapForWordSeparators(this._context.configuration.options.get(EditorOption.wordSeparators), []);
512
513
let column = position.column;
514
let distance = 0;
515
while (column > 1) {
516
const charCode = lineContent.charCodeAt(column - 2);
517
const charClass = wordSeparators.get(charCode);
518
if (charClass !== WordCharacterClass.Regular || distance > 50) {
519
return lineContent.substring(column - 1, position.column - 1);
520
}
521
distance++;
522
column--;
523
}
524
return lineContent.substring(0, position.column - 1);
525
}
526
527
private _getCharacterBeforePosition(position: Position): string {
528
if (position.column > 1) {
529
const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
530
const charBefore = lineContent.charAt(position.column - 2);
531
if (!strings.isHighSurrogate(charBefore.charCodeAt(0))) {
532
return charBefore;
533
}
534
}
535
return '';
536
}
537
538
private _setAccessibilityOptions(options: IComputedEditorOptions): void {
539
this._accessibilitySupport = options.get(EditorOption.accessibilitySupport);
540
const accessibilityPageSize = options.get(EditorOption.accessibilityPageSize);
541
if (this._accessibilitySupport === AccessibilitySupport.Enabled && accessibilityPageSize === EditorOptions.accessibilityPageSize.defaultValue) {
542
// If a screen reader is attached and the default value is not set we should automatically increase the page size to 500 for a better experience
543
this._accessibilityPageSize = 500;
544
} else {
545
this._accessibilityPageSize = accessibilityPageSize;
546
}
547
548
// When wrapping is enabled and a screen reader might be attached,
549
// we will size the textarea to match the width used for wrapping points computation (see `domLineBreaksComputer.ts`).
550
// This is because screen readers will read the text in the textarea and we'd like that the
551
// wrapping points in the textarea match the wrapping points in the editor.
552
const layoutInfo = options.get(EditorOption.layoutInfo);
553
const wrappingColumn = layoutInfo.wrappingColumn;
554
if (wrappingColumn !== -1 && this._accessibilitySupport !== AccessibilitySupport.Disabled) {
555
const fontInfo = options.get(EditorOption.fontInfo);
556
this._textAreaWrapping = true;
557
this._textAreaWidth = Math.round(wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
558
} else {
559
this._textAreaWrapping = false;
560
this._textAreaWidth = (canUseZeroSizeTextarea ? 0 : 1);
561
}
562
}
563
564
// --- begin event handlers
565
566
public override onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {
567
const options = this._context.configuration.options;
568
const layoutInfo = options.get(EditorOption.layoutInfo);
569
570
this._setAccessibilityOptions(options);
571
this._contentLeft = layoutInfo.contentLeft;
572
this._contentWidth = layoutInfo.contentWidth;
573
this._contentHeight = layoutInfo.height;
574
this._fontInfo = options.get(EditorOption.fontInfo);
575
this._emptySelectionClipboard = options.get(EditorOption.emptySelectionClipboard);
576
this._copyWithSyntaxHighlighting = options.get(EditorOption.copyWithSyntaxHighlighting);
577
this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');
578
const { tabSize } = this._context.viewModel.model.getOptions();
579
this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;
580
this.textArea.setAttribute('aria-label', ariaLabelForScreenReaderContent(options, this._keybindingService));
581
this.textArea.setAttribute('aria-required', options.get(EditorOption.ariaRequired) ? 'true' : 'false');
582
this.textArea.setAttribute('tabindex', String(options.get(EditorOption.tabIndex)));
583
584
if (e.hasChanged(EditorOption.domReadOnly) || e.hasChanged(EditorOption.readOnly)) {
585
this._ensureReadOnlyAttribute();
586
}
587
588
if (e.hasChanged(EditorOption.accessibilitySupport)) {
589
this._textAreaInput.writeNativeTextAreaContent('strategy changed');
590
}
591
592
return true;
593
}
594
public override onCursorStateChanged(e: viewEvents.ViewCursorStateChangedEvent): boolean {
595
this._selections = e.selections.slice(0);
596
this._modelSelections = e.modelSelections.slice(0);
597
// We must update the <textarea> synchronously, otherwise long press IME on macos breaks.
598
// See https://github.com/microsoft/vscode/issues/165821
599
this._textAreaInput.writeNativeTextAreaContent('selection changed');
600
return true;
601
}
602
public override onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean {
603
// true for inline decorations that can end up relayouting text
604
return true;
605
}
606
public override onFlushed(e: viewEvents.ViewFlushedEvent): boolean {
607
return true;
608
}
609
public override onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {
610
return true;
611
}
612
public override onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean {
613
return true;
614
}
615
public override onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean {
616
return true;
617
}
618
public override onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {
619
this._scrollLeft = e.scrollLeft;
620
this._scrollTop = e.scrollTop;
621
return true;
622
}
623
public override onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean {
624
return true;
625
}
626
627
// --- end event handlers
628
629
// --- begin view API
630
631
public isFocused(): boolean {
632
return this._textAreaInput.isFocused();
633
}
634
635
public focus(): void {
636
this._textAreaInput.focusTextArea();
637
}
638
639
public refreshFocusState() {
640
this._textAreaInput.refreshFocusState();
641
}
642
643
public getLastRenderData(): Position | null {
644
return this._lastRenderPosition;
645
}
646
647
public setAriaOptions(options: IEditorAriaOptions): void {
648
if (options.activeDescendant) {
649
this.textArea.setAttribute('aria-haspopup', 'true');
650
this.textArea.setAttribute('aria-autocomplete', 'list');
651
this.textArea.setAttribute('aria-activedescendant', options.activeDescendant);
652
} else {
653
this.textArea.setAttribute('aria-haspopup', 'false');
654
this.textArea.setAttribute('aria-autocomplete', 'both');
655
this.textArea.removeAttribute('aria-activedescendant');
656
}
657
if (options.role) {
658
this.textArea.setAttribute('role', options.role);
659
}
660
}
661
662
// --- end view API
663
664
private _ensureReadOnlyAttribute(): void {
665
const options = this._context.configuration.options;
666
// When someone requests to disable IME, we set the "readonly" attribute on the <textarea>.
667
// This will prevent composition.
668
const useReadOnly = !IME.enabled || (options.get(EditorOption.domReadOnly) && options.get(EditorOption.readOnly));
669
if (useReadOnly) {
670
this.textArea.setAttribute('readonly', 'true');
671
} else {
672
this.textArea.removeAttribute('readonly');
673
}
674
}
675
676
private _primaryCursorPosition: Position = new Position(1, 1);
677
private _primaryCursorVisibleRange: HorizontalPosition | null = null;
678
679
public prepareRender(ctx: RenderingContext): void {
680
this._primaryCursorPosition = new Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn);
681
this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primaryCursorPosition);
682
this._visibleTextArea?.prepareRender(ctx);
683
}
684
685
public render(ctx: RestrictedRenderingContext): void {
686
this._textAreaInput.writeNativeTextAreaContent('render');
687
this._render();
688
}
689
690
private _render(): void {
691
if (this._visibleTextArea) {
692
// The text area is visible for composition reasons
693
694
const visibleStart = this._visibleTextArea.visibleTextareaStart;
695
const visibleEnd = this._visibleTextArea.visibleTextareaEnd;
696
const startPosition = this._visibleTextArea.startPosition;
697
const endPosition = this._visibleTextArea.endPosition;
698
if (startPosition && endPosition && visibleStart && visibleEnd && visibleEnd.left >= this._scrollLeft && visibleStart.left <= this._scrollLeft + this._contentWidth) {
699
const top = (this._context.viewLayout.getVerticalOffsetForLineNumber(this._primaryCursorPosition.lineNumber) - this._scrollTop);
700
const lineCount = newlinecount(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));
701
702
let scrollLeft = this._visibleTextArea.widthOfHiddenLineTextBefore;
703
let left = (this._contentLeft + visibleStart.left - this._scrollLeft);
704
// See https://github.com/microsoft/vscode/issues/141725#issuecomment-1050670841
705
// Here we are adding +1 to avoid flickering that might be caused by having a width that is too small.
706
// This could be caused by rounding errors that might only show up with certain font families.
707
// In other words, a pixel might be lost when doing something like
708
// `Math.round(end) - Math.round(start)`
709
// vs
710
// `Math.round(end - start)`
711
let width = visibleEnd.left - visibleStart.left + 1;
712
if (left < this._contentLeft) {
713
// the textarea would be rendered on top of the margin,
714
// so reduce its width. We use the same technique as
715
// for hiding text before
716
const delta = (this._contentLeft - left);
717
left += delta;
718
scrollLeft += delta;
719
width -= delta;
720
}
721
if (width > this._contentWidth) {
722
// the textarea would be wider than the content width,
723
// so reduce its width.
724
width = this._contentWidth;
725
}
726
727
// Try to render the textarea with the color/font style to match the text under it
728
const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(startPosition.lineNumber);
729
const fontSize = this._context.viewModel.getFontSizeAtPosition(this._primaryCursorPosition);
730
const viewLineData = this._context.viewModel.getViewLineData(startPosition.lineNumber);
731
const startTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(startPosition.column - 1);
732
const endTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(endPosition.column - 1);
733
const textareaSpansSingleToken = (startTokenIndex === endTokenIndex);
734
const presentation = this._visibleTextArea.definePresentation(
735
(textareaSpansSingleToken ? viewLineData.tokens.getPresentation(startTokenIndex) : null)
736
);
737
738
this.textArea.domNode.scrollTop = lineCount * lineHeight;
739
this.textArea.domNode.scrollLeft = scrollLeft;
740
741
this._doRender({
742
lastRenderPosition: null,
743
top: top,
744
left: left,
745
width: width,
746
height: lineHeight,
747
useCover: false,
748
color: (TokenizationRegistry.getColorMap() || [])[presentation.foreground],
749
italic: presentation.italic,
750
bold: presentation.bold,
751
underline: presentation.underline,
752
strikethrough: presentation.strikethrough,
753
fontSize
754
});
755
}
756
return;
757
}
758
759
if (!this._primaryCursorVisibleRange) {
760
// The primary cursor is outside the viewport => place textarea to the top left
761
this._renderAtTopLeft();
762
return;
763
}
764
765
const left = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft;
766
if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) {
767
// cursor is outside the viewport
768
this._renderAtTopLeft();
769
return;
770
}
771
772
const top = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop;
773
if (top < 0 || top > this._contentHeight) {
774
// cursor is outside the viewport
775
this._renderAtTopLeft();
776
return;
777
}
778
779
// The primary cursor is in the viewport (at least vertically) => place textarea on the cursor
780
781
if (platform.isMacintosh || this._accessibilitySupport === AccessibilitySupport.Enabled) {
782
// For the popup emoji input, we will make the text area as high as the line height
783
// We will also make the fontSize and lineHeight the correct dimensions to help with the placement of these pickers
784
const lineNumber = this._primaryCursorPosition.lineNumber;
785
const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(lineNumber);
786
this._doRender({
787
lastRenderPosition: this._primaryCursorPosition,
788
top,
789
left: this._textAreaWrapping ? this._contentLeft : left,
790
width: this._textAreaWidth,
791
height: lineHeight,
792
useCover: false
793
});
794
// In case the textarea contains a word, we're going to try to align the textarea's cursor
795
// with our cursor by scrolling the textarea as much as possible
796
this.textArea.domNode.scrollLeft = this._primaryCursorVisibleRange.left;
797
const lineCount = this._textAreaInput.textAreaState.newlineCountBeforeSelection ?? newlinecount(this.textArea.domNode.value.substring(0, this.textArea.domNode.selectionStart));
798
this.textArea.domNode.scrollTop = lineCount * lineHeight;
799
return;
800
}
801
802
this._doRender({
803
lastRenderPosition: this._primaryCursorPosition,
804
top: top,
805
left: this._textAreaWrapping ? this._contentLeft : left,
806
width: this._textAreaWidth,
807
height: (canUseZeroSizeTextarea ? 0 : 1),
808
useCover: false
809
});
810
}
811
812
private _renderAtTopLeft(): void {
813
// (in WebKit the textarea is 1px by 1px because it cannot handle input to a 0x0 textarea)
814
// specifically, when doing Korean IME, setting the textarea to 0x0 breaks IME badly.
815
this._doRender({
816
lastRenderPosition: null,
817
top: 0,
818
left: 0,
819
width: this._textAreaWidth,
820
height: (canUseZeroSizeTextarea ? 0 : 1),
821
useCover: true
822
});
823
}
824
825
private _doRender(renderData: IRenderData): void {
826
this._lastRenderPosition = renderData.lastRenderPosition;
827
828
const ta = this.textArea;
829
const tac = this.textAreaCover;
830
831
applyFontInfo(ta, this._fontInfo);
832
ta.setTop(renderData.top);
833
ta.setLeft(renderData.left);
834
ta.setWidth(renderData.width);
835
ta.setHeight(renderData.height);
836
ta.setLineHeight(renderData.height);
837
838
ta.setFontSize(renderData.fontSize ?? this._fontInfo.fontSize);
839
ta.setColor(renderData.color ? Color.Format.CSS.formatHex(renderData.color) : '');
840
ta.setFontStyle(renderData.italic ? 'italic' : '');
841
if (renderData.bold) {
842
// fontWeight is also set by `applyFontInfo`, so only overwrite it if necessary
843
ta.setFontWeight('bold');
844
}
845
ta.setTextDecoration(`${renderData.underline ? ' underline' : ''}${renderData.strikethrough ? ' line-through' : ''}`);
846
847
tac.setTop(renderData.useCover ? renderData.top : 0);
848
tac.setLeft(renderData.useCover ? renderData.left : 0);
849
tac.setWidth(renderData.useCover ? renderData.width : 0);
850
tac.setHeight(renderData.useCover ? renderData.height : 0);
851
852
const options = this._context.configuration.options;
853
854
if (options.get(EditorOption.glyphMargin)) {
855
tac.setClassName('monaco-editor-background textAreaCover ' + Margin.OUTER_CLASS_NAME);
856
} else {
857
if (options.get(EditorOption.lineNumbers).renderType !== RenderLineNumbersType.Off) {
858
tac.setClassName('monaco-editor-background textAreaCover ' + LineNumbersOverlay.CLASS_NAME);
859
} else {
860
tac.setClassName('monaco-editor-background textAreaCover');
861
}
862
}
863
}
864
}
865
866
interface IRenderData {
867
lastRenderPosition: Position | null;
868
top: number;
869
left: number;
870
width: number;
871
height: number;
872
useCover: boolean;
873
874
fontSize?: string | null;
875
color?: Color | null;
876
italic?: boolean;
877
bold?: boolean;
878
underline?: boolean;
879
strikethrough?: boolean;
880
}
881
882
function measureText(targetDocument: Document, text: string, fontInfo: FontInfo, tabSize: number): number {
883
if (text.length === 0) {
884
return 0;
885
}
886
887
const container = targetDocument.createElement('div');
888
container.style.position = 'absolute';
889
container.style.top = '-50000px';
890
container.style.width = '50000px';
891
892
const regularDomNode = targetDocument.createElement('span');
893
applyFontInfo(regularDomNode, fontInfo);
894
regularDomNode.style.whiteSpace = 'pre'; // just like the textarea
895
regularDomNode.style.tabSize = `${tabSize * fontInfo.spaceWidth}px`; // just like the textarea
896
regularDomNode.append(text);
897
container.appendChild(regularDomNode);
898
899
targetDocument.body.appendChild(container);
900
901
const res = regularDomNode.offsetWidth;
902
903
container.remove();
904
905
return res;
906
}
907
908