viewLineRenderer.ts 21.9 KB
Newer Older
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

A
Alex Dima 已提交
7
import { ViewLineToken } from 'vs/editor/common/core/viewLineToken';
J
Johannes Rieken 已提交
8
import { CharCode } from 'vs/base/common/charCode';
A
Alex Dima 已提交
9
import { LineDecoration, LineDecorationsNormalizer } from 'vs/editor/common/viewLayout/lineDecorations';
A
Alex Dima 已提交
10
import * as strings from 'vs/base/common/strings';
A
Alex Dima 已提交
11

A
Alex Dima 已提交
12 13 14 15 16 17
export const enum RenderWhitespace {
	None = 0,
	Boundary = 1,
	All = 2
}

A
Alex Dima 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
class LinePart {
	_linePartBrand: void;

	/**
	 * last char index of this token (not inclusive).
	 */
	public readonly endIndex: number;
	public readonly type: string;

	constructor(endIndex: number, type: string) {
		this.endIndex = endIndex;
		this.type = type;
	}
}

A
Alex Dima 已提交
33
export class RenderLineInput {
34

35
	public readonly useMonospaceOptimizations: boolean;
36
	public readonly lineContent: string;
37
	public readonly mightContainRTL: boolean;
38
	public readonly fauxIndentLength: number;
A
Alex Dima 已提交
39
	public readonly lineTokens: ViewLineToken[];
A
Alex Dima 已提交
40
	public readonly lineDecorations: LineDecoration[];
41 42 43
	public readonly tabSize: number;
	public readonly spaceWidth: number;
	public readonly stopRenderingLineAfter: number;
A
Alex Dima 已提交
44
	public readonly renderWhitespace: RenderWhitespace;
45
	public readonly renderControlCharacters: boolean;
46
	public readonly fontLigatures: boolean;
A
Alex Dima 已提交
47 48

	constructor(
49
		useMonospaceOptimizations: boolean,
A
Alex Dima 已提交
50
		lineContent: string,
51
		mightContainRTL: boolean,
52
		fauxIndentLength: number,
A
Alex Dima 已提交
53
		lineTokens: ViewLineToken[],
A
Alex Dima 已提交
54
		lineDecorations: LineDecoration[],
A
Alex Dima 已提交
55
		tabSize: number,
56
		spaceWidth: number,
A
Alex Dima 已提交
57
		stopRenderingLineAfter: number,
58
		renderWhitespace: 'none' | 'boundary' | 'all',
59
		renderControlCharacters: boolean,
60
		fontLigatures: boolean
A
Alex Dima 已提交
61
	) {
62
		this.useMonospaceOptimizations = useMonospaceOptimizations;
A
Alex Dima 已提交
63
		this.lineContent = lineContent;
64
		this.mightContainRTL = mightContainRTL;
65
		this.fauxIndentLength = fauxIndentLength;
66 67
		this.lineTokens = lineTokens;
		this.lineDecorations = lineDecorations;
A
Alex Dima 已提交
68
		this.tabSize = tabSize;
69
		this.spaceWidth = spaceWidth;
A
Alex Dima 已提交
70
		this.stopRenderingLineAfter = stopRenderingLineAfter;
A
Alex Dima 已提交
71 72 73 74 75 76 77
		this.renderWhitespace = (
			renderWhitespace === 'all'
				? RenderWhitespace.All
				: renderWhitespace === 'boundary'
					? RenderWhitespace.Boundary
					: RenderWhitespace.None
		);
78
		this.renderControlCharacters = renderControlCharacters;
79
		this.fontLigatures = fontLigatures;
A
Alex Dima 已提交
80 81
	}

A
Alex Dima 已提交
82
	public equals(other: RenderLineInput): boolean {
A
Alex Dima 已提交
83
		return (
84
			this.useMonospaceOptimizations === other.useMonospaceOptimizations
85
			&& this.lineContent === other.lineContent
86
			&& this.mightContainRTL === other.mightContainRTL
87
			&& this.fauxIndentLength === other.fauxIndentLength
A
Alex Dima 已提交
88 89 90 91 92
			&& this.tabSize === other.tabSize
			&& this.spaceWidth === other.spaceWidth
			&& this.stopRenderingLineAfter === other.stopRenderingLineAfter
			&& this.renderWhitespace === other.renderWhitespace
			&& this.renderControlCharacters === other.renderControlCharacters
93
			&& this.fontLigatures === other.fontLigatures
A
Alex Dima 已提交
94
			&& LineDecoration.equalsArr(this.lineDecorations, other.lineDecorations)
A
Alex Dima 已提交
95
			&& ViewLineToken.equalsArr(this.lineTokens, other.lineTokens)
A
Alex Dima 已提交
96
		);
A
Alex Dima 已提交
97
	}
98 99
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
export const enum CharacterMappingConstants {
	PART_INDEX_MASK = 0b11111111111111110000000000000000,
	CHAR_INDEX_MASK = 0b00000000000000001111111111111111,

	CHAR_INDEX_OFFSET = 0,
	PART_INDEX_OFFSET = 16
}

/**
 * Provides a both direction mapping between a line's character and its rendered position.
 */
export class CharacterMapping {

	public static getPartIndex(partData: number): number {
		return (partData & CharacterMappingConstants.PART_INDEX_MASK) >>> CharacterMappingConstants.PART_INDEX_OFFSET;
	}

	public static getCharIndex(partData: number): number {
		return (partData & CharacterMappingConstants.CHAR_INDEX_MASK) >>> CharacterMappingConstants.CHAR_INDEX_OFFSET;
	}

	private readonly _data: Uint32Array;
	public readonly length: number;

124 125 126
	private readonly _partLengths: Uint16Array;

	constructor(length: number, partCount: number) {
127 128
		this.length = length;
		this._data = new Uint32Array(this.length);
129
		this._partLengths = new Uint16Array(partCount);
130 131 132 133 134 135 136 137 138 139
	}

	public setPartData(charOffset: number, partIndex: number, charIndex: number): void {
		let partData = (
			(partIndex << CharacterMappingConstants.PART_INDEX_OFFSET)
			| (charIndex << CharacterMappingConstants.CHAR_INDEX_OFFSET)
		) >>> 0;
		this._data[charOffset] = partData;
	}

140 141 142 143 144 145 146 147
	public setPartLength(partIndex: number, length: number): void {
		this._partLengths[partIndex] = length;
	}

	public getPartLengths(): Uint16Array {
		return this._partLengths;
	}

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
	public charOffsetToPartData(charOffset: number): number {
		if (this.length === 0) {
			return 0;
		}
		if (charOffset < 0) {
			return this._data[0];
		}
		if (charOffset >= this.length) {
			return this._data[this.length - 1];
		}
		return this._data[charOffset];
	}

	public partDataToCharOffset(partIndex: number, partLength: number, charIndex: number): number {
		if (this.length === 0) {
			return 0;
		}

		let searchEntry = (
			(partIndex << CharacterMappingConstants.PART_INDEX_OFFSET)
			| (charIndex << CharacterMappingConstants.CHAR_INDEX_OFFSET)
		) >>> 0;

		let min = 0;
		let max = this.length - 1;
		while (min + 1 < max) {
			let mid = ((min + max) >>> 1);
			let midEntry = this._data[mid];
			if (midEntry === searchEntry) {
				return mid;
			} else if (midEntry > searchEntry) {
				max = mid;
			} else {
				min = mid;
			}
		}

		if (min === max) {
			return min;
		}

		let minEntry = this._data[min];
		let maxEntry = this._data[max];

		if (minEntry === searchEntry) {
			return min;
		}
		if (maxEntry === searchEntry) {
			return max;
		}

		let minPartIndex = CharacterMapping.getPartIndex(minEntry);
		let minCharIndex = CharacterMapping.getCharIndex(minEntry);

		let maxPartIndex = CharacterMapping.getPartIndex(maxEntry);
		let maxCharIndex: number;

		if (minPartIndex !== maxPartIndex) {
			// sitting between parts
			maxCharIndex = partLength;
		} else {
			maxCharIndex = CharacterMapping.getCharIndex(maxEntry);
		}

		let minEntryDistance = charIndex - minCharIndex;
		let maxEntryDistance = maxCharIndex - charIndex;

		if (minEntryDistance <= maxEntryDistance) {
			return min;
		}
		return max;
	}
}

A
Alex Dima 已提交
222
export class RenderLineOutput {
A
Alex Dima 已提交
223
	_renderLineOutputBrand: void;
A
Alex Dima 已提交
224

225
	readonly characterMapping: CharacterMapping;
226
	readonly html: string;
227
	readonly containsRTL: boolean;
228
	readonly containsForeignElements: boolean;
A
Alex Dima 已提交
229

230
	constructor(characterMapping: CharacterMapping, html: string, containsRTL: boolean, containsForeignElements: boolean) {
231
		this.characterMapping = characterMapping;
232
		this.html = html;
233
		this.containsRTL = containsRTL;
234
		this.containsForeignElements = containsForeignElements;
A
Alex Dima 已提交
235
	}
236 237
}

A
Alex Dima 已提交
238 239
export function renderViewLine(input: RenderLineInput): RenderLineOutput {
	if (input.lineContent.length === 0) {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

		let containsForeignElements = false;

		// This is basically for IE's hit test to work
		let content: string = '<span><span>&nbsp;</span></span>';

		if (input.lineDecorations.length > 0) {
			// This line is empty, but it contains inline decorations
			let classNames: string[] = [];
			for (let i = 0, len = input.lineDecorations.length; i < len; i++) {
				const lineDecoration = input.lineDecorations[i];
				if (lineDecoration.insertsBeforeOrAfter) {
					classNames[i] = input.lineDecorations[i].className;
					containsForeignElements = true;
				}
			}

			if (containsForeignElements) {
				content = `<span><span class="${classNames.join(' ')}">&nbsp;</span></span>`;
			}
		}

A
Alex Dima 已提交
262
		return new RenderLineOutput(
263
			new CharacterMapping(0, 0),
264
			content,
265
			false,
266
			containsForeignElements
A
Alex Dima 已提交
267
		);
268 269
	}

A
Alex Dima 已提交
270 271 272 273 274
	return _renderLine(resolveRenderLineInput(input));
}

class ResolvedRenderLineInput {
	constructor(
275
		public readonly fontIsMonospace: boolean,
A
Alex Dima 已提交
276 277 278
		public readonly lineContent: string,
		public readonly len: number,
		public readonly isOverflowing: boolean,
A
Alex Dima 已提交
279
		public readonly parts: LinePart[],
280
		public readonly containsForeignElements: boolean,
A
Alex Dima 已提交
281
		public readonly tabSize: number,
282
		public readonly containsRTL: boolean,
A
Alex Dima 已提交
283 284 285 286 287
		public readonly spaceWidth: number,
		public readonly renderWhitespace: RenderWhitespace,
		public readonly renderControlCharacters: boolean,
	) {
		//
288
	}
A
Alex Dima 已提交
289
}
290

A
Alex Dima 已提交
291
function resolveRenderLineInput(input: RenderLineInput): ResolvedRenderLineInput {
292
	const useMonospaceOptimizations = input.useMonospaceOptimizations;
A
Alex Dima 已提交
293
	const lineContent = input.lineContent;
294

A
Alex Dima 已提交
295 296
	let isOverflowing: boolean;
	let len: number;
A
Alex Dima 已提交
297

A
Alex Dima 已提交
298 299 300 301 302 303 304
	if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) {
		isOverflowing = true;
		len = input.stopRenderingLineAfter;
	} else {
		isOverflowing = false;
		len = lineContent.length;
	}
305

306
	let tokens = transformAndRemoveOverflowing(input.lineTokens, input.fauxIndentLength, len);
A
Alex Dima 已提交
307
	if (input.renderWhitespace === RenderWhitespace.All || input.renderWhitespace === RenderWhitespace.Boundary) {
308
		tokens = _applyRenderWhitespace(lineContent, len, tokens, input.fauxIndentLength, input.tabSize, useMonospaceOptimizations, input.renderWhitespace === RenderWhitespace.Boundary);
A
Alex Dima 已提交
309
	}
310
	let containsForeignElements = false;
A
Alex Dima 已提交
311
	if (input.lineDecorations.length > 0) {
312 313 314 315 316 317 318
		for (let i = 0, len = input.lineDecorations.length; i < len; i++) {
			const lineDecoration = input.lineDecorations[i];
			if (lineDecoration.insertsBeforeOrAfter) {
				containsForeignElements = true;
				break;
			}
		}
A
Alex Dima 已提交
319 320
		tokens = _applyInlineDecorations(lineContent, len, tokens, input.lineDecorations);
	}
321
	let containsRTL = false;
322
	if (input.mightContainRTL) {
323 324
		containsRTL = strings.containsRTL(lineContent);
	}
325
	if (!containsRTL && !input.fontLigatures) {
326
		tokens = splitLargeTokens(lineContent, tokens);
327 328
	}

A
Alex Dima 已提交
329
	return new ResolvedRenderLineInput(
330
		useMonospaceOptimizations,
A
Alex Dima 已提交
331 332 333 334
		lineContent,
		len,
		isOverflowing,
		tokens,
335
		containsForeignElements,
A
Alex Dima 已提交
336
		input.tabSize,
337
		containsRTL,
A
Alex Dima 已提交
338 339 340 341
		input.spaceWidth,
		input.renderWhitespace,
		input.renderControlCharacters
	);
342 343
}

344 345 346 347
/**
 * In the rendering phase, characters are always looped until token.endIndex.
 * Ensure that all tokens end before `len` and the last one ends precisely at `len`.
 */
348 349 350 351 352 353 354 355
function transformAndRemoveOverflowing(tokens: ViewLineToken[], fauxIndentLength: number, len: number): LinePart[] {
	let result: LinePart[] = [], resultLen = 0;

	// The faux indent part of the line should have no token type
	if (fauxIndentLength > 0) {
		result[resultLen++] = new LinePart(fauxIndentLength, '');
	}

356
	for (let tokenIndex = 0, tokensLen = tokens.length; tokenIndex < tokensLen; tokenIndex++) {
A
Alex Dima 已提交
357 358
		const token = tokens[tokenIndex];
		const endIndex = token.endIndex;
359 360 361 362
		if (endIndex <= fauxIndentLength) {
			// The faux indent part of the line should have no token type
			continue;
		}
A
Alex Dima 已提交
363 364
		const type = token.getType();
		if (endIndex >= len) {
365
			result[resultLen++] = new LinePart(len, type);
366 367
			break;
		}
368
		result[resultLen++] = new LinePart(endIndex, type);
369
	}
370

371 372 373
	return result;
}

374 375 376 377 378 379 380 381 382 383 384 385
/**
 * written as a const enum to get value inlining.
 */
const enum Constants {
	LongToken = 50
}

/**
 * See https://github.com/Microsoft/vscode/issues/6885.
 * It appears that having very large spans causes very slow reading of character positions.
 * So here we try to avoid that.
 */
386
function splitLargeTokens(lineContent: string, tokens: LinePart[]): LinePart[] {
387
	let lastTokenEndIndex = 0;
A
Alex Dima 已提交
388
	let result: LinePart[] = [], resultLen = 0;
389 390 391 392 393 394 395 396 397
	for (let i = 0, len = tokens.length; i < len; i++) {
		const token = tokens[i];
		const tokenEndIndex = token.endIndex;
		let diff = (tokenEndIndex - lastTokenEndIndex);
		if (diff > Constants.LongToken) {
			const tokenType = token.type;
			const piecesCount = Math.ceil(diff / Constants.LongToken);
			for (let j = 1; j < piecesCount; j++) {
				let pieceEndIndex = lastTokenEndIndex + (j * Constants.LongToken);
398 399 400 401 402
				let lastCharInPiece = lineContent.charCodeAt(pieceEndIndex - 1);
				if (strings.isHighSurrogate(lastCharInPiece)) {
					// Don't cut in the middle of a surrogate pair
					pieceEndIndex--;
				}
A
Alex Dima 已提交
403
				result[resultLen++] = new LinePart(pieceEndIndex, tokenType);
404
			}
A
Alex Dima 已提交
405
			result[resultLen++] = new LinePart(tokenEndIndex, tokenType);
406 407 408 409 410 411 412 413 414 415 416 417 418 419
		} else {
			result[resultLen++] = token;
		}
		lastTokenEndIndex = tokenEndIndex;
	}

	return result;
}

/**
 * Whitespace is rendered by "replacing" tokens with a special-purpose `vs-whitespace` type that is later recognized in the rendering phase.
 * Moreover, a token is created for every visual indent because on some fonts the glyphs used for rendering whitespace (&rarr; or &middot;) do not have the same width as &nbsp;.
 * The rendering phase will generate `style="width:..."` for these tokens.
 */
A
Alex Dima 已提交
420
function _applyRenderWhitespace(lineContent: string, len: number, tokens: LinePart[], fauxIndentLength: number, tabSize: number, useMonospaceOptimizations: boolean, onlyBoundary: boolean): LinePart[] {
A
Alex Dima 已提交
421

A
Alex Dima 已提交
422
	let result: LinePart[] = [], resultLen = 0;
A
Alex Dima 已提交
423 424 425
	let tokenIndex = 0;
	let tokenType = tokens[tokenIndex].type;
	let tokenEndIndex = tokens[tokenIndex].endIndex;
426

A
Alex Dima 已提交
427 428 429 430 431 432 433 434 435
	let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
	let lastNonWhitespaceIndex: number;
	if (firstNonWhitespaceIndex === -1) {
		// The entire line is whitespace
		firstNonWhitespaceIndex = len;
		lastNonWhitespaceIndex = len;
	} else {
		lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent);
	}
436

A
Alex Dima 已提交
437 438 439 440 441 442 443 444
	let tmpIndent = 0;
	for (let charIndex = 0; charIndex < fauxIndentLength; charIndex++) {
		const chCode = lineContent.charCodeAt(charIndex);
		if (chCode === CharCode.Tab) {
			tmpIndent = tabSize;
		} else {
			tmpIndent++;
		}
445
	}
A
Alex Dima 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
	tmpIndent = tmpIndent % tabSize;

	let wasInWhitespace = false;
	for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
		const chCode = lineContent.charCodeAt(charIndex);

		let isInWhitespace: boolean;
		if (charIndex < firstNonWhitespaceIndex || charIndex > lastNonWhitespaceIndex) {
			// in leading or trailing whitespace
			isInWhitespace = true;
		} else if (chCode === CharCode.Tab) {
			// a tab character is rendered both in all and boundary cases
			isInWhitespace = true;
		} else if (chCode === CharCode.Space) {
			// hit a space character
			if (onlyBoundary) {
				// rendering only boundary whitespace
				if (wasInWhitespace) {
					isInWhitespace = true;
				} else {
					const nextChCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : CharCode.Null);
					isInWhitespace = (nextChCode === CharCode.Space || nextChCode === CharCode.Tab);
				}
			} else {
				isInWhitespace = true;
			}
		} else {
			isInWhitespace = false;
		}

		if (wasInWhitespace) {
			// was in whitespace token
478
			if (!isInWhitespace || (!useMonospaceOptimizations && tmpIndent >= tabSize)) {
A
Alex Dima 已提交
479
				// leaving whitespace token or entering a new indent
A
Alex Dima 已提交
480
				result[resultLen++] = new LinePart(charIndex, 'vs-whitespace');
A
Alex Dima 已提交
481 482 483 484 485
				tmpIndent = tmpIndent % tabSize;
			}
		} else {
			// was in regular token
			if (charIndex === tokenEndIndex || (isInWhitespace && charIndex > fauxIndentLength)) {
A
Alex Dima 已提交
486
				result[resultLen++] = new LinePart(charIndex, tokenType);
A
Alex Dima 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
				tmpIndent = tmpIndent % tabSize;
			}
		}

		if (chCode === CharCode.Tab) {
			tmpIndent = tabSize;
		} else {
			tmpIndent++;
		}

		wasInWhitespace = isInWhitespace;

		if (charIndex === tokenEndIndex) {
			tokenIndex++;
			tokenType = tokens[tokenIndex].type;
			tokenEndIndex = tokens[tokenIndex].endIndex;
		}
	}

	if (wasInWhitespace) {
		// was in whitespace token
A
Alex Dima 已提交
508
		result[resultLen++] = new LinePart(len, 'vs-whitespace');
A
Alex Dima 已提交
509 510
	} else {
		// was in regular token
A
Alex Dima 已提交
511
		result[resultLen++] = new LinePart(len, tokenType);
A
Alex Dima 已提交
512 513 514
	}

	return result;
515 516
}

517 518 519 520
/**
 * Inline decorations are "merged" on top of tokens.
 * Special care must be taken when multiple inline decorations are at play and they overlap.
 */
A
Alex Dima 已提交
521 522
function _applyInlineDecorations(lineContent: string, len: number, tokens: LinePart[], _lineDecorations: LineDecoration[]): LinePart[] {
	_lineDecorations.sort(LineDecoration.compare);
A
Alex Dima 已提交
523 524
	const lineDecorations = LineDecorationsNormalizer.normalize(_lineDecorations);
	const lineDecorationsLen = lineDecorations.length;
A
Alex Dima 已提交
525

A
Alex Dima 已提交
526
	let lineDecorationIndex = 0;
A
Alex Dima 已提交
527
	let result: LinePart[] = [], resultLen = 0, lastResultEndIndex = 0;
A
Alex Dima 已提交
528 529 530 531
	for (let tokenIndex = 0, len = tokens.length; tokenIndex < len; tokenIndex++) {
		const token = tokens[tokenIndex];
		const tokenEndIndex = token.endIndex;
		const tokenType = token.type;
532

A
Alex Dima 已提交
533 534
		while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) {
			const lineDecoration = lineDecorations[lineDecorationIndex];
535

A
Alex Dima 已提交
536 537
			if (lineDecoration.startOffset > lastResultEndIndex) {
				lastResultEndIndex = lineDecoration.startOffset;
A
Alex Dima 已提交
538
				result[resultLen++] = new LinePart(lastResultEndIndex, tokenType);
A
Alex Dima 已提交
539
			}
A
Alex Dima 已提交
540

541
			if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
542
				// This line decoration ends before this token ends
A
Alex Dima 已提交
543
				lastResultEndIndex = lineDecoration.endOffset + 1;
A
Alex Dima 已提交
544
				result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className);
A
Alex Dima 已提交
545 546
				lineDecorationIndex++;
			} else {
547 548
				// This line decoration continues on to the next token
				lastResultEndIndex = tokenEndIndex;
A
Alex Dima 已提交
549
				result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className);
A
Alex Dima 已提交
550 551 552
				break;
			}
		}
553

A
Alex Dima 已提交
554 555
		if (tokenEndIndex > lastResultEndIndex) {
			lastResultEndIndex = tokenEndIndex;
A
Alex Dima 已提交
556
			result[resultLen++] = new LinePart(lastResultEndIndex, tokenType);
557
		}
A
Alex Dima 已提交
558
	}
559

A
Alex Dima 已提交
560 561 562
	return result;
}

563 564 565 566
/**
 * This function is on purpose not split up into multiple functions to allow runtime type inference (i.e. performance reasons).
 * Notice how all the needed data is fully resolved and passed in (i.e. no other calls).
 */
A
Alex Dima 已提交
567
function _renderLine(input: ResolvedRenderLineInput): RenderLineOutput {
568
	const fontIsMonospace = input.fontIsMonospace;
569
	const containsForeignElements = input.containsForeignElements;
A
Alex Dima 已提交
570 571 572
	const lineContent = input.lineContent;
	const len = input.len;
	const isOverflowing = input.isOverflowing;
A
Alex Dima 已提交
573
	const parts = input.parts;
A
Alex Dima 已提交
574
	const tabSize = input.tabSize;
575
	const containsRTL = input.containsRTL;
A
Alex Dima 已提交
576 577 578 579
	const spaceWidth = input.spaceWidth;
	const renderWhitespace = input.renderWhitespace;
	const renderControlCharacters = input.renderControlCharacters;

A
Alex Dima 已提交
580
	const characterMapping = new CharacterMapping(len + 1, parts.length);
A
Alex Dima 已提交
581 582 583 584 585 586

	let charIndex = 0;
	let tabsCharDelta = 0;
	let charOffsetInPart = 0;

	let out = '<span>';
A
Alex Dima 已提交
587 588 589 590 591
	for (let partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
		const part = parts[partIndex];
		const partEndIndex = part.endIndex;
		const partType = part.type;
		const partRendersWhitespace = (renderWhitespace !== RenderWhitespace.None && (partType.indexOf('vs-whitespace') >= 0));
A
Alex Dima 已提交
592
		charOffsetInPart = 0;
A
Alex Dima 已提交
593

A
Alex Dima 已提交
594
		if (partRendersWhitespace) {
595 596 597

			let partContentCnt = 0;
			let partContent = '';
A
Alex Dima 已提交
598 599
			for (; charIndex < partEndIndex; charIndex++) {
				characterMapping.setPartData(charIndex, partIndex, charOffsetInPart);
A
Alex Dima 已提交
600
				const charCode = lineContent.charCodeAt(charIndex);
A
Alex Dima 已提交
601

A
Alex Dima 已提交
602
				if (charCode === CharCode.Tab) {
A
Alex Dima 已提交
603 604 605 606
					let insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
					tabsCharDelta += insertSpacesCount - 1;
					charOffsetInPart += insertSpacesCount - 1;
					if (insertSpacesCount > 0) {
607
						partContent += '&rarr;';
608
						partContentCnt++;
A
Alex Dima 已提交
609 610 611
						insertSpacesCount--;
					}
					while (insertSpacesCount > 0) {
612 613
						partContent += '&nbsp;';
						partContentCnt++;
A
Alex Dima 已提交
614 615
						insertSpacesCount--;
					}
616
				} else {
A
Alex Dima 已提交
617
					// must be CharCode.Space
618
					partContent += '&middot;';
619 620 621
					partContentCnt++;
				}

J
Johannes Rieken 已提交
622
				charOffsetInPart++;
A
Alex Dima 已提交
623
			}
A
Alex Dima 已提交
624

A
Alex Dima 已提交
625
			characterMapping.setPartLength(partIndex, partContentCnt);
626
			if (fontIsMonospace || containsForeignElements) {
A
Alex Dima 已提交
627
				out += `<span class="${partType}">${partContent}</span>`;
628
			} else {
A
Alex Dima 已提交
629
				out += `<span class="${partType}" style="width:${spaceWidth * partContentCnt}px">${partContent}</span>`;
630
			}
A
Alex Dima 已提交
631

632
		} else {
633 634

			let partContentCnt = 0;
635
			let partContent = '';
636

A
Alex Dima 已提交
637 638
			for (; charIndex < partEndIndex; charIndex++) {
				characterMapping.setPartData(charIndex, partIndex, charOffsetInPart);
A
Alex Dima 已提交
639
				const charCode = lineContent.charCodeAt(charIndex);
640 641

				switch (charCode) {
A
Alex Dima 已提交
642
					case CharCode.Tab:
643 644 645 646
						let insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
						tabsCharDelta += insertSpacesCount - 1;
						charOffsetInPart += insertSpacesCount - 1;
						while (insertSpacesCount > 0) {
647
							partContent += '&nbsp;';
648
							partContentCnt++;
649 650 651 652
							insertSpacesCount--;
						}
						break;

A
Alex Dima 已提交
653
					case CharCode.Space:
654
						partContent += '&nbsp;';
655
						partContentCnt++;
656 657
						break;

A
Alex Dima 已提交
658
					case CharCode.LessThan:
659
						partContent += '&lt;';
660
						partContentCnt++;
661 662
						break;

A
Alex Dima 已提交
663
					case CharCode.GreaterThan:
664
						partContent += '&gt;';
665
						partContentCnt++;
666 667
						break;

A
Alex Dima 已提交
668
					case CharCode.Ampersand:
669
						partContent += '&amp;';
670
						partContentCnt++;
671 672
						break;

A
Alex Dima 已提交
673
					case CharCode.Null:
674
						partContent += '&#00;';
675
						partContentCnt++;
676 677
						break;

A
Alex Dima 已提交
678 679
					case CharCode.UTF8_BOM:
					case CharCode.LINE_SEPARATOR_2028:
680
						partContent += '\ufffd';
681
						partContentCnt++;
682 683
						break;

A
Alex Dima 已提交
684
					case CharCode.CarriageReturn:
685
						// zero width space, because carriage return would introduce a line break
686
						partContent += '&#8203';
687
						partContentCnt++;
688 689 690
						break;

					default:
A
Alex Dima 已提交
691 692
						if (renderControlCharacters && charCode < 32) {
							partContent += String.fromCharCode(9216 + charCode);
693
							partContentCnt++;
694
						} else {
695 696
							partContent += String.fromCharCode(charCode);
							partContentCnt++;
697
						}
698 699
				}

J
Johannes Rieken 已提交
700
				charOffsetInPart++;
A
Alex Dima 已提交
701
			}
A
Alex Dima 已提交
702

A
Alex Dima 已提交
703
			characterMapping.setPartLength(partIndex, partContentCnt);
704
			if (containsRTL) {
A
Alex Dima 已提交
705
				out += `<span dir="ltr" class="${partType}">${partContent}</span>`;
706
			} else {
A
Alex Dima 已提交
707
				out += `<span class="${partType}">${partContent}</span>`;
708
			}
A
Alex Dima 已提交
709

A
Alex Dima 已提交
710
		}
711 712 713 714
	}

	// When getting client rects for the last character, we will position the
	// text range at the end of the span, insteaf of at the beginning of next span
A
Alex Dima 已提交
715
	characterMapping.setPartData(len, parts.length - 1, charOffsetInPart);
716

A
Alex Dima 已提交
717
	if (isOverflowing) {
718
		out += `<span>&hellip;</span>`;
719
	}
A
Alex Dima 已提交
720

721 722
	out += '</span>';

723
	return new RenderLineOutput(characterMapping, out, containsRTL, containsForeignElements);
724
}