viewLine.ts 21.8 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import Browser = require('vs/base/browser/browser');
import DomUtils = require('vs/base/browser/dom');

import {IVisibleLineData} from 'vs/editor/browser/view/viewLayer';
import {ILineParts, createLineParts} from 'vs/editor/common/viewLayout/viewLineParts';
A
Alex Dima 已提交
12
import {ClassNames, IViewContext, HorizontalRange} from 'vs/editor/browser/editorBrowser';
E
Erich Gamma 已提交
13 14 15 16 17 18 19 20 21 22 23 24
import EditorCommon = require('vs/editor/common/editorCommon');

export interface IViewLineData extends IVisibleLineData {

	/**
	 * Width of the line in pixels
	 */
	getWidth(): number;

	/**
	 * Visible ranges for a model range
	 */
A
Alex Dima 已提交
25
	getVisibleRangesForRange(startColumn:number, endColumn:number, endNode:HTMLElement): HorizontalRange[];
E
Erich Gamma 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39

	/**
	 * Returns the column for the text found at a specific offset inside a rendered dom node
	 */
	getColumnOfNodeOffset(lineNumber:number, spanNode:HTMLElement, offset:number): number;

	/**
	 * Let the line know that decorations might have changed
	 */
	onModelDecorationsChanged(): void;
}

class ViewLine implements IViewLineData {

A
Alex Dima 已提交
40
	protected _context:IViewContext;
E
Erich Gamma 已提交
41 42 43 44 45 46 47
	private _domNode: HTMLElement;

	private _lineParts: ILineParts;

	private _isInvalid: boolean;
	private _isMaybeInvalid: boolean;

A
Alex Dima 已提交
48
	protected _charOffsetInPart:number[];
E
Erich Gamma 已提交
49 50 51 52
	private _hasOverflowed:boolean;
	private _lastRenderedPartIndex:number;
	private _cachedWidth: number;

A
Alex Dima 已提交
53
	constructor(context:IViewContext) {
E
Erich Gamma 已提交
54 55 56 57 58 59 60 61 62 63 64 65
		this._context = context;

		this._domNode = null;

		this._isInvalid = true;
		this._isMaybeInvalid = false;
		this._lineParts = null;
		this._charOffsetInPart = [];
		this._hasOverflowed = false;
		this._lastRenderedPartIndex = 0;
	}

A
Alex Dima 已提交
66 67
	// --- begin IVisibleLineData

E
Erich Gamma 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 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 124 125 126 127 128 129
	public getDomNode(): HTMLElement {
		return this._domNode;
	}
	public setDomNode(domNode:HTMLElement): void {
		this._domNode = domNode;
	}

	public onContentChanged(): void {
		this._isInvalid = true;
	}
	public onLinesInsertedAbove(): void {
		this._isMaybeInvalid = true;
	}
	public onLinesDeletedAbove(): void {
		this._isMaybeInvalid = true;
	}
	public onLineChangedAbove(): void {
		this._isMaybeInvalid = true;
	}
	public onTokensChanged(): void {
		this._isMaybeInvalid = true;
	}
	public onModelDecorationsChanged(): void {
		this._isMaybeInvalid = true;
	}
	public onConfigurationChanged(e:EditorCommon.IConfigurationChangedEvent): void {
		this._isInvalid = true;
	}

	public shouldUpdateHTML(lineNumber:number, inlineDecorations:EditorCommon.IModelDecoration[]): boolean {
		var newLineParts:ILineParts = null;

		if (this._isMaybeInvalid || this._isInvalid) {
			// Compute new line parts only if there is some evidence that something might have changed
			newLineParts = this._computeLineParts(lineNumber, inlineDecorations);
		}

		// Decide if isMaybeInvalid flips isInvalid to true
		if (this._isMaybeInvalid) {
			if (!this._isInvalid) {
				if (!this._lineParts || !this._lineParts.equals(newLineParts)) {
					this._isInvalid = true;
				}
			}
			this._isMaybeInvalid = false;
		}

		if (this._isInvalid) {
			this._lineParts = newLineParts;
		}

		return this._isInvalid;
	}

	public getLineOuterHTML(out:string[], lineNumber:number, deltaTop:number): void {
		out.push('<div lineNumber="');
		out.push(lineNumber.toString());
		out.push('" style="top:');
		out.push(deltaTop.toString());
		out.push('px;height:');
		out.push(this._context.configuration.editor.lineHeight.toString());
		out.push('px;" class="');
A
Alex Dima 已提交
130
		out.push(ClassNames.VIEW_LINE);
E
Erich Gamma 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
		out.push('">');
		out.push(this.getLineInnerHTML(lineNumber));
		out.push('</div>');
	}

	public getLineInnerHTML(lineNumber: number): string {
		this._isInvalid = false;
		return this._renderMyLine(lineNumber, this._lineParts).join('');
	}

	public layoutLine(lineNumber:number, deltaTop:number): void {
		var currentLineNumber = this._domNode.getAttribute('lineNumber');
		if (currentLineNumber !== lineNumber.toString()) {
			this._domNode.setAttribute('lineNumber', lineNumber.toString());
		}
		DomUtils.StyleMutator.setTop(this._domNode, deltaTop);
		DomUtils.StyleMutator.setHeight(this._domNode, this._context.configuration.editor.lineHeight);
	}

A
Alex Dima 已提交
150 151
	// --- end IVisibleLineData

E
Erich Gamma 已提交
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
	private _computeLineParts(lineNumber:number, inlineDecorations:EditorCommon.IModelDecoration[]): ILineParts {
		return createLineParts(lineNumber, this._context.model.getLineContent(lineNumber), this._context.model.getLineTokens(lineNumber), inlineDecorations, this._context.configuration.editor.renderWhitespace);
	}

	private _renderMyLine(lineNumber:number, lineParts:ILineParts): string[] {

		this._bustReadingCache();

		var r = renderLine({
			lineContent: this._context.model.getLineContent(lineNumber),
			tabSize: this._context.configuration.getIndentationOptions().tabSize,
			stopRenderingLineAfter: this._context.configuration.editor.stopRenderingLineAfter,
			renderWhitespace: this._context.configuration.editor.renderWhitespace,
			parts: lineParts.getParts()
		});

		this._charOffsetInPart = r.charOffsetInPart;
		this._hasOverflowed = r.hasOverflowed;
		this._lastRenderedPartIndex = r.lastRenderedPartIndex;

		return r.output;
	}

	// --- Reading from the DOM methods

177
	protected _getReadingTarget(): HTMLElement {
E
Erich Gamma 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
		return <HTMLSpanElement>this._domNode.firstChild;
	}

	private _bustReadingCache(): void {
		this._cachedWidth = -1;
	}

	/**
	 * Width of the line in pixels
	 */
	public getWidth(): number {
		if (this._cachedWidth === -1) {
			this._cachedWidth = this._getReadingTarget().offsetWidth;
		}
		return this._cachedWidth;
	}

	/**
	 * Visible ranges for a model range
	 */
A
Alex Dima 已提交
198
	public getVisibleRangesForRange(startColumn:number, endColumn:number, endNode:HTMLElement): HorizontalRange[] {
E
Erich Gamma 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
		var stopRenderingLineAfter = this._context.configuration.editor.stopRenderingLineAfter;

		if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter && endColumn > stopRenderingLineAfter) {
			// This range is obviously not visible
			return null;
		}

		if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter) {
			startColumn = stopRenderingLineAfter;
		}

		if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter) {
			endColumn = stopRenderingLineAfter;
		}

A
Alex Dima 已提交
214
		return this._readVisibleRangesForRange(startColumn, endColumn, endNode);
E
Erich Gamma 已提交
215 216
	}

A
Alex Dima 已提交
217
	protected _readVisibleRangesForRange(startColumn:number, endColumn:number, endNode:HTMLElement): HorizontalRange[] {
E
Erich Gamma 已提交
218

A
Alex Dima 已提交
219
		var result:HorizontalRange[];
E
Erich Gamma 已提交
220
		if (startColumn === endColumn) {
A
Alex Dima 已提交
221
			result = this._readRawVisibleRangesForPosition(startColumn, endNode);
E
Erich Gamma 已提交
222
		} else {
A
Alex Dima 已提交
223
			result = this._readRawVisibleRangesForRange(startColumn, endColumn, endNode);
E
Erich Gamma 已提交
224 225 226 227 228 229 230 231
		}

		if (!result || result.length <= 1) {
			return result;
		}

		result.sort(compareVisibleRanges);

A
Alex Dima 已提交
232 233 234
		var output: HorizontalRange[] = [],
			prevRange: HorizontalRange = result[0],
			currRange: HorizontalRange;
E
Erich Gamma 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

		for (var i = 1, len = result.length; i < len; i++) {
			currRange = result[i];

			if (prevRange.left + prevRange.width + 0.3 /* account for browser's rounding errors*/ >= currRange.left) {
				prevRange.width = Math.max(prevRange.width, currRange.left + currRange.width - prevRange.left);
			} else {
				output.push(prevRange);
				prevRange = currRange;
			}
		}
		output.push(prevRange);

		return output;
	}

A
Alex Dima 已提交
251
	protected _readRawVisibleRangesForPosition(column:number, endNode:HTMLElement): HorizontalRange[] {
E
Erich Gamma 已提交
252 253 254

		if (this._charOffsetInPart.length === 0) {
			// This line is empty
A
Alex Dima 已提交
255
			return [new HorizontalRange(0, 0)];
E
Erich Gamma 已提交
256 257 258 259 260
		}

		var partIndex = findIndexInArrayWithMax(this._lineParts, column - 1, this._lastRenderedPartIndex),
			_charOffsetInPart = this._charOffsetInPart[column - 1];

A
Alex Dima 已提交
261
		return this._readRawVisibleRangesFrom(this._getReadingTarget(), partIndex, _charOffsetInPart, partIndex, _charOffsetInPart, endNode);
E
Erich Gamma 已提交
262 263
	}

A
Alex Dima 已提交
264
	private _readRawVisibleRangesForRange(startColumn:number, endColumn:number, endNode:HTMLElement): HorizontalRange[] {
E
Erich Gamma 已提交
265 266 267 268

		if (startColumn === 1 && endColumn === this._charOffsetInPart.length) {
			// This branch helps IE with bidi text & gives a performance boost to other browsers when reading visible ranges for an entire line

A
Alex Dima 已提交
269
			return [this._readRawVisibleRangeForEntireLine()];
E
Erich Gamma 已提交
270 271 272 273 274 275 276
		}

		var startPartIndex = findIndexInArrayWithMax(this._lineParts, startColumn - 1, this._lastRenderedPartIndex),
			start_charOffsetInPart = this._charOffsetInPart[startColumn - 1],
			endPartIndex = findIndexInArrayWithMax(this._lineParts, endColumn - 1, this._lastRenderedPartIndex),
			end_charOffsetInPart = this._charOffsetInPart[endColumn - 1];

A
Alex Dima 已提交
277
		return this._readRawVisibleRangesFrom(this._getReadingTarget(), startPartIndex, start_charOffsetInPart, endPartIndex, end_charOffsetInPart, endNode);
E
Erich Gamma 已提交
278 279
	}

A
Alex Dima 已提交
280 281
	private _readRawVisibleRangeForEntireLine(): HorizontalRange {
		return new HorizontalRange(0, this._getReadingTarget().offsetWidth);
E
Erich Gamma 已提交
282 283
	}

A
Alex Dima 已提交
284
	private _readRawVisibleRangesFrom(domNode:HTMLElement, startChildIndex:number, startOffset:number, endChildIndex:number, endOffset:number, endNode:HTMLElement): HorizontalRange[] {
E
Erich Gamma 已提交
285 286 287 288 289 290 291 292 293 294 295 296
		var range = RangeUtil.createRange();

		try {
			// Panic check
			var min = 0, max = domNode.children.length - 1;
			if (min > max) {
				return null;
			}
			startChildIndex = Math.min(max, Math.max(min, startChildIndex));
			endChildIndex = Math.min(max, Math.max(min, endChildIndex));

			// If crossing over to a span only to select offset 0, then use the previous span's maximum offset
297
			// Chrome is buggy and doesn't handle 0 offsets well sometimes.
E
Erich Gamma 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
			if (startChildIndex !== endChildIndex) {
				if (endChildIndex > 0 && endOffset === 0) {
					endChildIndex--;
					endOffset = Number.MAX_VALUE;
				}
			}

			var startElement = domNode.children[startChildIndex].firstChild,
				endElement = domNode.children[endChildIndex].firstChild;

			if (!startElement || !endElement) {
				return null;
			}

			startOffset = Math.min(startElement.textContent.length, Math.max(0, startOffset));
			endOffset = Math.min(endElement.textContent.length, Math.max(0, endOffset));

			range.setStart(startElement, startOffset);
			range.setEnd(endElement, endOffset);

			var clientRects = range.getClientRects(),
A
Alex Dima 已提交
319
				result:HorizontalRange[] = null;
E
Erich Gamma 已提交
320 321

			if (clientRects.length > 0) {
A
Alex Dima 已提交
322
				result = this._createRawVisibleRangesFromClientRects(clientRects);
E
Erich Gamma 已提交
323 324 325 326 327 328 329 330 331 332 333 334
			}

			return result;

		} catch (e) {
			// This is life ...
			return null;
		} finally {
			RangeUtil.detachRange(range, endNode);
		}
	}

A
Alex Dima 已提交
335
	protected _createRawVisibleRangesFromClientRects(clientRects:ClientRectList): HorizontalRange[] {
E
Erich Gamma 已提交
336 337 338
		var clientRectsLength = clientRects.length,
			cR:ClientRect,
			i:number,
A
Alex Dima 已提交
339
			result:HorizontalRange[] = [];
E
Erich Gamma 已提交
340 341 342

		for (i = 0; i < clientRectsLength; i++) {
			cR = clientRects[i];
A
Alex Dima 已提交
343
			result.push(new HorizontalRange(cR.left, cR.width));
E
Erich Gamma 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
		}

		return result;
	}

	public getColumnOfNodeOffset(lineNumber:number, spanNode:HTMLElement, offset:number): number {
		var spanIndex = -1;
		while (spanNode) {
			spanNode = <HTMLElement>spanNode.previousSibling;
			spanIndex++;
		}
		var lineParts = this._lineParts.getParts();

		if (spanIndex >= lineParts.length) {
			return this._context.configuration.editor.stopRenderingLineAfter;
		}

		if (offset === 0) {
			return lineParts[spanIndex].startIndex + 1;
		}

		var originalMin = lineParts[spanIndex].startIndex, originalMax:number, originalMaxStartOffset:number;

		if (spanIndex + 1 < lineParts.length) {
			// Stop searching characters at the beginning of the next part
			originalMax = lineParts[spanIndex + 1].startIndex;
			originalMaxStartOffset = this._charOffsetInPart[originalMax - 1] + this._charOffsetInPart[originalMax];
		} else {
			originalMax = this._context.model.getLineMaxColumn(lineNumber) - 1;
			originalMaxStartOffset = this._charOffsetInPart[originalMax];
		}


		var min = originalMin,
			mid:number,
			max = originalMax;

		if (this._context.configuration.editor.stopRenderingLineAfter !== -1) {
			max = Math.min(this._context.configuration.editor.stopRenderingLineAfter - 1, originalMax);
		}

		var midStartOffset:number, nextStartOffset:number, prevStartOffset:number, a:number, b:number;

		// Here are the variables and their relation plotted on an axis

		// prevStartOffset    a    midStartOffset    b    nextStartOffset
		// ------|------------|----------|-----------|-----------|--------->

		// Everything in (a;b] will match mid

		while (min < max) {
			mid = Math.floor( (min + max) / 2 );

			midStartOffset = this._charOffsetInPart[mid];

			if (mid === originalMax) {
				// Using Number.MAX_VALUE to ensure that any offset after midStartOffset will match mid
				nextStartOffset = Number.MAX_VALUE;
			} else if (mid + 1 === originalMax) {
				// mid + 1 is already in next part and might have the _charOffsetInPart = 0
				nextStartOffset = originalMaxStartOffset;
			} else {
				nextStartOffset = this._charOffsetInPart[mid + 1];
			}

			if (mid === originalMin) {
				// Using Number.MIN_VALUE to ensure that any offset before midStartOffset will match mid
				prevStartOffset = Number.MIN_VALUE;
			} else {
				prevStartOffset = this._charOffsetInPart[mid - 1];
			}

			a = (prevStartOffset + midStartOffset) / 2;
			b = (midStartOffset + nextStartOffset) / 2;

			if (a < offset && offset <= b) {
				// Hit!
				return mid + 1;
			}

			if (offset <= a) {
				max = mid - 1;
			} else {
				min = mid + 1;
			}
		}

		return min + 1;
	}
}

class IEViewLine extends ViewLine {

A
Alex Dima 已提交
437
	constructor(context:IViewContext) {
E
Erich Gamma 已提交
438 439 440
		super(context);
	}

A
Alex Dima 已提交
441
	protected _createRawVisibleRangesFromClientRects(clientRects:ClientRectList): HorizontalRange[] {
E
Erich Gamma 已提交
442 443 444
		var clientRectsLength = clientRects.length,
			cR:ClientRect,
			i:number,
A
Alex Dima 已提交
445
			result:HorizontalRange[] = [],
E
Erich Gamma 已提交
446 447
			ratioX = screen.logicalXDPI / screen.deviceXDPI;

A
Alex Dima 已提交
448
		result = new Array<HorizontalRange>(clientRectsLength);
E
Erich Gamma 已提交
449 450
		for (i = 0; i < clientRectsLength; i++) {
			cR = clientRects[i];
A
Alex Dima 已提交
451
			result[i] = new HorizontalRange(Math.max(0, cR.left * ratioX), cR.width * ratioX);
E
Erich Gamma 已提交
452 453 454 455 456 457 458 459
		}

		return result;
	}
}

class WebKitViewLine extends ViewLine {

A
Alex Dima 已提交
460
	constructor(context:IViewContext) {
E
Erich Gamma 已提交
461 462 463
		super(context);
	}

A
Alex Dima 已提交
464 465
	protected _readVisibleRangesForRange(startColumn:number, endColumn:number, endNode:HTMLElement): HorizontalRange[] {
		var output = super._readVisibleRangesForRange(startColumn, endColumn, endNode);
E
Erich Gamma 已提交
466

467 468 469
		if (this._context.configuration.editor.fontLigatures && endColumn > 1 && startColumn === endColumn && endColumn === this._charOffsetInPart.length) {
			if (output.length === 1) {
				let lastSpanBoundingClientRect = (<HTMLElement>this._getReadingTarget().lastChild).getBoundingClientRect();
A
Alex Dima 已提交
470
				output[0].left = lastSpanBoundingClientRect.right;
471 472 473
			}
		}

E
Erich Gamma 已提交
474 475 476 477
		if (!output || output.length === 0 || startColumn === endColumn || (startColumn === 1 && endColumn === this._charOffsetInPart.length)) {
			return output;
		}

478
		// WebKit is buggy and returns an expanded range (to contain words in some cases)
E
Erich Gamma 已提交
479 480 481 482
		// The last client rect is enlarged (I think)

		// This is an attempt to patch things up
		// Find position of previous column
A
Alex Dima 已提交
483
		var beforeEndVisibleRanges = this._readRawVisibleRangesForPosition(endColumn - 1, endNode);
E
Erich Gamma 已提交
484
		// Find position of last column
A
Alex Dima 已提交
485
		var endVisibleRanges = this._readRawVisibleRangesForPosition(endColumn, endNode);
E
Erich Gamma 已提交
486 487 488 489

		if (beforeEndVisibleRanges && beforeEndVisibleRanges.length > 0 && endVisibleRanges && endVisibleRanges.length > 0) {
			var beforeEndVisibleRange = beforeEndVisibleRanges[0];
			var endVisibleRange = endVisibleRanges[0];
A
Andre Weinand 已提交
490
			var isLTR = (beforeEndVisibleRange.left <= endVisibleRange.left);
E
Erich Gamma 已提交
491 492
			var lastRange = output[output.length - 1];

A
Andre Weinand 已提交
493
			if (isLTR && lastRange.left < endVisibleRange.left) {
E
Erich Gamma 已提交
494 495 496 497 498 499 500 501 502 503 504 505 506
				// Trim down the width of the last visible range to not go after the last column's position
				lastRange.width = endVisibleRange.left - lastRange.left;
			}
		}

		return output;
	}
}

class RangeUtil {

	/**
	 * Reusing the same range here
507
	 * because IE is buggy and constantly freezes when using a large number
E
Erich Gamma 已提交
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
	 * of ranges and calling .detach on them
	 */
	private static _handyReadyRange:Range;

	public static createRange(): Range {
		if (!RangeUtil._handyReadyRange) {
			RangeUtil._handyReadyRange = document.createRange();
		}
		return RangeUtil._handyReadyRange;
	}

	public static detachRange(range:Range, endNode:HTMLElement): void {
		// Move range out of the span node, IE doesn't like having many ranges in
		// the same spot and will act badly for lines containing dashes ('-')
		range.selectNodeContents(endNode);
	}
}

A
Alex Dima 已提交
526
function compareVisibleRanges(a: HorizontalRange, b: HorizontalRange): number {
A
Andre Weinand 已提交
527
	return a.left - b.left;
E
Erich Gamma 已提交
528 529 530 531 532 533 534
}

function findIndexInArrayWithMax(lineParts:ILineParts, desiredIndex: number, maxResult:number): number {
	var r = lineParts.findIndexOfOffset(desiredIndex);
	return r <= maxResult ? r : maxResult;
}

A
Alex Dima 已提交
535
export var createLine: (context: IViewContext) => IViewLineData = (function() {
E
Erich Gamma 已提交
536 537 538 539 540 541 542 543 544 545
	if (window.screen && window.screen.deviceXDPI && (navigator.userAgent.indexOf('Trident/6.0') >= 0 || navigator.userAgent.indexOf('Trident/5.0') >= 0)) {
		// IE11 doesn't need the screen.logicalXDPI / screen.deviceXDPI ratio multiplication
		// for TextRange.getClientRects() anymore
		return createIELine;
	} else if (Browser.isWebKit) {
		return createWebKitLine;
	}
	return createNormalLine;
})();

A
Alex Dima 已提交
546
function createIELine(context: IViewContext): IViewLineData {
E
Erich Gamma 已提交
547 548 549
	return new IEViewLine(context);
}

A
Alex Dima 已提交
550
function createWebKitLine(context: IViewContext): IViewLineData {
E
Erich Gamma 已提交
551 552 553
	return new WebKitViewLine(context);
}

A
Alex Dima 已提交
554
function createNormalLine(context: IViewContext): IViewLineData {
E
Erich Gamma 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
	return new ViewLine(context);
}

export interface IRenderLineInput {
	lineContent: string;
	tabSize: number;
	stopRenderingLineAfter: number;
	renderWhitespace: boolean;
	parts: EditorCommon.ILineToken[];
}

export interface IRenderLineOutput {
	charOffsetInPart: number[];
	hasOverflowed: boolean;
	lastRenderedPartIndex: number;
	partsCount: number;
	output: string[];
}

var _space = ' '.charCodeAt(0);
var _tab = '\t'.charCodeAt(0);
var _lowerThan = '<'.charCodeAt(0);
var _greaterThan = '>'.charCodeAt(0);
var _ampersand = '&'.charCodeAt(0);
var _carriageReturn = '\r'.charCodeAt(0);
var _lineSeparator = '\u2028'.charCodeAt(0); //http://www.fileformat.info/info/unicode/char/2028/index.htm
var _bom = 65279;
var _replacementCharacter = '\ufffd';

export function renderLine(input:IRenderLineInput): IRenderLineOutput {
	var lineText = input.lineContent;

	var result: IRenderLineOutput = {
		charOffsetInPart: [],
		hasOverflowed: false,
		lastRenderedPartIndex: 0,
		partsCount: 0,
		output: []
	};

	var partsCount = 0;

	result.output.push('<span>');
	if (lineText.length > 0) {
		var charCode: number,
			i: number,
			len = lineText.length,
			partClassName: string,
			partIndex = -1,
			nextPartIndex = 0,
			tabsCharDelta = 0,
			charOffsetInPart = 0,
			append = '',
			tabSize = input.tabSize,
			insertSpacesCount: number,
			stopRenderingLineAfter = input.stopRenderingLineAfter,
			renderWhitespace = false;

		var actualLineParts = input.parts;
		if (actualLineParts.length === 0) {
			throw new Error('Cannot render non empty line without line parts!');
		}

		if (stopRenderingLineAfter !== -1 && len > stopRenderingLineAfter - 1) {
			append = lineText.substr(stopRenderingLineAfter - 1, 1);
			len = stopRenderingLineAfter - 1;
			result.hasOverflowed = true;
		}

		for (i = 0; i < len; i++) {
			if (i === nextPartIndex) {
				partIndex++;
				nextPartIndex = (partIndex + 1 < actualLineParts.length ? actualLineParts[partIndex + 1].startIndex : Number.MAX_VALUE);
				if (i > 0) {
					result.output.push('</span>');
				}
				partsCount++;
				result.output.push('<span class="');
				partClassName = 'token ' + actualLineParts[partIndex].type.replace(/[^a-z0-9\-]/gi, ' ');
				if (input.renderWhitespace) {
					renderWhitespace = partClassName.indexOf('whitespace') >= 0;
				}
				result.output.push(partClassName);
				result.output.push('">');

				charOffsetInPart = 0;
			}

			result.charOffsetInPart[i] = charOffsetInPart;
			charCode = lineText.charCodeAt(i);

			switch (charCode) {
				case _tab:
					insertSpacesCount = tabSize - (i + tabsCharDelta) % tabSize;
					tabsCharDelta += insertSpacesCount - 1;
					charOffsetInPart += insertSpacesCount - 1;
					if (insertSpacesCount > 0) {
						result.output.push(renderWhitespace ? '&rarr;' : '&nbsp;');
						insertSpacesCount--;
					}
					while (insertSpacesCount > 0) {
						result.output.push('&nbsp;');
						insertSpacesCount--;
					}
					break;

				case _space:
					result.output.push(renderWhitespace ? '&middot;' : '&nbsp;');
					break;

				case _lowerThan:
					result.output.push('&lt;');
					break;

				case _greaterThan:
					result.output.push('&gt;');
					break;

				case _ampersand:
					result.output.push('&amp;');
					break;

				case 0:
					result.output.push('&#00;');
					break;

				case _bom:
				case _lineSeparator:
					result.output.push(_replacementCharacter);
					break;

				case _carriageReturn:
					// zero width space, because carriage return would introduce a line break
					result.output.push('&#8203');
					break;

				default:
					result.output.push(lineText.charAt(i));
			}

			charOffsetInPart ++;
		}
		result.output.push('</span>');

		// 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
		result.charOffsetInPart[len] = charOffsetInPart;

		// In case we stop rendering, we record here the index of the last span
		// that should be used for getting client rects
		result.lastRenderedPartIndex = partIndex;

		if (append.length > 0) {
			result.output.push('<span class="');
			result.output.push(partClassName);
			result.output.push('" style="color:grey">');
			result.output.push(append);
			result.output.push('&hellip;</span>');
		}
	} else {
		// This is basically for IE's hit test to work
		result.output.push('<span>&nbsp;</span>');
	}
	result.output.push('</span>');

	result.partsCount = partsCount;

	return result;
A
Andre Weinand 已提交
723
}