Closes #4483: migrate to eslint (#8702)

This commit is contained in:
Foo-x 2023-12-23 10:16:43 +09:00 committed by GitHub
parent de30a004ef
commit d712063aa0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
74 changed files with 7137 additions and 6350 deletions

231
.eslintrc.js Normal file
View File

@ -0,0 +1,231 @@
module.exports = {
env: {
es6: true,
node: true,
},
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'prettier',
],
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['eslint-plugin-jsdoc', 'eslint-plugin-prefer-arrow', '@typescript-eslint'],
root: true,
ignorePatterns: ['*.js'],
rules: {
'@typescript-eslint/adjacent-overload-signatures': 'error',
'@typescript-eslint/array-type': [
'error',
{
default: 'array-simple',
},
],
'@typescript-eslint/await-thenable': 'error',
'@typescript-eslint/ban-ts-comment': 'error',
'@typescript-eslint/ban-types': [
'error',
{
types: {
Object: {
message: 'Avoid using the `Object` type. Did you mean `object`?',
},
Function: {
message:
'Avoid using the `Function` type. Prefer a specific function type, like `() => void`.',
},
Boolean: {
message: 'Avoid using the `Boolean` type. Did you mean `boolean`?',
},
Number: {
message: 'Avoid using the `Number` type. Did you mean `number`?',
},
String: {
message: 'Avoid using the `String` type. Did you mean `string`?',
},
Symbol: {
message: 'Avoid using the `Symbol` type. Did you mean `symbol`?',
},
},
},
],
'@typescript-eslint/consistent-type-assertions': 'error',
'@typescript-eslint/dot-notation': 'error',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'variable',
format: ['camelCase', 'UPPER_CASE', 'PascalCase'],
leadingUnderscore: 'allow',
trailingUnderscore: 'forbid',
},
],
'@typescript-eslint/no-array-constructor': 'error',
// ignore the rule to conform to current code
'@typescript-eslint/no-base-to-string': 'off',
'@typescript-eslint/no-duplicate-enum-values': 'error',
'@typescript-eslint/no-duplicate-type-constituents': 'error',
'@typescript-eslint/no-empty-function': 'error',
'@typescript-eslint/no-empty-interface': 'error',
// ignore the rule to conform to current code
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-extra-non-null-assertion': 'error',
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-for-in-array': 'error',
'@typescript-eslint/no-implied-eval': 'error',
'@typescript-eslint/no-loss-of-precision': 'error',
'@typescript-eslint/no-misused-new': 'error',
// ignore the rule to conform to current code
'@typescript-eslint/no-misused-promises': 'off',
'@typescript-eslint/no-namespace': 'error',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/parameter-properties': 'error',
'@typescript-eslint/no-redundant-type-constituents': 'error',
'@typescript-eslint/no-shadow': [
'error',
{
hoist: 'all',
},
],
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
'@typescript-eslint/no-unnecessary-type-constraint': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
'@typescript-eslint/no-unsafe-call': 'error',
'@typescript-eslint/no-unsafe-declaration-merging': 'error',
// ignore the rule to conform to current code
'@typescript-eslint/no-unsafe-enum-comparison': 'off',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'@typescript-eslint/no-unused-expressions': 'error',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-var-requires': 'error',
'@typescript-eslint/prefer-as-const': 'error',
'@typescript-eslint/prefer-for-of': 'error',
'@typescript-eslint/prefer-function-type': 'error',
'@typescript-eslint/prefer-namespace-keyword': 'error',
// ignore the rule to conform to current code
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/restrict-plus-operands': 'error',
// ignore the rule to conform to current code
'@typescript-eslint/restrict-template-expressions': 'off',
'@typescript-eslint/triple-slash-reference': [
'error',
{
path: 'always',
types: 'prefer-import',
lib: 'always',
},
],
'@typescript-eslint/typedef': 'off',
'@typescript-eslint/unbound-method': 'error',
'@typescript-eslint/unified-signatures': 'error',
complexity: 'off',
'constructor-super': 'error',
'dot-notation': 'off',
eqeqeq: ['error', 'smart'],
'guard-for-in': 'error',
'id-denylist': [
'error',
'any',
'Number',
'number',
'String',
'string',
'Boolean',
'boolean',
'Undefined',
'undefined',
],
'id-match': 'error',
'jsdoc/check-alignment': 'error',
// ignore the rule to conform to current code
'jsdoc/check-indentation': 'off',
'max-classes-per-file': 'off',
'new-parens': 'error',
'no-array-constructor': 'off',
'no-bitwise': 'error',
'no-caller': 'error',
'no-cond-assign': 'error',
'no-console': [
'error',
{
allow: [
'log',
'warn',
'dir',
'timeLog',
'assert',
'clear',
'count',
'countReset',
'group',
'groupEnd',
'table',
'dirxml',
'error',
'groupCollapsed',
'Console',
'profile',
'profileEnd',
'timeStamp',
'context',
],
},
],
'no-debugger': 'error',
'no-empty': 'error',
'no-empty-function': 'off',
'no-eval': 'error',
'no-fallthrough': 'error',
'no-implied-eval': 'off',
'no-invalid-this': 'off',
'no-loss-of-precision': 'off',
'no-new-wrappers': 'error',
'no-redeclare': 'error',
'no-return-await': 'error',
'no-shadow': 'off',
'no-throw-literal': 'error',
'no-trailing-spaces': 'error',
'no-undef-init': 'error',
'no-underscore-dangle': 'off',
'no-unsafe-finally': 'error',
'no-unused-expressions': 'off',
'no-unused-labels': 'error',
'no-unused-vars': 'off',
'no-use-before-define': 'off',
'no-var': 'error',
'object-shorthand': 'error',
'one-var': ['error', 'never'],
'prefer-arrow/prefer-arrow-functions': [
'error',
{
allowStandaloneDeclarations: true,
},
],
'prefer-const': [
'error',
{
destructuring: 'all',
},
],
radix: 'error',
'require-await': 'off',
'spaced-comment': [
'error',
'always',
{
markers: ['/'],
},
],
'use-isnan': 'error',
'valid-typeof': 'off',
},
};

View File

@ -3,7 +3,7 @@
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": ["esbenp.prettier-vscode", "ms-vscode.vscode-typescript-tslint-plugin"],
"recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"],
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
"unwantedRecommendations": []
}

View File

@ -1,22 +1,22 @@
import * as vscode from 'vscode';
import { CompositionState } from './src/state/compositionState';
import { Globals } from './src/globals';
import { Jump } from './src/jumps/jump';
import { ModeHandler } from './src/mode/modeHandler';
import { ModeHandlerMap } from './src/mode/modeHandlerMap';
import { Mode } from './src/mode/mode';
import { Notation } from './src/configuration/notation';
import { Logger } from './src/util/logger';
import { StatusBar } from './src/statusBar';
import { VSCodeContext } from './src/util/vscodeContext';
import { ExCommandLine, SearchCommandLine } from './src/cmd_line/commandLine';
import { configuration } from './src/configuration/configuration';
import { globalState } from './src/state/globalState';
import { Notation } from './src/configuration/notation';
import { Globals } from './src/globals';
import { Jump } from './src/jumps/jump';
import { Mode } from './src/mode/mode';
import { ModeHandler } from './src/mode/modeHandler';
import { ModeHandlerMap } from './src/mode/modeHandlerMap';
import { Register } from './src/register/register';
import { SpecialKeys } from './src/util/specialKeys';
import { exCommandParser } from './src/vimscript/exCommandParser';
import { CompositionState } from './src/state/compositionState';
import { globalState } from './src/state/globalState';
import { StatusBar } from './src/statusBar';
import { taskQueue } from './src/taskQueue';
import { Logger } from './src/util/logger';
import { SpecialKeys } from './src/util/specialKeys';
import { VSCodeContext } from './src/util/vscodeContext';
import { exCommandParser } from './src/vimscript/exCommandParser';
let extensionContext: vscode.ExtensionContext;
let previousActiveEditorUri: vscode.Uri | undefined;
@ -355,7 +355,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
const compositionState = new CompositionState();
// Override VSCode commands
overrideCommand(context, 'type', async (args) => {
overrideCommand(context, 'type', async (args: { text: string }) => {
taskQueue.enqueueTask(async () => {
const mh = await getAndUpdateModeHandler();
if (mh) {
@ -363,7 +363,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
compositionState.composingText += args.text;
if (mh.vimState.currentMode === Mode.Insert) {
compositionState.insertedText = true;
vscode.commands.executeCommand('default:type', { text: args.text });
void vscode.commands.executeCommand('default:type', { text: args.text });
}
} else {
await mh.handleKeyEvent(args.text);
@ -372,33 +372,37 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
});
});
overrideCommand(context, 'replacePreviousChar', async (args) => {
taskQueue.enqueueTask(async () => {
const mh = await getAndUpdateModeHandler();
if (mh) {
if (compositionState.isInComposition) {
compositionState.composingText =
compositionState.composingText.substr(
0,
compositionState.composingText.length - args.replaceCharCnt,
) + args.text;
}
if (compositionState.insertedText) {
overrideCommand(
context,
'replacePreviousChar',
async (args: { replaceCharCnt: number; text: string }) => {
taskQueue.enqueueTask(async () => {
const mh = await getAndUpdateModeHandler();
if (mh) {
if (compositionState.isInComposition) {
compositionState.composingText =
compositionState.composingText.substr(
0,
compositionState.composingText.length - args.replaceCharCnt,
) + args.text;
}
if (compositionState.insertedText) {
await vscode.commands.executeCommand('default:replacePreviousChar', {
text: args.text,
replaceCharCnt: args.replaceCharCnt,
});
mh.vimState.cursorStopPosition = mh.vimState.editor.selection.start;
mh.vimState.cursorStartPosition = mh.vimState.editor.selection.start;
}
} else {
await vscode.commands.executeCommand('default:replacePreviousChar', {
text: args.text,
replaceCharCnt: args.replaceCharCnt,
});
mh.vimState.cursorStopPosition = mh.vimState.editor.selection.start;
mh.vimState.cursorStartPosition = mh.vimState.editor.selection.start;
}
} else {
await vscode.commands.executeCommand('default:replacePreviousChar', {
text: args.text,
replaceCharCnt: args.replaceCharCnt,
});
}
});
});
});
},
);
overrideCommand(context, 'compositionStart', async () => {
taskQueue.enqueueTask(async () => {
@ -440,7 +444,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
if (cmd) {
await new ExCommandLine(cmd, mh.vimState.currentMode).run(mh.vimState);
}
mh.updateView();
void mh.updateView();
}
});
@ -471,7 +475,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
command.command.slice(1, command.command.length),
mh.vimState.currentMode,
).run(mh.vimState);
mh.updateView();
void mh.updateView();
} else {
await vscode.commands.executeCommand(command.command, command.args);
}
@ -482,7 +486,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
registerCommand(context, 'toggleVim', async () => {
configuration.disableExtension = !configuration.disableExtension;
toggleExtension(configuration.disableExtension, compositionState);
void toggleExtension(configuration.disableExtension, compositionState);
});
for (const boundKey of configuration.boundKeyCombinations) {
@ -525,7 +529,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
}
// This is called last because getAndUpdateModeHandler() will change cursor
modeHandler.updateView({ drawSelection: true, revealRange: false });
void modeHandler.updateView({ drawSelection: true, revealRange: false });
}
}
@ -579,7 +583,7 @@ function overrideCommand(
return vscode.commands.executeCommand('default:' + command, args);
}
return callback(args);
return callback(args) as vscode.Disposable;
});
context.subscriptions.push(disposable);
}

View File

@ -15,9 +15,8 @@ import './src/configuration/validators/remappingValidator';
import * as vscode from 'vscode';
import { activate as activateFunc } from './extensionBase';
// tslint:disable-next-line: no-var-requires
require('setimmediate');
export async function activate(context: vscode.ExtensionContext) {
activateFunc(context, false);
void activateFunc(context, false);
}

View File

@ -1176,8 +1176,8 @@
"build-dev": "gulp build-dev",
"build-test": "gulp prepare-test",
"test": "node ./out/test/runTest.js",
"lint": "tslint --project .",
"lint:fix": "tslint --project . --fix",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"prettier": "prettier --write .",
"prettier:check": "prettier --check .",
"watch": "webpack -c webpack.dev.js --watch",
@ -1206,9 +1206,15 @@
"@types/parsimmon": "1.10.9",
"@types/sinon": "17.0.2",
"@types/vscode": "1.74.0",
"@typescript-eslint/eslint-plugin": "^6.9.0",
"@typescript-eslint/parser": "^6.9.0",
"@vscode/test-electron": "2.3.8",
"circular-dependency-plugin": "^5.2.2",
"clean-webpack-plugin": "4.0.0",
"eslint": "^8.52.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-jsdoc": "^46.8.2",
"eslint-plugin-prefer-arrow": "^1.2.3",
"event-stream": "4.0.1",
"fork-ts-checker-webpack-plugin": "9.0.2",
"gulp": "4.0.2",
@ -1224,7 +1230,6 @@
"prettier": "3.1.1",
"sinon": "17.0.1",
"ts-loader": "9.5.1",
"tslint": "6.1.3",
"typescript": "5.3.3",
"vsce": "2.15.0",
"webpack": "5.89.0",
@ -1234,6 +1239,6 @@
},
"lint-staged": {
"*.{ts,js,json,md,yml}": "prettier --write",
"*.ts": "tslint --fix"
"*.ts": "eslint --fix"
}
}

View File

@ -139,10 +139,10 @@ export class DocumentContentChangeAction extends BaseCommand {
}
private compressChanges(): void {
function merge(
const merge = (
first: vscode.TextDocumentContentChangeEvent,
second: vscode.TextDocumentContentChangeEvent,
): vscode.TextDocumentContentChangeEvent | undefined {
): vscode.TextDocumentContentChangeEvent | undefined => {
if (first.rangeOffset + first.text.length === second.rangeOffset) {
// Simple concatenation
return {
@ -171,7 +171,7 @@ export class DocumentContentChangeAction extends BaseCommand {
// TODO: YES - make an insertion and then autocomplete to something totally different (replace subsumes insert)
return undefined;
}
}
};
const compressed: vscode.TextDocumentContentChangeEvent[] = [];
let prev: vscode.TextDocumentContentChangeEvent | undefined;
@ -643,7 +643,7 @@ export class CommandShowCommandHistory extends BaseCommand {
}
ExCommandLine.onSearch = async (vimState: VimState) => {
new CommandShowCommandHistory().exec(vimState.cursorStopPosition, vimState);
void new CommandShowCommandHistory().exec(vimState.cursorStopPosition, vimState);
};
@RegisterAction
@ -1040,7 +1040,7 @@ class CommandOpenFile extends BaseCommand {
cmd: isNaN(line) ? undefined : { type: 'line_number', line: line - 1 },
createFileIfNotExists: false,
});
fileCommand.execute(vimState);
void fileCommand.execute(vimState);
}
}
}
@ -1087,7 +1087,7 @@ class CommandOpenLink extends BaseCommand {
keys = ['g', 'x'];
public override async exec(position: Position, vimState: VimState): Promise<void> {
vscode.commands.executeCommand('editor.action.openLink');
void vscode.commands.executeCommand('editor.action.openLink');
}
}
@ -1321,12 +1321,12 @@ class CommandTabNext extends BaseCommand {
// gt behaves differently than gT and goes to an absolute index tab
// (1-based), it does NOT iterate over next tabs
if (vimState.recordedState.count > 0) {
new TabCommand({
void new TabCommand({
type: TabCommandType.Absolute,
count: vimState.recordedState.count,
}).execute(vimState);
} else {
new TabCommand({
void new TabCommand({
type: TabCommandType.Next,
bang: false,
}).execute(vimState);
@ -1341,7 +1341,7 @@ class CommandTabPrevious extends BaseCommand {
override runsOnceForEachCountPrefix = true;
public override async exec(position: Position, vimState: VimState): Promise<void> {
new TabCommand({
void new TabCommand({
type: TabCommandType.Previous,
bang: false,
}).execute(vimState);

View File

@ -1,18 +1,18 @@
import * as vscode from 'vscode';
import { RegisterAction, BaseCommand } from '../base';
import { Mode } from '../../mode/mode';
import { VimState } from '../../state/vimState';
import { CommandLine, ExCommandLine, SearchCommandLine } from '../../cmd_line/commandLine';
import { ErrorCode, VimError } from '../../error';
import { Mode } from '../../mode/mode';
import { Register, RegisterMode } from '../../register/register';
import { RecordedState } from '../../state/recordedState';
import { TextEditor } from '../../textEditor';
import { VimState } from '../../state/vimState';
import { StatusBar } from '../../statusBar';
import { getPathDetails, readDirectory } from '../../util/path';
import { TextEditor } from '../../textEditor';
import { Clipboard } from '../../util/clipboard';
import { VimError, ErrorCode } from '../../error';
import { getPathDetails, readDirectory } from '../../util/path';
import { builtinExCommands } from '../../vimscript/exCommandParser';
import { SearchDirection } from '../../vimscript/pattern';
import { BaseCommand, RegisterAction } from '../base';
abstract class CommandLineAction extends BaseCommand {
modes = [Mode.CommandlineInProgress, Mode.SearchInProgressMode];
@ -413,7 +413,7 @@ class CommandAdvanceCurrentMatch extends CommandLineAction {
? SearchDirection.Backward
: undefined;
if (commandLine instanceof SearchCommandLine && direction !== undefined) {
commandLine.advanceCurrentMatch(vimState, direction);
void commandLine.advanceCurrentMatch(vimState, direction);
}
}
}
@ -423,6 +423,6 @@ class CommandLineType extends CommandLineAction {
keys = [['<character>']];
protected async run(vimState: VimState, commandLine: CommandLine): Promise<void> {
commandLine.typeCharacter(this.keysPressed[0]);
void commandLine.typeCharacter(this.keysPressed[0]);
}
}

View File

@ -1,32 +1,32 @@
import * as vscode from 'vscode';
import { Position } from 'vscode';
import { lineCompletionProvider } from '../../completion/lineCompletionProvider';
import { ErrorCode, VimError } from '../../error';
import { RecordedState } from '../../state/recordedState';
import { VimState } from '../../state/vimState';
import { StatusBar } from '../../statusBar';
import { isHighSurrogate, isLowSurrogate } from '../../util/util';
import { PositionDiff } from './../../common/motion/position';
import { configuration } from './../../configuration/configuration';
import { Mode } from './../../mode/mode';
import { Register, RegisterMode } from './../../register/register';
import { TextEditor } from './../../textEditor';
import { RegisterAction, BaseCommand } from './../base';
import { BaseCommand, RegisterAction } from './../base';
import { ArrowsInInsertMode } from './../motion';
import {
CommandInsertAfterCursor,
CommandInsertAtCursor,
CommandInsertAtFirstCharacter,
CommandInsertAtLineEnd,
DocumentContentChangeAction,
CommandReplaceAtCursorFromNormalMode,
CommandInsertAtLineBegin,
CommandInsertAtLastChange,
CommandInsertAtLineBegin,
CommandInsertAtLineEnd,
CommandInsertNewLineAbove,
CommandInsertNewLineBefore,
CommandReplaceAtCursorFromNormalMode,
DocumentContentChangeAction,
} from './actions';
import { DefaultDigraphs } from './digraphs';
import { StatusBar } from '../../statusBar';
import { VimError, ErrorCode } from '../../error';
import { Position } from 'vscode';
import { isHighSurrogate, isLowSurrogate } from '../../util/util';
@RegisterAction
export class CommandEscInsertMode extends BaseCommand {
@ -38,7 +38,7 @@ export class CommandEscInsertMode extends BaseCommand {
}
public override async exec(position: Position, vimState: VimState): Promise<void> {
vscode.commands.executeCommand('closeParameterHints');
void vscode.commands.executeCommand('closeParameterHints');
vimState.cursors = vimState.cursors.map((x) => x.withNewStop(x.stop.getLeft()));
if (vimState.returnToInsertAfterCommand && position.character !== 0) {

View File

@ -4,8 +4,8 @@ import { Position, Selection } from 'vscode';
import { SearchCommandLine } from '../../cmd_line/commandLine';
import { sorted } from '../../common/motion/position';
import { configuration } from '../../configuration/configuration';
import { VimError, ErrorCode } from '../../error';
import { isVisualMode, Mode } from '../../mode/mode';
import { ErrorCode, VimError } from '../../error';
import { Mode, isVisualMode } from '../../mode/mode';
import { Register } from '../../register/register';
import { globalState } from '../../state/globalState';
import { SearchState } from '../../state/searchState';
@ -15,8 +15,8 @@ import { TextEditor } from '../../textEditor';
import { TextObject } from '../../textobject/textobject';
import { reportSearch } from '../../util/statusBarTextUtils';
import { SearchDirection } from '../../vimscript/pattern';
import { RegisterAction, BaseCommand } from '../base';
import { failedMovement, IMovement } from '../baseMotion';
import { BaseCommand, RegisterAction } from '../base';
import { IMovement, failedMovement } from '../baseMotion';
/**
* Search for the word under the cursor; used by [g]* and [g]#
@ -110,7 +110,7 @@ async function createSearchStateAndMoveToMatch(args: {
{ ignoreSmartcase: true },
);
Register.setReadonlyRegister('/', globalState.searchState.searchString);
SearchCommandLine.addSearchStateToHistory(globalState.searchState);
void SearchCommandLine.addSearchStateToHistory(globalState.searchState);
// Turn one of the highlighting flags back on (turned off with :nohl)
globalState.hl = true;

View File

@ -3,7 +3,7 @@ import { OnlyCommand } from '../../cmd_line/commands/only';
import { QuitCommand } from '../../cmd_line/commands/quit';
import { Mode } from '../../mode/mode';
import { VimState } from '../../state/vimState';
import { RegisterAction, BaseCommand } from '../base';
import { BaseCommand, RegisterAction } from '../base';
@RegisterAction
class CommandQuit extends BaseCommand {
@ -16,7 +16,7 @@ class CommandQuit extends BaseCommand {
];
public override async exec(position: Position, vimState: VimState): Promise<void> {
new QuitCommand({}).execute(vimState);
void new QuitCommand({}).execute(vimState);
}
}
@ -29,7 +29,7 @@ class CommandOnly extends BaseCommand {
];
public override async exec(position: Position, vimState: VimState): Promise<void> {
new OnlyCommand().execute(vimState);
void new OnlyCommand().execute(vimState);
}
}

View File

@ -1,7 +1,7 @@
import { RegisterAction } from '../../base';
import { VimState } from '../../../state/vimState';
import { BaseMovement, failedMovement, IMovement } from '../../baseMotion';
import { Position, TextDocument } from 'vscode';
import { VimState } from '../../../state/vimState';
import { RegisterAction } from '../../base';
import { BaseMovement, failedMovement, IMovement } from '../../baseMotion';
type Type = 'function' | 'class';
type Edge = 'start' | 'end';
@ -22,7 +22,6 @@ interface StructureElement {
// Older browsers don't support lookbehind - in this case, use an inferior regex rather than crashing
let supportsLookbehind = true;
try {
// tslint:disable-next-line
new RegExp('(?<=x)');
} catch {
supportsLookbehind = false;

View File

@ -1,5 +1,10 @@
import * as vscode from 'vscode';
import { Position } from 'vscode';
import { reportLinesChanged, reportLinesYanked } from '../util/statusBarTextUtils';
import { isHighSurrogate, isLowSurrogate } from '../util/util';
import { ExCommandLine } from './../cmd_line/commandLine';
import { Cursor } from './../common/motion/cursor';
import { PositionDiff, earlierOf, sorted } from './../common/motion/position';
import { configuration } from './../configuration/configuration';
import { Mode, isVisualMode } from './../mode/mode';
@ -7,11 +12,6 @@ import { Register, RegisterMode } from './../register/register';
import { VimState } from './../state/vimState';
import { TextEditor } from './../textEditor';
import { BaseAction, RegisterAction } from './base';
import { reportLinesChanged, reportLinesYanked } from '../util/statusBarTextUtils';
import { ExCommandLine } from './../cmd_line/commandLine';
import { Position } from 'vscode';
import { isHighSurrogate, isLowSurrogate } from '../util/util';
import { Cursor } from './../common/motion/cursor';
export abstract class BaseOperator extends BaseAction {
override actionType = 'operator' as const;
@ -962,12 +962,11 @@ class ActionVisualReflowParagraph extends BaseOperator {
const result: string[] = [];
for (const { commentType, content, indentLevelAfterComment } of chunksToReflow) {
let lines: string[];
const indentAfterComment = Array(indentLevelAfterComment + 1).join(' ');
const commentLength = commentType.start.length + indentAfterComment.length;
// Start with a single empty content line.
lines = [``];
const lines: string[] = [``];
for (let line of content.split('\n')) {
// Preserve blank lines in output.

View File

@ -1,10 +1,10 @@
import * as vscode from 'vscode';
import { Position } from 'vscode';
import { Mode } from '../../../mode/mode';
import { configuration } from './../../../configuration/configuration';
import { TextEditor } from './../../../textEditor';
import { IEasyMotion, EasyMotionSearchAction, Marker, Match, SearchOptions } from './types';
import { Mode } from '../../../mode/mode';
import { Position } from 'vscode';
import { EasyMotionSearchAction, IEasyMotion, Marker, Match, SearchOptions } from './types';
export class EasyMotion implements IEasyMotion {
/**
@ -168,15 +168,15 @@ export class EasyMotion implements IEasyMotion {
// Sort by the index distance from the cursor index
matches.sort((a: Match, b: Match): number => {
const absDiffA = computeAboluteDiff(a.index);
const absDiffB = computeAboluteDiff(b.index);
return absDiffA - absDiffB;
function computeAboluteDiff(matchIndex: number) {
const computeAboluteDiff = (matchIndex: number) => {
const absDiff = Math.abs(cursorIndex - matchIndex);
// Prioritize the matches on the right side of the cursor index
return matchIndex < cursorIndex ? absDiff - 0.5 : absDiff;
}
};
const absDiffA = computeAboluteDiff(a.index);
const absDiffB = computeAboluteDiff(b.index);
return absDiffA - absDiffB;
});
return matches;
@ -253,7 +253,7 @@ export class EasyMotion implements IEasyMotion {
this.decorations[keystroke.length] = [];
}
//#region Hack (remove once backend handles this)
// #region Hack (remove once backend handles this)
/*
This hack is here because the backend for easy motion reports two adjacent
@ -283,7 +283,7 @@ export class EasyMotion implements IEasyMotion {
}
}
//#endregion
// #endregion
// First Char/One Char decoration
const firstCharFontColor =

View File

@ -1,31 +1,32 @@
import { Position, Range, window } from 'vscode';
import { VimState } from '../../state/vimState';
import { PositionDiff, sorted } from './../../common/motion/position';
import { configuration } from './../../configuration/configuration';
import { Mode } from './../../mode/mode';
import { RegisterAction, BaseCommand } from './../base';
import {
SelectABigWord,
SelectInnerWord,
SelectWord,
TextObject,
} from '../../textobject/textobject';
import { isIMovement } from '../baseMotion';
import {
MoveAroundBacktick,
MoveAroundCaret,
MoveAroundCurlyBrace,
MoveAroundDoubleQuotes,
MoveAroundParentheses,
MoveAroundTag,
MoveAroundSingleQuotes,
MoveAroundSquareBracket,
MoveAroundTag,
MoveFullWordBegin,
MoveInsideCharacter,
MoveInsideTag,
MoveQuoteMatch,
MoveWordBegin,
} from '../motion';
import { isIMovement } from '../baseMotion';
import { MoveFullWordBegin, MoveWordBegin } from '../motion';
import { PositionDiff, sorted } from './../../common/motion/position';
import { configuration } from './../../configuration/configuration';
import { Mode } from './../../mode/mode';
import { BaseCommand, RegisterAction } from './../base';
import { BaseOperator } from './../operator';
import {
SelectInnerWord,
TextObject,
SelectABigWord,
SelectWord,
} from '../../textobject/textobject';
import { Position, Range, window } from 'vscode';
type SurroundEdge = {
leftEdge: Range;
@ -91,17 +92,7 @@ class YankSurroundOperator extends SurroundOperator {
previousMode: vimState.currentMode,
};
}
// then collect ranges for all cursors
const multicursorIndex = this.multicursorIndex ?? 0;
vimState.surround!.edges.push(getYankRanges());
vimState.cursorStartPosition = start;
// when called from visual operator, use end for stop to keep visual selection
vimState.cursorStopPosition = vimState.currentMode === Mode.Visual ? end : start;
await vimState.setCurrentMode(Mode.SurroundInputMode);
return;
function getYankRanges(): SurroundEdge {
const getYankRanges = (): SurroundEdge => {
// for special handling for w motion.
// with "|surroundme ZONK" it will jump to Z, but we just want surroundme
const endPlus1 = new Range(end.getRight(), end.getRight());
@ -120,7 +111,14 @@ class YankSurroundOperator extends SurroundOperator {
rightEdge,
cursorIndex: multicursorIndex,
};
}
};
// then collect ranges for all cursors
const multicursorIndex = this.multicursorIndex ?? 0;
vimState.surround!.edges.push(getYankRanges());
vimState.cursorStartPosition = start;
// when called from visual operator, use end for stop to keep visual selection
vimState.cursorStopPosition = vimState.currentMode === Mode.Visual ? end : start;
await vimState.setCurrentMode(Mode.SurroundInputMode);
}
public override async runRepeat(
@ -212,6 +210,7 @@ class CommandSurroundDeleteSurround extends CommandSurround {
// for derived class, support ds2X
if (this.keysHasCnt) {
const cntKey = this.keysPressed[this.keysPressed.length - 2];
// eslint-disable-next-line radix
vimState.recordedState.count = parseInt(cntKey, undefined);
}
@ -256,6 +255,7 @@ class CommandSurroundChangeSurround extends CommandSurround {
// for derived class, support ds2X
if (this.keysHasCnt) {
const cntKey = this.keysPressed[this.keysPressed.length - 2];
// eslint-disable-next-line radix
vimState.recordedState.count = parseInt(cntKey, undefined);
}
@ -361,18 +361,18 @@ export class CommandSurroundAddSurroundingTag extends BaseCommand {
// record tag for repeat. this works because recordedState will store the actual objects
this.recordedTag = tagInput;
// local helper
const checkReplaceAttributes = (tag: string) => {
return tag.substring(tag.length - 1) === '>'
? { tag: tag.substring(0, tag.length - 1), keepAttributes: false }
: { tag, keepAttributes: true };
};
// check as special case (set by >) if we want to replace the attributes on tag or keep them (default)
vimState.surround.tag = checkReplaceAttributes(tagInput);
// finally, we can exec surround
await SurroundHelper.ExecuteSurround(vimState);
// local helper
function checkReplaceAttributes(tag: string) {
return tag.substring(tag.length - 1) === '>'
? { tag: tag.substring(0, tag.length - 1), keepAttributes: false }
: { tag, keepAttributes: true };
}
}
private async readTag(): Promise<string | undefined> {
@ -550,11 +550,8 @@ class SurroundHelper {
let rangeStart = targetMovement.start;
let rangeEnd = targetMovement.stop;
// good to go, now we can calculate our ranges based on rangeStart and rangeEnd
return vimState.surround.target === 't' ? getAdjustedRangesForTag() : getAdjustedRanges();
// some local helpers
function getAdjustedRanges(): SurroundEdge {
const getAdjustedRanges = (): SurroundEdge => {
if (movement() instanceof MoveInsideCharacter) {
// for parens, brackets, curly ... we have to adjust the right range
// there seems to be inconsistency between MoveInsideCharacter and MoveQuoteMatch
@ -573,17 +570,16 @@ class SurroundHelper {
rightEdge: new Range(rangeEnd.getLeft(delSpace), rangeEnd.getRight()),
cursorIndex: multicursorIndex,
};
}
function checkRemoveSpace(): number {
};
const checkRemoveSpace = (): number => {
// capiche?
const leftSpace = vimState.editor.document.getText(
new Range(rangeStart.getRight(), rangeStart.getRight(2)),
);
const rightSpace = vimState.editor.document.getText(new Range(rangeEnd.getLeft(), rangeEnd));
return removeSpace && leftSpace === ' ' && rightSpace === ' ' ? 1 : 0;
}
async function getAdjustedRangesForTag(): Promise<SurroundEdge | undefined> {
};
const getAdjustedRangesForTag = async (): Promise<SurroundEdge | undefined> => {
// we are on start of opening tag and end of closing tag
// return ranges from there to the other side
// start -> <foo>bar</foo> <-- stop
@ -613,7 +609,10 @@ class SurroundHelper {
cursorIndex: multicursorIndex,
};
}
}
};
// good to go, now we can calculate our ranges based on rangeStart and rangeEnd
return vimState.surround.target === 't' ? getAdjustedRangesForTag() : getAdjustedRanges();
}
/** executes our prepared surround changes */

View File

@ -1,23 +1,23 @@
import { CommandLineHistory, HistoryFile, SearchHistory } from '../history/historyFile';
import { Mode } from './../mode/mode';
import { Logger } from '../util/logger';
import { StatusBar } from '../statusBar';
import { VimError, ErrorCode } from '../error';
import { VimState } from '../state/vimState';
import { configuration } from '../configuration/configuration';
import { Register } from '../register/register';
import { RecordedState } from '../state/recordedState';
import { Parser } from 'parsimmon';
import { IndexedPosition, IndexedRange, SearchState } from '../state/searchState';
import { getWordLeftInText, getWordRightInText, WordType } from '../textobject/word';
import { SearchDirection } from '../vimscript/pattern';
import { reportSearch, escapeCSSIcons } from '../util/statusBarTextUtils';
import { SearchDecorations, getDecorationsForSearchMatchRanges } from '../util/decorationUtils';
import { Position, ExtensionContext, window } from 'vscode';
import { ExtensionContext, Position, window } from 'vscode';
import { configuration } from '../configuration/configuration';
import { ErrorCode, VimError } from '../error';
import { CommandLineHistory, HistoryFile, SearchHistory } from '../history/historyFile';
import { Register } from '../register/register';
import { globalState } from '../state/globalState';
import { RecordedState } from '../state/recordedState';
import { IndexedPosition, IndexedRange, SearchState } from '../state/searchState';
import { VimState } from '../state/vimState';
import { StatusBar } from '../statusBar';
import { WordType, getWordLeftInText, getWordRightInText } from '../textobject/word';
import { SearchDecorations, getDecorationsForSearchMatchRanges } from '../util/decorationUtils';
import { Logger } from '../util/logger';
import { escapeCSSIcons, reportSearch } from '../util/statusBarTextUtils';
import { scrollView } from '../util/util';
import { ExCommand } from '../vimscript/exCommand';
import { LineRange } from '../vimscript/lineRange';
import { SearchDirection } from '../vimscript/pattern';
import { Mode } from './../mode/mode';
import { RegisterCommand } from './commands/register';
import { SubstituteCommand } from './commands/substitute';
@ -256,7 +256,7 @@ export class ExCommandLine extends CommandLine {
public async run(vimState: VimState): Promise<void> {
Logger.info(`Executing :${this.text}`);
ExCommandLine.history.add(this.text);
void ExCommandLine.history.add(this.text);
this.historyIndex = ExCommandLine.history.get().length;
if (!(this.command instanceof RegisterCommand)) {
@ -309,12 +309,12 @@ export class ExCommandLine extends CommandLine {
public async escape(vimState: VimState): Promise<void> {
await vimState.setCurrentMode(Mode.Normal);
if (this.text.length > 0) {
ExCommandLine.history.add(this.text);
void ExCommandLine.history.add(this.text);
}
}
public async ctrlF(vimState: VimState): Promise<void> {
ExCommandLine.onSearch(vimState);
void ExCommandLine.onSearch(vimState);
}
}
@ -477,7 +477,7 @@ export class SearchCommandLine extends CommandLine {
this.cursorIndex = 0;
Register.setReadonlyRegister('/', this.text);
SearchCommandLine.addSearchStateToHistory(this.searchState);
void SearchCommandLine.addSearchStateToHistory(this.searchState);
globalState.hl = true;
if (this.searchState.getMatchRanges(vimState).length === 0) {
@ -522,7 +522,7 @@ export class SearchCommandLine extends CommandLine {
await vimState.setCurrentMode(this.previousMode);
if (this.text.length > 0) {
SearchCommandLine.addSearchStateToHistory(this.searchState);
void SearchCommandLine.addSearchStateToHistory(this.searchState);
}
}

View File

@ -1,7 +1,3 @@
import * as vscode from 'vscode';
import * as path from 'path';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';
import {
all,
alt,
@ -9,10 +5,15 @@ import {
optWhitespace,
regexp,
seqObj,
// eslint-disable-next-line id-denylist
string,
succeed,
whitespace,
} from 'parsimmon';
import * as path from 'path';
import * as vscode from 'vscode';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';
import { fileNameParser, numberParser } from '../../vimscript/parserUtils';
function isSourceBreakpoint(b: vscode.Breakpoint): b is vscode.SourceBreakpoint {
@ -212,7 +213,7 @@ export class Breakpoints {
// without arg
eof.result<DelBreakpointHere>({ type: 'here' }),
)
.map((a) => new AddBreakpointCommand(a)),
.map((a: AddBreakpoint) => new AddBreakpointCommand(a)),
del: whitespace
.then(
@ -241,7 +242,7 @@ export class Breakpoints {
// without arg
eof.result<DelBreakpointHere>({ type: 'here' }),
)
.map((a) => new DeleteBreakpointCommand(a)),
.map((a: DelBreakpoint) => new DeleteBreakpointCommand(a)),
list: succeed(new ListBreakpointsCommand()),
};

View File

@ -1,11 +1,12 @@
import * as vscode from 'vscode';
import { VimState } from '../../state/vimState';
import { Register, RegisterMode } from '../../register/register';
// eslint-disable-next-line id-denylist
import { Parser, alt, any, optWhitespace, seq, whitespace } from 'parsimmon';
import { Position } from 'vscode';
import { Register, RegisterMode } from '../../register/register';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';
import { LineRange } from '../../vimscript/lineRange';
import { Parser, alt, seq, any, whitespace, optWhitespace } from 'parsimmon';
import { numberParser } from '../../vimscript/parserUtils';
export interface IDeleteCommandArguments {
@ -20,6 +21,7 @@ export class DeleteCommand extends ExCommand {
numberParser.map((count) => {
return { register: undefined, count };
}),
// eslint-disable-next-line id-denylist
seq(any.fallback(undefined), whitespace.then(numberParser).fallback(undefined)).map(
([register, count]) => {
return { register, count };

View File

@ -1,13 +1,14 @@
import * as vscode from 'vscode';
import { configuration } from './../../configuration/configuration';
import { VimState } from '../../state/vimState';
// eslint-disable-next-line id-denylist
import { any, Parser, seq, whitespace } from 'parsimmon';
import { DefaultDigraphs } from '../../actions/commands/digraphs';
import { Digraph } from '../../configuration/iconfiguration';
import { VimState } from '../../state/vimState';
import { TextEditor } from '../../textEditor';
import { ExCommand } from '../../vimscript/exCommand';
import { any, Parser, seq, whitespace } from 'parsimmon';
import { bangParser, numberParser } from '../../vimscript/parserUtils';
import { Digraph } from '../../configuration/iconfiguration';
import { configuration } from './../../configuration/configuration';
export interface IDigraphsCommandArguments {
bang: boolean;
@ -50,7 +51,7 @@ export class DigraphsCommand extends ExCommand {
this.makeQuickPicks([...DefaultDigraphs.entries()]),
);
vscode.window.showQuickPick(digraphKeyAndContent).then(async (val) => {
void vscode.window.showQuickPick(digraphKeyAndContent).then(async (val) => {
if (val) {
const char = String.fromCharCode(...val.charCodes);
await TextEditor.insert(vimState.editor, char);

View File

@ -1,12 +1,13 @@
import { VimState } from '../../state/vimState';
// eslint-disable-next-line id-denylist
import { Parser, alt, optWhitespace, string } from 'parsimmon';
import {
CommandShowSearchHistory,
CommandShowCommandHistory,
CommandShowSearchHistory,
} from '../../actions/commands/actions';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';
import { SearchDirection } from '../../vimscript/pattern';
import { alt, optWhitespace, Parser, string } from 'parsimmon';
import { nameAbbrevParser } from '../../vimscript/parserUtils';
import { SearchDirection } from '../../vimscript/pattern';
export enum HistoryCommandType {
Cmd,

View File

@ -1,9 +1,9 @@
import { window, QuickPickItem } from 'vscode';
import { QuickPickItem, window } from 'vscode';
import { VimState } from '../../state/vimState';
import { globalState } from '../../state/globalState';
import { Jump } from '../../jumps/jump';
import { Cursor } from '../../common/motion/cursor';
import { Jump } from '../../jumps/jump';
import { globalState } from '../../state/globalState';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';
class JumpPickItem implements QuickPickItem {
@ -36,11 +36,11 @@ export class JumpsCommand extends ExCommand {
canPickMany: false,
});
if (item && item.jump.document !== undefined) {
window.showTextDocument(item.jump.document);
void window.showTextDocument(item.jump.document);
vimState.cursors = [new Cursor(item.jump.position, item.jump.position)];
}
} else {
window.showInformationMessage('No jumps available');
void window.showInformationMessage('No jumps available');
}
}
}

View File

@ -22,7 +22,7 @@ export class LeftCommand extends ExCommand {
}
async execute(vimState: VimState): Promise<void> {
this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
void this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
}
override async executeWithRange(vimState: VimState, range: LineRange): Promise<void> {
@ -61,7 +61,7 @@ export class RightCommand extends ExCommand {
}
async execute(vimState: VimState): Promise<void> {
this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
void this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
}
override async executeWithRange(vimState: VimState, range: LineRange): Promise<void> {
@ -105,7 +105,7 @@ export class CenterCommand extends ExCommand {
}
async execute(vimState: VimState): Promise<void> {
this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
void this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
}
override async executeWithRange(vimState: VimState, range: LineRange): Promise<void> {

View File

@ -1,11 +1,12 @@
import { window, QuickPickItem } from 'vscode';
import { QuickPickItem, window } from 'vscode';
import { VimState } from '../../state/vimState';
import { IMark } from '../../history/historyTracker';
// eslint-disable-next-line id-denylist
import { Parser, alt, noneOf, optWhitespace, regexp, seq, string, whitespace } from 'parsimmon';
import { Cursor } from '../../common/motion/cursor';
import { ErrorCode, VimError } from '../../error';
import { IMark } from '../../history/historyTracker';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';
import { alt, noneOf, optWhitespace, Parser, regexp, seq, string, whitespace } from 'parsimmon';
class MarkQuickPickItem implements QuickPickItem {
mark: IMark;
@ -56,7 +57,7 @@ export class MarksCommand extends ExCommand {
vimState.cursors = [new Cursor(item.mark.position, item.mark.position)];
}
} else {
window.showInformationMessage('No marks set');
void window.showInformationMessage('No marks set');
}
}
}

View File

@ -32,7 +32,7 @@ export class MoveCommand extends ExCommand {
if (sourceEnd < sourceStart) {
[sourceStart, sourceEnd] = [sourceEnd, sourceStart];
}
/*make sure
/* make sure
1. not move a range to the place inside itself.
2. not move a range to the place right below or above itself, which leads to no change.
*/

View File

@ -26,7 +26,7 @@ export class PrintCommand extends ExCommand {
async execute(vimState: VimState): Promise<void> {
// TODO: Wrong default for `:=`
this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
void this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
}
override async executeWithRange(vimState: VimState, range: LineRange): Promise<void> {

View File

@ -1,14 +1,15 @@
import { VimState } from '../../state/vimState';
import { configuration } from '../../configuration/configuration';
import { VimState } from '../../state/vimState';
import { Register } from '../../register/register';
import { StatusBar } from '../../statusBar';
import { VimError, ErrorCode } from '../../error';
// eslint-disable-next-line id-denylist
import { Parser, alt, any, optWhitespace, seq } from 'parsimmon';
import { Position } from 'vscode';
import { PutBeforeFromCmdLine, PutFromCmdLine } from '../../actions/commands/put';
import { ErrorCode, VimError } from '../../error';
import { Register } from '../../register/register';
import { StatusBar } from '../../statusBar';
import { ExCommand } from '../../vimscript/exCommand';
import { LineRange } from '../../vimscript/lineRange';
import { alt, any, optWhitespace, Parser, seq } from 'parsimmon';
import { bangParser } from '../../vimscript/parserUtils';
import { expressionParser } from '../expression';

View File

@ -1,13 +1,14 @@
import { readFileAsync } from 'platform/fs';
// eslint-disable-next-line id-denylist
import { all, alt, optWhitespace, Parser, seq, string, whitespace } from 'parsimmon';
import { SUPPORT_READ_COMMAND } from 'platform/constants';
import { readFileAsync } from 'platform/fs';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';
import { fileNameParser, FileOpt, fileOptParser } from '../../vimscript/parserUtils';
import { all, alt, optWhitespace, Parser, seq, string, whitespace } from 'parsimmon';
export type IReadCommandArguments = {
opt: FileOpt;
} & ({ cmd: string } | { file: string } | {});
} & ({ cmd: string } | { file: string } | object);
//
// Implements :read and :read!

View File

@ -1,17 +1,19 @@
import * as vscode from 'vscode';
import { VimState } from '../../state/vimState';
// eslint-disable-next-line id-denylist
import { Parser, any, optWhitespace } from 'parsimmon';
import { ErrorCode, VimError } from '../../error';
import { Register } from '../../register/register';
import { RecordedState } from '../../state/recordedState';
import { VimState } from '../../state/vimState';
import { StatusBar } from '../../statusBar';
import { VimError, ErrorCode } from '../../error';
import { ExCommand } from '../../vimscript/exCommand';
import { any, optWhitespace, Parser } from 'parsimmon';
export class RegisterCommand extends ExCommand {
public override isRepeatableWithDot: boolean = false;
public static readonly argParser: Parser<RegisterCommand> = optWhitespace.then(
// eslint-disable-next-line id-denylist
any.sepBy(optWhitespace).map((registers) => new RegisterCommand(registers)),
);
@ -38,7 +40,7 @@ export class RegisterCommand extends ExCommand {
StatusBar.displayError(vimState, VimError.fromCode(ErrorCode.NothingInRegister, register));
} else {
result = result.replace(/\n/g, '\\n');
vscode.window.showInformationMessage(`${register} ${result}`);
void vscode.window.showInformationMessage(`${register} ${result}`);
}
}
@ -78,10 +80,10 @@ export class RegisterCommand extends ExCommand {
}
}
vscode.window.showQuickPick(registerKeyAndContent).then(async (val) => {
void vscode.window.showQuickPick(registerKeyAndContent).then(async (val) => {
if (val) {
const result = val.description;
vscode.window.showInformationMessage(`${val.label} ${result}`);
void vscode.window.showInformationMessage(`${val.label} ${result}`);
}
});
}

View File

@ -168,7 +168,7 @@ export class RetabCommand extends ExCommand {
value: this.arguments.newTabstop.toString(),
});
setTabstop.execute(vimState);
void setTabstop.execute(vimState);
}
}
}

View File

@ -1,6 +1,7 @@
// eslint-disable-next-line id-denylist
import { alt, oneOf, Parser, regexp, seq, string, whitespace } from 'parsimmon';
import { configuration, optionAliases } from '../../configuration/configuration';
import { VimError, ErrorCode } from '../../error';
import { ErrorCode, VimError } from '../../error';
import { VimState } from '../../state/vimState';
import { StatusBar } from '../../statusBar';
import { ExCommand } from '../../vimscript/exCommand';
@ -160,7 +161,7 @@ export class SetCommand extends ExCommand {
}
const option = optionAliases.get(this.operation.option) ?? this.operation.option;
const currentValue = configuration[option];
const currentValue = configuration[option] as string | number | boolean | undefined;
if (currentValue === undefined) {
throw VimError.fromCode(ErrorCode.UnknownOption, option);
}
@ -245,7 +246,7 @@ export class SetCommand extends ExCommand {
`${option}+=${this.operation.value}`,
);
}
configuration[option] = currentValue + value;
configuration[option] = (currentValue as number) + value;
}
break;
}
@ -262,7 +263,7 @@ export class SetCommand extends ExCommand {
`${option}^=${this.operation.value}`,
);
}
configuration[option] = currentValue * value;
configuration[option] = (currentValue as number) * value;
}
break;
}
@ -270,7 +271,7 @@ export class SetCommand extends ExCommand {
if (type === 'boolean') {
throw VimError.fromCode(ErrorCode.InvalidArgument, `${option}-=${this.operation.value}`);
} else if (type === 'string') {
configuration[option] = currentValue.split(this.operation.value).join('');
configuration[option] = (currentValue as string).split(this.operation.value).join('');
} else {
const value = Number.parseInt(this.operation.value, 10);
if (isNaN(value)) {
@ -279,7 +280,7 @@ export class SetCommand extends ExCommand {
`${option}-=${this.operation.value}`,
);
}
configuration[option] = currentValue - value;
configuration[option] = (currentValue as number) - value;
}
break;
}

View File

@ -1,11 +1,12 @@
import { Position, Selection } from 'vscode';
// eslint-disable-next-line id-denylist
import { optWhitespace, Parser, seq, string } from 'parsimmon';
import { PositionDiff } from '../../common/motion/position';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';
import { Address, LineRange } from '../../vimscript/lineRange';
import { numberParser } from '../../vimscript/parserUtils';
import { PositionDiff } from '../../common/motion/position';
export type ShiftDirection = '>' | '<';
export type ShiftArgs = {
@ -37,7 +38,7 @@ export class ShiftCommand extends ExCommand {
}
public async execute(vimState: VimState): Promise<void> {
this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
void this.executeWithRange(vimState, new LineRange(new Address({ type: 'current_line' })));
}
public override async executeWithRange(vimState: VimState, range: LineRange): Promise<void> {

View File

@ -1,21 +1,22 @@
// eslint-disable-next-line id-denylist
import { Parser, alt, any, noneOf, oneOf, optWhitespace, regexp, seq, string } from 'parsimmon';
import { CancellationTokenSource, DecorationOptions, Position, Range, window } from 'vscode';
import { Jump } from '../../jumps/jump';
import { SearchState } from '../../state/searchState';
import { SubstituteState } from '../../state/substituteState';
import { VimError, ErrorCode } from '../../error';
import { VimState } from '../../state/vimState';
import { PositionDiff } from '../../common/motion/position';
import { configuration } from '../../configuration/configuration';
import { decoration } from '../../configuration/decoration';
import { ErrorCode, VimError } from '../../error';
import { Jump } from '../../jumps/jump';
import { globalState } from '../../state/globalState';
import { SearchState } from '../../state/searchState';
import { SubstituteState } from '../../state/substituteState';
import { VimState } from '../../state/vimState';
import { StatusBar } from '../../statusBar';
import { Address, LineRange } from '../../vimscript/lineRange';
import { ExCommand } from '../../vimscript/exCommand';
import { Pattern, PatternMatch, SearchDirection } from '../../vimscript/pattern';
import { alt, any, noneOf, oneOf, optWhitespace, Parser, regexp, seq, string } from 'parsimmon';
import { numberParser } from '../../vimscript/parserUtils';
import { PositionDiff } from '../../common/motion/position';
import { escapeCSSIcons } from '../../util/statusBarTextUtils';
import { SearchDecorations, ensureVisible, formatDecorationText } from '../../util/decorationUtils';
import { escapeCSSIcons } from '../../util/statusBarTextUtils';
import { ExCommand } from '../../vimscript/exCommand';
import { Address, LineRange } from '../../vimscript/lineRange';
import { numberParser } from '../../vimscript/parserUtils';
import { Pattern, PatternMatch, SearchDirection } from '../../vimscript/pattern';
type ReplaceStringComponent =
| { type: 'string'; value: string }
@ -151,6 +152,7 @@ export interface SubstituteFlags {
const replaceStringParser = (delimiter: string): Parser<ReplaceString> =>
alt<ReplaceStringComponent>(
string('\\').then(
// eslint-disable-next-line id-denylist
any.fallback(undefined).map<ReplaceStringComponent>((escaped) => {
if (escaped === undefined || escaped === '\\') {
return { type: 'string', value: '\\' };

View File

@ -1,13 +1,14 @@
// eslint-disable-next-line id-denylist
import { alt, optWhitespace, regexp, seq, string, whitespace } from 'parsimmon';
import * as path from 'path';
import * as vscode from 'vscode';
import { VimState } from '../../state/vimState';
import { ExCommand } from '../../vimscript/exCommand';
import {
bangParser,
FileCmd,
fileCmdParser,
FileOpt,
bangParser,
fileCmdParser,
fileOptParser,
numberParser,
} from '../../vimscript/parserUtils';

View File

@ -1,11 +1,12 @@
import * as fs from 'platform/fs';
// eslint-disable-next-line id-denylist
import { all, alt, optWhitespace, Parser, seq, string } from 'parsimmon';
import * as path from 'path';
import * as fs from 'platform/fs';
import * as vscode from 'vscode';
import { Logger } from '../../util/logger';
import { StatusBar } from '../../statusBar';
import { VimState } from '../../state/vimState';
import { StatusBar } from '../../statusBar';
import { Logger } from '../../util/logger';
import { ExCommand } from '../../vimscript/exCommand';
import { all, alt, optWhitespace, Parser, regexp, seq, string } from 'parsimmon';
import { bangParser, fileNameParser, FileOpt, fileOptParser } from '../../vimscript/parserUtils';
export type IWriteCommandArguments = {
@ -13,7 +14,7 @@ export type IWriteCommandArguments = {
opt: FileOpt;
bgWrite: boolean;
file?: string;
} & ({ cmd: string } | {});
} & ({ cmd: string } | object);
//
// Implements :write
@ -72,9 +73,11 @@ export class WriteCommand extends ExCommand {
await this.save(vimState);
await fs.chmodAsync(vimState.document.fileName, mode);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
StatusBar.setText(vimState, e.message);
}
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
StatusBar.setText(vimState, accessErr.message);
}
}
@ -126,6 +129,7 @@ export class WriteCommand extends ExCommand {
}C written`,
);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
StatusBar.setText(vimState, e.message);
}
}

View File

@ -1,4 +1,5 @@
import { alt, any, optWhitespace, Parser, seq, succeed, whitespace } from 'parsimmon';
// eslint-disable-next-line id-denylist
import { alt, any, optWhitespace, Parser, seq, whitespace } from 'parsimmon';
import { Position } from 'vscode';
import { YankOperator } from '../../actions/operator';
import { RegisterMode } from '../../register/register';
@ -18,6 +19,7 @@ export class YankCommand extends ExCommand {
numberParser.map((count) => {
return { register: undefined, count };
}),
// eslint-disable-next-line id-denylist
seq(any.fallback(undefined), whitespace.then(numberParser).fallback(undefined)).map(
([register, count]) => {
return { register, count };

View File

@ -1,4 +1,5 @@
import { Parser, optWhitespace, seqObj, string, alt } from 'parsimmon';
// eslint-disable-next-line id-denylist
import { Parser, alt, optWhitespace, seqObj, string } from 'parsimmon';
import { ErrorCode, VimError } from '../error';
import { integerParser } from '../vimscript/parserUtils';

View File

@ -1,25 +1,25 @@
import * as process from 'process';
import * as vscode from 'vscode';
import { Globals } from '../globals';
import { Notation } from './notation';
import { ValidatorResults } from './iconfigurationValidator';
import { VSCodeContext } from '../util/vscodeContext';
import { configurationValidator } from './configurationValidator';
import { decoration } from './decoration';
import * as process from 'process';
import { ValidatorResults } from './iconfigurationValidator';
import { Notation } from './notation';
import {
Digraph,
IAutoSwitchInputMethod,
ICamelCaseMotionConfiguration,
IConfiguration,
IHighlightedYankConfiguration,
IKeyRemapping,
IModeSpecificStrings,
IAutoSwitchInputMethod,
IHighlightedYankConfiguration,
ICamelCaseMotionConfiguration,
ITargetsConfiguration,
Digraph,
} from './iconfiguration';
import * as packagejson from '../../package.json';
import { SUPPORT_VIMRC } from 'platform/constants';
import * as packagejson from '../../package.json';
// https://stackoverflow.com/questions/51465182/how-to-remove-index-signature-using-mapped-types/51956054#51956054
type RemoveIndex<T> = {
@ -115,13 +115,17 @@ class Configuration implements IConfiguration {
? Globals.mockConfiguration
: this.getConfiguration('vim');
// tslint:disable-next-line: forin
// eslint-disable-next-line guard-for-in
for (const option in this) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
let val = vimConfigs[option];
if (val !== null && val !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (val.constructor.name === Object.name) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
val = Configuration.unproxify(val);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this[option] = val;
}
}
@ -184,11 +188,11 @@ class Configuration implements IConfiguration {
}
}
VSCodeContext.set(`vim.use${boundKey.key}`, useKey);
void VSCodeContext.set(`vim.use${boundKey.key}`, useKey);
}
VSCodeContext.set('vim.overrideCopy', this.overrideCopy);
VSCodeContext.set('vim.overrideCtrlC', this.overrideCopy || this.useCtrlKeys);
void VSCodeContext.set('vim.overrideCopy', this.overrideCopy);
void VSCodeContext.set('vim.overrideCtrlC', this.overrideCopy || this.useCtrlKeys);
return validatorResults;
}
@ -356,6 +360,7 @@ class Configuration implements IConfiguration {
['interval', false],
]),
})
// eslint-disable-next-line id-denylist
number!: boolean;
@overlapSetting({
@ -447,8 +452,10 @@ class Configuration implements IConfiguration {
};
getCursorStyleForMode(modeName: string): vscode.TextEditorCursorStyle | undefined {
// @ts-ignore: TODO: this function should take the mode directly
const cursorStyle = this.cursorStylePerMode[modeName.toLowerCase()];
// TODO: this function should take the mode directly
const cursorStyle = (this.cursorStylePerMode as unknown as Record<string, string | undefined>)[
modeName.toLowerCase()
];
if (cursorStyle) {
return this.cursorStyleFromString(cursorStyle);
}
@ -486,10 +493,12 @@ class Configuration implements IConfiguration {
private static unproxify(obj: { [key: string]: any }): object {
const result: { [key: string]: any } = {};
// tslint:disable-next-line: forin
// eslint-disable-next-line guard-for-in
for (const key in obj) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const val = obj[key];
if (val !== null && val !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
result[key] = val;
}
}
@ -510,21 +519,26 @@ function overlapSetting(args: {
// if the value is not defined or empty
// look at the equivalent `editor` setting
// if that is not defined then defer to the default value
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
let val = this['_' + propertyKey];
if (val !== undefined && val !== '') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return val;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
val = this.getConfiguration('editor').get(args.settingName, args.defaultValue);
if (args.map && val !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
val = args.map.get(val);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return val;
},
set(value) {
// synchronize the vim setting with the `editor` equivalent
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
this['_' + propertyKey] = value;
if (value === undefined || value === '' || Globals.isTesting) {
@ -541,6 +555,7 @@ function overlapSetting(args: {
}
// update configuration asynchronously
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
this.getConfiguration('editor').update(
args.settingName,
value,

View File

@ -294,6 +294,7 @@ export interface IConfiguration {
/**
* Show line numbers
*/
// eslint-disable-next-line id-denylist
number: boolean;
/**

View File

@ -16,7 +16,7 @@ export class ValidatorResults {
this.errors = this.errors.concat(validationResults.get());
}
public get(): ReadonlyArray<IValidatorResult> {
public get(): readonly IValidatorResult[] {
return this.errors;
}

View File

@ -1,13 +1,13 @@
import * as vscode from 'vscode';
import { IKeyRemapping } from './iconfiguration';
import { Logger } from '../util/logger';
import { ModeHandler } from '../mode/modeHandler';
import { Mode } from '../mode/mode';
import { configuration } from '../configuration/configuration';
import { ErrorCode, ForceStopRemappingError, VimError } from '../error';
import { Mode } from '../mode/mode';
import { ModeHandler } from '../mode/modeHandler';
import { StatusBar } from '../statusBar';
import { VimError, ErrorCode, ForceStopRemappingError } from '../error';
import { Logger } from '../util/logger';
import { SpecialKeys } from '../util/specialKeys';
import { exCommandParser } from '../vimscript/exCommandParser';
import { IKeyRemapping } from './iconfiguration';
interface IRemapper {
/**
@ -280,7 +280,7 @@ export class Remapper implements IRemapper {
// Create Timeout
vimState.recordedState.bufferedKeysTimeoutObj = setTimeout(() => {
modeHandler.handleKeyEvent(SpecialKeys.TimeoutFinished);
void modeHandler.handleKeyEvent(SpecialKeys.TimeoutFinished);
}, configuration.timeout);
return true;
}
@ -440,6 +440,7 @@ export class Remapper implements IRemapper {
await modeHandler.handleMultipleKeyEvents(remainingKeys);
} catch (e) {
Logger.trace(
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
`${this.configKey}. Stopped the remapping in the middle, ignoring the rest. Reason: ${e.message}`,
);
} finally {
@ -496,7 +497,7 @@ export class Remapper implements IRemapper {
} else {
commandString = command.command;
commandArgs = Array.isArray(command.args)
? command.args
? (command.args as string[])
: command.args
? [command.args]
: [];

View File

@ -1,10 +1,10 @@
import { execFileSync } from 'child_process';
import { existsSync } from 'fs';
import * as path from 'path';
import * as process from 'process';
import { configurationValidator } from '../configurationValidator';
import { IConfiguration } from '../iconfiguration';
import { IConfigurationValidator, ValidatorResults } from '../iconfigurationValidator';
import { execFileSync } from 'child_process';
import * as path from 'path';
import { existsSync } from 'fs';
import { configurationValidator } from '../configurationValidator';
import * as process from 'process';
export class NeovimValidator implements IConfigurationValidator {
validate(config: IConfiguration): Promise<ValidatorResults> {
@ -33,6 +33,7 @@ export class NeovimValidator implements IConfigurationValidator {
}
execFileSync(config.neovimPath, ['--version']);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
let errorMessage = `Invalid neovimPath. ${e.message}.`;
if (triedToParsePath) {
errorMessage += `Tried to parse PATH ${config.neovimPath}.`;

View File

@ -1,9 +1,9 @@
import * as vscode from 'vscode';
import { IConfiguration, IKeyRemapping } from '../iconfiguration';
import { Notation } from '../notation';
import { IConfigurationValidator, ValidatorResults } from '../iconfigurationValidator';
import { configurationValidator } from '../configurationValidator';
import { PluginDefaultMappings } from '../../actions/plugins/pluginDefaultMappings';
import { configurationValidator } from '../configurationValidator';
import { IConfiguration, IKeyRemapping } from '../iconfiguration';
import { IConfigurationValidator, ValidatorResults } from '../iconfigurationValidator';
import { Notation } from '../notation';
export class RemappingValidator implements IConfigurationValidator {
private commandMap!: Map<string, boolean>;
@ -23,6 +23,7 @@ export class RemappingValidator implements IConfigurationValidator {
'commandLineModeKeyBindingsNonRecursive',
];
for (const modeKeyBindingsKey of modeKeyBindingsKeys) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const keybindings = config[modeKeyBindingsKey];
// add default mappings for activated plugins
// because we process keybindings backwards in next loop, user mapping will override
@ -31,6 +32,7 @@ export class RemappingValidator implements IConfigurationValidator {
config,
)) {
// note concat(all mappings) does not work somehow
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
keybindings.push(pluginMapping);
}
@ -41,7 +43,9 @@ export class RemappingValidator implements IConfigurationValidator {
if (!modeKeyBindingsMap) {
modeKeyBindingsMap = new Map<string, IKeyRemapping>();
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
for (let i = keybindings.length - 1; i >= 0; i--) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const remapping = keybindings[i] as IKeyRemapping;
// set 'recursive' of the remapping according to where it was stored
@ -52,6 +56,7 @@ export class RemappingValidator implements IConfigurationValidator {
result.concat(remappingError);
if (remappingError.hasError) {
// errors with remapping, skip
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
keybindings.splice(i, 1);
continue;
}

View File

@ -68,7 +68,7 @@ export class VimrcImpl {
}
}
} catch (err) {
window.showWarningMessage(`vimrc file "${configPath}" is broken, err=${err}`);
void window.showWarningMessage(`vimrc file "${configPath}" is broken, err=${err}`);
}
}
@ -81,7 +81,7 @@ export class VimrcImpl {
return;
}
if (!(await fs.existsAsync(_path))) {
window
void window
.showWarningMessage(`No .vimrc found at ${_path}.`, 'Create it')
.then(async (choice: string | undefined) => {
if (choice === 'Create it') {
@ -94,7 +94,7 @@ export class VimrcImpl {
const resource = document
? { uri: document.uri, languageId: document.languageId }
: undefined;
vscode.workspace
void vscode.workspace
.getConfiguration('vim', resource)
.update('vimrc.path', newVimrc.fsPath, true);
await vscode.workspace.openTextDocument(newVimrc);

View File

@ -1,7 +1,35 @@
import * as vscode from 'vscode';
import { BaseAction, KeypressState, BaseCommand, getRelevantAction } from './../actions/base';
import * as process from 'process';
import { Position, Range, Uri } from 'vscode';
import { BaseMovement } from '../actions/baseMotion';
import { BaseOperator } from '../actions/operator';
import { EasyMotion } from '../actions/plugins/easymotion/easymotion';
import { SearchByNCharCommand } from '../actions/plugins/easymotion/easymotion.cmd';
import { IBaseAction } from '../actions/types';
import { Cursor } from '../common/motion/cursor';
import { configuration } from '../configuration/configuration';
import { decoration } from '../configuration/decoration';
import { Notation } from '../configuration/notation';
import { Remappers } from '../configuration/remapper';
import { Jump } from '../jumps/jump';
import { globalState } from '../state/globalState';
import { RemapState } from '../state/remapState';
import { StatusBar } from '../statusBar';
import { IModeHandler, executeTransformations } from '../transformations/execute';
import { isTextTransformation } from '../transformations/transformations';
import { SearchDecorations, getDecorationsForSearchMatchRanges } from '../util/decorationUtils';
import { Logger } from '../util/logger';
import { SpecialKeys } from '../util/specialKeys';
import { scrollView } from '../util/util';
import { VSCodeContext } from '../util/vscodeContext';
import { BaseAction, BaseCommand, KeypressState, getRelevantAction } from './../actions/base';
import {
ActionOverrideCmdD,
CommandNumber,
CommandQuitRecordMacro,
DocumentContentChangeAction,
} from './../actions/commands/actions';
import {
CommandBackspaceInInsertMode,
CommandEscInsertMode,
@ -10,43 +38,14 @@ import {
InsertCharAbove,
InsertCharBelow,
} from './../actions/commands/insert';
import { Jump } from '../jumps/jump';
import { Logger } from '../util/logger';
import { Mode, VSCodeVimCursorType, isVisualMode, getCursorStyle, isStatusBarMode } from './mode';
import { PairMatcher } from './../common/matching/matcher';
import { earlierOf, laterOf } from './../common/motion/position';
import { Cursor } from '../common/motion/cursor';
import { RecordedState } from './../state/recordedState';
import { IBaseAction } from '../actions/types';
import { ForceStopRemappingError, VimError } from './../error';
import { Register, RegisterMode } from './../register/register';
import { Remappers } from '../configuration/remapper';
import { StatusBar } from '../statusBar';
import { TextEditor } from './../textEditor';
import { VimError, ForceStopRemappingError } from './../error';
import { RecordedState } from './../state/recordedState';
import { VimState } from './../state/vimState';
import { VSCodeContext } from '../util/vscodeContext';
import { configuration } from '../configuration/configuration';
import { decoration } from '../configuration/decoration';
import { scrollView } from '../util/util';
import {
CommandQuitRecordMacro,
DocumentContentChangeAction,
ActionOverrideCmdD,
CommandNumber,
} from './../actions/commands/actions';
import { isTextTransformation } from '../transformations/transformations';
import { executeTransformations, IModeHandler } from '../transformations/execute';
import { globalState } from '../state/globalState';
import { Notation } from '../configuration/notation';
import { SpecialKeys } from '../util/specialKeys';
import { SearchDecorations, getDecorationsForSearchMatchRanges } from '../util/decorationUtils';
import { BaseOperator } from '../actions/operator';
import { SearchByNCharCommand } from '../actions/plugins/easymotion/easymotion.cmd';
import { Position, Uri } from 'vscode';
import { RemapState } from '../state/remapState';
import * as process from 'process';
import { EasyMotion } from '../actions/plugins/easymotion/easymotion';
import { Range } from 'vscode';
import { TextEditor } from './../textEditor';
import { Mode, VSCodeVimCursorType, getCursorStyle, isStatusBarMode, isVisualMode } from './mode';
interface IModeHandlerMap {
get(editorId: Uri): ModeHandler | undefined;
@ -398,7 +397,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
await this.setCurrentMode(Mode.Normal);
}
this.updateView({ drawSelection: toDraw, revealRange: false });
void this.updateView({ drawSelection: toDraw, revealRange: false });
}
}
@ -1615,7 +1614,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
this.vimState.editor.setDecorations(decoration.easyMotionIncSearch, easyMotionHighlightRanges);
for (const viewChange of this.vimState.postponedCodeViewChanges) {
vscode.commands.executeCommand(viewChange.command, viewChange.args);
void vscode.commands.executeCommand(viewChange.command, viewChange.args);
}
this.vimState.postponedCodeViewChanges = [];
@ -1627,7 +1626,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
StatusBar.clear(this.vimState, false);
// NOTE: this is not being awaited to save the 15-20ms block - I think this is fine
VSCodeContext.set('vim.mode', Mode[this.vimState.currentMode]);
void VSCodeContext.set('vim.mode', Mode[this.vimState.currentMode]);
// Tell VSCode that the cursor position changed, so it updates its highlights for `editor.occurrencesHighlight`.
const range = new vscode.Range(
@ -1635,7 +1634,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
this.vimState.cursorStopPosition,
);
if (!/\s+/.test(this.vimState.document.getText(range))) {
vscode.commands.executeCommand('editor.action.wordHighlight.trigger');
void vscode.commands.executeCommand('editor.action.wordHighlight.trigger');
}
}
@ -1680,6 +1679,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
}
dispose() {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
this.disposables.map((d) => d.dispose());
}
}

View File

@ -1,18 +1,17 @@
import { ChildProcess, spawn } from 'child_process';
import { exists } from 'fs';
import { Neovim } from 'neovim/lib/api/Neovim';
import { attach } from 'neovim/lib/attach';
import { dirname } from 'path';
import * as util from 'util';
import * as vscode from 'vscode';
import { Logger } from '../util/logger';
import { sorted } from './../common/motion/position';
import { Position, TextDocument } from 'vscode';
import { configuration } from '../configuration/configuration';
import { Register, RegisterMode } from '../register/register';
import { TextEditor } from '../textEditor';
import { Logger } from '../util/logger';
import { sorted } from './../common/motion/position';
import { VimState } from './../state/vimState';
import { configuration } from '../configuration/configuration';
import { dirname } from 'path';
import { exists } from 'fs';
import { spawn, ChildProcess } from 'child_process';
import { attach } from 'neovim/lib/attach';
import { Neovim } from 'neovim/lib/api/Neovim';
import { Position } from 'vscode';
import { TextDocument } from 'vscode';
export class NeovimWrapper implements vscode.Disposable {
private process?: ChildProcess;
@ -42,6 +41,7 @@ export class NeovimWrapper implements vscode.Disposable {
await Promise.race([nvimAttach, timeout]);
} catch (e) {
configuration.enableNeovim = false;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
throw new Error(`Failed to attach to neovim process. ${e.message}`);
}

View File

@ -50,7 +50,7 @@ export class HistoryBase {
}
public async clear() {
this.context.workspaceState.update(this.historyKey, undefined);
void this.context.workspaceState.update(this.historyKey, undefined);
this.history = [];
}
@ -60,14 +60,16 @@ export class HistoryBase {
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parsedData = JSON.parse(data);
if (!Array.isArray(parsedData)) {
throw Error('Unexpected format in history. Expected JSON.');
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.history = parsedData;
}
async save(): Promise<void> {
this.context.workspaceState.update(this.historyKey, JSON.stringify(this.history));
void this.context.workspaceState.update(this.historyKey, JSON.stringify(this.history));
}
}

View File

@ -1,7 +1,7 @@
import * as vscode from 'vscode';
import { promisify } from 'util';
import * as util from 'util';
import * as fs from 'fs';
import * as util from 'util';
import { promisify } from 'util';
import * as vscode from 'vscode';
export const constants = {
UV_FS_SYMLINK_DIR: 1,
@ -95,6 +95,7 @@ export async function readFileAsync(path: string, encoding: BufferEncoding): Pro
}
export async function mkdirAsync(path: string, options: any): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
await promisify(fs.mkdir)(path, options);
}

View File

@ -1,6 +1,6 @@
import * as vscode from 'vscode';
import * as path from 'path';
import { readFileAsync, mkdirAsync, writeFileAsync, unlinkSync } from 'platform/fs';
import { mkdirAsync, readFileAsync, unlinkSync, writeFileAsync } from 'platform/fs';
import * as vscode from 'vscode';
import { Globals } from '../../globals';
import { Logger } from '../../util/logger';
@ -69,6 +69,7 @@ export class HistoryBase {
try {
data = await readFileAsync(this.historyKey, 'utf-8');
} catch (err) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (err.code === 'ENOENT') {
Logger.debug(`History does not exist. path=${this.historyKey}`);
} else {
@ -82,10 +83,12 @@ export class HistoryBase {
}
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parsedData = JSON.parse(data);
if (!Array.isArray(parsedData)) {
throw Error('Unexpected format in history file. Expected JSON.');
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.history = parsedData;
} catch (e) {
Logger.warn(`Deleting corrupted history file. path=${this.historyKey} err=${e}.`);
@ -99,6 +102,7 @@ export class HistoryBase {
try {
await mkdirAsync(Globals.extensionStoragePath, { recursive: true });
} catch (createDirectoryErr) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (createDirectoryErr.code !== 'EEXIST') {
throw createDirectoryErr;
}

View File

@ -1,8 +1,8 @@
import { Clipboard } from './../util/clipboard';
import { RecordedState } from './../state/recordedState';
import { VimState } from './../state/vimState';
import { readFileAsync, writeFileAsync } from 'platform/fs';
import { Globals } from '../globals';
import { RecordedState } from './../state/recordedState';
import { VimState } from './../state/vimState';
import { Clipboard } from './../util/clipboard';
/**
* This is included in the register file.
@ -135,7 +135,7 @@ export class Register {
this.isClipboardRegister(register) &&
!(content instanceof RecordedState)
) {
Clipboard.Copy(content);
void Clipboard.Copy(content);
}
this.processNumberedRegisters(vimState, content);
@ -182,7 +182,7 @@ export class Register {
if (multicursorIndex === 0 && this.isClipboardRegister(register)) {
const newContent = contentByCursor[multicursorIndex].text;
if (!(newContent instanceof RecordedState)) {
Clipboard.Copy(newContent);
void Clipboard.Copy(newContent);
}
}
}
@ -338,11 +338,14 @@ export class Register {
public static loadFromDisk(supportNode: boolean): void {
if (supportNode) {
Register.registers = new Map();
import('path').then((path) => {
readFileAsync(path.join(Globals.extensionStoragePath, '.registers'), 'utf8').then(
void import('path').then((path) => {
void readFileAsync(path.join(Globals.extensionStoragePath, '.registers'), 'utf8').then(
(savedRegisters) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parsed = JSON.parse(savedRegisters);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (parsed.version === REGISTER_FORMAT_VERSION) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
Register.registers = new Map(parsed.registers);
}
},

View File

@ -1,8 +1,8 @@
import * as vscode from 'vscode';
import { Mode } from './mode/mode';
import { configuration } from './configuration/configuration';
import { VimState } from './state/vimState';
import { VimError } from './error';
import { Mode } from './mode/mode';
import { VimState } from './state/vimState';
import { Logger } from './util/logger';
class StatusBarImpl implements vscode.Disposable {
@ -125,8 +125,9 @@ class StatusBarImpl implements vscode.Disposable {
let foreground: string | undefined;
let background: string | undefined;
// @ts-ignore
const colorToSet = configuration.statusBarColors[Mode[mode].toLowerCase()];
const colorToSet = (
configuration.statusBarColors as unknown as Record<string, string | string[] | undefined>
)[Mode[mode].toLowerCase()];
if (colorToSet !== undefined) {
if (typeof colorToSet === 'string') {
@ -156,7 +157,7 @@ class StatusBarImpl implements vscode.Disposable {
}
if (currentColorCustomizations !== colorCustomizations) {
workbenchConfiguration.update('colorCustomizations', colorCustomizations, true);
void workbenchConfiguration.update('colorCustomizations', colorCustomizations, true);
}
}
}

View File

@ -19,4 +19,4 @@ class TaskQueue {
}
}
export let taskQueue = new TaskQueue();
export const taskQueue = new TaskQueue();

View File

@ -1,7 +1,7 @@
import * as _ from 'lodash';
import { Position, TextDocument } from 'vscode';
import { configuration } from '../configuration/configuration';
import { getAllPositions, getAllEndPositions } from './util';
import { getAllEndPositions, getAllPositions } from './util';
export enum WordType {
Normal,
@ -181,7 +181,6 @@ function makeCamelCaseWordRegex(characterSet: string): RegExp {
// Older browsers don't support lookbehind - in this case, use an inferior regex rather than crashing
let supportsLookbehind = true;
try {
// tslint:disable-next-line
new RegExp('(?<=x)');
} catch {
supportsLookbehind = false;

View File

@ -1,26 +1,26 @@
import * as vscode from 'vscode';
import { Logger } from '../util/logger';
import {
isTextTransformation,
TextTransformations,
Transformation,
isMultiCursorTextTransformation,
InsertTextVSCodeTransformation,
areAllSameTransformation,
overlappingTransformations,
} from './transformations';
import { ExCommandLine } from '../cmd_line/commandLine';
import { Cursor } from '../common/motion/cursor';
import { PositionDiff } from '../common/motion/position';
import { Globals } from '../globals';
import { Mode } from '../mode/mode';
import { Register } from '../register/register';
import { RecordedState } from '../state/recordedState';
import { TextEditor } from '../textEditor';
import { Cursor } from '../common/motion/cursor';
import { VimState } from '../state/vimState';
import { Transformer } from './transformer';
import { Globals } from '../globals';
import { keystrokesExpressionParser } from '../vimscript/expression';
import { globalState } from '../state/globalState';
import { RecordedState } from '../state/recordedState';
import { VimState } from '../state/vimState';
import { TextEditor } from '../textEditor';
import { Logger } from '../util/logger';
import { keystrokesExpressionParser } from '../vimscript/expression';
import {
InsertTextVSCodeTransformation,
TextTransformations,
Transformation,
areAllSameTransformation,
isMultiCursorTextTransformation,
isTextTransformation,
overlappingTransformations,
} from './transformations';
import { Transformer } from './transformer';
export interface IModeHandler {
vimState: VimState;
@ -41,12 +41,12 @@ export async function executeTransformations(
const vimState = modeHandler.vimState;
const textTransformations: TextTransformations[] = transformations.filter((x) =>
const textTransformations = transformations.filter((x): x is TextTransformations =>
isTextTransformation(x),
) as any;
);
const multicursorTextTransformations: InsertTextVSCodeTransformation[] = transformations.filter(
(x) => isMultiCursorTextTransformation(x),
) as any;
(x): x is InsertTextVSCodeTransformation => isMultiCursorTextTransformation(x),
);
const otherTransformations = transformations.filter(
(x) => !isTextTransformation(x) && !isMultiCursorTextTransformation(x),
@ -116,6 +116,7 @@ export async function executeTransformations(
} catch (e) {
// Messages like "TextEditor(vs.editor.ICodeEditor:1,$model8) has been disposed" can be ignored.
// They occur when the user switches to a new tab while an action is running.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (e.name !== 'DISPOSED') {
throw e;
}
@ -232,6 +233,7 @@ export async function executeTransformations(
break;
case 'vscodeCommand':
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
await vscode.commands.executeCommand(transformation.command, ...transformation.args);
break;

View File

@ -245,6 +245,7 @@ const getRangeFromTextTransformation = (transformation: TextTransformations): Ra
return undefined;
}
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
throw new Error('Unhandled text transformation: ' + transformation);
};
@ -278,8 +279,8 @@ export const areAllSameTransformation = (transformations: Transformation[]): boo
return transformations.every((t) => {
return Object.entries(t).every(([key, value]) => {
// @ts-ignore: TODO: this is all quite janky
return firstTransformation[key] === value;
// TODO: this is all quite janky
return (firstTransformation as unknown as Record<string, any>)[key] === value;
});
});
};

View File

@ -1,4 +1,4 @@
import { Range, DecorationOptions } from 'vscode';
import { DecorationOptions, Range } from 'vscode';
/**
* Alias for the types of arrays that can be passed to a TextEditor's setDecorations method
@ -54,7 +54,7 @@ export function formatDecorationText(
.replace(/ /g, '\u00a0') // " " NO-BREAK SPACE
.replace(/\t/g, '\u00a0'.repeat(tabsize))
// Decorations can't change the apparent # of lines in the editor, so we must settle for a single-line version of our text
.replace(/\r\n|[\r\n]/g, newlineReplacement as any)}\u200b`;
.replace(/\r\n|[\r\n]/g, newlineReplacement as string)}\u200b`;
}
/**

View File

@ -1,5 +1,5 @@
import { VimError, ErrorCode } from '../error';
import { configuration } from '../configuration/configuration';
import { ErrorCode, VimError } from '../error';
class ExternalCommand {
private previousExternalCommand: string | undefined;
@ -61,9 +61,11 @@ class ExternalCommand {
}
if (process.stdout !== null) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
process.stdout.on('data', (chunk) => output.push(chunk));
}
if (process.stderr !== null) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
process.stderr.on('data', (chunk) => output.push(chunk));
}

View File

@ -1,4 +1,4 @@
import * as vscode from 'vscode';
// eslint-disable-next-line id-denylist
import { all, alt, optWhitespace, Parser, regexp, seq, string, succeed } from 'parsimmon';
import { AsciiCommand } from '../cmd_line/commands/ascii';
import { BangCommand } from '../cmd_line/commands/bang';
@ -6,7 +6,6 @@ import { Breakpoints } from '../cmd_line/commands/breakpoints';
import { BufferDeleteCommand } from '../cmd_line/commands/bufferDelete';
import { CloseCommand } from '../cmd_line/commands/close';
import { CopyCommand } from '../cmd_line/commands/copy';
import { MoveCommand } from '../cmd_line/commands/move';
import { DeleteCommand } from '../cmd_line/commands/delete';
import { DigraphsCommand } from '../cmd_line/commands/digraph';
import { FileCommand } from '../cmd_line/commands/file';
@ -17,12 +16,14 @@ import { HistoryCommand } from '../cmd_line/commands/history';
import { ClearJumpsCommand, JumpsCommand } from '../cmd_line/commands/jumps';
import { CenterCommand, LeftCommand, RightCommand } from '../cmd_line/commands/leftRightCenter';
import { DeleteMarksCommand, MarksCommand } from '../cmd_line/commands/marks';
import { MoveCommand } from '../cmd_line/commands/move';
import { NohlCommand } from '../cmd_line/commands/nohl';
import { OnlyCommand } from '../cmd_line/commands/only';
import { PrintCommand } from '../cmd_line/commands/print';
import { PutExCommand } from '../cmd_line/commands/put';
import { QuitCommand } from '../cmd_line/commands/quit';
import { ReadCommand } from '../cmd_line/commands/read';
import { RedoCommand } from '../cmd_line/commands/redo';
import { RegisterCommand } from '../cmd_line/commands/register';
import { RetabCommand } from '../cmd_line/commands/retab';
import { SetCommand } from '../cmd_line/commands/set';
@ -46,7 +47,6 @@ import { StatusBar } from '../statusBar';
import { ExCommand } from './exCommand';
import { LineRange } from './lineRange';
import { nameAbbrevParser } from './parserUtils';
import { RedoCommand } from '../cmd_line/commands/redo';
type ArgParser = Parser<ExCommand>;

View File

@ -1,4 +1,5 @@
import { alt, any, Parser, regexp, string, noneOf } from 'parsimmon';
// eslint-disable-next-line id-denylist
import { Parser, alt, any, noneOf, regexp, string } from 'parsimmon';
import { configuration } from '../configuration/configuration';
const leaderParser = regexp(/<leader>/).map(() => configuration.leader); // lazy evaluation of configuration.leader
@ -9,6 +10,7 @@ const specialCharacterParser = alt(specialCharacters, leaderParser);
// TODO: Move to a more general location
// TODO: Add more special characters
const escapedParser = string('\\')
// eslint-disable-next-line id-denylist
.then(any.fallback(undefined))
.map((escaped) => {
if (escaped === undefined) {

View File

@ -1,3 +1,4 @@
// eslint-disable-next-line id-denylist
import { alt, any, optWhitespace, Parser, seq, string, succeed } from 'parsimmon';
import { Position, Range } from 'vscode';
import { ErrorCode, VimError } from '../error';
@ -61,7 +62,7 @@ type LineSpecifier =
type: 'last_substitute_pattern_next';
};
const lineSpecifierParser: Parser<LineSpecifier> = alt(
const lineSpecifierParser: Parser<LineSpecifier> = alt<LineSpecifier>(
numberParser.map((num) => {
return { type: 'number', num };
}),

View File

@ -1,3 +1,4 @@
// eslint-disable-next-line id-denylist
import { alt, any, Parser, regexp, seq, string, succeed, whitespace } from 'parsimmon';
export const numberParser: Parser<number> = regexp(/\d+/).map((num) => Number.parseInt(num, 10));
@ -20,6 +21,7 @@ export function nameAbbrevParser(abbrev: string, rest: string): Parser<string> {
// TODO: `:help filename-modifiers`
export const fileNameParser: Parser<string> = alt<string>(
string('\\').then(
// eslint-disable-next-line id-denylist
any.fallback(undefined).map((escaped) => {
if (escaped === undefined || escaped === '\\') {
return '\\';

View File

@ -1,4 +1,5 @@
import { alt, any, lazy, noneOf, oneOf, Parser, seq, string, seqMap, eof } from 'parsimmon';
// eslint-disable-next-line id-denylist
import { Parser, alt, any, eof, lazy, noneOf, oneOf, seq, seqMap, string } from 'parsimmon';
import { Position, Range, TextDocument } from 'vscode';
import { configuration } from '../configuration/configuration';
import { VimState } from '../state/vimState';
@ -208,6 +209,7 @@ export class Pattern {
.then(eof)
.map(() => ({ emptyBranch: true })), // Trailing | matches everything
string('\\')
// eslint-disable-next-line id-denylist
.then(any.fallback(undefined))
.map((escaped) => {
if (escaped === undefined) {
@ -229,6 +231,7 @@ export class Pattern {
alt(
// Allow unescaped delimiter inside [], and don't transform ^ or $
string('\\')
// eslint-disable-next-line id-denylist
.then(any.fallback(undefined))
.map((escaped) => '\\' + (escaped ?? '\\')),
noneOf(']'),
@ -248,12 +251,16 @@ export class Pattern {
if (typeof atom === 'string') {
patternString += atom;
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (atom.emptyBranch) {
emptyBranch = true;
patternString += '|';
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} else if (atom.ignorecase) {
caseOverride = true;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} else if (atom.inSelection) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
inSelection = atom.inSelection;
} else if (caseOverride === undefined) {
caseOverride = false;

View File

@ -2,10 +2,10 @@ import * as assert from 'assert';
import * as vscode from 'vscode';
import { BaseAction } from '../../src/actions/base';
import { VimState } from '../../src/state/vimState';
import { setupWorkspace, cleanUpWorkspace } from './../testUtils';
import { Mode } from '../../src/mode/mode';
import { EasyMotion } from '../../src/actions/plugins/easymotion/easymotion';
import { Mode } from '../../src/mode/mode';
import { VimState } from '../../src/state/vimState';
import { cleanUpWorkspace, setupWorkspace } from './../testUtils';
class TestAction1D extends BaseAction {
keys = ['a', 'b'];
@ -55,13 +55,11 @@ suite('base action', () => {
[['<Esc>'], ['<Esc>'], true],
];
for (const test in testCases) {
if (testCases.hasOwnProperty(test)) {
const [left, right, expected] = testCases[test];
for (const test of testCases) {
const [left, right, expected] = test;
const actual = BaseAction.CompareKeypressSequence(left, right);
assert.strictEqual(actual, expected, `${left}. ${right}.`);
}
const actual = BaseAction.CompareKeypressSequence(left, right);
assert.strictEqual(actual, expected, `${left}. ${right}.`);
}
});

View File

@ -4,9 +4,9 @@ import * as vscode from 'vscode';
import { join } from 'path';
import { getAndUpdateModeHandler } from '../../extension';
import { ExCommandLine } from '../../src/cmd_line/commandLine';
import * as error from '../../src/error';
import { ModeHandler } from '../../src/mode/modeHandler';
import * as t from '../testUtils';
import * as error from '../../src/error';
suite('Buffer delete', () => {
let modeHandler: ModeHandler;
@ -53,8 +53,8 @@ suite('Buffer delete', () => {
for (let i = 0; i < 3; i++) {
const uri: vscode.Uri = vscode.Uri.parse(join(dirPath, `${i}`));
filePaths.push(uri.toString());
vscode.workspace.openTextDocument(uri).then((doc: vscode.TextDocument) => {
doc.save();
void vscode.workspace.openTextDocument(uri).then((doc: vscode.TextDocument) => {
void doc.save();
});
}

View File

@ -1,16 +1,16 @@
import { strict as assert } from 'assert';
import * as vscode from 'vscode';
import { Remappers, Remapper } from '../../src/configuration/remapper';
import { getAndUpdateModeHandler } from '../../extension';
import { IKeyRemapping } from '../../src/configuration/iconfiguration';
import { Remapper, Remappers } from '../../src/configuration/remapper';
import { Mode } from '../../src/mode/mode';
import { ModeHandler } from '../../src/mode/modeHandler';
import { Configuration } from '../testConfiguration';
import { setupWorkspace, cleanUpWorkspace, assertEqualLines } from '../testUtils';
import { IKeyRemapping } from '../../src/configuration/iconfiguration';
import { IRegisterContent, Register } from '../../src/register/register';
import { getAndUpdateModeHandler } from '../../extension';
import { VimState } from '../../src/state/vimState';
import { StatusBar } from '../../src/statusBar';
import { Configuration } from '../testConfiguration';
import { assertEqualLines, cleanUpWorkspace, setupWorkspace } from '../testUtils';
suite('Remapper', () => {
let modeHandler: ModeHandler;
@ -252,6 +252,7 @@ suite('Remapper', () => {
try {
actual = await remapper.sendKey(['j', 'j'], modeHandler);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
assert.fail(e);
}
@ -278,6 +279,7 @@ suite('Remapper', () => {
try {
actual = await remapper.sendKey(['0'], modeHandler);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
assert.fail(e);
}
@ -315,6 +317,7 @@ suite('Remapper', () => {
try {
actual = await remapper.sendKey(['<C-e>'], modeHandler);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
assert.fail(e);
}
@ -341,6 +344,7 @@ suite('Remapper', () => {
try {
actual = await remapper.sendKey([leaderKey, 'w'], modeHandler);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
assert.fail(e);
}
@ -369,6 +373,7 @@ suite('Remapper', () => {
try {
actual = await remapper.sendKey([leaderKey, 'c'], modeHandler);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
assert.fail(e);
}

View File

@ -4,7 +4,7 @@ import { ErrorCode, ErrorMessage } from '../src/error';
suite('Error', () => {
test('error code has message', () => {
// tslint:disable-next-line: forin
// eslint-disable-next-line guard-for-in
for (const errorCodeString in ErrorCode) {
const errorCode = Number(errorCodeString);
if (!isNaN(errorCode)) {

View File

@ -1,7 +1,6 @@
import * as assert from 'assert';
import * as sinon from 'sinon';
import vscode from 'vscode';
import { Position } from 'vscode';
import vscode, { Position } from 'vscode';
import { HistoryTracker, IMark } from '../src/history/historyTracker';
import { Jump } from '../src/jumps/jump';
@ -23,7 +22,7 @@ suite('historyTracker unit tests', () => {
const setupHistoryTracker = (vimState = setupVimState()) => new HistoryTracker(vimState);
const buildMockPosition = (): Position => sandbox.createStubInstance(Position) as any;
const buildMockPosition = (): Position => sandbox.createStubInstance(Position);
setup(() => {
sandbox = sinon.createSandbox();
@ -169,7 +168,6 @@ suite('historyTracker unit tests', () => {
});
});
// tslint:disable: no-empty
class TextEditorStub implements vscode.TextEditor {
readonly document!: vscode.TextDocument;
selection!: vscode.Selection;
@ -178,7 +176,9 @@ class TextEditorStub implements vscode.TextEditor {
options!: vscode.TextEditorOptions;
readonly viewColumn!: vscode.ViewColumn;
constructor() {}
constructor() {
// NoOp
}
async edit(
callback: (editBuilder: vscode.TextEditorEdit) => void,
options?: { undoStopBefore: boolean; undoStopAfter: boolean },
@ -187,11 +187,7 @@ class TextEditorStub implements vscode.TextEditor {
}
async insertSnippet(
snippet: vscode.SnippetString,
location?:
| vscode.Position
| vscode.Range
| ReadonlyArray<Position>
| ReadonlyArray<vscode.Range>,
location?: vscode.Position | vscode.Range | readonly Position[] | readonly vscode.Range[],
options?: { undoStopBefore: boolean; undoStopAfter: boolean },
) {
return true;
@ -199,8 +195,16 @@ class TextEditorStub implements vscode.TextEditor {
setDecorations(
decorationType: vscode.TextEditorDecorationType,
rangesOrOptions: vscode.Range[] | vscode.DecorationOptions[],
) {}
revealRange(range: vscode.Range, revealType?: vscode.TextEditorRevealType) {}
show(column?: vscode.ViewColumn) {}
hide() {}
) {
// NoOp
}
revealRange(range: vscode.Range, revealType?: vscode.TextEditorRevealType) {
// NoOp
}
show(column?: vscode.ViewColumn) {
// NoOp
}
hide() {
// NoOp
}
}

View File

@ -9,9 +9,9 @@
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
import * as path from 'path';
import Mocha from 'mocha';
import glob from 'glob';
import Mocha from 'mocha';
import * as path from 'path';
import { Globals } from '../src/globals';
import { Configuration } from './testConfiguration';
@ -50,9 +50,9 @@ export function run(): Promise<void> {
c();
}
});
} catch (err) {
console.error(err);
e(err);
} catch (error) {
console.error(error);
e(error);
}
});
});

View File

@ -1,13 +1,13 @@
import * as assert from 'assert';
import { Configuration } from '../testConfiguration';
import { setupWorkspace, cleanUpWorkspace } from '../testUtils';
import { InputMethodSwitcher } from '../../src/actions/plugins/imswitcher';
import { Mode } from '../../src/mode/mode';
import { Configuration } from '../testConfiguration';
import { cleanUpWorkspace, setupWorkspace } from '../testUtils';
suite('Input method plugin', () => {
let savedCmd = '';
function fakeExecuteChinese(cmd: string): Promise<string> {
const fakeExecuteChinese = (cmd: string): Promise<string> => {
return new Promise<string>((resolve, reject) => {
if (cmd === 'im-select') {
resolve('chinese');
@ -16,9 +16,9 @@ suite('Input method plugin', () => {
resolve('');
}
});
}
};
function fakeExecuteDefault(cmd: string): Promise<string> {
const fakeExecuteDefault = (cmd: string): Promise<string> => {
return new Promise<string>((resolve, reject) => {
if (cmd === 'im-select') {
resolve('default');
@ -27,7 +27,7 @@ suite('Input method plugin', () => {
resolve('');
}
});
}
};
setup(async () => {
const configuration = new Configuration();

View File

@ -2,14 +2,14 @@ import * as assert from 'assert';
import * as vscode from 'vscode';
import { getAndUpdateModeHandler } from '../../extension';
import { EasyMotion } from '../../src/actions/plugins/easymotion/easymotion';
import { ModeHandler } from '../../src/mode/modeHandler';
import { Register } from '../../src/register/register';
import { RecordedState } from '../../src/state/recordedState';
import { VimState } from '../../src/state/vimState';
import { Clipboard } from '../../src/util/clipboard';
import { assertEqualLines, cleanUpWorkspace, setupWorkspace } from '../testUtils';
import { RecordedState } from '../../src/state/recordedState';
import { newTest } from '../testSimplifier';
import { EasyMotion } from '../../src/actions/plugins/easymotion/easymotion';
import { assertEqualLines, cleanUpWorkspace, setupWorkspace } from '../testUtils';
suite('register', () => {
let modeHandler: ModeHandler;
@ -137,6 +137,7 @@ suite('register', () => {
const actual = await Register.get(vimState.recordedState.registerName);
assert.strictEqual(actual?.text, expected);
} catch (err) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
assert.fail(err);
}
});

View File

@ -26,4 +26,4 @@ async function main() {
}
}
main();
void main();

View File

@ -92,6 +92,7 @@ export class Configuration implements IConfiguration {
tabstop = 2;
editorCursorStyle = vscode.TextEditorCursorStyle.Line;
expandtab = true;
// eslint-disable-next-line id-denylist
number = true;
relativenumber = false;
iskeyword = ''; // Use `editor.wordSeparators`

View File

@ -1,22 +1,21 @@
import { strict as assert } from 'assert';
import * as vscode from 'vscode';
import * as sinon from 'sinon';
import * as vscode from 'vscode';
import { Globals } from '../src/globals';
import { Mode } from '../src/mode/mode';
import { assertEqualLines, reloadConfiguration } from './testUtils';
import { globalState } from '../src/state/globalState';
import { IKeyRemapping } from '../src/configuration/iconfiguration';
import * as os from 'os';
import { Position } from 'vscode';
import { IConfiguration, IKeyRemapping } from '../src/configuration/iconfiguration';
import { VimrcImpl } from '../src/configuration/vimrc';
import { vimrcKeyRemappingBuilder } from '../src/configuration/vimrcKeyRemappingBuilder';
import { IConfiguration } from '../src/configuration/iconfiguration';
import { Position } from 'vscode';
import { ModeHandlerMap } from '../src/mode/modeHandlerMap';
import { StatusBar } from '../src/statusBar';
import { Register } from '../src/register/register';
import { Globals } from '../src/globals';
import { Mode } from '../src/mode/mode';
import { ModeHandler } from '../src/mode/modeHandler';
import { ModeHandlerMap } from '../src/mode/modeHandlerMap';
import { Register } from '../src/register/register';
import { globalState } from '../src/state/globalState';
import { StatusBar } from '../src/statusBar';
import { TextEditor } from '../src/textEditor';
import { assertEqualLines, reloadConfiguration } from './testUtils';
function newTestGeneric<T extends ITestObject | ITestWithRemapsObject>(
testObj: T,
@ -33,7 +32,9 @@ function newTestGeneric<T extends ITestObject | ITestWithRemapsObject>(
if (testObj.config) {
for (const key in testObj.config) {
if (testObj.config.hasOwnProperty(key)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const value = testObj.config[key];
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
Globals.mockConfiguration[key] = value;
}
}
@ -41,6 +42,7 @@ function newTestGeneric<T extends ITestObject | ITestWithRemapsObject>(
}
await innerTest(testObj);
} catch (reason) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
reason.stack = stack;
throw reason;
} finally {
@ -156,15 +158,15 @@ function tokenizeKeySequence(sequence: string): string[] {
// no close bracket, probably trying to do a left shift, take literal
// char sequence
function rawTokenize(characters: string): void {
// tslint:disable-next-line:prefer-for-of
const rawTokenize = (characters: string): void => {
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < characters.length; i++) {
result.push(characters[i]);
}
}
};
// don't use a for of here, since the iterator doesn't split surrogate pairs
// tslint:disable-next-line:prefer-for-of
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < sequence.length; i++) {
const char = sequence[i];
@ -234,6 +236,7 @@ async function testIt(testObj: ITestObject): Promise<ModeHandler> {
if (testObj.stub) {
const confirmStub = sinon
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
.stub(testObj.stub.stubClass.prototype, testObj.stub.methodName)
.resolves(testObj.stub.returnValue);
await modeHandler.handleMultipleKeyEvents(tokenizeKeySequence(testObj.keysPressed));
@ -534,5 +537,5 @@ async function parseVimRCMappings(lines: string[]): Promise<void> {
}
}
export type { ITestObject };
export { testIt };
export type { ITestObject };

View File

@ -1,23 +1,23 @@
import { strict as assert } from 'assert';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { join } from 'path';
import { promisify } from 'util';
import * as vscode from 'vscode';
import * as path from 'path';
import { Configuration } from './testConfiguration';
import { Globals } from '../src/globals';
import { ValidatorResults } from '../src/configuration/iconfigurationValidator';
import { IConfiguration } from '../src/configuration/iconfiguration';
import { ExCommandLine } from '../src/cmd_line/commandLine';
import { IConfiguration } from '../src/configuration/iconfiguration';
import { Globals } from '../src/globals';
import { StatusBar } from '../src/statusBar';
import { Configuration } from './testConfiguration';
class TestMemento implements vscode.Memento {
private mapping = new Map<string, any>();
get<T>(key: string): T | undefined;
get<T>(key: string, defaultValue: T): T;
get(key: any, defaultValue?: any) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument
return this.mapping.get(key) || defaultValue;
}
@ -109,6 +109,7 @@ export async function WaitForEditorsToClose(numExpectedEditors: number = 0): Pro
try {
await waitForTextEditorsToClose;
} catch (error) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
assert.fail(error);
}
}
@ -155,8 +156,9 @@ export async function cleanUpWorkspace(): Promise<void> {
}
export async function reloadConfiguration() {
const validatorResults =
(await require('../src/configuration/configuration').configuration.load()) as ValidatorResults;
const validatorResults = await (
await import('../src/configuration/configuration')
).configuration.load();
for (const validatorResult of validatorResults.get()) {
console.warn(validatorResult);
}

View File

@ -1,15 +0,0 @@
{
"extends": "tslint:recommended",
"rules": {
"array-type": { "options": "array-simple" },
"await-promise": [true, "Thenable"],
"max-classes-per-file": false,
"no-console": [true, "debug", "info", "time", "timeEnd", "trace"],
"no-duplicate-variable": true,
"no-parameter-properties": true,
"no-return-await": true,
"no-switch-case-fall-through": true,
"no-unnecessary-type-assertion": true,
"prefer-const": { "options": { "destructuring": "all" } }
}
}

12240
yarn.lock

File diff suppressed because it is too large Load Diff