vscode#TextDocument TypeScript Examples
The following examples show how to use
vscode#TextDocument.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From dendron with GNU Affero General Public License v3.0 | 7 votes |
isInFencedCodeBlock = (
documentOrContent: TextDocument | string,
lineNum: number
): boolean => {
const content =
typeof documentOrContent === "string"
? documentOrContent
: documentOrContent.getText();
const textBefore = content
.slice(0, positionToOffset(content, { line: lineNum, column: 0 }))
.replace(REGEX_FENCED_CODE_BLOCK, "")
.replace(/<!--[\W\w]+?-->/g, "");
// So far `textBefore` should contain no valid fenced code block or comment
return /^( {0,3}|\t)```[^`\r\n]*$[\w\W]*$/gm.test(textBefore);
}
Example #2
Source File: utils.ts From vscode-stripe with MIT License | 7 votes |
export function getJavaFilePathOfTextDocument(document: TextDocument): string | undefined {
if (document) {
const resource = document.uri;
if (resource.scheme === 'file' && resource.fsPath.endsWith('.java')) {
return path.normalize(resource.fsPath);
}
}
return undefined;
}
Example #3
Source File: DoExport.ts From vscode-alxmldocumentation with MIT License | 6 votes |
public async ExportPdf(activeEditor: TextEditor | undefined) {
if ((activeEditor === undefined) || (activeEditor === null)) {
return;
}
this.activeEditor = activeEditor;
this.VerifyPrerequisite();
var document: TextDocument = activeEditor!.document;
document.save();
this.output = this.getOutputChannel(Configuration.OutputChannelName());
this.output.show(true);
this.output.appendLine(this.extensionManifest.displayName + ' version ' + this.extensionManifest.version);
this.output.appendLine('Copyright (C) 365 business development. All rights reserved');
this.output.appendLine('');
try
{
this.output.appendLine(`${StringUtil.GetTimestamp()} Starting documentation PDF file export.`);
let startTime = Date.now();
await ALObjectDocumentationExport.ExportAsPdf(this.output);
let endTime = Date.now();
this.output.appendLine(`${StringUtil.GetTimestamp()} PDF file creation has finished. Processing took ${Math.round((endTime - startTime) * 100 / 100)}ms.`);
} catch (ex) {
window.showErrorMessage('An error occurred while processing. See output for further information.');
this.output.appendLine('');
this.output.appendLine(ex.message);
return;
}
}
Example #4
Source File: ahkHoverProvider.ts From vscode-autohotkey with MIT License | 6 votes |
public async provideHover(document: TextDocument, position: Position, token: CancellationToken) {
const context = this.buildContext(document, position)
const snippetHover = this.tryGetSnippetHover(context)
if (snippetHover) {
return snippetHover;
}
const method = await Parser.getMethodByName(document, context.word)
if (method) {
const markdonw = new MarkdownString("", true).appendCodeblock(method.full)
if (method.comment) {
markdonw.appendText(method.comment)
}
return new Hover(markdonw)
}
return null
}
Example #5
Source File: element-completion-item-povider.ts From element-ui-helper with MIT License | 6 votes |
/**
* 提供自动完成提示
*
* @param document 文档
* @param position 位置
* @param token token
* @param context 上下文
*/
provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext): ProviderResult<CompletionItem[] | CompletionList<CompletionItem>> {
this._document = document
this._position = position
this.token = token
let tag: TagObject | undefined = this.getPreTag()
let attr = this.getPreAttr()
if (!tag || !/^[E|e]l/.test(tag.text || '')) {
// 如果不是element的标签(E|el开头) 则返回 null 表示没有hover
return null
} else if (this.isAttrValueStart(tag, attr)) {
// 如果是属性值的开始
return this.getAttrValueCompletionItems(tag.text, attr)
} else if (this.isEventStart(tag)) {
// 优先判定事件
return this.getEventCompletionItems(tag.text)
} else if (this.isAttrStart(tag)) {
// 判断属性
return this.getAttrCompletionItems(tag.text)
} else if (this.isTagStart()) {
// 判断标签
return this.getTagCompletionItems(tag.text)
}
return null
}
Example #6
Source File: spProviders.ts From sourcepawn-vscode with MIT License | 6 votes |
public async provideReferences(
document: TextDocument,
position: Position,
context: ReferenceContext,
token: CancellationToken
): Promise<Location[]> {
return referencesProvider(
this.itemsRepository,
position,
document,
context,
token
);
}
Example #7
Source File: lexDefinition.ts From yash with MIT License | 6 votes |
export function doLEXFindDefinition(document: TextDocument, position: Position, lexDocument: LexDocument): Definition | null {
const offset = document.offsetAt(position);
const node = lexDocument.getEmbeddedCode(offset);
if (node) {
return null;
}
const word = document.getText(document.getWordRangeAtPosition(position));
var symbol: ISymbol | undefined = lexDocument.defines[word] || lexDocument.states[word];
let location: Location | null = null;
if (symbol) {
location = new Location(document.uri, new Range(document.positionAt(symbol.definition[0]), document.positionAt(symbol.definition[1])));
}
return location;
}
Example #8
Source File: comment-lens-provider.ts From vscode-code-review with MIT License | 6 votes |
public provideCodeLenses(document: TextDocument, token: CancellationToken): CodeLens[] | Thenable<CodeLens[]> {
return this.exportFactory.getFilesContainingComments().then((filesWithComments) => {
const codeLenses: CodeLens[] = [];
filesWithComments.forEach((el) => {
if (document.fileName.endsWith(el.data.group)) {
el.data.lines.forEach((csvEntry) => {
const fileSection: ReviewFileExportSection = {
group: csvEntry.filename,
lines: el.data.lines,
};
const csvRef: CsvEntry | undefined = csvEntry;
const prio = Number(csvEntry.priority); // be sure the value is a number
const priorityString = prio
? ` | Priority: ${csvEntry.priority}${symbolForPriority(Number(csvEntry.priority))}`
: '';
const command: Command = {
title: `Code Review: ${csvEntry.title}${priorityString}`,
tooltip: csvEntry.comment,
command: 'codeReview.openSelection',
arguments: [fileSection, csvRef],
};
rangesFromStringDefinition(csvEntry.lines).forEach((range: Range) => {
codeLenses.push(new CodeLens(range, command));
});
});
}
});
return codeLenses;
});
}
Example #9
Source File: format.ts From format-imports-vscode with MIT License | 6 votes |
export async function formatDocument(document: TextDocument, from: TriggeredFrom) {
const log = logger('vscode.formatDocument');
if (!isSupported(document)) return undefined;
const { uri: fileUri, languageId, eol } = document;
const { fsPath: fileName } = fileUri;
log.debug('Triggered from:', from);
try {
const config = resolveConfig(fileUri, languageId, eol, from === 'onCommand');
if (from === 'onSave' && config.autoFormat !== 'onSave') {
log.info('Auto format is', config.autoFormat);
return undefined;
}
if (isFileExcludedByConfig(fileName, config)) {
const { exclude, excludeGlob } = config;
log.info('Excluded fileName:', fileName, 'via config:', { exclude, excludeGlob });
return undefined;
}
const sourceText = document.getText();
const newText = await formatSourceFromFile(sourceText, fileName, config);
log.info('Finished', newText === undefined ? 'format with no-op' : 'format');
return newText;
} catch (e: unknown) {
log.error('Found exception:', e);
void window
.showErrorMessage(
'Something is wrong. Please open the logs and report an issue.',
'Open logs & report an issue',
)
.then(v => {
if (!v) return;
vscChannel.show();
const p = new URLSearchParams({
title: `Exception: ${e instanceof Error ? e.message : e}`,
});
void commands.executeCommand('vscode.open', Uri.parse(ISSUE_URL + p.toString()));
});
}
return undefined;
}
Example #10
Source File: WorkspaceWatcher.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
async onDidSaveTextDocument(document: TextDocument) {
if (SchemaUtils.isSchemaUri(document.uri)) {
await this._schemaSyncService.onDidSave({
document,
});
} else {
await this.onDidSaveNote(document);
}
}
Example #11
Source File: gopExtraInfo.ts From vscode-goplus with Apache License 2.0 | 6 votes |
public provideHover(document: TextDocument, position: Position, token: CancellationToken): Thenable<Hover> {
if (!this.goPlusConfig) {
this.goPlusConfig = getGoPlusConfig(document.uri);
}
let goPlusConfig = this.goPlusConfig;
// Temporary fix to fall back to godoc if guru is the set docsTool
if (goPlusConfig['docsTool'] === 'guru') {
goPlusConfig = Object.assign({}, goPlusConfig, { docsTool: 'godoc' });
}
return definitionLocation(document, position, goPlusConfig, true, token).then(
(definitionInfo) => {
if (definitionInfo == null) {
return null;
}
const lines = definitionInfo.declarationlines
.filter((line) => line !== '')
.map((line) => line.replace(/\t/g, ' '));
let text;
text = lines.join('\n').replace(/\n+$/, '');
const hoverTexts = new vscode.MarkdownString();
hoverTexts.appendCodeblock(text, 'go');
if (definitionInfo.doc != null) {
hoverTexts.appendMarkdown(definitionInfo.doc);
}
const hover = new Hover(hoverTexts);
return hover;
},
() => {
return null;
}
);
}
Example #12
Source File: DrawioEditorService.ts From vscode-drawio with GNU General Public License v3.0 | 6 votes |
public async createDrawioEditorInWebview(
webviewPanel: WebviewPanel,
document:
| { kind: "text"; document: TextDocument }
| { kind: "drawio"; document: DrawioBinaryDocument },
options: DrawioClientOptions
): Promise<DrawioEditor> {
const instance =
await this.drawioClientFactory.createDrawioClientInWebview(
document.document.uri,
webviewPanel,
options
);
const config = this.config.getDiagramConfig(document.document.uri);
const editor = new DrawioEditor(
PrivateSymbol,
webviewPanel,
instance,
document,
config
);
this.openedEditors.add(editor);
this.onEditorOpenedEmitter.emit({ editor });
editor.webviewPanel.onDidDispose(() => {
this.openedEditors.delete(editor);
});
return editor;
}
Example #13
Source File: json-reader.ts From Json-to-Dart-Model with MIT License | 6 votes |
onChange(document: TextDocument) {
if (this.hasData) {
if (document.fileName.endsWith('/models.jsonc') ||
document.uri.path.match(`${this.dirName}/`) !== null &&
document.languageId === 'jsonc' ||
document.uri.path.match(`${this.dirName}/`) !== null &&
document.languageId === 'json'
) {
const len = this.allData.length;
let i = 0;
while (i < len) {
const err = this.allData[i][0];
if (err) { break; }
++i;
}
while (this.length !== len) {
transformFromFile();
this.length = len;
}
};
}
}
Example #14
Source File: macroAutocompletionProvider.ts From vscode-dbt-power-user with MIT License | 6 votes |
provideCompletionItems(
document: TextDocument,
position: Position,
token: CancellationToken,
context: CompletionContext
): ProviderResult<CompletionItem[] | CompletionList<CompletionItem>> {
const range = document.getWordRangeAtPosition(position);
if (range && isEnclosedWithinCodeBlock(document, range)) {
return this.getAutoCompleteItems(document.uri);
}
return undefined;
}
Example #15
Source File: holes.ts From vscode-lean4 with Apache License 2.0 | 6 votes |
provideCodeActions(document: TextDocument, range: Range): Command[] {
const cmds: Command[] = [];
for (const hole of this.holes) {
if (!range.intersection(mkRange(hole))) { continue; }
for (const action of hole.results) {
cmds.push({
title: action.description,
command: this.executeHoleCommand,
arguments: [hole.file, hole.start.line, hole.start.column, action.name],
});
}
}
return cmds;
}
Example #16
Source File: extension.test.ts From typescript-explicit-types with GNU General Public License v3.0 | 6 votes |
performTypeGeneration = async (element: string, document: TextDocument, { expectedType }: TypeGenerationOptions = {}) => {
let fileText = document.getText();
const f1Position = fileText.indexOf(element);
const wordRange = document.getWordRangeAtPosition(document.positionAt(f1Position));
if (!wordRange) {
assert.fail(`${element} not found in file`);
}
const actions = await executeCodeActionProvider(document.uri, wordRange);
const generateAction = actions?.find((action) => action.command!.command === commandId);
if (!generateAction) assert.fail('Generate action not found');
const command = generateAction.command!;
await commands.executeCommand.apply(null, [command.command, ...command.arguments!]);
if (expectedType) {
fileText = document.getText();
const res = fileText.includes(`${element}: ${expectedType}`);
assert.strictEqual(res, true);
} else {
const diagnostics = languages
.getDiagnostics(document.uri)
.filter((x) => [DiagnosticSeverity.Error, DiagnosticSeverity.Warning].includes(x.severity));
assert.strictEqual(diagnostics.length, 0, JSON.stringify(diagnostics));
}
}
Example #17
Source File: HandlerService.ts From joplin-utils with MIT License | 6 votes |
/**
* close note watch
* @param e
*/
async handleCloseTextDocument(e: TextDocument) {
console.log('vscode.workspace.onDidCloseTextDocument: ', e)
if (
e.languageId === 'markdown' &&
path.dirname(e.uri.fsPath) === path.resolve(GlobalContext.context.globalStorageUri.fsPath, '.tempNote')
) {
const noteId = JoplinNoteUtil.getNoteIdByFileName(e.fileName)
if (!noteId) {
return
}
console.log('close note: ', noteId)
await remove(e.fileName)
GlobalContext.openNoteMap.delete(noteId)
GlobalContext.openNoteResourceMap.delete(noteId)
} else if (GlobalContext.openResourceMap.has(e.uri.fsPath)) {
const resourceId = GlobalContext.openResourceMap.get(e.fileName)!
console.log('close resourceId: ', resourceId)
await remove(e.fileName)
GlobalContext.openResourceMap.delete(resourceId)
}
}
Example #18
Source File: parser.ts From vscode-discord with MIT License | 6 votes |
private makeFileInfo(document: TextDocument) {
const linecount = document.lineCount;
const currentline =
window.activeTextEditor.selection.active.line + 1 > linecount
? linecount
: window.activeTextEditor.selection.active.line + 1;
return this.config
.get<string>("fileInfoText")
.replace(/{linecount}/g, linecount.toString())
.replace(/{currentline}/g, currentline.toString())
.replace(/{language}/g, document.languageId);
}
Example #19
Source File: extension.ts From vscode-crestron-splus with GNU General Public License v3.0 | 6 votes |
public async provideDocumentRangeFormattingEdits(
document: TextDocument,
range: Range,
_options: FormattingOptions,
_token: CancellationToken
): Promise<TextEdit[]> {
return this.provideEdits(document, {
rangeEnd: document.offsetAt(range.end),
rangeStart: document.offsetAt(range.start),
});
}
Example #20
Source File: hoverProvider.ts From vscode-stripe with MIT License | 6 votes |
async provideHover(
document: TextDocument,
position: Position,
token: CancellationToken,
): Promise<Hover | undefined> {
const languageClient: LanguageClient | undefined = await getActiveJavaLanguageClient();
if (!languageClient) {
return undefined;
}
if (javaServerMode === ServerMode.STANDARD) {
if (!this.delegateProvider) {
this.delegateProvider = createClientHoverProvider(languageClient);
}
return this.delegateProvider.provideHover(document, position, token);
} else {
const params = {
textDocument: languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document),
position: languageClient.code2ProtocolConverter.asPosition(position),
};
const hoverResponse = await languageClient.sendRequest(HoverRequest.type, params, token);
return languageClient.protocol2CodeConverter.asHover(hoverResponse);
}
}
Example #21
Source File: ReferenceRenameProvider.ts From memo with MIT License | 6 votes |
public async prepareRename(
document: TextDocument,
position: Position,
): Promise<Range | { range: Range; placeholder: string }> {
if (document.isDirty) {
throw new Error('Rename is not available for unsaved files. Please save your changes first.');
}
const refAtPos = getReferenceAtPosition(document, position);
if (refAtPos) {
const { range, ref } = refAtPos;
const unknownUris = containsUnknownExt(ref) ? await findFilesByExts([extractExt(ref)]) : [];
const augmentedUris = unknownUris.length
? sortPaths([...cache.getWorkspaceCache().allUris, ...unknownUris], {
pathKey: 'path',
shallowFirst: true,
})
: cache.getWorkspaceCache().allUris;
if (!findUriByRef(augmentedUris, ref)) {
throw new Error(
'Rename is not available for nonexistent links. Create file first by clicking on the link.',
);
}
return new Range(
new Position(range.start.line, range.start.character + openingBracketsLength),
new Position(range.start.line, range.start.character + openingBracketsLength + ref.length),
);
}
throw new Error('Rename is not available. Please try when focused on the link.');
}
Example #22
Source File: startTask.ts From vscode-todo-md with MIT License | 6 votes |
export async function startTask(taskTreeItem?: TaskTreeItem) {
const workspaceEdit = new WorkspaceEdit();
let lineNumber: number;
let document: TextDocument;
if (taskTreeItem instanceof TaskTreeItem) {
lineNumber = taskTreeItem.task.lineNumber;
document = await getActiveOrDefaultDocument();
startTaskAtLineWorkspaceEdit(workspaceEdit, document, lineNumber);
} else {
const editor = window.activeTextEditor;
if (!editor) {
return undefined;
}
document = editor.document;
for (const line of getSelectedLineNumbers(editor)) {
startTaskAtLineWorkspaceEdit(workspaceEdit, document, line);
}
}
return await applyEdit(workspaceEdit, document);
}