diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 3cddffd8b..000000000 --- a/.eslintrc.js +++ /dev/null @@ -1,30 +0,0 @@ -module.exports = { - env: { - browser: true, - es6: true, - node: true - }, - extends: [ - "plugin:@typescript-eslint/eslint-recommended" - ], - globals: { - Atomics: 'readonly', - SharedArrayBuffer: 'readonly' - }, - parser: '@typescript-eslint/parser', - parserOptions: { - ecmaVersion: 2018, - sourceType: 'module' - }, - plugins: [ - '@typescript-eslint', - "jsdoc" - ], - rules: { - "semi": "error", - "no-extra-semi": "warn", - "curly": "warn", - "quotes": ["error", "single", { "allowTemplateLiterals": true } ], - "eqeqeq": "error" - } -} \ No newline at end of file diff --git a/.eslintrc.yml b/.eslintrc.yml new file mode 100644 index 000000000..535c6fcbc --- /dev/null +++ b/.eslintrc.yml @@ -0,0 +1,14 @@ +env: + node: true +extends: + - 'eslint:recommended' + - 'plugin:@typescript-eslint/recommended' + - 'plugin:@typescript-eslint/recommended-requiring-type-checking' +parser: '@typescript-eslint/parser' +parserOptions: + ecmaVersion: 12 + sourceType: module + project: ./tsconfig.json +plugins: + - '@typescript-eslint' + - 'jsdoc' diff --git a/devreplay.json b/devreplay.json index a9ebe00bb..a17a03e29 100644 --- a/devreplay.json +++ b/devreplay.json @@ -1,4 +1,12 @@ [ + { + "condition": [ + "assert.equal" + ], + "consequent": [ + "assert.strictEqual" + ] + }, { "condition": [ "show(${1:column}, ${2:preservalFocus})" diff --git a/src/apiImplementation.ts b/src/apiImplementation.ts index e91b929f7..01ca36017 100644 --- a/src/apiImplementation.ts +++ b/src/apiImplementation.ts @@ -6,8 +6,6 @@ import { RExtension } from './api'; export class RExtensionImplementation implements RExtension { - constructor(){} - public helpPanel?: HelpPanel; } diff --git a/src/extension.ts b/src/extension.ts index 7b1d94897..cf7da04b0 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,3 +1,8 @@ +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-unsafe-return */ +/* eslint-disable @typescript-eslint/restrict-template-expressions */ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ 'use strict'; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below @@ -12,18 +17,18 @@ import { createRTerm, deleteTerminal, runSelectionInTerm, runTextInTerm } from './rTerminal'; import { getWordOrSelection, surroundSelection } from './selection'; import { attachActive, deploySessionWatcher, globalenv, showPlotHistory, startRequestWatcher } from './session'; -import { config, ToRStringLiteral, getRpath, getRpathFromSystem } from './util'; +import { config, ToRStringLiteral, getRpathFromSystem } from './util'; import { launchAddinPicker, trackLastActiveTextEditor } from './rstudioapi'; import { RMarkdownCodeLensProvider, RMarkdownCompletionItemProvider, selectCurrentChunk, runCurrentChunk, runAboveChunks, runCurrentAndBelowChunks, runBelowChunks, runPreviousChunk, runNextChunk, runAllChunks, goToPreviousChunk, goToNextChunk } from './rmarkdown'; import * as path from 'path'; -import { HelpPanel, HelpPanelOptions, HelpProvider, RHelpProviderOptions } from './rHelpPanel'; +import { HelpPanel, HelpPanelOptions, HelpProvider } from './rHelpPanel'; import { RHelpClient } from './rHelpProviderBuiltin'; import { RHelp } from './rHelpProviderCustom'; import { RExtensionImplementation as RExtension } from './apiImplementation'; -const wordPattern = /(-?\d*\.\d\w*)|([^\`\~\!\@\$\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\<\>\/\s]+)/g; +const wordPattern = /(-?\d*\.\d\w*)|([^`~!@$^&*()=+[{\]}\\|;:'",<>/\s]+)/g; // Get with names(roxygen2:::default_tags()) const roxygenTagCompletionItems = [ @@ -42,7 +47,7 @@ export let globalRHelpPanel: HelpPanel | null = null; // This method is called when your extension is activated // Your extension is activated the very first time the command is executed -export async function activate(context: ExtensionContext) { +export async function activate(context: ExtensionContext): Promise { // used to export an interface to the help panel // used e.g. by vscode-r-debugger to show the help panel from within debug sessions @@ -50,7 +55,7 @@ export async function activate(context: ExtensionContext) { // get the "vanilla" R path from config let rPath = config().get('helpPanel.rpath', '') || await getRpathFromSystem(); - if(rPath.match(/^[^'"].* .*[^'"]$/)){ + if(/^[^'"].* .*[^'"]$/.exec(rPath)){ rPath = `"${rPath}"`; } const rHelpProviderOptions = { @@ -70,7 +75,7 @@ export async function activate(context: ExtensionContext) { helpProvider = new RHelpClient(rHelpProviderOptions); } } catch(e) { - window.showErrorMessage(`Help Panel not available: ${e.message}`); + void window.showErrorMessage(`Help Panel not available`); } // launch the help panel (displays the html provided by helpProvider) @@ -86,11 +91,11 @@ export async function activate(context: ExtensionContext) { context.subscriptions.push(rHelpPanel); context.subscriptions.push(commands.registerCommand('r.showHelp', () => { - rHelpPanel.showHelpForInput(); + void rHelpPanel.showHelpForInput(); })); context.subscriptions.push(commands.registerCommand('r.searchHelp', () => { - rHelpPanel.searchHelp(); + void rHelpPanel.searchHelp(); })); context.subscriptions.push(commands.registerCommand('r.showDoc', () => { @@ -117,14 +122,14 @@ export async function activate(context: ExtensionContext) { async function saveDocument(document: TextDocument) { if (document.isUntitled) { - window.showErrorMessage('Document is unsaved. Please save and retry running R command.'); + void window.showErrorMessage('Document is unsaved. Please save and retry running R command.'); return false; } const isSaved: boolean = document.isDirty ? (await document.save()) : true; if (!isSaved) { - window.showErrorMessage('Cannot run R command: document could not be saved.'); + void window.showErrorMessage('Cannot run R command: document could not be saved.'); return false; } @@ -143,7 +148,7 @@ export async function activate(context: ExtensionContext) { if (echo) { rPath = [rPath, 'echo = TRUE'].join(', '); } - runTextInTerm(`source(${rPath})`); + void runTextInTerm(`source(${rPath})`); } } @@ -159,31 +164,31 @@ export async function activate(context: ExtensionContext) { rPath = [rPath, 'echo = TRUE'].join(', '); } if (outputFormat === undefined) { - runTextInTerm(`rmarkdown::render(${rPath})`); + void runTextInTerm(`rmarkdown::render(${rPath})`); } else { - runTextInTerm(`rmarkdown::render(${rPath}, "${outputFormat}")`); + void runTextInTerm(`rmarkdown::render(${rPath}, "${outputFormat}")`); } } } async function runSelection() { - runSelectionInTerm(true); + await runSelectionInTerm(true); } async function runSelectionRetainCursor() { - runSelectionInTerm(false); + await runSelectionInTerm(false); } async function runSelectionOrWord(rFunctionName: string[]) { const text = getWordOrSelection(); const wrappedText = surroundSelection(text, rFunctionName); - runTextInTerm(wrappedText); + await runTextInTerm(wrappedText); } async function runCommandWithSelectionOrWord(rCommand: string) { const text = getWordOrSelection(); const call = rCommand.replace(/\$\$/g, text); - runTextInTerm(call); + await runTextInTerm(call); } async function runCommandWithEditorPath(rCommand: string) { @@ -192,12 +197,12 @@ export async function activate(context: ExtensionContext) { if (isSaved) { const rPath = ToRStringLiteral(wad.fileName, ''); const call = rCommand.replace(/\$\$/g, rPath); - runTextInTerm(call); + await runTextInTerm(call); } } async function runCommand(rCommand: string) { - runTextInTerm(rCommand); + await runTextInTerm(rCommand); } async function runFromBeginningToLine() { @@ -206,7 +211,7 @@ export async function activate(context: ExtensionContext) { const endPos = new Position(endLine, charactersOnLine); const range = new Range(new Position(0, 0), endPos); const text = window.activeTextEditor.document.getText(range); - runTextInTerm(text); + await runTextInTerm(text); } async function runFromLineToEnd() { @@ -215,7 +220,7 @@ export async function activate(context: ExtensionContext) { const endLine = window.activeTextEditor.document.lineCount; const range = new Range(startPos, new Position(endLine, 0)); const text = window.activeTextEditor.document.getText(range); - runTextInTerm(text); + await runTextInTerm(text); } languages.registerCompletionItemProvider('r', { @@ -243,13 +248,13 @@ export async function activate(context: ExtensionContext) { commands.registerCommand('r.head', () => runSelectionOrWord(['head'])), commands.registerCommand('r.thead', () => runSelectionOrWord(['t', 'head'])), commands.registerCommand('r.names', () => runSelectionOrWord(['names'])), - commands.registerCommand('r.runSource', () => { runSource(false); }), - commands.registerCommand('r.knitRmd', () => { knitRmd(false, undefined); }), - commands.registerCommand('r.knitRmdToPdf', () => { knitRmd(false, 'pdf_document'); }), - commands.registerCommand('r.knitRmdToHtml', () => { knitRmd(false, 'html_document'); }), - commands.registerCommand('r.knitRmdToAll', () => { knitRmd(false, 'all'); }), + commands.registerCommand('r.runSource', () => { void runSource(false); }), + commands.registerCommand('r.knitRmd', () => { void knitRmd(false, undefined); }), + commands.registerCommand('r.knitRmdToPdf', () => { void knitRmd(false, 'pdf_document'); }), + commands.registerCommand('r.knitRmdToHtml', () => { void knitRmd(false, 'html_document'); }), + commands.registerCommand('r.knitRmdToAll', () => { void knitRmd(false, 'all'); }), commands.registerCommand('r.createRTerm', createRTerm), - commands.registerCommand('r.runSourcewithEcho', () => { runSource(true); }), + commands.registerCommand('r.runSourcewithEcho', () => { void runSource(true); }), commands.registerCommand('r.runSelection', runSelection), commands.registerCommand('r.runFromBeginningToLine', runFromBeginningToLine), commands.registerCommand('r.runFromLineToEnd', runFromLineToEnd), @@ -291,7 +296,7 @@ export async function activate(context: ExtensionContext) { if (config().get('sessionWatcher')) { console.info('Initialize session watcher'); languages.registerHoverProvider('r', { - provideHover(document, position, token) { + provideHover(document, position, ) { const wordRange = document.getWordRangeAtPosition(position); const text = document.getText(wordRange); @@ -299,52 +304,6 @@ export async function activate(context: ExtensionContext) { }, }); - function getBracketCompletionItems(document: TextDocument, position: Position, token: CancellationToken, items: CompletionItem[]) { - let range = new Range(new Position(position.line, 0), position); - let expectOpenBrackets = 0; - let symbol: string; - - loop1: - while (range.start.line >= 0) { - if (token.isCancellationRequested) { return; } - const text = document.getText(range); - for (let i = text.length - 1; i >= 0; i -= 1) { - const chr = text.charAt(i); - if (chr === ']') { - expectOpenBrackets += 1; - // tslint:disable-next-line: triple-equals - } else if (chr === '[') { - if (expectOpenBrackets === 0) { - const symbolPosition = new Position(range.start.line, i - 1); - const symbolRange = document.getWordRangeAtPosition(symbolPosition); - symbol = document.getText(symbolRange); - break loop1; - } else { - expectOpenBrackets -= 1; - } - } - } - if (range.start.line > 0) { - range = document.lineAt(range.start.line - 1).range; - } else { - break; - } - } - - if (!token.isCancellationRequested && symbol !== undefined) { - const obj = globalenv[symbol]; - if (obj !== undefined && obj.names !== undefined) { - const doc = new MarkdownString('Element of `' + symbol + '`'); - obj.names.map((name: string) => { - const item = new CompletionItem(name, CompletionItemKind.Field); - item.detail = '[session]'; - item.documentation = doc; - items.push(item); - }); - } - } - } - languages.registerCompletionItemProvider('r', { provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken, completionContext: CompletionContext) { const items = []; @@ -358,7 +317,8 @@ export async function activate(context: ExtensionContext) { CompletionItemKind.Function : CompletionItemKind.Field); item.detail = '[session]'; - item.documentation = new MarkdownString('```r\n' + obj.str + '\n```'); + // eslint-disable-next-line @typescript-eslint/restrict-plus-operands + item.documentation = new MarkdownString(`\`\`\`r\n${obj.str}\n\`\`\``); items.push(item); }); } else if (completionContext.triggerCharacter === '$' || completionContext.triggerCharacter === '@') { @@ -411,6 +371,52 @@ export async function activate(context: ExtensionContext) { return rExtension; } +function getBracketCompletionItems(document: TextDocument, position: Position, token: CancellationToken, items: CompletionItem[]) { + let range = new Range(new Position(position.line, 0), position); + let expectOpenBrackets = 0; + let symbol: string; + + loop1: + while (range.start.line >= 0) { + if (token.isCancellationRequested) { return; } + const text = document.getText(range); + for (let i = text.length - 1; i >= 0; i -= 1) { + const chr = text.charAt(i); + if (chr === ']') { + expectOpenBrackets += 1; + // tslint:disable-next-line: triple-equals + } else if (chr === '[') { + if (expectOpenBrackets === 0) { + const symbolPosition = new Position(range.start.line, i - 1); + const symbolRange = document.getWordRangeAtPosition(symbolPosition); + symbol = document.getText(symbolRange); + break loop1; + } else { + expectOpenBrackets -= 1; + } + } + } + if (range.start.line > 0) { + range = document.lineAt(range.start.line - 1).range; + } else { + break; + } + } + + if (!token.isCancellationRequested && symbol !== undefined) { + const obj = globalenv[symbol]; + if (obj !== undefined && obj.names !== undefined) { + const doc = new MarkdownString('Element of `' + symbol + '`'); + obj.names.map((name: string) => { + const item = new CompletionItem(name, CompletionItemKind.Field); + item.detail = '[session]'; + item.documentation = doc; + items.push(item); + }); + } + } +} + // This method is called when your extension is deactivated // Export function deactivate() { diff --git a/src/lineCache.ts b/src/lineCache.ts index 1a97507d0..c9a7b2800 100644 --- a/src/lineCache.ts +++ b/src/lineCache.ts @@ -14,13 +14,13 @@ export class LineCache { this.lineCache = new Map(); this.endsInOperatorCache = new Map(); } - public addLineToCache(line: number) { + public addLineToCache(line: number): void { const cleaned = cleanLine(this.getLine(line)); const endsInOperator = doesLineEndInOperator(cleaned); this.lineCache.set(line, cleaned); this.endsInOperatorCache.set(line, endsInOperator); } - public getEndsInOperatorFromCache(line: number) { + public getEndsInOperatorFromCache(line: number): boolean { const lineInCache = this.lineCache.has(line); if (!lineInCache) { this.addLineToCache(line); @@ -29,7 +29,7 @@ export class LineCache { return (s); } - public getLineFromCache(line: number) { + public getLineFromCache(line: number): string { const lineInCache = this.lineCache.has(line); if (!lineInCache) { this.addLineToCache(line); @@ -67,7 +67,7 @@ function cleanLine(text: string) { } function doesLineEndInOperator(text: string) { - const endingOperatorIndex = text.search(/(,|\+|!|\$|\^|&|\*|-|=|:|~|\||\/|\?|%.*%)(\s*|\s*\#.*)$/); + const endingOperatorIndex = text.search(/(,|\+|!|\$|\^|&|\*|-|=|:|~|\||\/|\?|%.*%)(\s*|\s*#.*)$/); const spacesOnlyIndex = text.search(/^\s*$/); return ((endingOperatorIndex >= 0) || (spacesOnlyIndex >= 0)); diff --git a/src/preview.ts b/src/preview.ts index 92330c692..f3acd348e 100644 --- a/src/preview.ts +++ b/src/preview.ts @@ -7,7 +7,7 @@ import { runTextInTerm } from './rTerminal'; import { getWordOrSelection } from './selection'; import { checkForSpecialCharacters, checkIfFileExists, delay } from './util'; -export async function previewEnvironment() { +export async function previewEnvironment(): Promise { if (!checkcsv()) { return; } @@ -21,11 +21,11 @@ export async function previewEnvironment() { + `${envClass},` + `${envOut}), '` + `${pathToTmpCsv}', row.names=FALSE, quote = TRUE)`; - runTextInTerm(rWriteCsvCommand); + await runTextInTerm(rWriteCsvCommand); await openTmpCSV(pathToTmpCsv, tmpDir); } -export async function previewDataframe() { +export async function previewDataframe(): Promise { if (!checkcsv()) { return undefined; } @@ -33,7 +33,7 @@ export async function previewDataframe() { const dataframeName = getWordOrSelection(); if (!checkForSpecialCharacters(dataframeName)) { - window.showInformationMessage('This does not appear to be a dataframe.'); + void window.showInformationMessage('This does not appear to be a dataframe.'); return false; } @@ -44,7 +44,7 @@ export async function previewDataframe() { const pathToTmpCsv = `${tmpDir}/${dataframeName}.csv`; const rWriteCsvCommand = `write.csv(${dataframeName}, ` + `'${pathToTmpCsv}', row.names = FALSE, quote = FALSE)`; - runTextInTerm(rWriteCsvCommand); + await runTextInTerm(rWriteCsvCommand); await openTmpCSV(pathToTmpCsv, tmpDir); } @@ -52,7 +52,7 @@ async function openTmpCSV(pathToTmpCsv: string, tmpDir: string) { await delay(350); // Needed since file size has not yet changed if (!checkIfFileExists(pathToTmpCsv)) { - window.showErrorMessage('Dataframe failed to display.'); + void window.showErrorMessage('Dataframe failed to display.'); removeSync(tmpDir); return false; @@ -61,14 +61,14 @@ async function openTmpCSV(pathToTmpCsv: string, tmpDir: string) { // Async poll for R to complete writing CSV. const success = await waitForFileToFinish(pathToTmpCsv); if (!success) { - window.showWarningMessage('Visual Studio Code currently limits opening files to 20 MB.'); + void window.showWarningMessage('Visual Studio Code currently limits opening files to 20 MB.'); removeSync(tmpDir); return false; } // Open CSV in Excel Viewer and clean up. - workspace.openTextDocument(pathToTmpCsv) + void workspace.openTextDocument(pathToTmpCsv) .then(async (file) => { await commands.executeCommand('csv.preview', file.uri); removeSync(tmpDir); @@ -118,11 +118,11 @@ function checkcsv() { if (iscsv !== undefined && iscsv.isActive) { return true; } - window.showInformationMessage('This function need to install `GrapeCity.gc-excelviewer`, will you install?', - 'Yes', 'No') + void window.showInformationMessage('This function need to install `GrapeCity.gc-excelviewer`, will you install?', + 'Yes', 'No') .then((select) => { if (select === 'Yes') { - commands.executeCommand('workbench.extensions.installExtension', 'GrapeCity.gc-excelviewer'); + void commands.executeCommand('workbench.extensions.installExtension', 'GrapeCity.gc-excelviewer'); } }); diff --git a/src/rGitignore.ts b/src/rGitignore.ts index e0a7deff1..3cef8b7cd 100644 --- a/src/rGitignore.ts +++ b/src/rGitignore.ts @@ -20,9 +20,9 @@ const ignoreFiles = ['.Rhistory', '*.knit.md', 'rsconnect/'].join('\n'); -export function createGitignore() { +export function createGitignore(): void { if (workspace.workspaceFolders[0].uri.path === undefined) { - window.showWarningMessage('Please open workspace to create .gitignore'); + void window.showWarningMessage('Please open workspace to create .gitignore'); return; } @@ -30,10 +30,10 @@ export function createGitignore() { writeFile(ignorePath, ignoreFiles, (err) => { try { if (err) { - window.showErrorMessage(err.name); + void window.showErrorMessage(err.name); } } catch (e) { - window.showErrorMessage(e.message); + void window.showErrorMessage(e); } }); } diff --git a/src/rHelpPanel.ts b/src/rHelpPanel.ts index 637b9ceb1..37d856096 100644 --- a/src/rHelpPanel.ts +++ b/src/rHelpPanel.ts @@ -1,5 +1,10 @@ +/* eslint-disable @typescript-eslint/restrict-template-expressions */ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/no-unsafe-return */ -import * as vscode from 'vscode'; +import { commands, window, QuickPickItem, Uri, Webview, WebviewPanel, WebviewOptions, WebviewPanelOnDidChangeViewStateEvent, ViewColumn } from 'vscode'; import * as cheerio from 'cheerio'; @@ -13,7 +18,7 @@ interface AdditionalInfo { href?: string, pkgName?: string } -interface DocumentedItem extends vscode.QuickPickItem, AdditionalInfo {} +interface DocumentedItem extends QuickPickItem, AdditionalInfo {} // This interface needs to be implemented by a separate class that actually provides the R help pages export interface HelpProvider { @@ -72,16 +77,16 @@ export class HelpPanel { readonly helpProvider: HelpProvider; // the webview panel where the help is shown - private panel?: vscode.WebviewPanel; - private viewColumn?: vscode.ViewColumn = vscode.ViewColumn.Two; + private panel?: WebviewPanel; + private viewColumn?: ViewColumn = ViewColumn.Two; // locations on disk, only changed on construction - readonly webviewScriptFile: vscode.Uri; // the javascript added to help pages - readonly webviewStyleFile: vscode.Uri; // the css file applied to help pages + readonly webviewScriptFile: Uri; // the javascript added to help pages + readonly webviewStyleFile: Uri; // the css file applied to help pages // virtual locations used by webview, changed each time a new webview is created - private webviewScriptUri?: vscode.Uri; - private webviewStyleUri?: vscode.Uri; + private webviewScriptUri?: Uri; + private webviewStyleUri?: Uri; // keep track of history to go back/forward: private currentEntry: HistoryEntry|null = null; @@ -89,17 +94,17 @@ export class HelpPanel { private forwardHistory: HistoryEntry[] = []; // cache parsed index files (list of installed packages, functions in packages) - private cachedIndexFiles: Map = new Map(); + private cachedIndexFiles: Map = new Map(); constructor(rHelp: HelpProvider, options: HelpPanelOptions){ this.helpProvider = rHelp; - this.webviewScriptFile = vscode.Uri.file(options.webviewScriptPath); - this.webviewStyleFile = vscode.Uri.file(options.webviewStylePath); + this.webviewScriptFile = Uri.file(options.webviewScriptPath); + this.webviewStyleFile = Uri.file(options.webviewStylePath); } // used to close files etc. - public dispose(){ + public dispose(): void{ if(this.helpProvider.dispose){ this.helpProvider.dispose(); } @@ -109,15 +114,17 @@ export class HelpPanel { } // prompts user for a package and function name to show: - public async showHelpForInput(){ + public async showHelpForInput(): Promise { // get list of installed packages for the user to pick from let packages: DocumentedItem[]; try { packages = await this.getParsedIndexFile(`/doc/html/packages.html`); - } catch (error) {} + } catch (error) { + // continue even failed making package + } if(!packages){ - vscode.window.showErrorMessage('Help provider not available!'); + void window.showErrorMessage('Help provider not available!'); return false; } @@ -140,7 +147,7 @@ export class HelpPanel { }); // let user choose from found packages - const qp = await vscode.window.showQuickPick(packages, { + const qp = await window.showQuickPick(packages, { matchOnDescription: true, placeHolder: 'Please select a package' }); @@ -153,7 +160,7 @@ export class HelpPanel { } else{ // no packages found -> let user type const defaultPkg = 'doc'; - pkgName = await vscode.window.showInputBox({ + pkgName = await window.showInputBox({ value: defaultPkg, prompt: 'Please enter the package name' }); @@ -199,7 +206,7 @@ export class HelpPanel { } // let user pick function/item - const qp = await vscode.window.showQuickPick(functions, { + const qp = await window.showQuickPick(functions, { matchOnDescription: true, placeHolder: 'Please select a documentation entry' }); @@ -211,7 +218,7 @@ export class HelpPanel { } else{ // if no functions/items were found, let user type const defaultFnc = (pkgName==='doc' ? 'index.html' : '00Index'); - fncName = await vscode.window.showInputBox({ + fncName = await window.showInputBox({ value: defaultFnc, prompt: 'Please enter the function name' }); @@ -230,8 +237,8 @@ export class HelpPanel { } // search function, similar to typing `?? ...` in R - public async searchHelp(){ - const searchTerm = await vscode.window.showInputBox({ + public async searchHelp(): Promise{ + const searchTerm = await window.showInputBox({ value: '', prompt: 'Please enter a search term' }); @@ -246,7 +253,7 @@ export class HelpPanel { } // shows help for package and function name - public showHelpForFunctionName(fncName: string, pkgName: string){ + public showHelpForFunctionName(fncName: string, pkgName: string): void { let helpFile: HelpFile|Promise; @@ -258,26 +265,26 @@ export class HelpPanel { helpFile = this.helpProvider.getHelpFileFromRequestPath(requestPath); } - this.showHelpFile(helpFile); + void this.showHelpFile(helpFile); } // shows help for request path as used by R's internal help server - public showHelpForPath(requestPath: string, viewer?: string|any){ + public showHelpForPath(requestPath: string, viewer?: string|any): void{ if(typeof viewer === 'string'){ - this.viewColumn = vscode.ViewColumn[String(viewer)]; + this.viewColumn = ViewColumn[String(viewer)]; } const helpFile = this.helpProvider.getHelpFileFromRequestPath(requestPath); if(helpFile){ - this.showHelpFile(helpFile); + void this.showHelpFile(helpFile); } else{ console.error(`Couldn't handle path:\n${requestPath}\n`); } } // shows (internal) help file object in webview - private async showHelpFile(helpFile: HelpFile|Promise, updateHistory: boolean = true, currentScrollY: number = 0): Promise{ + private async showHelpFile(helpFile: HelpFile|Promise, updateHistory = true, currentScrollY = 0): Promise{ // get or create webview: const webview = this.getWebview(); @@ -307,20 +314,20 @@ export class HelpPanel { } // retrieves the stored webview or creates a new one if the webview was closed - private getWebview(): vscode.Webview { + private getWebview(): Webview { // create webview if necessary if(!this.panel){ - const webViewOptions: vscode.WebviewOptions = { + const webViewOptions: WebviewOptions = { enableScripts: true, }; - this.panel = vscode.window.createWebviewPanel('rhelp', 'R Help', this.viewColumn, webViewOptions); + this.panel = window.createWebviewPanel('rhelp', 'R Help', this.viewColumn, webViewOptions); // virtual uris used to access local files this.webviewScriptUri = this.panel.webview.asWebviewUri(this.webviewScriptFile); this.webviewStyleUri = this.panel.webview.asWebviewUri(this.webviewStyleFile); // called e.g. when the webview panel is closed by the user - this.panel.onDidDispose((e: void) => { + this.panel.onDidDispose(() => { this.panel = undefined; this.webviewScriptUri = undefined; this.webviewStyleUri = undefined; @@ -328,12 +335,12 @@ export class HelpPanel { // sent by javascript added to the help pages, e.g. when a link or mouse button is clicked this.panel.webview.onDidReceiveMessage((e: any) => { - this.handleMessage(e); + void this.handleMessage(e); }); // set context variable to show forward/backward buttons - this.panel.onDidChangeViewState((e: vscode.WebviewPanelOnDidChangeViewStateEvent) => { - vscode.commands.executeCommand('setContext', 'r.helpPanel.active', e.webviewPanel.active); + this.panel.onDidChangeViewState((e: WebviewPanelOnDidChangeViewStateEvent) => { + void commands.executeCommand('setContext', 'r.helpPanel.active', e.webviewPanel.active); }); } @@ -344,7 +351,7 @@ export class HelpPanel { } // go back/forward in the history of the webview: - public goBack(currentScrollY: number = 0){ + public goBack(currentScrollY = 0): void{ const entry = this.history.pop(); if(entry){ if(this.currentEntry){ // should always be true @@ -354,7 +361,7 @@ export class HelpPanel { this.showHistoryEntry(entry); } } - public goForward(currentScrollY: number = 0){ + public goForward(currentScrollY = 0): void{ const entry = this.forwardHistory.pop(); if(entry){ if(this.currentEntry){ // should always be true @@ -366,7 +373,7 @@ export class HelpPanel { } private showHistoryEntry(entry: HistoryEntry){ const helpFile = entry.helpFile; - this.showHelpFile(helpFile, false); + void this.showHelpFile(helpFile, false); } // handle message produced by javascript inside the help page @@ -379,7 +386,7 @@ export class HelpPanel { console.log('Link clicked: ' + href); // remove first to path entries (if these are webview internal stuff): - const uri = vscode.Uri.parse(href); + const uri = Uri.parse(href); const parts = uri.path.split('/'); if(parts[0] !== 'library' && parts[0] !== 'doc'){ parts.shift(); @@ -402,7 +409,7 @@ export class HelpPanel { // if successful, show helpfile: if(helpFile){ - this.showHelpFile(helpFile, true, currentScrollY); + void this.showHelpFile(helpFile, true, currentScrollY); } } else if(msg.message === 'mouseClick'){ // use the additional mouse buttons to go forward/backwards @@ -415,7 +422,7 @@ export class HelpPanel { } } else if(msg.message === 'text'){ // used for logging/debugging - console.log('Message (text): ' + msg.text); + console.log(`Message (text): ${msg.text}`); } else{ console.log('Unknown message:', msg); } @@ -429,8 +436,8 @@ export class HelpPanel { const relPath = helpFile.requestPath + (helpFile.hash || ''); // check if file is html - const re = new RegExp('.*', 'ms'); - if(!helpFile.html.match(re)){ + const re = new RegExp('.*', 'ms'); + if(!re.exec(helpFile.html)){ helpFile.html = `
${helpFile.html}
`; } @@ -446,12 +453,12 @@ export class HelpPanel { // apply syntax highlighting to each code section: codeSections.each((i, section) => { const newChildNodes = []; - section.children.forEach((subSection, j) => { + section.children.forEach((subSection,) => { if(subSection.type === 'text'){ const styledCode = hljs.highlight('r', subSection.data); const newChildren = cheerio.parseHTML(styledCode.value); - for(const [i, newChild] of newChildren.entries()){ + for(const [, newChild] of newChildren.entries()){ newChildNodes.push(newChild); } } diff --git a/src/rHelpProviderBuiltin.ts b/src/rHelpProviderBuiltin.ts index 1450735f8..92c227568 100644 --- a/src/rHelpProviderBuiltin.ts +++ b/src/rHelpProviderBuiltin.ts @@ -1,13 +1,12 @@ - - - -import * as cp from 'child_process'; - +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-unsafe-call */ +import { ChildProcess, exec } from 'child_process'; import * as http from 'http'; +import * as kill from 'tree-kill' import * as rHelpPanel from './rHelpPanel'; -const kill = require('tree-kill'); +// const kill = require('tree-kill'); export interface RHelpClientOptions extends rHelpPanel.RHelpProviderOptions { // path of the R executable @@ -17,7 +16,7 @@ export interface RHelpClientOptions extends rHelpPanel.RHelpProviderOptions { // Class to forward help requests to a backgorund R instance that is running a help server export class RHelpClient implements rHelpPanel.HelpProvider { - private cp: cp.ChildProcess; + private cp: ChildProcess; private port: number|Promise; private readonly rPath: string; private readonly cwd?: string; @@ -28,12 +27,12 @@ export class RHelpClient implements rHelpPanel.HelpProvider { this.port = this.launchRHelpServer(); // is a promise for now! } - public refresh(){ + public refresh(): void { kill(this.cp.pid); // more reliable than cp.kill (?) this.port = this.launchRHelpServer(); } - public async launchRHelpServer(){ + public async launchRHelpServer(): Promise{ const lim = '---vsc---'; const re = new RegExp(`.*${lim}(.*)${lim}.*`, 'ms'); @@ -45,19 +44,19 @@ export class RHelpClient implements rHelpPanel.HelpProvider { const cpOptions = { cwd: this.cwd }; - this.cp = cp.exec(cmd, cpOptions); + this.cp = exec(cmd, cpOptions); let str = ''; // promise containing the first output of the r process (contains only the port number) const outputPromise = new Promise((resolve, reject) => { this.cp.stdout.on('data', (data) => { str += data.toString(); - if(str.match(re)){ + if(re.exec(str)){ resolve(str.replace(re, '$1')); } }); this.cp.on('close', (code) => { - console.log('R process closed with code ' + code); + console.log(`R process closed with code ${code}`); reject(); }); }); @@ -95,7 +94,7 @@ export class RHelpClient implements rHelpPanel.HelpProvider { const maxForwards = 3; for (let index = 0; index < maxForwards; index++) { const htmlPromise = new Promise((resolve, reject) => { - let content: string = ''; + let content = ''; http.get(url, (res: http.IncomingMessage) => { if(res.statusCode === 302){ resolve({redirect: res.headers.location}); @@ -131,7 +130,7 @@ export class RHelpClient implements rHelpPanel.HelpProvider { return ret; } - dispose(){ + dispose(): void { if(this.cp){ this.cp.kill(); } diff --git a/src/rHelpProviderCustom.ts b/src/rHelpProviderCustom.ts index 6889e7b49..6fb388428 100644 --- a/src/rHelpProviderCustom.ts +++ b/src/rHelpProviderCustom.ts @@ -105,7 +105,7 @@ export class RHelp implements rHelpPanel.HelpProvider { } } - public dispose() { + public dispose(): void { // remove temp directory const options: fs.RmDirOptions = { recursive: true @@ -243,7 +243,7 @@ export class RHelp implements rHelpPanel.HelpProvider { // produce the .Rd file of a function: const cmd1 = `${this.rPath} -e ${cmd1a} -e ${cmd1b} --vanilla --silent --slave > ${rdFileName}`; try{ - const out1 = cp.execSync(cmd1, options); + cp.execSync(cmd1, options); } catch(e){ console.log('Failed to extract .Rd file'); return null; @@ -252,7 +252,7 @@ export class RHelp implements rHelpPanel.HelpProvider { // convert the .Rd file to .html const cmd3a = `"tools::Rd2HTML('${rdFileName}', Links=tools::findHTMLlinks())"`; const cmd3 = `${this.rPath} -e ${cmd3a} --vanilla --silent --slave`; - let htmlContent: string = ''; + let htmlContent = ''; try{ htmlContent = cp.execSync(cmd3, options); } catch(e){ @@ -260,7 +260,7 @@ export class RHelp implements rHelpPanel.HelpProvider { return null; } - fs.unlink(rdFileName, (e) => {}); + fs.unlink(rdFileName, () => { /* no process */ }); return htmlContent; } diff --git a/src/rTerminal.ts b/src/rTerminal.ts index 533a80c21..dcf95328e 100644 --- a/src/rTerminal.ts +++ b/src/rTerminal.ts @@ -38,13 +38,13 @@ export async function createRTerm(preserveshow?: boolean): Promise { return true; } - window.showErrorMessage('Cannot find R client. Please check R path in preferences and reload.'); + void window.showErrorMessage('Cannot find R client. Please check R path in preferences and reload.'); return false; }); } -export async function restartRTerminal(){ +export async function restartRTerminal(): Promise{ if (typeof rTerm !== 'undefined'){ rTerm.dispose(); deleteTerminal(rTerm); @@ -52,7 +52,7 @@ export async function restartRTerminal(){ } } -export function deleteTerminal(term: Terminal) { +export function deleteTerminal(term: Terminal): void { if (isDeepStrictEqual(term, rTerm)) { rTerm = undefined; if (config().get('sessionWatcher')) { @@ -61,10 +61,10 @@ export function deleteTerminal(term: Terminal) { } } -export async function chooseTerminal() { +export async function chooseTerminal(): Promise { if (config().get('alwaysUseActiveTerminal')) { if (window.terminals.length < 1) { - window.showInformationMessage('There are no open terminals.'); + void window.showInformationMessage('There are no open terminals.'); return undefined; } @@ -109,8 +109,7 @@ export async function chooseTerminal() { msg += `Terminal ${i}: ${window.terminals[i].name} `; } console.info(msg); - // tslint:disable-next-line: max-line-length - window.showErrorMessage('Error identifying terminal! Please run command "Developer: Toggle Developer Tools", find the message starting with "[chooseTerminal]", and copy the message to https://github.com/Ikuyadeu/vscode-R/issues'); + void window.showErrorMessage('Error identifying terminal! Please run command "Developer: Toggle Developer Tools", find the message starting with "[chooseTerminal]", and copy the message to https://github.com/Ikuyadeu/vscode-R/issues'); return undefined; } @@ -118,7 +117,7 @@ export async function chooseTerminal() { } if (rTerm === undefined) { - const success = createRTerm(true); + const success = await createRTerm(true); await delay(200); // Let RTerm warm up if (!success) { return undefined; @@ -128,21 +127,21 @@ export async function chooseTerminal() { return rTerm; } -export function runSelectionInTerm(moveCursor: boolean) { +export async function runSelectionInTerm(moveCursor: boolean): Promise { const selection = getSelection(); if (moveCursor && selection.linesDownToMoveCursor > 0) { const lineCount = window.activeTextEditor.document.lineCount; if (selection.linesDownToMoveCursor + window.activeTextEditor.selection.end.line === lineCount) { const endPos = new Position(lineCount, window.activeTextEditor.document.lineAt(lineCount - 1).text.length); - window.activeTextEditor.edit(e => e.insert(endPos, '\n')); + await window.activeTextEditor.edit(e => e.insert(endPos, '\n')); } - commands.executeCommand('cursorMove', { to: 'down', value: selection.linesDownToMoveCursor }); - commands.executeCommand('cursorMove', { to: 'wrappedLineFirstNonWhitespaceCharacter' }); + await commands.executeCommand('cursorMove', { to: 'down', value: selection.linesDownToMoveCursor }); + await commands.executeCommand('cursorMove', { to: 'wrappedLineFirstNonWhitespaceCharacter' }); } - runTextInTerm(selection.selectedText); + await runTextInTerm(selection.selectedText); } -export async function runChunksInTerm(chunks: Range[]) { +export async function runChunksInTerm(chunks: Range[]): Promise { const text = chunks .map((chunk) => window.activeTextEditor.document.getText(chunk).trim()) .filter((chunk) => chunk.length > 0) @@ -152,7 +151,7 @@ export async function runChunksInTerm(chunks: Range[]) { } } -export async function runTextInTerm(text: string) { +export async function runTextInTerm(text: string): Promise { const term = await chooseTerminal(); if (term === undefined) { return; diff --git a/src/rmarkdown.ts b/src/rmarkdown.ts index 30b343081..681e68192 100644 --- a/src/rmarkdown.ts +++ b/src/rmarkdown.ts @@ -147,7 +147,7 @@ export class RMarkdownCodeLensProvider implements CodeLensProvider { return sorted; }); } - public resolveCodeLens(codeLens: CodeLens, token: CancellationToken) { + public resolveCodeLens(codeLens: CodeLens): CodeLens { return codeLens; } } @@ -287,25 +287,25 @@ function _getStartLine() { } export async function runCurrentChunk(chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine()) { + line: number = _getStartLine()): Promise { const currentChunk = getCurrentChunk(chunks, line); - runChunksInTerm([currentChunk.codeRange]); + await runChunksInTerm([currentChunk.codeRange]); } export async function runPreviousChunk(chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine()) { + line: number = _getStartLine()): Promise { const previousChunk = getPreviousChunk(chunks, line); - runChunksInTerm([previousChunk.codeRange]); + await runChunksInTerm([previousChunk.codeRange]); } export async function runNextChunk(chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine()) { + line: number = _getStartLine()): Promise { const nextChunk = getNextChunk(chunks, line); - runChunksInTerm([nextChunk.codeRange]); + await runChunksInTerm([nextChunk.codeRange]); } export async function runAboveChunks(chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine()) { + line: number = _getStartLine()): Promise { const previousChunk = getPreviousChunk(chunks, line); const firstChunkId = 1; const previousChunkId = previousChunk.id; @@ -316,11 +316,11 @@ export async function runAboveChunks(chunks: RMarkdownChunk[] = _getChunks(), const chunk = chunks.filter(e => e.id === i)[0]; codeRanges.push(chunk.codeRange); } - runChunksInTerm(codeRanges); + await runChunksInTerm(codeRanges); } export async function runBelowChunks(chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine()) { + line: number = _getStartLine()): Promise { const nextChunk = getNextChunk(chunks, line); const nextChunkId = nextChunk.id; @@ -332,11 +332,11 @@ export async function runBelowChunks(chunks: RMarkdownChunk[] = _getChunks(), const chunk = chunks.filter(e => e.id === i)[0]; codeRanges.push(chunk.codeRange); } - runChunksInTerm(codeRanges); + await runChunksInTerm(codeRanges); } -export async function runCurrentAndBelowChunks( - chunks: RMarkdownChunk[] = _getChunks(), line: number = _getStartLine()) { +export async function runCurrentAndBelowChunks(chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine()): Promise { const currentChunk = getCurrentChunk(chunks, line); const currentChunkId = currentChunk.id; const lastChunkId = chunks.length; @@ -347,10 +347,10 @@ export async function runCurrentAndBelowChunks( const chunk = chunks.filter(e => e.id === i)[0]; codeRanges.push(chunk.codeRange); } - runChunksInTerm(codeRanges); + await runChunksInTerm(codeRanges); } -export async function runAllChunks(chunks: RMarkdownChunk[] = _getChunks()) { +export async function runAllChunks(chunks: RMarkdownChunk[] = _getChunks()): Promise { const firstChunkId = 1; const lastChunkId = chunks.length; @@ -361,7 +361,7 @@ export async function runAllChunks(chunks: RMarkdownChunk[] = _getChunks()) { const chunk = chunks.filter(e => e.id === i)[0]; codeRanges.push(chunk.codeRange); } - runChunksInTerm(codeRanges); + await runChunksInTerm(codeRanges); } function goToChunk(chunk: RMarkdownChunk) { @@ -370,20 +370,20 @@ function goToChunk(chunk: RMarkdownChunk) { window.activeTextEditor.selection = new Selection(line, 0, line, 0); } -export async function goToPreviousChunk(chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine()) { +export function goToPreviousChunk(chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine()): void { const previousChunk = getPreviousChunk(chunks, line); goToChunk(previousChunk); } -export async function goToNextChunk(chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine()) { +export function goToNextChunk(chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine()): void { const nextChunk = getNextChunk(chunks, line); goToChunk(nextChunk); } -export async function selectCurrentChunk( - chunks: RMarkdownChunk[] = _getChunks(), line: number = _getStartLine()) { +export function selectCurrentChunk(chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine()): void { const editor = window.activeTextEditor; const currentChunk = getCurrentChunk__CursorWithinChunk(chunks, line); const lines = editor.document.getText().split(/\r?\n/); @@ -418,7 +418,7 @@ export class RMarkdownCompletionItemProvider implements CompletionItemProvider { }); } - public provideCompletionItems(document: TextDocument, position: Position) { + public provideCompletionItems(document: TextDocument, position: Position): CompletionItem[] { const line = document.lineAt(position).text; if (isChunkStartLine(line) && getChunkLanguage(line) === 'r') { return this.chunkOptionCompletionItems; diff --git a/src/rstudioapi.ts b/src/rstudioapi.ts index 77ca449ef..53f0c49c0 100644 --- a/src/rstudioapi.ts +++ b/src/rstudioapi.ts @@ -1,3 +1,10 @@ +/* eslint-disable @typescript-eslint/restrict-plus-operands */ +/* eslint-disable @typescript-eslint/restrict-template-expressions */ +/* eslint-disable @typescript-eslint/no-unsafe-return */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ import { window, TextEditor, TextDocument, Uri, workspace, WorkspaceEdit, Position, Range, Selection, @@ -6,16 +13,16 @@ import { import { sessionDir, sessionDirectoryExists, writeResponse, writeSuccessResponse } from './session'; import fs = require('fs-extra'); import path = require('path'); -import { chooseTerminal, runTextInTerm, restartRTerminal } from './rTerminal'; +import { runTextInTerm, restartRTerminal } from './rTerminal'; import { config } from './util'; let lastActiveTextEditor: TextEditor; -export async function dispatchRStudioAPICall(action: string, args: any, sd: string) { +export async function dispatchRStudioAPICall(action: string, args: any, sd: string): Promise { switch (action) { case 'active_editor_context': { - await writeResponse(await activeEditorContext(), sd); + await writeResponse(activeEditorContext(), sd); break; } case 'insert_or_modify_text': { @@ -29,7 +36,7 @@ export async function dispatchRStudioAPICall(action: string, args: any, sd: stri break; } case 'show_dialog': { - await showDialog(args.message); + showDialog(args.message); await writeSuccessResponse(sd); break; } @@ -78,7 +85,7 @@ export async function dispatchRStudioAPICall(action: string, args: any, sd: stri } //rstudioapi -export async function activeEditorContext() { +export function activeEditorContext() { // info returned from RStudio: // list with: // id @@ -97,7 +104,7 @@ export async function activeEditorContext() { export async function documentContext(id: string) { const target = findTargetUri(id); const targetDocument = await workspace.openTextDocument(target); - console.info(`[documentContext] getting context for: ${target}`); + console.info(`[documentContext] getting context for: ${target.path}`); return { id: targetDocument.uri }; @@ -108,7 +115,7 @@ export async function insertOrModifyText(query: any[], id: string = null) { const target = findTargetUri(id); const targetDocument = await workspace.openTextDocument(target); - console.info(`[insertTextAtPosition] inserting text into: ${target}`); + console.info(`[insertTextAtPosition] inserting text into: ${target.path}`); const edit = new WorkspaceEdit(); query.forEach((op) => { @@ -130,12 +137,12 @@ export async function insertOrModifyText(query: any[], id: string = null) { } }); - workspace.applyEdit(edit); + void workspace.applyEdit(edit); } -export async function replaceTextInCurrentSelection(text: string, id: string) { +export async function replaceTextInCurrentSelection(text: string, id: string): Promise { const target = findTargetUri(id); - console.info(`[replaceTextInCurrentSelection] inserting: ${text} into ${target}`); + console.info(`[replaceTextInCurrentSelection] inserting: ${text} into ${target.path}`); const edit = new WorkspaceEdit(); edit.replace( target, @@ -145,13 +152,13 @@ export async function replaceTextInCurrentSelection(text: string, id: string) { await workspace.applyEdit(edit); } -export async function showDialog(message: string) { +export function showDialog(message: string): void { - window.showInformationMessage(message); + void window.showInformationMessage(message); } -export async function navigateToFile(file: string, line: number, column: number) { +export async function navigateToFile(file: string, line: number, column: number): Promise{ const targetDocument = await workspace.openTextDocument(Uri.file(file)); const editor = await window.showTextDocument(targetDocument); @@ -160,7 +167,7 @@ export async function navigateToFile(file: string, line: number, column: number) editor.revealRange(new Range(targetPosition, targetPosition)); } -export async function setSelections(ranges: number[][], id: string) { +export async function setSelections(ranges: number[][], id: string): Promise { // Setting selections can only be done on TextEditors not TextDocuments, but // it is the latter which are the things actually referred to by `id`. In // VSCode it's not possible to get a list of the open text editors. it is not @@ -195,17 +202,17 @@ export async function setSelections(ranges: number[][], id: string) { editor.selections = selectionObjects; } -export async function documentSave(id: string) { +export async function documentSave(id: string): Promise { const target = findTargetUri(id); const targetDocument = await workspace.openTextDocument(target); await targetDocument.save(); } -export async function documentSaveAll() { +export async function documentSaveAll(): Promise { await workspace.saveAll(); } -export function projectPath() { +export function projectPath(): { path: string; } { if (typeof workspace.workspaceFolders !== 'undefined') { // Is there a root folder open? @@ -239,7 +246,7 @@ export function projectPath() { }; } -export async function documentNew(text: string, type: string, position: number[]) { +export async function documentNew(text: string, type: string, position: number[]): Promise { const documentUri = Uri.parse('untitled:' + path.join(projectPath().path, 'new_document.' + type)); const targetDocument = await workspace.openTextDocument(documentUri); const edit = new WorkspaceEdit(); @@ -251,7 +258,7 @@ export async function documentNew(text: string, type: string, position: number[] )), text); - workspace.applyEdit(edit).then(async () => { + void workspace.applyEdit(edit).then(async () => { const editor = await window.showTextDocument(targetDocument); editor.selections = [new Selection( parsePosition(position, targetDocument), @@ -269,13 +276,13 @@ interface AddinItem extends QuickPickItem { let addinQuickPicks: AddinItem[] = undefined; -export async function getAddinPickerItems() { +export async function getAddinPickerItems(): Promise { if (typeof addinQuickPicks === 'undefined') { const addins: any[] = await fs.readJSON(path.join(sessionDir, 'addins.json')). then( (result) => result, - (reason) => { + () => { throw ('Could not find list of installed addins.' + ' options(vsc.rstudioapi = TRUE) must be set in your .Rprofile to use ' + ' RStudio Addins'); @@ -298,11 +305,11 @@ export async function getAddinPickerItems() { return addinQuickPicks; } -export function purgeAddinPickerItems() { +export function purgeAddinPickerItems(): void { addinQuickPicks = undefined; } -export async function launchAddinPicker() { +export async function launchAddinPicker(): Promise { if (!config().get('sessionWatcher')) { throw ('{rstudioapi} emulation requires session watcher to be enabled in extension config.'); @@ -396,7 +403,7 @@ function normaliseEditText(text: string, editLocation: any, } // window.onActiveTextEditorDidChange handler -export function trackLastActiveTextEditor(editor: TextEditor) { +export function trackLastActiveTextEditor(editor: TextEditor): void { if (typeof editor !== 'undefined') { lastActiveTextEditor = editor; } diff --git a/src/selection.ts b/src/selection.ts index 09116b94c..bb4218a30 100644 --- a/src/selection.ts +++ b/src/selection.ts @@ -31,7 +31,10 @@ export function surroundSelection(text: string, rFunctionName: string[]): string return text; } -export function getSelection() { +export function getSelection(): { + linesDownToMoveCursor: number; + selectedText: string; +} { const selection = { linesDownToMoveCursor: 0, selectedText: '' }; const { start, end } = window.activeTextEditor.selection; const currentDocument = window.activeTextEditor.document; @@ -182,7 +185,10 @@ function getNextChar(p: PositionNeg, * @param getLine A function that returns the string at the given line of the document. * @param lineCount The number of lines in the document. */ -export function extendSelection(line: number, getLine: (line: number) => string, lineCount: number) { +export function extendSelection(line: number, getLine: (line: number) => string, lineCount: number): { + startLine: number; + endLine: number; +} { const lc = new LineCache(getLine, lineCount); const getLineFromCache = (x) => lc.getLineFromCache(x); const getEndsInOperatorFromCache = (x) => lc.getEndsInOperatorFromCache(x); diff --git a/src/session.ts b/src/session.ts index 846388707..c2bd99f34 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1,4 +1,7 @@ -// tslint:disable: no-console +/* eslint-disable @typescript-eslint/restrict-template-expressions */ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-explicit-any */ 'use strict'; import fs = require('fs-extra'); @@ -31,11 +34,10 @@ let plotFile: string; let plotLockFile: string; let plotTimeStamp: number; let plotDir: string; -let requestWatcher: FSWatcher; let globalEnvWatcher: FSWatcher; let plotWatcher: FSWatcher; -export function deploySessionWatcher(extensionPath: string) { +export function deploySessionWatcher(extensionPath: string): void { console.info(`[deploySessionWatcher] extensionPath: ${extensionPath}`); resDir = path.join(extensionPath, 'dist', 'resources'); watcherDir = path.join(os.homedir(), '.vscode-R'); @@ -55,7 +57,7 @@ export function deploySessionWatcher(extensionPath: string) { console.info('[deploySessionWatcher] Done'); } -export function startRequestWatcher(sessionStatusBarItem: StatusBarItem) { +export function startRequestWatcher(sessionStatusBarItem: StatusBarItem): void { console.info('[startRequestWatcher] Starting'); requestFile = path.join(watcherDir, 'request.log'); requestLockFile = path.join(watcherDir, 'request.lock'); @@ -64,18 +66,18 @@ export function startRequestWatcher(sessionStatusBarItem: StatusBarItem) { if (!fs.existsSync(requestLockFile)) { fs.createFileSync(requestLockFile); } - requestWatcher = fs.watch(requestLockFile, {}, (event: string, filename: string) => { - updateRequest(sessionStatusBarItem); + fs.watch(requestLockFile, {}, () => { + void updateRequest(sessionStatusBarItem); }); console.info('[startRequestWatcher] Done'); } -export function attachActive() { +export function attachActive(): void { if (config().get('sessionWatcher')) { console.info('[attachActive]'); - runTextInTerm('.vsc.attach()'); + void runTextInTerm('.vsc.attach()'); } else { - window.showInformationMessage('This command requires that r.sessionWatcher be enabled.'); + void window.showInformationMessage('This command requires that r.sessionWatcher be enabled.'); } } @@ -95,11 +97,11 @@ function removeDirectory(dir: string) { console.info('[removeDirectory] Done'); } -export function sessionDirectoryExists() { +export function sessionDirectoryExists(): boolean { return (fs.existsSync(sessionDir)); } -export function removeSessionFiles() { +export function removeSessionFiles(): void { console.info('[removeSessionFiles] ', sessionDir); if (sessionDirectoryExists()) { removeDirectory(sessionDir); @@ -117,10 +119,10 @@ function updateSessionWatcher() { globalEnvWatcher.close(); } if (fs.existsSync(globalenvLockFile)) { - globalEnvWatcher = fs.watch(globalenvLockFile, {}, (event: string, filename: string) => { - updateGlobalenv(); + globalEnvWatcher = fs.watch(globalenvLockFile, {}, () => { + void updateGlobalenv(); }); - updateGlobalenv(); + void updateGlobalenv(); } else { console.info('[updateSessionWatcher] globalenvLockFile not found'); } @@ -133,10 +135,10 @@ function updateSessionWatcher() { plotWatcher.close(); } if (fs.existsSync(plotLockFile)) { - plotWatcher = fs.watch(plotLockFile, {}, (event: string, filename: string) => { - updatePlot(); + plotWatcher = fs.watch(plotLockFile, {}, () => { + void updatePlot(); }); - updatePlot(); + void updatePlot(); } else { console.info('[updateSessionWatcher] plotLockFile not found'); } @@ -150,7 +152,7 @@ async function updatePlot() { if (newTimeStamp !== plotTimeStamp) { plotTimeStamp = newTimeStamp; if (fs.existsSync(plotFile) && fs.statSync(plotFile).size > 0) { - commands.executeCommand('vscode.open', Uri.file(plotFile), { + void commands.executeCommand('vscode.open', Uri.file(plotFile), { preserveFocus: true, preview: true, viewColumn: ViewColumn[plotView], @@ -179,9 +181,9 @@ async function updateGlobalenv() { } function showBrowser(url: string, title: string, viewer: string | boolean) { - console.info(`[showBrowser] uri: ${url}, viewer: ${viewer}`); + console.info(`[showBrowser] uri: ${url}, viewer: ${viewer.toString()}`); if (viewer === false) { - env.openExternal(Uri.parse(url)); + void env.openExternal(Uri.parse(url)); } else { const port = parseInt(new URL(url).port); const panel = window.createWebviewPanel( @@ -229,9 +231,9 @@ function getBrowserHtml(url: string) { } async function showWebView(file: string, title: string, viewer: string | boolean) { - console.info(`[showWebView] file: ${file}, viewer: ${viewer}`); + console.info(`[showWebView] file: ${file}, viewer: ${viewer.toString()}`); if (viewer === false) { - env.openExternal(Uri.parse(file)); + void env.openExternal(Uri.parse(file)); } else { const dir = path.dirname(file); const panel = window.createWebviewPanel('webview', title, @@ -283,7 +285,7 @@ async function showDataView(source: string, type: string, title: string, file: s const content = await getListHtml(panel.webview, file); panel.webview.html = content; } else { - commands.executeCommand('vscode.open', Uri.file(file), { + await commands.executeCommand('vscode.open', Uri.file(file), { preserveFocus: true, preview: true, viewColumn: ViewColumn[viewer], @@ -385,10 +387,10 @@ async function getListHtml(webview: Webview, file: string) { `; } -export async function showPlotHistory() { +export async function showPlotHistory(): Promise { if (config().get('sessionWatcher')) { if (plotDir === undefined) { - window.showErrorMessage('No session is attached.'); + void window.showErrorMessage('No session is attached.'); } else { const files = await fs.readdir(plotDir); if (files.length > 0) { @@ -405,11 +407,11 @@ export async function showPlotHistory() { const html = getPlotHistoryHtml(panel.webview, files); panel.webview.html = html; } else { - window.showInformationMessage('There is no plot to show yet.'); + void window.showInformationMessage('There is no plot to show yet.'); } } } else { - window.showInformationMessage('This command requires that r.sessionWatcher be enabled.'); + void window.showInformationMessage('This command requires that r.sessionWatcher be enabled.'); } } @@ -465,7 +467,7 @@ function isFromWorkspace(dir: string) { return false; } -export async function writeResponse(responseData: object, responseSessionDir: string) { +export async function writeResponse(responseData: Record, responseSessionDir: string): Promise { const responseFile = path.join(responseSessionDir, 'response.log'); const responseLockFile = path.join(responseSessionDir, 'response.lock'); @@ -480,11 +482,11 @@ export async function writeResponse(responseData: object, responseSessionDir: st console.info(`[writeRespnse] responseFile: ${responseFile}`); await fs.writeFile(responseFile, responseString); responseTimeStamp = Date.now(); - await fs.writeFile(responseLockFile, responseTimeStamp + '\n'); + await fs.writeFile(responseLockFile, `${responseTimeStamp}\n`); } -export async function writeSuccessResponse(responseSessionDir: string) { - writeResponse({ result: true }, responseSessionDir); +export async function writeSuccessResponse(responseSessionDir: string): Promise { + await writeResponse({ result: true }, responseSessionDir); } async function updateRequest(sessionStatusBarItem: StatusBarItem) { @@ -523,11 +525,11 @@ async function updateRequest(sessionStatusBarItem: StatusBarItem) { break; } case 'webview': { - showWebView(request.file, request.title, request.viewer); + void showWebView(request.file, request.title, request.viewer); break; } case 'dataview': { - showDataView(request.source, + void showDataView(request.source, request.type, request.title, request.file, request.viewer); break; } diff --git a/src/test/runTest.ts b/src/test/runTest.ts index a3e10548d..fbe0c5f08 100644 --- a/src/test/runTest.ts +++ b/src/test/runTest.ts @@ -20,4 +20,4 @@ async function main() { } } -main(); +void main(); diff --git a/src/test/suite/extension.test.ts b/src/test/suite/extension.test.ts index b5f075ac7..b5abe5aac 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -20,15 +20,15 @@ suite('Extension Tests', () => { y } `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 4); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); - assert.equal(extendSelection(3, f, doc.length).startLine, 3); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); - assert.equal(extendSelection(4, f, doc.length).startLine, 0); - assert.equal(extendSelection(4, f, doc.length).endLine, 4); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 4); }); test('Selecting two-line () bracketed expression', () => { @@ -36,11 +36,11 @@ suite('Extension Tests', () => { a = list(x = 1, y = 2) `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 2); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); }); test('Selecting three-line () bracketed expression', () => { @@ -49,13 +49,13 @@ suite('Extension Tests', () => { y = 2, z = 3) `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 3); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 3); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting two-line piped expression', () => { @@ -63,11 +63,11 @@ suite('Extension Tests', () => { 1 + 1 %>% print() `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 2); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); }); test('Selecting two-line piped expression with gap', () => { @@ -76,13 +76,13 @@ suite('Extension Tests', () => { print() `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 3); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 3); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting three-line piped expression', () => { @@ -91,13 +91,13 @@ suite('Extension Tests', () => { sum() %>% print() `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 3); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 3); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting nested bracketed expression with brackets on different lines', () => { @@ -108,17 +108,17 @@ suite('Extension Tests', () => { ) ) `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 5); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 4); - assert.equal(extendSelection(3, f, doc.length).startLine, 3); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); - assert.equal(extendSelection(4, f, doc.length).startLine, 2); - assert.equal(extendSelection(4, f, doc.length).endLine, 4); - assert.equal(extendSelection(5, f, doc.length).startLine, 0); - assert.equal(extendSelection(5, f, doc.length).endLine, 5); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 5); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(5, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(5, f, doc.length).endLine, 5); }); test('Selecting nested bracketed expression with brackets on same line', () => { @@ -128,15 +128,15 @@ suite('Extension Tests', () => { 2 )} `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 4); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 4); - assert.equal(extendSelection(3, f, doc.length).startLine, 3); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); - assert.equal(extendSelection(4, f, doc.length).startLine, 0); - assert.equal(extendSelection(4, f, doc.length).endLine, 4); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 4); }); test('Selecting brackets and pipes', () => { @@ -148,19 +148,19 @@ suite('Extension Tests', () => { 2 ) `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 6); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 6); - assert.equal(extendSelection(4, f, doc.length).startLine, 0); - assert.equal(extendSelection(4, f, doc.length).endLine, 6); - assert.equal(extendSelection(5, f, doc.length).startLine, 5); - assert.equal(extendSelection(5, f, doc.length).endLine, 5); - assert.equal(extendSelection(6, f, doc.length).startLine, 0); - assert.equal(extendSelection(6, f, doc.length).endLine, 6); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 6); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 6); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 6); + assert.strictEqual(extendSelection(5, f, doc.length).startLine, 5); + assert.strictEqual(extendSelection(5, f, doc.length).endLine, 5); + assert.strictEqual(extendSelection(6, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(6, f, doc.length).endLine, 6); const doc2 = ` { @@ -171,21 +171,21 @@ suite('Extension Tests', () => { 2 ) `.split('\n'); - function f2(i) {return (doc2[i]); } - assert.equal(extendSelection(1, f2, doc2.length).startLine, 0); - assert.equal(extendSelection(1, f2, doc2.length).endLine, 7); - assert.equal(extendSelection(2, f2, doc2.length).startLine, 2); - assert.equal(extendSelection(2, f2, doc2.length).endLine, 2); - assert.equal(extendSelection(3, f2, doc2.length).startLine, 0); - assert.equal(extendSelection(3, f2, doc2.length).endLine, 7); - assert.equal(extendSelection(4, f2, doc2.length).startLine, 0); - assert.equal(extendSelection(4, f2, doc2.length).endLine, 7); - assert.equal(extendSelection(5, f2, doc2.length).startLine, 0); - assert.equal(extendSelection(5, f2, doc2.length).endLine, 7); - assert.equal(extendSelection(6, f2, doc2.length).startLine, 6); - assert.equal(extendSelection(6, f2, doc2.length).endLine, 6); - assert.equal(extendSelection(7, f2, doc2.length).startLine, 0); - assert.equal(extendSelection(7, f2, doc2.length).endLine, 7); + function f2(i: number) {return (doc2[i]); } + assert.strictEqual(extendSelection(1, f2, doc2.length).startLine, 0); + assert.strictEqual(extendSelection(1, f2, doc2.length).endLine, 7); + assert.strictEqual(extendSelection(2, f2, doc2.length).startLine, 2); + assert.strictEqual(extendSelection(2, f2, doc2.length).endLine, 2); + assert.strictEqual(extendSelection(3, f2, doc2.length).startLine, 0); + assert.strictEqual(extendSelection(3, f2, doc2.length).endLine, 7); + assert.strictEqual(extendSelection(4, f2, doc2.length).startLine, 0); + assert.strictEqual(extendSelection(4, f2, doc2.length).endLine, 7); + assert.strictEqual(extendSelection(5, f2, doc2.length).startLine, 0); + assert.strictEqual(extendSelection(5, f2, doc2.length).endLine, 7); + assert.strictEqual(extendSelection(6, f2, doc2.length).startLine, 6); + assert.strictEqual(extendSelection(6, f2, doc2.length).endLine, 6); + assert.strictEqual(extendSelection(7, f2, doc2.length).startLine, 0); + assert.strictEqual(extendSelection(7, f2, doc2.length).endLine, 7); }); test('Selecting large RStudio comparison', () => { @@ -208,41 +208,41 @@ suite('Extension Tests', () => { # 16. RStudio sends lines 16-17; vscode-R sends 1-17 } # 17. RStudio sends lines 1-17; vscode-R sends 1-17 `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 17); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 4); - assert.equal(extendSelection(3, f, doc.length).startLine, 2); - assert.equal(extendSelection(3, f, doc.length).endLine, 4); - assert.equal(extendSelection(4, f, doc.length).startLine, 2); - assert.equal(extendSelection(4, f, doc.length).endLine, 4); - assert.equal(extendSelection(5, f, doc.length).startLine, 5); - assert.equal(extendSelection(5, f, doc.length).endLine, 15); - assert.equal(extendSelection(6, f, doc.length).startLine, 6); - assert.equal(extendSelection(6, f, doc.length).endLine, 14); - assert.equal(extendSelection(7, f, doc.length).startLine, 7); - assert.equal(extendSelection(7, f, doc.length).endLine, 13); - assert.equal(extendSelection(8, f, doc.length).startLine, 8); - assert.equal(extendSelection(8, f, doc.length).endLine, 12); - assert.equal(extendSelection(9, f, doc.length).startLine, 9); - assert.equal(extendSelection(9, f, doc.length).endLine, 11); - assert.equal(extendSelection(10, f, doc.length).startLine, 10); - assert.equal(extendSelection(10, f, doc.length).endLine, 10); - assert.equal(extendSelection(11, f, doc.length).startLine, 9); - assert.equal(extendSelection(11, f, doc.length).endLine, 11); - assert.equal(extendSelection(12, f, doc.length).startLine, 8); - assert.equal(extendSelection(12, f, doc.length).endLine, 12); - assert.equal(extendSelection(13, f, doc.length).startLine, 7); - assert.equal(extendSelection(13, f, doc.length).endLine, 13); - assert.equal(extendSelection(14, f, doc.length).startLine, 6); - assert.equal(extendSelection(14, f, doc.length).endLine, 14); - assert.equal(extendSelection(15, f, doc.length).startLine, 5); - assert.equal(extendSelection(15, f, doc.length).endLine, 15); - assert.equal(extendSelection(16, f, doc.length).startLine, 0); - assert.equal(extendSelection(16, f, doc.length).endLine, 17); - assert.equal(extendSelection(17, f, doc.length).startLine, 0); - assert.equal(extendSelection(17, f, doc.length).endLine, 17); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 17); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(5, f, doc.length).startLine, 5); + assert.strictEqual(extendSelection(5, f, doc.length).endLine, 15); + assert.strictEqual(extendSelection(6, f, doc.length).startLine, 6); + assert.strictEqual(extendSelection(6, f, doc.length).endLine, 14); + assert.strictEqual(extendSelection(7, f, doc.length).startLine, 7); + assert.strictEqual(extendSelection(7, f, doc.length).endLine, 13); + assert.strictEqual(extendSelection(8, f, doc.length).startLine, 8); + assert.strictEqual(extendSelection(8, f, doc.length).endLine, 12); + assert.strictEqual(extendSelection(9, f, doc.length).startLine, 9); + assert.strictEqual(extendSelection(9, f, doc.length).endLine, 11); + assert.strictEqual(extendSelection(10, f, doc.length).startLine, 10); + assert.strictEqual(extendSelection(10, f, doc.length).endLine, 10); + assert.strictEqual(extendSelection(11, f, doc.length).startLine, 9); + assert.strictEqual(extendSelection(11, f, doc.length).endLine, 11); + assert.strictEqual(extendSelection(12, f, doc.length).startLine, 8); + assert.strictEqual(extendSelection(12, f, doc.length).endLine, 12); + assert.strictEqual(extendSelection(13, f, doc.length).startLine, 7); + assert.strictEqual(extendSelection(13, f, doc.length).endLine, 13); + assert.strictEqual(extendSelection(14, f, doc.length).startLine, 6); + assert.strictEqual(extendSelection(14, f, doc.length).endLine, 14); + assert.strictEqual(extendSelection(15, f, doc.length).startLine, 5); + assert.strictEqual(extendSelection(15, f, doc.length).endLine, 15); + assert.strictEqual(extendSelection(16, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(16, f, doc.length).endLine, 17); + assert.strictEqual(extendSelection(17, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(17, f, doc.length).endLine, 17); }); test('Selecting block with missing opening bracket', () => { @@ -253,17 +253,17 @@ suite('Extension Tests', () => { 2 ) `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 1); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); - assert.equal(extendSelection(3, f, doc.length).startLine, 3); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); - assert.equal(extendSelection(4, f, doc.length).startLine, 4); - assert.equal(extendSelection(4, f, doc.length).endLine, 4); - assert.equal(extendSelection(5, f, doc.length).startLine, 5); - assert.equal(extendSelection(5, f, doc.length).endLine, 5); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 1); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 4); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(5, f, doc.length).startLine, 5); + assert.strictEqual(extendSelection(5, f, doc.length).endLine, 5); }); test('Selecting block with missing closing bracket', () => { @@ -271,11 +271,11 @@ suite('Extension Tests', () => { c( 2 `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 1); - assert.equal(extendSelection(1, f, doc.length).endLine, 1); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 1); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 1); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); }); test('Selecting block with missing closing bracket and gap', () => { @@ -284,13 +284,13 @@ suite('Extension Tests', () => { 2 `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 1); - assert.equal(extendSelection(1, f, doc.length).endLine, 1); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); - assert.equal(extendSelection(3, f, doc.length).startLine, 3); - assert.equal(extendSelection(3, f, doc.length).endLine, 4); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 1); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 1); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 4); }); test('Selecting block with missing opening bracket 2', () => { @@ -298,11 +298,11 @@ suite('Extension Tests', () => { 2 ) `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 1); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 1); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); }); test('Selecting block with missing opening bracket and gap', () => { @@ -311,13 +311,13 @@ suite('Extension Tests', () => { 2 ) `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 2); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); - assert.equal(extendSelection(3, f, doc.length).startLine, 3); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting block with missing opening bracket and gap after', () => { @@ -327,15 +327,15 @@ suite('Extension Tests', () => { ) `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 2); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); - assert.equal(extendSelection(3, f, doc.length).startLine, 3); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); - assert.equal(extendSelection(4, f, doc.length).startLine, 4); - assert.equal(extendSelection(4, f, doc.length).endLine, 5); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 4); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 5); }); test('Selecting longer badly-formed block', () => { @@ -351,9 +351,9 @@ suite('Extension Tests', () => { ), ID = '2')) )), data = data.frame(id = c(1,2)) `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 1); - assert.equal(extendSelection(1, f, doc.length).endLine, 1); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 1); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 1); }); test('Selecting with comments', () => { @@ -363,15 +363,15 @@ suite('Extension Tests', () => { # } } `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 4); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 4); - assert.equal(extendSelection(4, f, doc.length).startLine, 0); - assert.equal(extendSelection(4, f, doc.length).endLine, 4); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 4); }); test('Selecting multi-line square bracket', () => { @@ -379,11 +379,11 @@ suite('Extension Tests', () => { a[1 ] `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 2); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); }); test('Selecting ggplot plot', () => { @@ -391,11 +391,11 @@ suite('Extension Tests', () => { ggplot(aes(speed, dist), data = cars) + geom_point() `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 2); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); }); test('Selecting multi-line bracket with pipe', () => { @@ -405,15 +405,15 @@ suite('Extension Tests', () => { z = 3) %>% print() `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 4); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 4); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 4); - assert.equal(extendSelection(4, f, doc.length).startLine, 0); - assert.equal(extendSelection(4, f, doc.length).endLine, 4); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 4); }); test('Selecting shorter RStudio comparison', () => { @@ -428,25 +428,25 @@ suite('Extension Tests', () => { } # 8. RStudio sends lines 1-9; vscode-R sends lines 2-8 ) # 9. RStudio and vscode-R send lines 1-9 `.split('\n'); - function f(i) {return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 9); - assert.equal(extendSelection(2, f, doc.length).startLine, 2); - assert.equal(extendSelection(2, f, doc.length).endLine, 8); - assert.equal(extendSelection(3, f, doc.length).startLine, 3); - assert.equal(extendSelection(3, f, doc.length).endLine, 7); - assert.equal(extendSelection(4, f, doc.length).startLine, 4); - assert.equal(extendSelection(4, f, doc.length).endLine, 6); - assert.equal(extendSelection(5, f, doc.length).startLine, 5); - assert.equal(extendSelection(5, f, doc.length).endLine, 5); - assert.equal(extendSelection(6, f, doc.length).startLine, 4); - assert.equal(extendSelection(6, f, doc.length).endLine, 6); - assert.equal(extendSelection(7, f, doc.length).startLine, 3); - assert.equal(extendSelection(7, f, doc.length).endLine, 7); - assert.equal(extendSelection(8, f, doc.length).startLine, 2); - assert.equal(extendSelection(8, f, doc.length).endLine, 8); - assert.equal(extendSelection(9, f, doc.length).startLine, 0); - assert.equal(extendSelection(9, f, doc.length).endLine, 9); + function f(i: number) {return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 9); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 8); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 7); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 4); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 6); + assert.strictEqual(extendSelection(5, f, doc.length).startLine, 5); + assert.strictEqual(extendSelection(5, f, doc.length).endLine, 5); + assert.strictEqual(extendSelection(6, f, doc.length).startLine, 4); + assert.strictEqual(extendSelection(6, f, doc.length).endLine, 6); + assert.strictEqual(extendSelection(7, f, doc.length).startLine, 3); + assert.strictEqual(extendSelection(7, f, doc.length).endLine, 7); + assert.strictEqual(extendSelection(8, f, doc.length).startLine, 2); + assert.strictEqual(extendSelection(8, f, doc.length).endLine, 8); + assert.strictEqual(extendSelection(9, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(9, f, doc.length).endLine, 9); }); test('Selecting single line with double quotes', () => { @@ -454,9 +454,9 @@ suite('Extension Tests', () => { "hello" a + b `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 1); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 1); }); test('Selecting single line with single quotes', () => { @@ -464,9 +464,9 @@ suite('Extension Tests', () => { 'hello' a + b `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 1); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 1); }); test('Selecting single line with backticks', () => { @@ -474,9 +474,9 @@ suite('Extension Tests', () => { \`hello\` a + b `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 1); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 1); }); test('Selecting multi-line bracket with unmatched brackets in string', () => { @@ -485,11 +485,11 @@ suite('Extension Tests', () => { paste0("[[", i) }) `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 3); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting multi-line call with square bracket function', () => { @@ -499,11 +499,11 @@ suite('Extension Tests', () => { 3 ) `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 4); - assert.equal(extendSelection(4, f, doc.length).startLine, 0); - assert.equal(extendSelection(4, f, doc.length).endLine, 4); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 4); + assert.strictEqual(extendSelection(4, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(4, f, doc.length).endLine, 4); }); test('Selecting multi-line function definition with unmatched bracket', () => { @@ -512,11 +512,11 @@ suite('Extension Tests', () => { x[i] } `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 3); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting multi-line brackets with mixed quotes', () => { @@ -525,11 +525,11 @@ suite('Extension Tests', () => { paste0('"', i) }) `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 3); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting multi-line brackets with pipe and unmatched bracket in string', () => { @@ -538,13 +538,13 @@ suite('Extension Tests', () => { y = "[") %>% print() `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 3); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 3); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting multi-line brackets with escaped quote', () => { @@ -553,11 +553,11 @@ suite('Extension Tests', () => { paste0("\\"", i) }) `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 3); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting multi-line brackets with escaped quotes in multi-line string', () => { @@ -566,11 +566,11 @@ suite('Extension Tests', () => { hello\\"" ) `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 3); - assert.equal(extendSelection(3, f, doc.length).startLine, 0); - assert.equal(extendSelection(3, f, doc.length).endLine, 3); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 3); + assert.strictEqual(extendSelection(3, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(3, f, doc.length).endLine, 3); }); test('Selecting multi-line brackets with multi-line string and unmatched brackets', () => { @@ -581,11 +581,11 @@ suite('Extension Tests', () => { \`[[\` is also a function" ) `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 5); - assert.equal(extendSelection(5, f, doc.length).startLine, 0); - assert.equal(extendSelection(5, f, doc.length).endLine, 5); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 5); + assert.strictEqual(extendSelection(5, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(5, f, doc.length).endLine, 5); }); test('Selecting multi-line expression with escaped backtick and ending operator', () => { @@ -593,11 +593,11 @@ suite('Extension Tests', () => { \`hello\\\`\` + 1 `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 2); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 2); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 2); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 2); }); test('Selecting multi-line expression with comment char in quotes', () => { @@ -608,11 +608,11 @@ suite('Extension Tests', () => { paste("'") %>% print() # } # `.split('\n'); - function f(i) { return (doc[i]); } - assert.equal(extendSelection(1, f, doc.length).startLine, 0); - assert.equal(extendSelection(1, f, doc.length).endLine, 5); - assert.equal(extendSelection(2, f, doc.length).startLine, 0); - assert.equal(extendSelection(2, f, doc.length).endLine, 5); + function f(i: number) { return (doc[i]); } + assert.strictEqual(extendSelection(1, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(1, f, doc.length).endLine, 5); + assert.strictEqual(extendSelection(2, f, doc.length).startLine, 0); + assert.strictEqual(extendSelection(2, f, doc.length).endLine, 5); }); }); diff --git a/src/test/suite/index.ts b/src/test/suite/index.ts index bd78b7755..ba49ec708 100644 --- a/src/test/suite/index.ts +++ b/src/test/suite/index.ts @@ -1,3 +1,5 @@ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-unsafe-call */ import * as path from 'path'; import * as Mocha from 'mocha'; import * as glob from 'glob'; diff --git a/src/util.ts b/src/util.ts index eaf138471..57b05a531 100644 --- a/src/util.ts +++ b/src/util.ts @@ -3,16 +3,16 @@ import { existsSync } from 'fs-extra'; import path = require('path'); import fs = require('fs'); -import { window, workspace } from 'vscode'; +import { window, workspace, WorkspaceConfiguration } from 'vscode'; import winreg = require('winreg'); -export function config() { +export function config(): WorkspaceConfiguration { return workspace.getConfiguration('r'); } function getRfromEnvPath(platform: string) { - let splitChar: string = ':'; - let fileExtension: string = ''; + let splitChar = ':'; + let fileExtension = ''; if (platform === 'win32') { splitChar = ';'; @@ -29,9 +29,9 @@ function getRfromEnvPath(platform: string) { return ''; } -export async function getRpathFromSystem() { +export async function getRpathFromSystem(): Promise { - let rpath: string = ''; + let rpath = ''; const platform: string = process.platform; if ( platform === 'win32') { @@ -54,9 +54,9 @@ export async function getRpathFromSystem() { return rpath; } -export async function getRpath() { +export async function getRpath(): Promise { - let rpath: string = ''; + let rpath = ''; const platform: string = process.platform; if ( platform === 'win32') { @@ -73,12 +73,12 @@ export async function getRpath() { return rpath; } - window.showErrorMessage(`${process.platform} can't use R`); + void window.showErrorMessage(`${process.platform} can't use R`); return undefined; } -export function ToRStringLiteral(s: string, quote: string) { +export function ToRStringLiteral(s: string, quote: string): string { if (s === undefined) { return 'NULL'; } @@ -96,14 +96,14 @@ export function ToRStringLiteral(s: string, quote: string) { quote); } -export async function delay(ms: number) { +export async function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } -export function checkForSpecialCharacters(text: string) { - return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?\s]/g.test(text); +export function checkForSpecialCharacters(text: string): boolean { + return !/[~`!#$%^&*+=\-[\]\\';,/{}|\\":<>?\s]/g.test(text); } -export function checkIfFileExists(filePath: string) { +export function checkIfFileExists(filePath: string): boolean { return existsSync(filePath); } diff --git a/src/viewer.ts b/src/viewer.ts index 7917e476b..6ca9bd460 100644 --- a/src/viewer.ts +++ b/src/viewer.ts @@ -2,7 +2,7 @@ import { commands, ExtensionContext, ViewColumn, window } from 'vscode'; -export function activate(context: ExtensionContext) { +export function activate(context: ExtensionContext): void { context.subscriptions.push(commands.registerCommand('catCoding.start', () => { // Create and show panel const panel = window.createWebviewPanel('catCoding', 'Cat Coding', ViewColumn.One, { });