當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript TextDocument.getText方法代碼示例

本文整理匯總了TypeScript中vscode.TextDocument.getText方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript TextDocument.getText方法的具體用法?TypeScript TextDocument.getText怎麽用?TypeScript TextDocument.getText使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在vscode.TextDocument的用法示例。


在下文中一共展示了TextDocument.getText方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: applyChanges

export function applyChanges(original: TextDocument, modified: TextDocument, diffs: LineChange[]): string {
	const result: string[] = [];
	let currentLine = 0;

	for (let diff of diffs) {
		const isInsertion = diff.originalEndLineNumber === 0;
		const isDeletion = diff.modifiedEndLineNumber === 0;

		result.push(original.getText(new Range(currentLine, 0, isInsertion ? diff.originalStartLineNumber : diff.originalStartLineNumber - 1, 0)));

		if (!isDeletion) {
			let fromLine = diff.modifiedStartLineNumber - 1;
			let fromCharacter = 0;

			if (isInsertion && diff.originalStartLineNumber === original.lineCount) {
				fromLine = original.lineCount - 1;
				fromCharacter = original.lineAt(fromLine).range.end.character;
			}

			result.push(modified.getText(new Range(fromLine, fromCharacter, diff.modifiedEndLineNumber, 0)));
		}

		currentLine = isInsertion ? diff.originalStartLineNumber : diff.originalEndLineNumber;
	}

	result.push(original.getText(new Range(currentLine, 0, original.lineCount, 0)));

	return result.join('');
}
開發者ID:m-khosravi,項目名稱:vscode,代碼行數:29,代碼來源:staging.ts

示例2: provideCompletionItems

	public provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): Thenable<CompletionList> {

		let fileName = basename(document.fileName);

		let currentWord = this.getCurrentWord(document, position);
		let overwriteRange : Range;

		let items: CompletionItem[] = [];
		let isIncomplete = false;

		let offset = document.offsetAt(position);
		let location = getLocation(document.getText(), offset);

		let node = location.previousNode;
		if (node && node.offset <= offset && offset <= node.offset + node.length && (node.type === 'property' || node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
			overwriteRange = new Range(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
		} else {
			overwriteRange = new Range(document.positionAt(offset - currentWord.length), position);
		}
		let filterText = document.getText(new Range(overwriteRange.start, position));

		let proposed: { [key: string]: boolean } = {};
		let collector: ISuggestionsCollector = {
			add: (suggestion: CompletionItem) => {
				if (!proposed[suggestion.label]) {
					proposed[suggestion.label] = true;
					suggestion.textEdit = TextEdit.replace(overwriteRange, suggestion.insertText);
					suggestion.filterText = filterText;

					items.push(suggestion);
				}
			},
			setAsIncomplete: () => isIncomplete = true,
			error: (message: string) => console.error(message),
			log: (message: string) => console.log(message)
		};

		let collectPromise : Thenable<any> = null;

		if (location.isAtPropertyKey) {
			let addValue = !location.previousNode || !location.previousNode.columnOffset;
			let isLast = this.isLast(document, position);
			collectPromise = this.jsonContribution.collectPropertySuggestions(fileName, location, currentWord, addValue, isLast, collector);
		} else {
			if (location.path.length === 0) {
				collectPromise = this.jsonContribution.collectDefaultSuggestions(fileName, collector);
			} else {
				collectPromise = this.jsonContribution.collectValueSuggestions(fileName, location, collector);
			}
		}
		if (collectPromise) {
			return collectPromise.then(() => {
				if (items.length > 0) {
					return new CompletionList(items, isIncomplete);
				}
				return null;
			});
		}
		return null;
	}
開發者ID:Aarushi-Ign,項目名稱:vscode,代碼行數:60,代碼來源:jsonContributions.ts

示例3: applyLineChanges

export function applyLineChanges(original: TextDocument, modified: TextDocument, diffs: LineChange[]): string {
	const result: string[] = [];
	let currentLine = 0;

	for (let diff of diffs) {
		const isInsertion = diff.originalEndLineNumber === 0;
		const isDeletion = diff.modifiedEndLineNumber === 0;

		result.push(original.getText(new Range(currentLine, 0, isInsertion ? diff.originalStartLineNumber : diff.originalStartLineNumber - 1, 0)));

		if (!isDeletion) {
			let fromLine = diff.modifiedStartLineNumber - 1;
			let fromCharacter = 0;

			// if this is an insertion at the very end of the document,
			// then we must start the next range after the last character of the
			// previous line, in order to take the correct eol
			if (isInsertion && diff.originalStartLineNumber === original.lineCount) {
				fromLine -= 1;
				fromCharacter = modified.lineAt(fromLine).range.end.character;
			}

			result.push(modified.getText(new Range(fromLine, fromCharacter, diff.modifiedEndLineNumber, 0)));
		}

		currentLine = isInsertion ? diff.originalStartLineNumber : diff.originalEndLineNumber;
	}

	result.push(original.getText(new Range(currentLine, 0, original.lineCount, 0)));

	return result.join('');
}
開發者ID:DonJayamanne,項目名稱:vscode,代碼行數:32,代碼來源:staging.ts

示例4: resolve

        return new Promise<Command[]>((resolve, reject) => {
            let commands: Command[] = [
                {
                    command: 'python.sortImports',
                    title: 'Sort Imports'
                }
            ];

            if (vscode.window.activeTextEditor.document === document && !vscode.window.activeTextEditor.selection.isEmpty) {
                let wordRange = document.getWordRangeAtPosition(range.start);
                // If no word has been selected by the user, then don't display rename
                // If something has been selected, then ensure we have selected a word (i.e. end and start matches the word range) 
                if (wordRange && !wordRange.isEmpty && wordRange.isEqual(vscode.window.activeTextEditor.selection)) {
                    let word = document.getText(wordRange).trim();
                    if (word.length > 0) {
                        commands.push({ command: 'editor.action.rename', title: 'Rename Symbol' });
                    }
                }
            }

            if (!range.isEmpty) {
                let word = document.getText(range).trim();
                if (word.trim().length > 0) {
                    commands.push({ command: 'python.refactorExtractVariable', title: 'Extract Variable', arguments: [range] });
                    commands.push({ command: 'python.refactorExtractMethod', title: 'Extract Method', arguments: [range] });
                }
            }
            resolve(commands);
        });
開發者ID:walkoncross,項目名稱:pythonVSCode,代碼行數:29,代碼來源:codeActionProvider.ts

示例5: provideCompletionItems

  provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken) : CompletionItem[] {
    const start = new Position(position.line, 0);
    const range = new Range(start, position);
    const currentWord = document.getText(range).trim();
    const text = document.getText();
    const value = isValue(cssSchema, currentWord);
    const config = workspace.getConfiguration('languageStylus');

    let symbols = [],
        atRules = [],
        properties = [],
        values = [];

    if (value) {
      values = getValues(cssSchema, currentWord);
      symbols = compact(getAllSymbols(text, currentWord)).filter(item =>
        item.kind === CompletionItemKind.Variable
      );
    } else {
      atRules = getAtRules(cssSchema, currentWord);
      properties = getProperties(cssSchema, currentWord, config.get('useSeparator', true));
      symbols = compact(getAllSymbols(text, currentWord));
    }

    const completions = [].concat(
      symbols,
      atRules,
      properties,
      values,
      config.get('useBuiltinFunctions', true) ? builtIn : []
    );

    return completions;
  }
開發者ID:d4rkr00t,項目名稱:language-stylus,代碼行數:34,代碼來源:completion-item-provider.ts

示例6: provideDefinition

    public async provideDefinition(document: TextDocument, position: Position, token: CancellationToken): Promise<Definition> {
        if (!VariableUtility.isVariableReference(document, position)) {
            return;
        }

        let documentLines = document.getText().split(Constants.LineSplitterRegex);

        let wordRange = document.getWordRangeAtPosition(position);
        let selectedVariableName = document.getText(wordRange);

        let locations = VariableUtility.getDefinitionRanges(documentLines, selectedVariableName);
        return locations.map(location => new Location(document.uri, location));
    }
開發者ID:Huachao,項目名稱:vscode-restclient,代碼行數:13,代碼來源:customVariableDefinitionProvider.ts

示例7: Promise

 return new Promise( (resolve, reject) => {
     
     let wordRange = document.getWordRangeAtPosition( position );
     let word = document.getText( wordRange )
     
     var finder = new VariableFinder();
     var results = finder.findDefinitionInText( document.getText(), word );
     
     if( results.length > 0 ) {
         let hover = new Hover( {language: 'cm', value: `${results[0].type} ${word}` } );
         resolve( hover ); 
     } else {
         resolve();
     }
 });
開發者ID:acauan,項目名稱:vscode-cm,代碼行數:15,代碼來源:cmHover.ts

示例8: doValidate

async function doValidate(document: TextDocument) {
	let report = null;

	let documentWasClosed = false; // track whether the document was closed while getInstalledModules/'npm ls' runs
	const listener = workspace.onDidCloseTextDocument(doc => {
		if (doc.uri === document.uri) {
			documentWasClosed = true;
		}
	});

	try {
		report = await getInstalledModules(path.dirname(document.fileName));
	} catch (e) {
		listener.dispose();
		return;
	}
	try {
		diagnosticCollection.clear();

		if (report.invalid && report.invalid === true) {
			return;
		}
		if (!anyModuleErrors(report)) {
			return;
		}
		if (documentWasClosed || !document.getText()) {
			return;
		}
		const sourceRanges = parseSourceRanges(document.getText());
		const dependencies = report.dependencies;
		const diagnostics: Diagnostic[] = [];

		for (var moduleName in dependencies) {
			if (dependencies.hasOwnProperty(moduleName)) {
				const diagnostic = getDiagnostic(document, report, moduleName, sourceRanges);
				if (diagnostic) {
					diagnostic.source = 'npm';
					diagnostics.push(diagnostic);
				}
			}
		}
		//console.log("diagnostic count ", diagnostics.length, " ", document.uri.fsPath);
		diagnosticCollection.set(document.uri, diagnostics);
	} catch (e) {
		window.showInformationMessage(`[npm-script-runner] Cannot validate the package.json ` + e);
		console.log(`npm-script-runner: 'error while validating package.json stacktrace: ${e.stack}`);
	}
}
開發者ID:scytalezero,項目名稱:vscode-npm-scripts,代碼行數:48,代碼來源:main.ts

示例9: provideReferences

 public async provideReferences(document: TextDocument, position: Position, context: ReferenceContext, token: CancellationToken): Promise<Location[]> {
     if (!VariableUtility.isVariableDefinition(document, position) && !VariableUtility.isVariableReference(document, position)) {
         return;
     }
     let documentLines = document.getText().split(Constants.LineSplitterRegex);
     let wordRange = document.getWordRangeAtPosition(position);
     let selectedVariableName = document.getText(wordRange);
     let locations: Range[] = [];
     if (context.includeDeclaration) {
         let definitionLocations = VariableUtility.getDefinitionRanges(documentLines, selectedVariableName);
         locations.push(...definitionLocations);
     }
     let referenceLocations = VariableUtility.getReferenceRanges(documentLines, selectedVariableName);
     locations.push(...referenceLocations);
     return locations.map(location => new Location(document.uri, location));
 }
開發者ID:Huachao,項目名稱:vscode-restclient,代碼行數:16,代碼來源:customVariableReferenceProvider.ts

示例10: provideDocumentHighlights

	public async provideDocumentHighlights(
		resource: TextDocument,
		position: Position,
		token: CancellationToken
	): Promise<DocumentHighlight[]> {
		const filepath = this.client.normalizePath(resource.uri);
		if (!filepath) {
			return [];
		}

		const args = vsPositionToTsFileLocation(filepath, position);
		try {
			const response = await this.client.execute('occurrences', args, token);
			const data = response.body;
			if (data && data.length) {
				// Workaround for https://github.com/Microsoft/TypeScript/issues/12780
				// Don't highlight string occurrences
				const firstOccurrence = data[0];
				if (this.client.apiVersion.has213Features() && firstOccurrence.start.offset > 1) {
					// Check to see if contents around first occurrence are string delimiters
					const contents = resource.getText(new Range(firstOccurrence.start.line - 1, firstOccurrence.start.offset - 1 - 1, firstOccurrence.end.line - 1, firstOccurrence.end.offset - 1 + 1));
					if (contents && contents.length > 2 && stringDelimiters.indexOf(contents[0]) >= 0 && contents[0] === contents[contents.length - 1]) {
						return [];
					}
				}
				return data.map(item =>
					new DocumentHighlight(
						tsTextSpanToVsRange(item),
						item.isWriteAccess ? DocumentHighlightKind.Write : DocumentHighlightKind.Read));
			}
			return [];
		} catch {
			return [];
		}
	}
開發者ID:JarnoNijboer,項目名稱:vscode,代碼行數:35,代碼來源:documentHighlightProvider.ts


注:本文中的vscode.TextDocument.getText方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。