vscode#TextEditor TypeScript Examples
The following examples show how to use
vscode#TextEditor.
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: decoration-utils.ts From vscode-code-review with MIT License | 7 votes |
/**
* Highlight a matching review comment with decorations an underline decoration
*
* @param csvEntries The selection to highlight
* @param editor The editor to work on
* @return all highlighting decorations
*/
underlineDecoration(csvEntries: CsvEntry[], editor: TextEditor): void {
const decorationOptions: DecorationOptions[] = [];
// build decoration options for each comment block
csvEntries.forEach((entry) => {
// iterate over multi-selections
rangesFromStringDefinition(entry.lines).forEach((range: Range) => {
decorationOptions.push({ range });
});
});
editor.setDecorations(this.decorationDeclarationType, decorationOptions);
}
Example #2
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 #3
Source File: formatting.ts From twee3-language-tools with MIT License | 6 votes |
function getContext(editor: TextEditor, cursorPos: Position, startPattern: string, endPattern: string): string {
let startPositionCharacter = cursorPos.character - startPattern.length;
let endPositionCharacter = cursorPos.character + endPattern.length;
if (startPositionCharacter < 0) {
startPositionCharacter = 0;
}
let leftText = editor.document.getText(new Range(cursorPos.line, startPositionCharacter, cursorPos.line, cursorPos.character));
let rightText = editor.document.getText(new Range(cursorPos.line, cursorPos.character, cursorPos.line, endPositionCharacter));
if (rightText === endPattern) {
if (leftText === startPattern) {
return `${startPattern}|${endPattern}`;
} else {
return `${startPattern}text|${endPattern}`;
}
}
return '|';
}
Example #4
Source File: review-comment.ts From vscode-code-review with MIT License | 6 votes |
/**
* Append a new comment
* @param comment The comment message
* @param editor The working text editor
*/
async addComment(comment: CsvEntry, editor: TextEditor | null = null) {
this.checkFileExists();
if (!this.getSelectedLines(comment, editor)) {
return;
}
comment.filename = standardizeFilename(this.workspaceRoot, editor!.document.fileName);
setCsvFileLines(this.reviewFile, [CsvStructure.formatAsCsvLine(this.finalizeComment(comment))], false);
}
Example #5
Source File: counterExamplesView.ts From ide-vscode with MIT License | 6 votes |
private async updateCounterExamples(editor?: TextEditor, debounce: boolean = true): Promise<void> {
if(editor == null) {
return;
}
const document = editor.document.uri;
if(!this.documentsWithActiveCounterExamples.has(document)) {
return;
}
this.hideCounterExamples(editor);
try {
const params: ICounterExampleParams = { textDocument: { uri: document.toString() } };
const counterExamples = debounce
? await this.getCounterExamplesDebounced(params)
: await this.languageClient.getCounterExamples(params);
if(!this.disposed) {
this.showCounterExamples(counterExamples, editor);
}
} catch(error: unknown) {
if(!(error instanceof DebounceError)) {
window.showErrorMessage(`CounterExample request failed: ${error}`);
}
}
}
Example #6
Source File: WSUtilsV2.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
async trySelectRevealNonNoteAnchor(
editor: TextEditor,
anchor: DNoteAnchorBasic
): Promise<void> {
let position: Position | undefined;
switch (anchor.type) {
case "line":
// Line anchors are direct line numbers from the start
position = new Position(anchor.line - 1 /* line 1 is index 0 */, 0);
break;
case "block":
// We don't parse non note files for anchors, so read the document and find where the anchor is
position = editor?.document.positionAt(
editor?.document.getText().indexOf(AnchorUtils.anchor2string(anchor))
);
break;
default:
// not supported for non-note files
position = undefined;
}
if (position) {
// if we did find the anchor, then select and scroll to it
editor.selection = new Selection(position, position);
editor.revealRange(editor.selection);
}
}
Example #7
Source File: ExecutionHighlighter.ts From vscode-realtime-debugging with GNU General Public License v3.0 | 6 votes |
constructor(
private readonly textEditor: TextEditor,
private readonly range: Range,
onHide: () => void
) {
this.type = window.createTextEditorDecorationType({
backgroundColor: "orange",
});
textEditor.setDecorations(this.type, [range]);
setTimeout(() => {
this.dispose();
onHide();
}, 1000);
}
Example #8
Source File: AbbreviationRewriterFeature.ts From vscode-lean4 with Apache License 2.0 | 6 votes |
private shouldEnableRewriterForEditor(editor: TextEditor): boolean {
if (!this.config.inputModeEnabled.get()) {
return false;
}
if (!languages.match(this.config.languages.get(), editor.document)) {
return false;
}
return true;
}
Example #9
Source File: command.ts From typescript-explicit-types with GNU General Public License v3.0 | 6 votes |
generateType = async (
{ typescriptHoverResult, typePosition, isFunction }: GenerateTypeInfo,
editor: TextEditor,
isAutoFormatOn?: boolean
) => {
const indexes = findMatchIndexes(/:/gm, typescriptHoverResult);
const dirtyType = typescriptHoverResult.slice(isFunction ? indexes.slice(-1)[0] : indexes[0]);
const cleanType = dirtyType.replace(/(`)/gm, '').replace(/\n+$/, '');
await editor.edit((editor) => editor.insert(typePosition, cleanType));
if (!isAutoFormatOn) return;
const document = editor.document;
const text = document.getText();
const typeIndex = text.indexOf(cleanType.replace(/\n/gm, '\r\n'), document.offsetAt(typePosition));
if (typeIndex < 0) return;
const typePositionStart = document.positionAt(typeIndex);
const typePositionEnd = document.positionAt(typeIndex + cleanType.length + (cleanType.match(/\n/gm)?.length ?? 0));
const typeRange = new Range(typePositionStart, typePositionEnd);
if (!typeRange) return;
if (isAutoFormatOn) {
const edits = await executeFormatDocumentProvider(document.uri);
if (!edits) return;
const workspaceEdit = new WorkspaceEdit();
workspaceEdit.set(document.uri, edits);
await workspace.applyEdit(workspaceEdit);
}
}
Example #10
Source File: listener.ts From vscode-discord with MIT License | 6 votes |
public listen() {
// just make sure that no double registration happens
this.dispose();
const fileSwitch = window.onDidChangeActiveTextEditor,
fileEdit = workspace.onDidChangeTextDocument,
debugStart = debug.onDidStartDebugSession,
debugEnd = debug.onDidTerminateDebugSession,
diagnostictsChange = languages.onDidChangeDiagnostics;
if (this.config.get("showFile"))
this.disposables.push(
fileSwitch((e: TextEditor) => this.parser.fileSwitch(e)),
fileEdit((e: TextDocumentChangeEvent) =>
this.parser.fileEdit(e)
)
);
if (this.config.get("showDebugging"))
this.disposables.push(
debugStart(() => this.parser.toggleDebug()),
debugEnd(() => this.parser.toggleDebug())
);
if (this.config.get("showProblems"))
this.disposables.push(
diagnostictsChange(() => this.parser.diagnosticsChange())
);
}
Example #11
Source File: archiveCompletedTasks.ts From vscode-todo-md with MIT License | 6 votes |
export function archiveCompletedTasks(editor: TextEditor) {
const selection = editor.selection;
if (selection.isEmpty) {
// Archive all completed tasks
// TODO: should there be a function `getCompletedTasks()`?
const completedTasks = $state.tasks.filter(t => t.done);
archiveTasks(completedTasks, editor.document);
} else {
// Archive only selected completed tasks
const selectedCompletedTasks = [];
for (let i = selection.start.line; i <= selection.end.line; i++) {
const task = getTaskAtLineExtension(i);
if (task && task.done) {
selectedCompletedTasks.push(task);
}
}
archiveTasks(selectedCompletedTasks, editor.document);
}
}
Example #12
Source File: client.ts From vala-vscode with MIT License | 6 votes |
peekSymbol(_editor: TextEditor, _edit: TextEditorEdit, lspCurrentLocation: lsp.Location, lspTargetLocation: lsp.Location): void {
let currentLocation = new Location(
Uri.parse(lspCurrentLocation.uri),
new Range(
new Position(lspCurrentLocation.range.start.line, lspCurrentLocation.range.start.character),
new Position(lspCurrentLocation.range.end.line, lspCurrentLocation.range.end.character)
)
);
let targetLocation = new Location(
Uri.parse(lspTargetLocation.uri),
new Range(
new Position(lspTargetLocation.range.start.line, lspTargetLocation.range.start.character),
new Position(lspTargetLocation.range.end.line, lspTargetLocation.range.end.character)
)
);
commands.executeCommand(
'editor.action.peekLocations',
currentLocation.uri, // anchor uri and position
currentLocation.range.end,
[targetLocation], // results (vscode.Location[])
'peek', // mode ('peek' | 'gotoAndPeek' | 'goto')
'Nothing found' // <- message
);
}
Example #13
Source File: extension.ts From vscode-plugin-swimming with MIT License | 6 votes |
function closeWriteCode(
_textEditor: TextEditor,
_edit: TextEditorEdit,
..._args: any[]
) {
isWriteCodePauseMap.clear();
isWritingCodeMap.clear();
commands.executeCommand('workbench.action.reloadWindow');
}
Example #14
Source File: DoComment.ts From vscode-alxmldocumentation with MIT License | 5 votes |
/**
* Do comment on current event.
* @param activeEditor TextEditor object.
* @param event TextDocumentContentChangeEvent object.
*/
public async DoComment(activeEditor: TextEditor, event: TextDocumentContentChangeEvent) {
this.event = event;
this.vsCodeApi = new VSCodeApi(activeEditor);
this.activeEditor = activeEditor;
if ((this.event === undefined) || (this.event === null) || (this.activeEditor === undefined) || (this.activeEditor === null)) {
return;
}
// if action comes from snippet an additional '/// ' is included
var doubleDocCommentIndex = this.vsCodeApi.ReadLineAtCurrent().indexOf('/// /// ');
if (doubleDocCommentIndex !== -1) {
const position: Position = this.vsCodeApi.GetPosition(this.vsCodeApi.GetActiveLine(), doubleDocCommentIndex);
const anchor: Position = this.vsCodeApi.GetPosition(position.line, position.character + 4);
const replaceSelection = this.vsCodeApi.GetSelectionByPosition(anchor, position);
this.activeEditor.edit((editBuilder) => {
editBuilder.replace(replaceSelection, '');
});
}
// If we're not we in a XML documentation line
if (!(this.vsCodeApi.ReadLine(this.vsCodeApi.GetActiveLine()).trim().startsWith('///'))) {
if (this.event.text !== '/') {
return;
}
}
if (!this.IsDoCommentTrigger()) {
return;
}
if (this.isEnterKey) {
var indent = StringUtil.GetIndentSpaces(this.vsCodeApi.ReadLine(this.vsCodeApi.GetActiveLine()).indexOf('///'));
const position: Position = this.vsCodeApi.GetActivePosition();
const anchor: Position = this.vsCodeApi.GetPosition(this.vsCodeApi.GetNextLine(), indent.length);
const replaceSelection = this.vsCodeApi.GetSelectionByPosition(anchor, position);
this.activeEditor.edit((editBuilder) => {
editBuilder.replace(replaceSelection, `\n${indent}/// `);
});
return;
}
if (this.vsCodeApi.ReadLine(this.vsCodeApi.GetNextLine()).trim().startsWith('///')) {
return;
}
if (!Configuration.DirectDocumentationIsEnabled(this.activeEditor.document.uri)) {
return;
}
await this.WriteDocString();
}
Example #15
Source File: activator.ts From plugin-vscode with Apache License 2.0 | 5 votes |
function showDiagramEditor(context: ExtensionContext, langClient: ExtendedLangClient): void {
const didChangeDisposable = workspace.onDidChangeTextDocument(
_.debounce((e: TextDocumentChangeEvent) => {
if (activeEditor && (e.document === activeEditor.document) &&
e.document.fileName.endsWith('.bal')) {
if (preventDiagramUpdate) {
return;
}
updateWebView(e.document.uri);
}
}, DEBOUNCE_WAIT));
const changeActiveEditorDisposable = window.onDidChangeActiveTextEditor(
(activatedEditor: TextEditor | undefined) => {
if (window.activeTextEditor && activatedEditor
&& (activatedEditor.document === window.activeTextEditor.document)
&& activatedEditor.document.fileName.endsWith('.bal')) {
activeEditor = window.activeTextEditor;
updateWebView(activatedEditor.document.uri);
}
});
if (diagramViewPanel) {
diagramViewPanel.reveal(ViewColumn.Two, true);
return;
}
// Create and show a new webview
diagramViewPanel = window.createWebviewPanel(
'ballerinaDiagram',
"Ballerina Diagram",
{ viewColumn: ViewColumn.Two, preserveFocus: true },
getCommonWebViewOptions()
);
diagramViewPanel.iconPath = {
light: Uri.file(join(context.extensionPath, 'resources/images/icons/design-view.svg')),
dark: Uri.file(join(context.extensionPath, 'resources/images/icons/design-view-inverse.svg'))
};
const editor = window.activeTextEditor;
if (!editor) {
return;
}
activeEditor = editor;
rpcHandler = WebViewRPCHandler.create(diagramViewPanel, langClient);
const html = render(editor.document.uri);
if (diagramViewPanel && html) {
diagramViewPanel.webview.html = html;
}
diagramViewPanel.onDidDispose(() => {
diagramViewPanel = undefined;
didChangeDisposable.dispose();
changeActiveEditorDisposable.dispose();
});
}
Example #16
Source File: formatting.ts From twee3-language-tools with MIT License | 5 votes |
export function styleByWrapping(editor: TextEditor, startPattern: string, endPattern = startPattern) {
let selections = editor.selections;
let batchEdit = new WorkspaceEdit();
let shifts: [Position, number][] = [];
let newSelections: Selection[] = selections.slice();
for (const [i, selection] of selections.entries()) {
let cursorPos = selection.active;
const shift = shifts.map(([pos, s]) => (selection.start.line === pos.line && selection.start.character >= pos.character) ? s : 0)
.reduce((a, b) => a + b, 0);
if (selection.isEmpty) {
const context = getContext(editor, cursorPos, startPattern, endPattern);
// Patterns are added for SugarCube
// No selected text
if (
startPattern === endPattern &&
["**", "*", "__", "_", "//", "''"].includes(startPattern) &&
context === `${startPattern}text|${endPattern}`
) {
// `**text|**` to `**text**|`
let newCursorPos = cursorPos.with({ character: cursorPos.character + shift + endPattern.length });
newSelections[i] = new Selection(newCursorPos, newCursorPos);
continue;
} else if (context === `${startPattern}|${endPattern}`) {
// `**|**` to `|`
let start = cursorPos.with({ character: cursorPos.character - startPattern.length });
let end = cursorPos.with({ character: cursorPos.character + endPattern.length });
wrapRange(editor, batchEdit, shifts, newSelections, i, shift, cursorPos, new Range(start, end), false, startPattern, endPattern);
} else {
// Select word under cursor
// The markdown extension uses a custom regex very similar to this one for their def
// of word. This removes the exclusion of certain characters since formats use them.
let wordRange = editor.document.getWordRangeAtPosition(cursorPos, /(-?\d*\.\d\w*)|([^\!\@\#\%\^\&\(\)\-\=\+\[\{\]\}\\\|\;\:\"\,\.\<\>\?\s\,\。\《\》\?\;\:\‘\“\’\”\(\)\【\】\、]+)/g);
if (wordRange == undefined) {
wordRange = selection;
}
// One special case: toggle strikethrough in task list
const currentTextLine = editor.document.lineAt(cursorPos.line);
if (startPattern === '~~' && /^\s*[\*\+\-] (\[[ x]\] )? */g.test(currentTextLine.text)) {
let match = currentTextLine.text.match(/^\s*[\*\+\-] (\[[ x]\] )? */g) as RegExpMatchArray;
wordRange = currentTextLine.range.with(new Position(cursorPos.line, match[0].length));
}
wrapRange(editor, batchEdit, shifts, newSelections, i, shift, cursorPos, wordRange, false, startPattern, endPattern);
}
} else {
// Text selected
wrapRange(editor, batchEdit, shifts, newSelections, i, shift, cursorPos, selection, true, startPattern, endPattern);
}
}
return workspace.applyEdit(batchEdit).then(() => {
editor.selections = newSelections;
});
}
Example #17
Source File: decoration-utils.test.ts From vscode-code-review with MIT License | 5 votes |
suite('Decoration Utils', () => {
let editorStub: TextEditor;
let lastSetDecorationConf: TextEditorDecorationType | undefined;
let lastSetDecorationSelection!: Selection[] | DecorationOptions[] | undefined;
beforeEach(() => {
editorStub = ({
selections: [new Selection(new Position(0, 1), new Position(2, 6))],
setDecorations: (conf: TextEditorDecorationType, selection: Selection[]) => {
lastSetDecorationConf = conf;
lastSetDecorationSelection = selection;
},
} as unknown) as TextEditor;
});
afterEach(() => {
lastSetDecorationConf = undefined;
lastSetDecorationSelection = undefined;
});
suite('underlineDecoration', () => {
test('should underline comments', () => {
const contextStub = {
asAbsolutePath: (p) => p,
} as ExtensionContext;
const deco = new Decorations(contextStub);
const csvEntries = [{ lines: '1:0-3:4|9:0-11:3' } as CsvEntry, { lines: '17:3-19:2' } as CsvEntry];
const decoration = deco.underlineDecoration(csvEntries, editorStub);
const decorationOptions = lastSetDecorationSelection as DecorationOptions[];
assert.ok(deco);
assert.deepStrictEqual(lastSetDecorationConf, deco.decorationDeclarationType);
assert.strictEqual(decorationOptions[0].range.start.line, 0);
assert.strictEqual(decorationOptions[0].range.start.character, 0);
assert.strictEqual(decorationOptions[0].range.end.line, 2);
assert.strictEqual(decorationOptions[0].range.end.character, 4);
assert.strictEqual(decorationOptions[1].range.start.line, 8);
assert.strictEqual(decorationOptions[1].range.start.character, 0);
assert.strictEqual(decorationOptions[1].range.end.line, 10);
assert.strictEqual(decorationOptions[1].range.end.character, 3);
assert.strictEqual(decorationOptions[2].range.start.line, 16);
assert.strictEqual(decorationOptions[2].range.start.character, 3);
assert.strictEqual(decorationOptions[2].range.end.line, 18);
assert.strictEqual(decorationOptions[2].range.end.character, 2);
});
});
suite('commentIconDecoration', () => {
test('should underline comments', () => {
const contextStub = {
asAbsolutePath: (p) => p,
} as ExtensionContext;
const deco = new Decorations(contextStub);
const csvEntries = [{ lines: '1:0-3:4|9:0-11:3' } as CsvEntry, { lines: '17:3-19:2' } as CsvEntry];
const decoration = deco.commentIconDecoration(csvEntries, editorStub);
const decorationOptions = lastSetDecorationSelection as DecorationOptions[];
assert.ok(deco);
assert.deepStrictEqual(lastSetDecorationConf, deco.commentDecorationType);
assert.strictEqual(decorationOptions[0].range.start.line, 0);
assert.strictEqual(decorationOptions[0].range.start.character, 1024);
assert.strictEqual(decorationOptions[0].range.end.line, 0);
assert.strictEqual(decorationOptions[0].range.end.character, 1024);
assert.strictEqual(decorationOptions[1].range.start.line, 8);
assert.strictEqual(decorationOptions[1].range.start.character, 1024);
assert.strictEqual(decorationOptions[1].range.end.line, 8);
assert.strictEqual(decorationOptions[1].range.end.character, 1024);
assert.strictEqual(decorationOptions[2].range.start.line, 16);
assert.strictEqual(decorationOptions[2].range.start.character, 1024);
assert.strictEqual(decorationOptions[2].range.end.line, 16);
assert.strictEqual(decorationOptions[2].range.end.character, 1024);
});
});
suite('colorizedBackgroundDecoration', () => {
test('should colorize the given selection with decoration', () => {
const selections = [new Range(new Position(2, 5), new Position(2, 5))];
const decoration = colorizedBackgroundDecoration(selections, editorStub, '#fdfdfd');
assert.ok(decoration);
assert.deepStrictEqual(lastSetDecorationConf, decoration);
assert.deepStrictEqual(lastSetDecorationSelection, selections);
});
});
});
Example #18
Source File: extension.ts From format-imports-vscode with MIT License | 5 votes |
async function sortImportsByCommand(editor: TextEditor, _: TextEditorEdit, from?: TriggeredFrom) {
if (!editor) return;
const { document } = editor;
if (!document) return;
const newSourceText = await formatDocument(document, from === 'codeAction' ? from : 'onCommand');
if (newSourceText === undefined) return;
void editor.edit(edit => edit.replace(fullRange(document), newSourceText));
}
Example #19
Source File: WorkspaceWatcher.ts From dendron with GNU Affero General Public License v3.0 | 5 votes |
activate(context: ExtensionContext) {
this._extension.addDisposable(
workspace.onWillSaveTextDocument(
this.onWillSaveTextDocument,
this,
context.subscriptions
)
);
this._extension.addDisposable(
workspace.onDidChangeTextDocument(
this._quickDebouncedOnDidChangeTextDocument,
this,
context.subscriptions
)
);
this._extension.addDisposable(
workspace.onDidSaveTextDocument(
this.onDidSaveTextDocument,
this,
context.subscriptions
)
);
// NOTE: currently, this is only used for logging purposes
if (Logger.isDebug()) {
this._extension.addDisposable(
workspace.onDidOpenTextDocument(
this.onDidOpenTextDocument,
this,
context.subscriptions
)
);
}
this._extension.addDisposable(
workspace.onWillRenameFiles(
this.onWillRenameFiles,
this,
context.subscriptions
)
);
this._extension.addDisposable(
workspace.onDidRenameFiles(
this.onDidRenameFiles,
this,
context.subscriptions
)
);
this._extension.addDisposable(
window.onDidChangeActiveTextEditor(
sentryReportingCallback((editor: TextEditor | undefined) => {
if (
editor?.document &&
this.getNewlyOpenedDocument(editor.document)
) {
this.onFirstOpen(editor);
}
}),
this,
context.subscriptions
)
);
}