vscode#Range TypeScript Examples
The following examples show how to use
vscode#Range.
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 sourcepawn-vscode with MIT License | 7 votes |
export function positiveRange(
lineNb: number,
start: number = 0,
end: number = 0
): Range {
lineNb = lineNb > 0 ? lineNb : 0;
start = start > 0 ? start : 0;
end = end > 0 ? end : 0;
return new Range(lineNb, start, lineNb, end);
}
Example #2
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 #3
Source File: RegisterProvider.ts From vscode-alxmldocumentation with MIT License | 6 votes |
private RegisterCodeActions() {
commands.registerCommand(`${ALXmlDocConfigurationPrefix}.fixDocumentation`, ( alProcedure: ALProcedure ) => {
ALFixDocumentation.FixDocumentation(window.activeTextEditor, alProcedure);
});
commands.registerCommand(`${ALXmlDocConfigurationPrefix}.fixSummaryDocumentation`, ( alProcedure: ALProcedure ) => {
ALFixDocumentation.FixSummaryDocumentation(window.activeTextEditor, alProcedure);
});
commands.registerCommand(`${ALXmlDocConfigurationPrefix}.fixParameterDocumentation`, ( alProcedure: ALProcedure ) => {
ALFixDocumentation.FixParameterDocumentation(window.activeTextEditor, alProcedure);
});
commands.registerCommand(`${ALXmlDocConfigurationPrefix}.fixReturnDocumentation`, ( alProcedure: ALProcedure ) => {
ALFixDocumentation.FixReturnTypeDocumentation(window.activeTextEditor, alProcedure);
});
commands.registerCommand(`${ALXmlDocConfigurationPrefix}.fixUnnecessaryParameterDocumentation`, ( alProcedure: ALProcedure, range: Range ) => {
ALFixDocumentation.FixUnnecessaryParameterDocumentation(window.activeTextEditor, alProcedure, range);
});
commands.registerCommand(`${ALXmlDocConfigurationPrefix}.fixObjectDocumentation`, ( alObject: ALObject ) => {
ALFixDocumentation.FixObjectDocumentation(window.activeTextEditor, alObject);
});
}
Example #4
Source File: ahkHoverProvider.ts From vscode-autohotkey with MIT License | 6 votes |
private buildContext(document: TextDocument, position: Position): Context {
const line = position.line;
const wordRange = document.getWordRangeAtPosition(position)
let word = document.getText(wordRange);
if (wordRange.start.character > 0) {
const preChart = document.getText(new Range(line, wordRange.start.character - 1, line, wordRange.start.character))
if (preChart == "#") {
word = "#" + word;
}
}
const nextChart = document.getText(new Range(line, wordRange.end.character, line, wordRange.end.character + 1))
return { word, nextChart }
}
Example #5
Source File: element-completion-item-povider.ts From element-ui-helper with MIT License | 6 votes |
/**
* 获取前置属性
*/
getPreAttr(): string {
let txt = this.getTextBeforePosition(this._position).replace(/"[^'"]*(\s*)[^'"]*$/, '')
let end = this._position.character
let start = txt.lastIndexOf(' ', end) + 1
let parsedTxt = this._document.getText(new Range(this._position.line, start, this._position.line, end))
return this.matchAttr(this.attrReg, parsedTxt)
}
Example #6
Source File: coverage.ts From gnucobol-debug with GNU General Public License v3.0 | 6 votes |
private updateStatus() {
const editor = window.activeTextEditor;
if (editor === undefined) {
this.statusBar.hide();
return;
}
const red: Range[] = [];
const green: Range[] = [];
for (const coverage of this.coverages) {
for (const line of coverage.lines) {
if (this.sourceMap.hasLineCobol(coverage.file, line.line)) {
const map = this.sourceMap.getLineCobol(coverage.file, line.line);
if (editor.document.uri.fsPath !== map.fileCobol) {
continue;
}
const range = new Range(map.lineCobol - 1, 0, map.lineCobol - 1, Number.MAX_VALUE);
if (line.executed) {
green.push(range);
} else {
red.push(range);
}
}
}
}
if (red.length === 0 || !this.highlight) {
editor.setDecorations(this.RED, []);
} else {
editor.setDecorations(this.RED, red);
}
if (green.length === 0 || !this.highlight) {
editor.setDecorations(this.GREEN, []);
} else {
editor.setDecorations(this.GREEN, green);
}
this.statusBar.text = (this.highlight ? `$(eye) ` : `$(eye-closed) `) + Math.ceil(green.length * 100 / Math.max(1, red.length + green.length)) + '%';
this.statusBar.tooltip = `Covered ${green.length} of ${red.length} lines`;
this.statusBar.show();
}
Example #7
Source File: spDefineItem.ts From sourcepawn-vscode with MIT License | 6 votes |
constructor(
name: string,
value: string,
description: string,
file: string,
range: Range,
IsBuiltIn: boolean,
fullRange: Range
) {
this.name = name;
this.value = value;
this.description = description;
this.filePath = file;
this.range = range;
this.references = [];
this.IsBuiltIn = IsBuiltIn;
this.fullRange = fullRange;
}
Example #8
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 #9
Source File: codelens-provider.ts From plugin-vscode with Apache License 2.0 | 6 votes |
private createCodeLens(execPosition: ExecutorPosition, execType: EXEC_TYPE): CodeLens {
const startLine = execPosition.range.startLine.line;
const startColumn = execPosition.range.startLine.offset;
const endLine = execPosition.range.endLine.line;
const endColumn = execPosition.range.endLine.offset;
const codeLens = new CodeLens(new Range(startLine, startColumn, endLine, endColumn));
codeLens.command = {
title: execType.toString(),
tooltip: `${execType.toString()} ${execPosition.name}`,
command: execPosition.kind === EXEC_POSITION_TYPE.SOURCE ? (execType === EXEC_TYPE.RUN ? PALETTE_COMMANDS.RUN :
SOURCE_DEBUG_COMMAND) : (execType === EXEC_TYPE.RUN ? PALETTE_COMMANDS.TEST : TEST_DEBUG_COMMAND),
arguments: execPosition.kind === EXEC_POSITION_TYPE.SOURCE ? [] : (execType === EXEC_TYPE.RUN ?
[EXEC_ARG.TESTS, execPosition.name] : [execPosition.name])
};
return codeLens;
}
Example #10
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 #11
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 #12
Source File: counterExamplesView.ts From ide-vscode with MIT License | 6 votes |
private static createDecorator(counterExample: ICounterExampleItem): DecorationOptions {
const contentText = Object.entries(counterExample.variables)
.map(([ name, value ]) => `${name} = ${value}`)
.join(' ');
// TODO earlier versions showed a warning that there are references present.
const line = counterExample.position.line;
return {
range: new Range(
new Position(line, counterExample.position.character + 1),
new Position(line, Number.MAX_VALUE)
),
renderOptions: {
after: { contentText }
}
};
}
Example #13
Source File: CopyNoteRef.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
hasNextHeader(opts: { selection: Selection }) {
const { selection } = opts;
const lineEndForSelection = selection.end.line;
const editor = VSCodeUtils.getActiveTextEditor() as TextEditor;
const lineEndForDoc = editor.document.lineCount;
const text = editor.document.getText(
new Range(
new Position(lineEndForSelection + 1, 0),
new Position(lineEndForDoc, 0)
)
);
return !_.isNull(text.match(/^#+\s/m));
}
Example #14
Source File: CodeLinkFeature.ts From vscode-drawio with GNU General Public License v3.0 | 6 votes |
constructor(
public readonly uri: Uri | undefined,
private obj?: Range | string
) {
if (obj instanceof Range) {
this.range = obj as Range;
} else if (typeof obj == "string") {
this.symbol = obj as string;
}
}
Example #15
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 #16
Source File: annotationProvider.ts From vscode-inline-parameters with MIT License | 6 votes |
public static parameterAnnotation(
message: string,
range: Range
): DecorationOptions {
return {
range,
renderOptions: {
before: {
contentText: message,
color: new ThemeColor("inlineparameters.annotationForeground"),
backgroundColor: new ThemeColor("inlineparameters.annotationBackground"),
fontStyle: workspace.getConfiguration("inline-parameters").get("fontStyle"),
fontWeight: workspace.getConfiguration("inline-parameters").get("fontWeight"),
textDecoration: `;
font-size: ${workspace.getConfiguration("inline-parameters").get("fontSize")};
margin: ${workspace.getConfiguration("inline-parameters").get("margin")};
padding: ${workspace.getConfiguration("inline-parameters").get("padding")};
border-radius: ${workspace.getConfiguration("inline-parameters").get("borderRadius")};
border: ${workspace.getConfiguration("inline-parameters").get("border")};
vertical-align: middle;
`,
},
} as DecorationInstanceRenderOptions,
} as DecorationOptions
}
Example #17
Source File: modelDefinitionProvider.ts From vscode-dbt-power-user with MIT License | 6 votes |
private getDefinitionFor(
name: string,
currentFilePath: Uri
): Definition | undefined {
const projectRootpath = this.dbtProjectContainer.getProjectRootpath(
currentFilePath
);
if (projectRootpath === undefined) {
return;
}
const nodeMap = this.modelToLocationMap.get(projectRootpath.fsPath);
if (nodeMap === undefined) {
return;
}
const location = nodeMap.get(name);
if (location) {
return new Location(Uri.file(location.path), new Range(0, 0, 0, 0));
}
return undefined;
}
Example #18
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 #19
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 #20
Source File: commands.ts From vscode-cadence with Apache License 2.0 | 6 votes |
refreshCodeLenses = (): void => {
window.visibleTextEditors.forEach((editor) => {
if (editor.document.lineCount !== 0) {
return
}
// NOTE: We add a space to the end of the last line to force
// Codelens to refresh.
const lineCount = editor.document.lineCount
const lastLine = editor.document.lineAt(lineCount - 1)
editor.edit((edit) => {
if (lastLine.isEmptyOrWhitespace) {
edit.insert(new Position(lineCount - 1, 0), ' ')
edit.delete(new Range(lineCount - 1, 0, lineCount - 1, 1000))
} else {
edit.insert(new Position(lineCount - 1, 1000), '\n')
}
}).then(() => {}, () => {})
})
}
Example #21
Source File: externalUtils.ts From joplin-utils with MIT License | 6 votes |
mathEnvCheck = (doc: TextDocument, pos: Position): string => {
const lineTextBefore = doc.lineAt(pos.line).text.substring(0, pos.character)
const lineTextAfter = doc.lineAt(pos.line).text.substring(pos.character)
if (
/(^|[^\$])\$(|[^ \$].*)\\\w*$/.test(lineTextBefore) &&
lineTextAfter.includes('$')
) {
// Inline math
return 'inline'
} else {
const textBefore = doc.getText(new Range(new Position(0, 0), pos))
const textAfter = doc.getText().substr(doc.offsetAt(pos))
let matches
if (
(matches = textBefore.match(/\$\$/g)) !== null &&
matches.length % 2 !== 0 &&
textAfter.includes('$$')
) {
// $$ ... $$
return 'display'
} else {
return ''
}
}
}
Example #22
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 #23
Source File: sqlFluffLinter.ts From vscode-sqlfluff with MIT License | 6 votes |
public process(lines: string[]): Diagnostic[] {
let diagnostics: Diagnostic[] = [];
lines.forEach((line) => {
let filePaths: Array<FilePath> = JSON.parse(line);
filePaths.forEach((filePath: FilePath) => {
filePath.violations.forEach((violation: Violation) => {
diagnostics.push({
range: new Range(violation.line_no-1, violation.line_pos, violation.line_no-1, violation.line_pos),
severity: DiagnosticSeverity.Error,
message: violation.description,
code: violation.code,
source: 'sqlfluff'
});
});
});
});
return diagnostics;
}
Example #24
Source File: stripeLinter.ts From vscode-stripe with MIT License | 6 votes |
// prepareAPIKeyDiagnostics regex matches all instances of a Stripe API Key in a supplied line of text
// will return a list of Diagnostics pointing at instances of the Stripe API Keys it found
prepareLineDiagnostics =
(message: string) =>
(line: string, index: number): Diagnostic[] => {
const diagnostics: Diagnostic[] = [];
let match;
while ((match = stripeKeysRegex.exec(line)) !== null) {
const severity = /sk_live/.test(match[0])
? DiagnosticSeverity.Error
: DiagnosticSeverity.Warning;
// specify line and character range to draw the squiggly line under the API Key in the document
const range = new Range(index, match.index, index, match.index + match[0].length);
// create new diagnostic and add to the list of total diagnostics for this line of code
const diagnostic = new Diagnostic(range, message, severity);
this.telemetry.sendEvent('diagnostics.show', severity);
diagnostics.push(diagnostic);
}
return diagnostics;
};
Example #25
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 #26
Source File: documentActions.ts From vscode-todo-md with MIT License | 6 votes |
/**
* Reveal the line/task in the file.
*
* Move cursor, reveal range, highlight the line for a moment
*/
export async function revealTask(lineNumber: number, document?: TextDocument) {
const documentToReveal = document ?? await getActiveOrDefaultDocument();
const editor = await window.showTextDocument(documentToReveal);
const range = new Range(lineNumber, 0, lineNumber, 0);
editor.selection = new Selection(range.start, range.end);
editor.revealRange(range, TextEditorRevealType.Default);
// Highlight for a short time revealed range
const lineHighlightDecorationType = window.createTextEditorDecorationType({
backgroundColor: '#ffa30468',
isWholeLine: true,
});
editor.setDecorations(lineHighlightDecorationType, [range]);
setTimeout(() => {
editor.setDecorations(lineHighlightDecorationType, []);
}, 700);
}