Update dependency prettier to v3 (#8486)

This commit is contained in:
renovate[bot] 2023-09-09 19:57:26 -04:00 committed by GitHub
parent 71d80acb4d
commit 8c544d512e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
125 changed files with 848 additions and 839 deletions

View File

@ -54,7 +54,7 @@ export async function activate(context: vscode.ExtensionContext) {
await vscode.window.showWarningMessage('No .vimrc found. Please set `vim.vimrc.path.`'); await vscode.window.showWarningMessage('No .vimrc found. Please set `vim.vimrc.path.`');
} }
}, },
false false,
); );
} }

View File

@ -27,7 +27,7 @@ interface ICodeKeybinding {
} }
export async function getAndUpdateModeHandler( export async function getAndUpdateModeHandler(
forceSyncAndUpdate = false forceSyncAndUpdate = false,
): Promise<ModeHandler | undefined> { ): Promise<ModeHandler | undefined> {
const activeTextEditor = vscode.window.activeTextEditor; const activeTextEditor = vscode.window.activeTextEditor;
if (activeTextEditor === undefined || activeTextEditor.document.isClosed) { if (activeTextEditor === undefined || activeTextEditor.document.isClosed) {
@ -122,7 +122,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
Logger.info('Configuration changed'); Logger.info('Configuration changed');
await loadConfiguration(); await loadConfiguration();
}, },
false false,
); );
registerEventListener(context, vscode.workspace.onDidChangeTextDocument, async (event) => { registerEventListener(context, vscode.workspace.onDidChangeTextDocument, async (event) => {
@ -136,7 +136,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
} }
Logger.debug( Logger.debug(
`${event.contentChanges.length} change(s) to ${event.document.fileName} because ${event.reason}` `${event.contentChanges.length} change(s) to ${event.document.fileName} because ${event.reason}`,
); );
for (const x of event.contentChanges) { for (const x of event.contentChanges) {
Logger.trace(`\t-${x.rangeLength}, +'${x.text}'`); Logger.trace(`\t-${x.rangeLength}, +'${x.text}'`);
@ -204,7 +204,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
} }
} }
}, },
false false,
); );
// window events // window events
@ -250,12 +250,12 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
if (mh) { if (mh) {
globalState.jumpTracker.handleFileJump( globalState.jumpTracker.handleFileJump(
lastClosedModeHandler ? Jump.fromStateNow(lastClosedModeHandler.vimState) : null, lastClosedModeHandler ? Jump.fromStateNow(lastClosedModeHandler.vimState) : null,
Jump.fromStateNow(mh.vimState) Jump.fromStateNow(mh.vimState),
); );
} }
}, },
true, true,
true true,
); );
registerEventListener( registerEventListener(
@ -285,13 +285,13 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
(hash, s) => (hash, s) =>
hash + hash +
`[${s.anchor.line}, ${s.anchor.character}; ${s.active.line}, ${s.active.character}]`, `[${s.anchor.line}, ${s.anchor.character}; ${s.active.line}, ${s.active.character}]`,
'' '',
); );
const idx = mh.selectionsChanged.ourSelections.indexOf(selectionsHash); const idx = mh.selectionsChanged.ourSelections.indexOf(selectionsHash);
if (idx > -1) { if (idx > -1) {
mh.selectionsChanged.ourSelections.splice(idx, 1); mh.selectionsChanged.ourSelections.splice(idx, 1);
Logger.trace( Logger.trace(
`Ignoring selection: ${selectionsHash}. ${mh.selectionsChanged.ourSelections.length} left` `Ignoring selection: ${selectionsHash}. ${mh.selectionsChanged.ourSelections.length} left`,
); );
return; return;
} else if (mh.selectionsChanged.ignoreIntermediateSelections) { } else if (mh.selectionsChanged.ignoreIntermediateSelections) {
@ -325,7 +325,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
await mh.handleSelectionChange(e); await mh.handleSelectionChange(e);
}, },
true, true,
false false,
); );
registerEventListener( registerEventListener(
@ -344,7 +344,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
StatusBar.clear(mh.vimState, true); StatusBar.clear(mh.vimState, true);
} }
} }
} },
); );
const compositionState = new CompositionState(); const compositionState = new CompositionState();
@ -372,7 +372,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
compositionState.composingText = compositionState.composingText =
compositionState.composingText.substr( compositionState.composingText.substr(
0, 0,
compositionState.composingText.length - args.replaceCharCnt compositionState.composingText.length - args.replaceCharCnt,
) + args.text; ) + args.text;
} }
if (compositionState.insertedText) { if (compositionState.insertedText) {
@ -439,7 +439,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
if (!args) { if (!args) {
throw new Error( throw new Error(
"'args' is undefined. For this remap to work it needs to have 'args' with an '\"after\": string[]' and/or a '\"commands\": { command: string; args: any[] }[]'" "'args' is undefined. For this remap to work it needs to have 'args' with an '\"after\": string[]' and/or a '\"commands\": { command: string; args: any[] }[]'",
); );
} }
@ -455,7 +455,7 @@ export async function activate(context: vscode.ExtensionContext, handleLocal: bo
if (command.command.startsWith(':')) { if (command.command.startsWith(':')) {
await new ExCommandLine( await new ExCommandLine(
command.command.slice(1, command.command.length), command.command.slice(1, command.command.length),
mh.vimState.currentMode mh.vimState.currentMode,
).run(mh.vimState); ).run(mh.vimState);
mh.updateView(); mh.updateView();
} else { } else {
@ -544,7 +544,7 @@ async function toggleExtension(isDisabled: boolean, compositionState: Compositio
function overrideCommand( function overrideCommand(
context: vscode.ExtensionContext, context: vscode.ExtensionContext,
command: string, command: string,
callback: (...args: any[]) => any callback: (...args: any[]) => any,
) { ) {
const disposable = vscode.commands.registerCommand(command, async (args) => { const disposable = vscode.commands.registerCommand(command, async (args) => {
if (configuration.disableExtension) { if (configuration.disableExtension) {
@ -571,7 +571,7 @@ export function registerCommand(
context: vscode.ExtensionContext, context: vscode.ExtensionContext,
command: string, command: string,
callback: (...args: any[]) => any, callback: (...args: any[]) => any,
requiresActiveEditor: boolean = true requiresActiveEditor: boolean = true,
) { ) {
const disposable = vscode.commands.registerCommand(command, async (args) => { const disposable = vscode.commands.registerCommand(command, async (args) => {
if (requiresActiveEditor && !vscode.window.activeTextEditor) { if (requiresActiveEditor && !vscode.window.activeTextEditor) {
@ -588,7 +588,7 @@ export function registerEventListener<T>(
event: vscode.Event<T>, event: vscode.Event<T>,
listener: (e: T) => void, listener: (e: T) => void,
exitOnExtensionDisable = true, exitOnExtensionDisable = true,
exitOnTests = false exitOnTests = false,
) { ) {
const disposable = event(async (e) => { const disposable = event(async (e) => {
if (exitOnExtensionDisable && configuration.disableExtension) { if (exitOnExtensionDisable && configuration.disableExtension) {

View File

@ -23,14 +23,14 @@ function validateArgs(done) {
return done( return done(
new PluginError('updateVersion', { new PluginError('updateVersion', {
message: 'Missing `--semver` option. Possible values: patch, minor, major', message: 'Missing `--semver` option. Possible values: patch, minor, major',
}) }),
); );
} }
if (!['patch', 'minor', 'major'].includes(options.semver)) { if (!['patch', 'minor', 'major'].includes(options.semver)) {
return done( return done(
new PluginError('updateVersion', { new PluginError('updateVersion', {
message: 'Invalid `--semver` option. Possible values: patch, minor, major', message: 'Invalid `--semver` option. Possible values: patch, minor, major',
}) }),
); );
} }
@ -65,18 +65,18 @@ function updatePath() {
const filePath = f.path; const filePath = f.path;
let platformRelativepath = path.relative( let platformRelativepath = path.relative(
path.dirname(filePath), path.dirname(filePath),
path.resolve(process.cwd(), 'out/src/platform/node') path.resolve(process.cwd(), 'out/src/platform/node'),
); );
platformRelativepath = platformRelativepath.replace(/\\/g, '/'); platformRelativepath = platformRelativepath.replace(/\\/g, '/');
f.contents = Buffer.from( f.contents = Buffer.from(
contents.replace( contents.replace(
/\(\"platform\/([^"]*)\"\)/g, /\(\"platform\/([^"]*)\"\)/g,
'("' + (platformRelativepath === '' ? './' : platformRelativepath + '/') + '$1")' '("' + (platformRelativepath === '' ? './' : platformRelativepath + '/') + '$1")',
), ),
'utf8' 'utf8',
); );
return f; return f;
}) }),
); );
return es.duplex(input, output); return es.duplex(input, output);
} }
@ -108,7 +108,7 @@ gulp.task('webpack', function () {
config: webpack_config, config: webpack_config,
entry: ['./extension.ts', './extensionWeb.ts'], entry: ['./extension.ts', './extensionWeb.ts'],
}, },
webpack webpack,
).pipe(gulp.dest('out')); ).pipe(gulp.dest('out'));
}); });
@ -118,7 +118,7 @@ gulp.task('webpack-dev', function () {
config: webpack_dev_config, config: webpack_dev_config,
entry: ['./extension.ts'], entry: ['./extension.ts'],
}, },
webpack webpack,
).pipe(gulp.dest('out')); ).pipe(gulp.dest('out'));
}); });
@ -148,7 +148,7 @@ gulp.task('run-test', function (done) {
{ {
cwd: process.cwd(), cwd: process.cwd(),
stdio: 'inherit', stdio: 'inherit',
} },
); );
dockerBuildCmd.on('exit', function (exitCode) { dockerBuildCmd.on('exit', function (exitCode) {
@ -156,7 +156,7 @@ gulp.task('run-test', function (done) {
return done( return done(
new PluginError('test', { new PluginError('test', {
message: 'Docker build failed.', message: 'Docker build failed.',
}) }),
); );
} }

View File

@ -1184,7 +1184,7 @@
"minimist": "1.2.8", "minimist": "1.2.8",
"mocha": "10.2.0", "mocha": "10.2.0",
"plugin-error": "2.0.1", "plugin-error": "2.0.1",
"prettier": "2.8.8", "prettier": "3.0.0",
"sinon": "15.2.0", "sinon": "15.2.0",
"ts-loader": "9.4.4", "ts-loader": "9.4.4",
"tslint": "6.1.3", "tslint": "6.1.3",

View File

@ -95,7 +95,7 @@ export abstract class BaseAction implements IBaseAction {
public static CompareKeypressSequence( public static CompareKeypressSequence(
one: readonly string[] | readonly string[][], one: readonly string[] | readonly string[][],
two: readonly string[] two: readonly string[],
): boolean { ): boolean {
if (BaseAction.is2DArray(one)) { if (BaseAction.is2DArray(one)) {
for (const sequence of one) { for (const sequence of one) {
@ -206,7 +206,7 @@ export abstract class BaseCommand extends BaseAction {
a.start.line > b.start.line || a.start.line > b.start.line ||
(a.start.line === b.start.line && a.start.character > b.start.character) (a.start.line === b.start.line && a.start.character > b.start.character)
? 1 ? 1
: -1 : -1,
); );
let cursorIndex = 0; let cursorIndex = 0;
@ -255,7 +255,7 @@ const actionMap = new Map<Mode, Array<new () => BaseAction>>();
*/ */
export function getRelevantAction( export function getRelevantAction(
keysPressed: string[], keysPressed: string[],
vimState: VimState vimState: VimState,
): BaseAction | KeypressState { ): BaseAction | KeypressState {
const possibleActionsForMode = actionMap.get(vimState.currentMode) ?? []; const possibleActionsForMode = actionMap.get(vimState.currentMode) ?? [];

View File

@ -84,7 +84,7 @@ export abstract class BaseMovement extends BaseAction {
position: Position, position: Position,
vimState: VimState, vimState: VimState,
firstIteration: boolean, firstIteration: boolean,
lastIteration: boolean lastIteration: boolean,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
throw new Error('Not implemented!'); throw new Error('Not implemented!');
} }
@ -98,7 +98,7 @@ export abstract class BaseMovement extends BaseAction {
position: Position, position: Position,
vimState: VimState, vimState: VimState,
firstIteration: boolean, firstIteration: boolean,
lastIteration: boolean lastIteration: boolean,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
return this.execAction(position, vimState, firstIteration, lastIteration); return this.execAction(position, vimState, firstIteration, lastIteration);
} }
@ -111,7 +111,7 @@ export abstract class BaseMovement extends BaseAction {
public async execActionWithCount( public async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
let result!: Position | IMovement; let result!: Position | IMovement;
let prevResult = failedMovement(vimState); let prevResult = failedMovement(vimState);

View File

@ -85,7 +85,7 @@ export class DocumentContentChangeAction extends BaseCommand {
const linesAffected = change.range.end.line - change.range.start.line + 1; const linesAffected = change.range.end.line - change.range.start.line + 1;
const resultLines = change.text.split('\n').length; const resultLines = change.text.split('\n').length;
originalLeftBoundary = originalLeftBoundary.with( originalLeftBoundary = originalLeftBoundary.with(
Math.max(0, originalLeftBoundary.line + resultLines - linesAffected) Math.max(0, originalLeftBoundary.line + resultLines - linesAffected),
); );
continue; continue;
} }
@ -103,7 +103,7 @@ export class DocumentContentChangeAction extends BaseCommand {
const replaceRange = new vscode.Range( const replaceRange = new vscode.Range(
translate(change.range.start), translate(change.range.start),
translate(change.range.end) translate(change.range.end),
); );
if (replaceRange.start.isAfter(rightBoundary)) { if (replaceRange.start.isAfter(rightBoundary)) {
@ -125,13 +125,13 @@ export class DocumentContentChangeAction extends BaseCommand {
vimState.recordedState.transformer.insert( vimState.recordedState.transformer.insert(
replaceRange.start, replaceRange.start,
change.text, change.text,
PositionDiff.exactPosition(translate(this.cursorEnd)) PositionDiff.exactPosition(translate(this.cursorEnd)),
); );
} else { } else {
vimState.recordedState.transformer.replace( vimState.recordedState.transformer.replace(
replaceRange, replaceRange,
change.text, change.text,
PositionDiff.exactPosition(translate(this.cursorEnd)) PositionDiff.exactPosition(translate(this.cursorEnd)),
); );
} }
} }
@ -140,7 +140,7 @@ export class DocumentContentChangeAction extends BaseCommand {
private compressChanges(): void { private compressChanges(): void {
function merge( function merge(
first: vscode.TextDocumentContentChangeEvent, first: vscode.TextDocumentContentChangeEvent,
second: vscode.TextDocumentContentChangeEvent second: vscode.TextDocumentContentChangeEvent,
): vscode.TextDocumentContentChangeEvent | undefined { ): vscode.TextDocumentContentChangeEvent | undefined {
if (first.rangeOffset + first.text.length === second.rangeOffset) { if (first.rangeOffset + first.text.length === second.rangeOffset) {
// Simple concatenation // Simple concatenation
@ -400,7 +400,7 @@ class CommandExecuteMacro extends BaseCommand {
if (!Register.isValidRegister(register) || isFilenameRegister) { if (!Register.isValidRegister(register) || isFilenameRegister) {
StatusBar.displayError( StatusBar.displayError(
vimState, vimState,
VimError.fromCode(ErrorCode.InvalidRegisterName, `'${register}'`) VimError.fromCode(ErrorCode.InvalidRegisterName, `'${register}'`),
); );
} }
@ -534,8 +534,8 @@ class CommandOverrideCopy extends BaseCommand {
return vimState.document.getText( return vimState.document.getText(
new vscode.Range( new vscode.Range(
earlierOf(range.start.getLineBegin(), range.stop.getLineBegin()), earlierOf(range.start.getLineBegin(), range.stop.getLineBegin()),
laterOf(range.start.getLineEnd(), range.stop.getLineEnd()) laterOf(range.start.getLineEnd(), range.stop.getLineEnd()),
) ),
); );
}) })
.join('\n'); .join('\n');
@ -572,7 +572,7 @@ class CommandCmdA extends BaseCommand {
vimState.cursorStartPosition = new Position(0, vimState.desiredColumn); vimState.cursorStartPosition = new Position(0, vimState.desiredColumn);
vimState.cursorStopPosition = new Position( vimState.cursorStopPosition = new Position(
vimState.document.lineCount - 1, vimState.document.lineCount - 1,
vimState.desiredColumn vimState.desiredColumn,
); );
await vimState.setCurrentMode(Mode.VisualLine); await vimState.setCurrentMode(Mode.VisualLine);
} }
@ -677,13 +677,13 @@ export class CommandShowSearchHistory extends BaseCommand {
const nextMatch = searchState.getNextSearchMatchPosition( const nextMatch = searchState.getNextSearchMatchPosition(
vimState, vimState,
vimState.cursorStartPosition, vimState.cursorStartPosition,
this.direction this.direction,
); );
if (!nextMatch) { if (!nextMatch) {
throw VimError.fromCode( throw VimError.fromCode(
this.direction > 0 ? ErrorCode.SearchHitBottom : ErrorCode.SearchHitTop, this.direction > 0 ? ErrorCode.SearchHitBottom : ErrorCode.SearchHitTop,
searchState.searchString searchState.searchString,
); );
} }
@ -757,11 +757,11 @@ class CommandGoToOtherSideOfHighlightedText extends BaseCommand {
[vimState.cursorStartPosition, vimState.cursorStopPosition] = [ [vimState.cursorStartPosition, vimState.cursorStopPosition] = [
new vscode.Position( new vscode.Position(
vimState.cursorStartPosition.line, vimState.cursorStartPosition.line,
vimState.cursorStopPosition.character vimState.cursorStopPosition.character,
), ),
new vscode.Position( new vscode.Position(
vimState.cursorStopPosition.line, vimState.cursorStopPosition.line,
vimState.cursorStartPosition.character vimState.cursorStartPosition.character,
), ),
]; ];
} else { } else {
@ -881,7 +881,7 @@ class CommandChangeToLineEnd extends BaseCommand {
position position
.getDown(Math.max(0, count - 1)) .getDown(Math.max(0, count - 1))
.getLineEnd() .getLineEnd()
.getLeft() .getLeft(),
); );
} }
} }
@ -896,7 +896,7 @@ class CommandClearLine extends BaseCommand {
await new operator.ChangeOperator(this.multicursorIndex).runRepeat( await new operator.ChangeOperator(this.multicursorIndex).runRepeat(
vimState, vimState,
position, position,
vimState.recordedState.count || 1 vimState.recordedState.count || 1,
); );
} }
@ -1016,7 +1016,7 @@ class CommandOpenFile extends BaseCommand {
} else { } else {
const range = new vscode.Range( const range = new vscode.Range(
position.prevWordStart(vimState.document, { wordType: WordType.FileName, inclusive: true }), position.prevWordStart(vimState.document, { wordType: WordType.FileName, inclusive: true }),
position.nextWordStart(vimState.document, { wordType: WordType.FileName }) position.nextWordStart(vimState.document, { wordType: WordType.FileName }),
); );
fullFilePath = vimState.document.getText(range).trim(); fullFilePath = vimState.document.getText(range).trim();
@ -1257,7 +1257,7 @@ export class CommandInsertNewLineBefore extends BaseCommand {
for (let i = 1; i < count; i++) { for (let i = 1; i < count; i++) {
const newPos = new Position( const newPos = new Position(
vimState.cursorStartPosition.line - i, vimState.cursorStartPosition.line - i,
vimState.cursorStartPosition.character vimState.cursorStartPosition.character,
); );
vimState.cursors.push(new Cursor(newPos, newPos)); vimState.cursors.push(new Cursor(newPos, newPos));
@ -1360,7 +1360,7 @@ export class ActionDeleteChar extends BaseCommand {
await new operator.DeleteOperator(this.multicursorIndex).run( await new operator.DeleteOperator(this.multicursorIndex).run(
vimState, vimState,
position, position,
position.getRight(timesToRepeat - 1).getLeftIfEOL() position.getRight(timesToRepeat - 1).getLeftIfEOL(),
); );
await vimState.setCurrentMode(Mode.Normal); await vimState.setCurrentMode(Mode.Normal);
@ -1409,7 +1409,7 @@ export class ActionDeleteLastChar extends BaseCommand {
await new operator.DeleteOperator(this.multicursorIndex).run( await new operator.DeleteOperator(this.multicursorIndex).run(
vimState, vimState,
position.getLeft(timesToRepeat), position.getLeft(timesToRepeat),
position.getLeft() position.getLeft(),
); );
} }
} }
@ -1435,7 +1435,7 @@ class ActionJoin extends BaseCommand {
startPosition: Position, startPosition: Position,
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<void> { ): Promise<void> {
count = count - 1 || 1; count = count - 1 || 1;
@ -1531,7 +1531,7 @@ class ActionJoin extends BaseCommand {
vimState.cursorStartPosition = vimState.cursorStopPosition = new Position( vimState.cursorStartPosition = vimState.cursorStopPosition = new Position(
startPosition.line, startPosition.line,
trimmedLinesContent.length - columnDeltaOffset trimmedLinesContent.length - columnDeltaOffset,
); );
await vimState.setCurrentMode(Mode.Normal); await vimState.setCurrentMode(Mode.Normal);
} }
@ -1545,7 +1545,7 @@ class ActionJoin extends BaseCommand {
a.start.line > b.start.line || a.start.line > b.start.line ||
(a.start.line === b.start.line && a.start.character > b.start.character) (a.start.line === b.start.line && a.start.character > b.start.character)
? 1 ? 1
: -1 : -1,
); );
const resultingCursors: Cursor[] = []; const resultingCursors: Cursor[] = [];
@ -1619,7 +1619,10 @@ class ActionJoinNoWhitespace extends BaseCommand {
public async execJoin(count: number, position: Position, vimState: VimState): Promise<void> { public async execJoin(count: number, position: Position, vimState: VimState): Promise<void> {
const replaceRange = new vscode.Range( const replaceRange = new vscode.Range(
new Position(position.line, 0), new Position(position.line, 0),
new Position(Math.min(position.line + count, vimState.document.lineCount - 1), 0).getLineEnd() new Position(
Math.min(position.line + count, vimState.document.lineCount - 1),
0,
).getLineEnd(),
); );
const joinedText = vimState.document.getText(replaceRange).replace(/\r?\n/g, ''); const joinedText = vimState.document.getText(replaceRange).replace(/\r?\n/g, '');
@ -1693,7 +1696,7 @@ class ActionReplaceCharacter extends BaseCommand {
vimState.recordedState.transformer.vscodeCommand('tab'); vimState.recordedState.transformer.vscodeCommand('tab');
vimState.recordedState.transformer.moveCursor( vimState.recordedState.transformer.moveCursor(
PositionDiff.offset({ character: -1 }), PositionDiff.offset({ character: -1 }),
this.multicursorIndex this.multicursorIndex,
); );
} else if (toReplace === '\n') { } else if (toReplace === '\n') {
// A newline replacement always inserts exactly one newline (regardless // A newline replacement always inserts exactly one newline (regardless
@ -1774,7 +1777,7 @@ class ActionReplaceCharacterVisual extends BaseCommand {
text: Array(end.character + 1 + visualSelectionOffset).join(toInsert), text: Array(end.character + 1 + visualSelectionOffset).join(toInsert),
range: new vscode.Range( range: new vscode.Range(
new Position(end.line, 0), new Position(end.line, 0),
new Position(end.line, end.character + visualSelectionOffset) new Position(end.line, end.character + visualSelectionOffset),
), ),
manuallySetCursorPositions: true, manuallySetCursorPositions: true,
}); });
@ -1826,7 +1829,7 @@ class ActionReplaceCharacterVisualBlock extends BaseCommand {
const topLeft = visualBlockGetTopLeftPosition( const topLeft = visualBlockGetTopLeftPosition(
vimState.cursorStopPosition, vimState.cursorStopPosition,
vimState.cursorStartPosition vimState.cursorStartPosition,
); );
vimState.cursors = [new Cursor(topLeft, topLeft)]; vimState.cursors = [new Cursor(topLeft, topLeft)];
await vimState.setCurrentMode(Mode.Normal); await vimState.setCurrentMode(Mode.Normal);
@ -1860,7 +1863,7 @@ class ActionDeleteVisualBlock extends BaseCommand {
const topLeft = visualBlockGetTopLeftPosition( const topLeft = visualBlockGetTopLeftPosition(
vimState.cursorStopPosition, vimState.cursorStopPosition,
vimState.cursorStartPosition vimState.cursorStartPosition,
); );
vimState.cursors = [new Cursor(topLeft, topLeft)]; vimState.cursors = [new Cursor(topLeft, topLeft)];
@ -1891,7 +1894,7 @@ class ActionShiftDVisualBlock extends BaseCommand {
const topLeft = visualBlockGetTopLeftPosition( const topLeft = visualBlockGetTopLeftPosition(
vimState.cursorStopPosition, vimState.cursorStopPosition,
vimState.cursorStartPosition vimState.cursorStartPosition,
); );
const text = lines.length === 1 ? lines[0] : lines.join('\n'); const text = lines.length === 1 ? lines[0] : lines.join('\n');
@ -1997,7 +2000,7 @@ abstract class ActionGoToInsertVisualLineModeCommand extends BaseCommand {
abstract getCursorRangeForLine( abstract getCursorRangeForLine(
line: vscode.TextLine, line: vscode.TextLine,
selectionStart: Position, selectionStart: Position,
selectionEnd: Position selectionEnd: Position,
): Cursor; ): Cursor;
public override async exec(position: Position, vimState: VimState): Promise<void> { public override async exec(position: Position, vimState: VimState): Promise<void> {
@ -2037,7 +2040,7 @@ class ActionGoToInsertVisualLineMode extends ActionGoToInsertVisualLineModeComma
getCursorRangeForLine(line: vscode.TextLine): Cursor { getCursorRangeForLine(line: vscode.TextLine): Cursor {
const startCharacterPosition = new Position( const startCharacterPosition = new Position(
line.lineNumber, line.lineNumber,
line.firstNonWhitespaceCharacterIndex line.firstNonWhitespaceCharacterIndex,
); );
return new Cursor(startCharacterPosition, startCharacterPosition); return new Cursor(startCharacterPosition, startCharacterPosition);
} }
@ -2062,7 +2065,7 @@ class ActionGoToInsertVisualMode extends ActionGoToInsertVisualLineModeCommand {
getCursorRangeForLine( getCursorRangeForLine(
line: vscode.TextLine, line: vscode.TextLine,
selectionStart: Position, selectionStart: Position,
selectionEnd: Position selectionEnd: Position,
): Cursor { ): Cursor {
const startCharacterPosition = const startCharacterPosition =
line.lineNumber === selectionStart.line line.lineNumber === selectionStart.line
@ -2080,7 +2083,7 @@ class ActionGoToInsertVisualModeAppend extends ActionGoToInsertVisualLineModeCom
getCursorRangeForLine( getCursorRangeForLine(
line: vscode.TextLine, line: vscode.TextLine,
selectionStart: Position, selectionStart: Position,
selectionEnd: Position selectionEnd: Position,
): Cursor { ): Cursor {
const endCharacterPosition = const endCharacterPosition =
line.lineNumber === selectionEnd.line line.lineNumber === selectionEnd.line
@ -2113,7 +2116,7 @@ class ActionGoToInsertVisualBlockModeAppend extends BaseCommand {
vimState.editor, vimState.editor,
' '.repeat(insertionColumn - line.text.length), ' '.repeat(insertionColumn - line.text.length),
line.range.end, line.range.end,
false false,
); );
} }
const newCursor = new Position(lineNum, insertionColumn); const newCursor = new Position(lineNum, insertionColumn);
@ -2138,7 +2141,7 @@ export class ActionDeleteCharVisualLineMode extends BaseCommand {
await new operator.DeleteOperator(this.multicursorIndex).run( await new operator.DeleteOperator(this.multicursorIndex).run(
vimState, vimState,
start.getLineBegin(), start.getLineBegin(),
end.getLineEnd() end.getLineEnd(),
); );
} }
} }
@ -2153,7 +2156,7 @@ class ActionDeleteLineVisualMode extends BaseCommand {
await new operator.DeleteOperator(this.multicursorIndex).run( await new operator.DeleteOperator(this.multicursorIndex).run(
vimState, vimState,
start.getLineBegin(), start.getLineBegin(),
end.getLineEnd() end.getLineEnd(),
); );
} }
} }
@ -2182,7 +2185,7 @@ class ActionChangeLineVisualMode extends BaseCommand {
await new operator.ChangeOperator(this.multicursorIndex).run( await new operator.ChangeOperator(this.multicursorIndex).run(
vimState, vimState,
start.getLineBegin(), start.getLineBegin(),
end.getLineEnd().getLeftIfEOL() end.getLineEnd().getLeftIfEOL(),
); );
} }
} }
@ -2206,7 +2209,7 @@ class ActionChangeChar extends BaseCommand {
await new operator.ChangeOperator(this.multicursorIndex).run( await new operator.ChangeOperator(this.multicursorIndex).run(
vimState, vimState,
position, position,
position.getRight((vimState.recordedState.count || 1) - 1) position.getRight((vimState.recordedState.count || 1) - 1),
); );
} }
@ -2252,7 +2255,7 @@ class ToggleCaseAndMoveForward extends BaseCommand {
position, position,
shouldWrapKey(vimState.currentMode, '~') shouldWrapKey(vimState.currentMode, '~')
? position.getOffsetThroughLineBreaks(count) ? position.getOffsetThroughLineBreaks(count)
: position.getRight(count) : position.getRight(count),
); );
vimState.recordedState.transformer.addTransformation({ vimState.recordedState.transformer.addTransformation({
@ -2294,7 +2297,7 @@ abstract class IncrementDecrementNumberAction extends BaseCommand {
wordLoop: for (let { start, end, word } of TextEditor.iterateWords( wordLoop: for (let { start, end, word } of TextEditor.iterateWords(
vimState.document, vimState.document,
whereToStart whereToStart,
)) { )) {
if (start.isAfter(range.stop)) { if (start.isAfter(range.stop)) {
break; break;
@ -2321,7 +2324,7 @@ abstract class IncrementDecrementNumberAction extends BaseCommand {
num, num,
this.offset * stepNum * (vimState.recordedState.count || 1), this.offset * stepNum * (vimState.recordedState.count || 1),
start, start,
end end,
); );
if (this.staircase) { if (this.staircase) {
@ -2330,7 +2333,7 @@ abstract class IncrementDecrementNumberAction extends BaseCommand {
if (vimState.currentMode === Mode.Normal) { if (vimState.currentMode === Mode.Normal) {
vimState.recordedState.transformer.moveCursor( vimState.recordedState.transformer.moveCursor(
PositionDiff.exactPosition(pos.getLeft(num.suffix.length)) PositionDiff.exactPosition(pos.getLeft(num.suffix.length)),
); );
} }
break wordLoop; break wordLoop;
@ -2355,7 +2358,7 @@ abstract class IncrementDecrementNumberAction extends BaseCommand {
start: NumericString, start: NumericString,
offset: number, offset: number,
startPos: Position, startPos: Position,
endPos: Position endPos: Position,
): Promise<Position> { ): Promise<Position> {
const oldLength = endPos.character + 1 - startPos.character; const oldLength = endPos.character + 1 - startPos.character;
start.value += offset; start.value += offset;
@ -2381,7 +2384,7 @@ abstract class IncrementDecrementNumberAction extends BaseCommand {
switch (vimState.currentMode) { switch (vimState.currentMode) {
case Mode.Normal: { case Mode.Normal: {
ranges.push( ranges.push(
new Cursor(vimState.cursorStopPosition, vimState.cursorStopPosition.getLineEnd()) new Cursor(vimState.cursorStopPosition, vimState.cursorStopPosition.getLineEnd()),
); );
break; break;
} }
@ -2411,8 +2414,8 @@ abstract class IncrementDecrementNumberAction extends BaseCommand {
ranges.push( ranges.push(
new Cursor( new Cursor(
new Position(line, topLeft.character), new Position(line, topLeft.character),
new Position(line, bottomRight.character) new Position(line, bottomRight.character),
) ),
); );
} }
break; break;
@ -2420,7 +2423,7 @@ abstract class IncrementDecrementNumberAction extends BaseCommand {
default: default:
throw new Error( throw new Error(
`Unexpected mode ${vimState.currentMode} in IncrementDecrementNumberAction.getPositions()` `Unexpected mode ${vimState.currentMode} in IncrementDecrementNumberAction.getPositions()`,
); );
} }
return ranges; return ranges;
@ -2469,7 +2472,7 @@ export class CommandUnicodeName extends BaseCommand {
// TODO: Handle charCode > 127 by also including <M-x> // TODO: Handle charCode > 127 by also including <M-x>
StatusBar.setText( StatusBar.setText(
vimState, vimState,
`<${char}> ${charCode}, Hex ${charCode.toString(16)}, Octal ${charCode.toString(8)}` `<${char}> ${charCode}, Hex ${charCode.toString(16)}, Octal ${charCode.toString(8)}`,
); );
} }
} }
@ -2537,7 +2540,7 @@ class ActionOverrideCmdDInsert extends BaseCommand {
if (idx === 0) { if (idx === 0) {
return new vscode.Selection( return new vscode.Selection(
curPos.prevWordStart(vimState.document), curPos.prevWordStart(vimState.document),
curPos.getLeft().nextWordEnd(vimState.document, { inclusive: true }).getRight() curPos.getLeft().nextWordEnd(vimState.document, { inclusive: true }).getRight(),
); );
} else { } else {
// Since we're adding the selections ourselves, we need to make sure // Since we're adding the selections ourselves, we need to make sure

View File

@ -119,11 +119,11 @@ class CommandLineTab extends CommandLineAction {
p.sep, p.sep,
currentUri, currentUri,
isRemote, isRemote,
shouldAddDotItems shouldAddDotItems,
); );
const startWithBaseNameRegex = new RegExp( const startWithBaseNameRegex = new RegExp(
`^${baseName}`, `^${baseName}`,
process.platform === 'win32' ? 'i' : '' process.platform === 'win32' ? 'i' : '',
); );
newCompletionItems = dirItems newCompletionItems = dirItems
.map((name): [RegExpExecArray | null, string] => [startWithBaseNameRegex.exec(name), name]) .map((name): [RegExpExecArray | null, string] => [startWithBaseNameRegex.exec(name), name])
@ -298,7 +298,7 @@ class CommandInsertRegisterContentInCommandLine extends CommandLineAction {
if (register === undefined) { if (register === undefined) {
StatusBar.displayError( StatusBar.displayError(
vimState, vimState,
VimError.fromCode(ErrorCode.NothingInRegister, vimState.recordedState.registerName) VimError.fromCode(ErrorCode.NothingInRegister, vimState.recordedState.registerName),
); );
return; return;
} }

View File

@ -77,7 +77,7 @@ export class CommandEscInsertMode extends BaseCommand {
a instanceof CommandInsertAtLineBegin || a instanceof CommandInsertAtLineBegin ||
a instanceof CommandInsertAtLineEnd || a instanceof CommandInsertAtLineEnd ||
a instanceof CommandInsertAtFirstCharacter || a instanceof CommandInsertAtFirstCharacter ||
a instanceof CommandInsertAtLastChange a instanceof CommandInsertAtLastChange,
) !== undefined; ) !== undefined;
// If this is the type to repeat insert, do this now // If this is the type to repeat insert, do this now
@ -98,7 +98,7 @@ export class CommandEscInsertMode extends BaseCommand {
// Add a transform containing the change // Add a transform containing the change
vimState.recordedState.transformer.addTransformation( vimState.recordedState.transformer.addTransformation(
changeAction.getTransformation(positionDiff) changeAction.getTransformation(positionDiff),
); );
} }
} }
@ -177,13 +177,13 @@ abstract class IndentCommand extends BaseCommand {
vimState.recordedState.transformer.replace( vimState.recordedState.transformer.replace(
new vscode.Range( new vscode.Range(
position.getLineBegin(), position.getLineBegin(),
position.with({ character: line.firstNonWhitespaceCharacterIndex }) position.with({ character: line.firstNonWhitespaceCharacterIndex }),
), ),
TextEditor.setIndentationLevel( TextEditor.setIndentationLevel(
line.text, line.text,
newIndentationWidth, newIndentationWidth,
vimState.editor.options.insertSpaces as boolean vimState.editor.options.insertSpaces as boolean,
).match(/^(\s*)/)![1] ).match(/^(\s*)/)![1],
); );
} }
} }
@ -342,7 +342,7 @@ class CommandInsertRegisterContent extends BaseCommand {
if (register === undefined) { if (register === undefined) {
StatusBar.displayError( StatusBar.displayError(
vimState, vimState,
VimError.fromCode(ErrorCode.NothingInRegister, this.keysPressed[1]) VimError.fromCode(ErrorCode.NothingInRegister, this.keysPressed[1]),
); );
return; return;
} }
@ -530,7 +530,7 @@ class NewLineInsertMode extends BaseCommand {
vimState.recordedState.transformer.insert( vimState.recordedState.transformer.insert(
position, position,
'\n', '\n',
PositionDiff.offset({ character: -1 }) PositionDiff.offset({ character: -1 }),
); );
} }
} }

View File

@ -29,7 +29,7 @@ abstract class BasePutCommand extends BaseCommand {
if (register === undefined) { if (register === undefined) {
StatusBar.displayError( StatusBar.displayError(
vimState, vimState,
VimError.fromCode(ErrorCode.NothingInRegister, vimState.recordedState.registerName) VimError.fromCode(ErrorCode.NothingInRegister, vimState.recordedState.registerName),
); );
return; return;
} }
@ -57,7 +57,7 @@ abstract class BasePutCommand extends BaseCommand {
} }
text = this.adjustIndent( text = this.adjustIndent(
lineToMatch !== undefined ? vimState.document.lineAt(lineToMatch).text : '', lineToMatch !== undefined ? vimState.document.lineAt(lineToMatch).text : '',
text text,
); );
} }
@ -67,12 +67,12 @@ abstract class BasePutCommand extends BaseCommand {
replaceRange, replaceRange,
registerMode, registerMode,
count, count,
text text,
); );
vimState.recordedState.transformer.moveCursor( vimState.recordedState.transformer.moveCursor(
PositionDiff.exactPosition(newCursorPosition), PositionDiff.exactPosition(newCursorPosition),
this.multicursorIndex ?? 0 this.multicursorIndex ?? 0,
); );
if (registerMode === RegisterMode.LineWise) { if (registerMode === RegisterMode.LineWise) {
@ -84,7 +84,7 @@ abstract class BasePutCommand extends BaseCommand {
mode, mode,
replaceRange, replaceRange,
registerMode, registerMode,
text text,
)) { )) {
vimState.recordedState.transformer.addTransformation(transformation); vimState.recordedState.transformer.addTransformation(transformation);
} }
@ -104,7 +104,7 @@ abstract class BasePutCommand extends BaseCommand {
vimState, vimState,
vimState.document.getText(replaceRange), vimState.document.getText(replaceRange),
this.multicursorIndex, this.multicursorIndex,
true true,
); );
} }
} }
@ -178,7 +178,7 @@ abstract class BasePutCommand extends BaseCommand {
mode: Mode, mode: Mode,
replaceRange: vscode.Range, replaceRange: vscode.Range,
registerMode: RegisterMode, registerMode: RegisterMode,
text: string text: string,
): Transformation[] { ): Transformation[] {
// Pasting block-wise content is very different, except in VisualLine mode, where it works exactly like line-wise // Pasting block-wise content is very different, except in VisualLine mode, where it works exactly like line-wise
if (registerMode === RegisterMode.BlockWise && mode !== Mode.VisualLine) { if (registerMode === RegisterMode.BlockWise && mode !== Mode.VisualLine) {
@ -202,7 +202,7 @@ abstract class BasePutCommand extends BaseCommand {
} else { } else {
range = new vscode.Range( range = new vscode.Range(
replaceRange.start.with({ line: replaceRange.start.line + idx }), replaceRange.start.with({ line: replaceRange.start.line + idx }),
replaceRange.end.with({ line: replaceRange.start.line + idx }) replaceRange.end.with({ line: replaceRange.start.line + idx }),
); );
} }
} else { } else {
@ -259,7 +259,7 @@ abstract class BasePutCommand extends BaseCommand {
for (let line = replaceRange.start.line; line <= replaceRange.end.line; line++) { for (let line = replaceRange.start.line; line <= replaceRange.end.line; line++) {
const range = new vscode.Range( const range = new vscode.Range(
new Position(line, replaceRange.start.character), new Position(line, replaceRange.start.character),
new Position(line, replaceRange.end.character) new Position(line, replaceRange.end.character),
); );
const lineText = !text.includes('\n') || line === replaceRange.start.line ? text : ''; const lineText = !text.includes('\n') || line === replaceRange.start.line ? text : '';
transformations.push({ transformations.push({
@ -273,7 +273,7 @@ abstract class BasePutCommand extends BaseCommand {
for (let line = replaceRange.start.line; line <= replaceRange.end.line; line++) { for (let line = replaceRange.start.line; line <= replaceRange.end.line; line++) {
const range = new vscode.Range( const range = new vscode.Range(
new Position(line, replaceRange.start.character), new Position(line, replaceRange.start.character),
new Position(line, replaceRange.end.character) new Position(line, replaceRange.end.character),
); );
transformations.push({ transformations.push({
type: 'replaceText', type: 'replaceText',
@ -307,7 +307,7 @@ abstract class BasePutCommand extends BaseCommand {
protected abstract getReplaceRange( protected abstract getReplaceRange(
mode: Mode, mode: Mode,
cursor: Cursor, cursor: Cursor,
registerMode: RegisterMode registerMode: RegisterMode,
): vscode.Range; ): vscode.Range;
protected abstract adjustLinewiseRegisterText(mode: Mode, text: string): string; protected abstract adjustLinewiseRegisterText(mode: Mode, text: string): string;
@ -320,7 +320,7 @@ abstract class BasePutCommand extends BaseCommand {
replaceRange: vscode.Range, replaceRange: vscode.Range,
registerMode: RegisterMode, registerMode: RegisterMode,
count: number, count: number,
text: string text: string,
): Position; ): Position;
} }
@ -379,7 +379,7 @@ class PutCommand extends BasePutCommand {
replaceRange: vscode.Range, replaceRange: vscode.Range,
registerMode: RegisterMode, registerMode: RegisterMode,
count: number, count: number,
text: string text: string,
): Position { ): Position {
const rangeStart = replaceRange.start; const rangeStart = replaceRange.start;
if (mode === Mode.Normal || mode === Mode.Visual) { if (mode === Mode.Normal || mode === Mode.Visual) {
@ -430,7 +430,7 @@ class PutBeforeCommand extends PutCommand {
protected override getReplaceRange( protected override getReplaceRange(
mode: Mode, mode: Mode,
cursor: Cursor, cursor: Cursor,
registerMode: RegisterMode registerMode: RegisterMode,
): vscode.Range { ): vscode.Range {
if (mode === Mode.Normal) { if (mode === Mode.Normal) {
if (registerMode === RegisterMode.CharacterWise || registerMode === RegisterMode.BlockWise) { if (registerMode === RegisterMode.CharacterWise || registerMode === RegisterMode.BlockWise) {
@ -451,7 +451,7 @@ class PutBeforeCommand extends PutCommand {
replaceRange: vscode.Range, replaceRange: vscode.Range,
registerMode: RegisterMode, registerMode: RegisterMode,
count: number, count: number,
text: string text: string,
): Position { ): Position {
const rangeStart = replaceRange.start; const rangeStart = replaceRange.start;
if (mode === Mode.Normal || mode === Mode.VisualBlock) { if (mode === Mode.Normal || mode === Mode.VisualBlock) {
@ -472,7 +472,7 @@ function PlaceCursorAfterText<TBase extends new (...args: any[]) => PutCommand>(
replaceRange: vscode.Range, replaceRange: vscode.Range,
registerMode: RegisterMode, registerMode: RegisterMode,
count: number, count: number,
text: string text: string,
): Position { ): Position {
const rangeStart = replaceRange.start; const rangeStart = replaceRange.start;
if (mode === Mode.Normal || mode === Mode.Visual) { if (mode === Mode.Normal || mode === Mode.Visual) {
@ -511,7 +511,7 @@ function PlaceCursorAfterText<TBase extends new (...args: any[]) => PutCommand>(
} else if (registerMode === RegisterMode.BlockWise) { } else if (registerMode === RegisterMode.BlockWise) {
return new Position( return new Position(
replaceRange.start.line + lines.length - 1, replaceRange.start.line + lines.length - 1,
replaceRange.start.character + lines[lines.length - 1].length replaceRange.start.character + lines[lines.length - 1].length,
); );
} else { } else {
return rangeStart.with({ character: rangeStart.character + text.length }); return rangeStart.with({ character: rangeStart.character + text.length });
@ -577,7 +577,7 @@ function ExCommand<TBase extends new (...args: any[]) => PutCommand>(Base: TBase
protected override getReplaceRange( protected override getReplaceRange(
mode: Mode, mode: Mode,
cursor: Cursor, cursor: Cursor,
registerMode: RegisterMode registerMode: RegisterMode,
): vscode.Range { ): vscode.Range {
const line = this.insertLine ?? laterOf(cursor.start, cursor.stop).line; const line = this.insertLine ?? laterOf(cursor.start, cursor.stop).line;
const pos = this.putBefore() ? new Position(line, 0) : new Position(line, 0).getLineEnd(); const pos = this.putBefore() ? new Position(line, 0) : new Position(line, 0).getLineEnd();
@ -590,12 +590,12 @@ function ExCommand<TBase extends new (...args: any[]) => PutCommand>(Base: TBase
replaceRange: vscode.Range, replaceRange: vscode.Range,
registerMode: RegisterMode, registerMode: RegisterMode,
count: number, count: number,
text: string text: string,
): Position { ): Position {
const lines = text.split('\n'); const lines = text.split('\n');
return new Position( return new Position(
replaceRange.start.line + lines.length - (this.putBefore() ? 1 : 0), replaceRange.start.line + lines.length - (this.putBefore() ? 1 : 0),
firstNonBlankChar(lines[lines.length - 1]) firstNonBlankChar(lines[lines.length - 1]),
); );
} }
}; };

View File

@ -27,7 +27,7 @@ class ExitReplaceMode extends BaseCommand {
.repeat(timesToRepeat - 1); .repeat(timesToRepeat - 1);
vimState.recordedState.transformer.replace( vimState.recordedState.transformer.replace(
new Range(position, position.getRight(newText.length)), new Range(position, position.getRight(newText.length)),
newText newText,
); );
} else { } else {
vimState.cursorStopPosition = vimState.cursorStopPosition.getLeft(); vimState.cursorStopPosition = vimState.cursorStopPosition.getLeft();

View File

@ -98,7 +98,7 @@ abstract class CommandScrollAndMoveCursor extends BaseCommand {
// This makes <C-d> less wonky when `editor.scrollBeyondLastLine` is enabled // This makes <C-d> less wonky when `editor.scrollBeyondLastLine` is enabled
scrollLines = Math.min( scrollLines = Math.min(
moveLines, moveLines,
vimState.document.lineCount - 1 - visibleRanges[visibleRanges.length - 1].end.line vimState.document.lineCount - 1 - visibleRanges[visibleRanges.length - 1].end.line,
); );
} }
@ -123,11 +123,11 @@ abstract class CommandScrollAndMoveCursor extends BaseCommand {
const newPositionLine = clamp( const newPositionLine = clamp(
position.line + (this.to === 'down' ? moveLines : -moveLines), position.line + (this.to === 'down' ? moveLines : -moveLines),
0, 0,
vimState.document.lineCount - 1 vimState.document.lineCount - 1,
); );
vimState.cursorStopPosition = new Position( vimState.cursorStopPosition = new Position(
newPositionLine, newPositionLine,
vimState.desiredColumn vimState.desiredColumn,
).obeyStartOfLine(vimState.document); ).obeyStartOfLine(vimState.document);
} }
} }
@ -190,7 +190,7 @@ class CommandCenterScroll extends BaseCommand {
// In these modes you want to center on the cursor position // In these modes you want to center on the cursor position
vimState.editor.revealRange( vimState.editor.revealRange(
new vscode.Range(vimState.cursorStopPosition, vimState.cursorStopPosition), new vscode.Range(vimState.cursorStopPosition, vimState.cursorStopPosition),
vscode.TextEditorRevealType.InCenter vscode.TextEditorRevealType.InCenter,
); );
} }
} }
@ -212,13 +212,13 @@ class CommandCenterScrollFirstChar extends BaseCommand {
// This particular one moves cursor to first non blank char though // This particular one moves cursor to first non blank char though
vimState.editor.revealRange( vimState.editor.revealRange(
new vscode.Range(vimState.cursorStopPosition, vimState.cursorStopPosition), new vscode.Range(vimState.cursorStopPosition, vimState.cursorStopPosition),
vscode.TextEditorRevealType.InCenter vscode.TextEditorRevealType.InCenter,
); );
// Move cursor to first char of line // Move cursor to first char of line
vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine( vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine(
vimState.document, vimState.document,
vimState.cursorStopPosition.line vimState.cursorStopPosition.line,
); );
} }
} }
@ -274,7 +274,7 @@ class CommandTopScrollFirstChar extends BaseCommand {
// Move cursor to first char of line // Move cursor to first char of line
vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine( vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine(
vimState.document, vimState.document,
vimState.cursorStopPosition.line vimState.cursorStopPosition.line,
); );
} }
} }
@ -330,7 +330,7 @@ class CommandBottomScrollFirstChar extends BaseCommand {
// Move cursor to first char of line // Move cursor to first char of line
vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine( vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine(
vimState.document, vimState.document,
vimState.cursorStopPosition.line vimState.cursorStopPosition.line,
); );
} }
} }

View File

@ -25,7 +25,7 @@ async function searchCurrentWord(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
direction: SearchDirection, direction: SearchDirection,
isExact: boolean isExact: boolean,
): Promise<void> { ): Promise<void> {
let currentWord = TextEditor.getWord(vimState.document, position); let currentWord = TextEditor.getWord(vimState.document, position);
@ -107,7 +107,7 @@ async function createSearchStateAndMoveToMatch(args: {
args.direction, args.direction,
vimState.cursorStopPosition, vimState.cursorStopPosition,
searchString, searchString,
{ ignoreSmartcase: true } { ignoreSmartcase: true },
); );
Register.setReadonlyRegister('/', globalState.searchState.searchString); Register.setReadonlyRegister('/', globalState.searchState.searchString);
SearchCommandLine.addSearchStateToHistory(globalState.searchState); SearchCommandLine.addSearchStateToHistory(globalState.searchState);
@ -117,7 +117,7 @@ async function createSearchStateAndMoveToMatch(args: {
const nextMatch = globalState.searchState.getNextSearchMatchPosition( const nextMatch = globalState.searchState.getNextSearchMatchPosition(
vimState, vimState,
args.searchStartCursorPosition args.searchStartCursorPosition,
); );
if (nextMatch) { if (nextMatch) {
vimState.cursorStopPosition = nextMatch.pos; vimState.cursorStopPosition = nextMatch.pos;
@ -125,7 +125,7 @@ async function createSearchStateAndMoveToMatch(args: {
reportSearch( reportSearch(
nextMatch.index, nextMatch.index,
globalState.searchState.getMatchRanges(vimState).length, globalState.searchState.getMatchRanges(vimState).length,
vimState vimState,
); );
} else { } else {
StatusBar.displayError( StatusBar.displayError(
@ -134,8 +134,8 @@ async function createSearchStateAndMoveToMatch(args: {
args.direction === SearchDirection.Forward args.direction === SearchDirection.Forward
? ErrorCode.SearchHitBottom ? ErrorCode.SearchHitBottom
: ErrorCode.SearchHitTop, : ErrorCode.SearchHitTop,
globalState.searchState.searchString globalState.searchState.searchString,
) ),
); );
} }
} }
@ -249,7 +249,7 @@ abstract class SearchObject extends TextObject {
this.direction, this.direction,
vimState.cursorStopPosition, vimState.cursorStopPosition,
searchState.searchString, searchState.searchString,
{} {},
); );
// At first, try to search for current word, and stop searching if matched. // At first, try to search for current word, and stop searching if matched.
@ -294,7 +294,7 @@ abstract class SearchObject extends TextObject {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<IMovement> { ): Promise<IMovement> {
return this.execAction(position, vimState); return this.execAction(position, vimState);
} }

View File

@ -127,7 +127,7 @@ export class PythonDocument {
// Calculate position of last non-white character) // Calculate position of last non-white character)
end: new Position( end: new Position(
endLine.line, endLine.line,
endLine.text.search(PythonDocument.reLastNonWhiteSpaceCharacter) - 1 endLine.text.search(PythonDocument.reLastNonWhiteSpaceCharacter) - 1,
), ),
}); });
} }
@ -181,7 +181,7 @@ export class PythonDocument {
position: Position, position: Position,
vimState: VimState, vimState: VimState,
forward: boolean, forward: boolean,
start: boolean start: boolean,
): Position | IMovement { ): Position | IMovement {
const direction = forward ? 'next' : 'prev'; const direction = forward ? 'next' : 'prev';
const edge = start ? 'start' : 'end'; const edge = start ? 'start' : 'end';
@ -207,7 +207,7 @@ abstract class BasePythonMovement extends BaseMovement {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const document = vimState.document; const document = vimState.document;
return ( return (

View File

@ -58,7 +58,7 @@ abstract class MoveByScreenLine extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const multicursorIndex = this.multicursorIndex ?? 0; const multicursorIndex = this.multicursorIndex ?? 0;
@ -133,7 +133,7 @@ abstract class MoveByScreenLine extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<IMovement> { ): Promise<IMovement> {
const multicursorIndex = this.multicursorIndex ?? 0; const multicursorIndex = this.multicursorIndex ?? 0;
if (multicursorIndex === 0) { if (multicursorIndex === 0) {
@ -184,7 +184,7 @@ abstract class MoveByScreenLineMaintainDesiredColumn extends MoveByScreenLine {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const prevDesiredColumn = vimState.desiredColumn; const prevDesiredColumn = vimState.desiredColumn;
const prevLine = vimState.editor.selection.active.line; const prevLine = vimState.editor.selection.active.line;
@ -316,7 +316,7 @@ class MoveDown extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position> { ): Promise<Position> {
vimState.currentRegisterMode = RegisterMode.LineWise; vimState.currentRegisterMode = RegisterMode.LineWise;
return position.getDown(); return position.getDown();
@ -354,7 +354,7 @@ class MoveUp extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position> { ): Promise<Position> {
vimState.currentRegisterMode = RegisterMode.LineWise; vimState.currentRegisterMode = RegisterMode.LineWise;
return position.getUp(); return position.getUp();
@ -454,7 +454,7 @@ class ArrowsInReplaceMode extends BaseMovement {
throw new Error(`Unexpected 'arrow' key: ${this.keys[0]}`); throw new Error(`Unexpected 'arrow' key: ${this.keys[0]}`);
} }
(vimState.modeData as ModeDataFor<Mode.Replace>).replaceState.resetChanges( (vimState.modeData as ModeDataFor<Mode.Replace>).replaceState.resetChanges(
this.multicursorIndex ?? 0 this.multicursorIndex ?? 0,
); );
return newPosition; return newPosition;
} }
@ -467,7 +467,7 @@ class CommandNextSearchMatch extends BaseMovement {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const searchState = globalState.searchState; const searchState = globalState.searchState;
@ -481,7 +481,7 @@ class CommandNextSearchMatch extends BaseMovement {
if (searchState.getMatchRanges(vimState).length === 0) { if (searchState.getMatchRanges(vimState).length === 0) {
StatusBar.displayError( StatusBar.displayError(
vimState, vimState,
VimError.fromCode(ErrorCode.PatternNotFound, searchState.searchString) VimError.fromCode(ErrorCode.PatternNotFound, searchState.searchString),
); );
return failedMovement(vimState); return failedMovement(vimState);
} }
@ -503,8 +503,8 @@ class CommandNextSearchMatch extends BaseMovement {
searchState.direction === SearchDirection.Forward searchState.direction === SearchDirection.Forward
? ErrorCode.SearchHitBottom ? ErrorCode.SearchHitBottom
: ErrorCode.SearchHitTop, : ErrorCode.SearchHitTop,
searchState.searchString searchState.searchString,
) ),
); );
return failedMovement(vimState); return failedMovement(vimState);
} }
@ -522,7 +522,7 @@ class CommandPreviousSearchMatch extends BaseMovement {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const searchState = globalState.searchState; const searchState = globalState.searchState;
@ -536,7 +536,7 @@ class CommandPreviousSearchMatch extends BaseMovement {
if (searchState.getMatchRanges(vimState).length === 0) { if (searchState.getMatchRanges(vimState).length === 0) {
StatusBar.displayError( StatusBar.displayError(
vimState, vimState,
VimError.fromCode(ErrorCode.PatternNotFound, searchState.searchString) VimError.fromCode(ErrorCode.PatternNotFound, searchState.searchString),
); );
return failedMovement(vimState); return failedMovement(vimState);
} }
@ -550,7 +550,7 @@ class CommandPreviousSearchMatch extends BaseMovement {
? searchState.getNextSearchMatchPosition( ? searchState.getNextSearchMatchPosition(
vimState, vimState,
position.getRight(), position.getRight(),
SearchDirection.Backward SearchDirection.Backward,
) )
: searchState.getNextSearchMatchPosition(vimState, position, SearchDirection.Backward); : searchState.getNextSearchMatchPosition(vimState, position, SearchDirection.Backward);
@ -561,8 +561,8 @@ class CommandPreviousSearchMatch extends BaseMovement {
searchState.direction === SearchDirection.Forward searchState.direction === SearchDirection.Forward
? ErrorCode.SearchHitTop ? ErrorCode.SearchHitTop
: ErrorCode.SearchHitBottom, : ErrorCode.SearchHitBottom,
searchState.searchString searchState.searchString,
) ),
); );
return failedMovement(vimState); return failedMovement(vimState);
} }
@ -715,7 +715,7 @@ class MoveLeft extends BaseMovement {
}; };
return shouldWrapKey(vimState.currentMode, this.keysPressed[0]) return shouldWrapKey(vimState.currentMode, this.keysPressed[0])
? position.getLeftThroughLineBreaks( ? position.getLeftThroughLineBreaks(
[Mode.Insert, Mode.Replace].includes(vimState.currentMode) [Mode.Insert, Mode.Replace].includes(vimState.currentMode),
) )
: getLeftWhile(position); : getLeftWhile(position);
} }
@ -743,7 +743,7 @@ class MoveRight extends BaseMovement {
}; };
return shouldWrapKey(vimState.currentMode, this.keysPressed[0]) return shouldWrapKey(vimState.currentMode, this.keysPressed[0])
? position.getRightThroughLineBreaks( ? position.getRightThroughLineBreaks(
[Mode.Insert, Mode.Replace].includes(vimState.currentMode) [Mode.Insert, Mode.Replace].includes(vimState.currentMode),
) )
: getRightWhile(position); : getRightWhile(position);
} }
@ -756,12 +756,12 @@ class MoveDownNonBlank extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
vimState.currentRegisterMode = RegisterMode.LineWise; vimState.currentRegisterMode = RegisterMode.LineWise;
return TextEditor.getFirstNonWhitespaceCharOnLine( return TextEditor.getFirstNonWhitespaceCharOnLine(
vimState.document, vimState.document,
position.getDown(Math.max(count, 1)).line position.getDown(Math.max(count, 1)).line,
); );
} }
} }
@ -773,12 +773,12 @@ class MoveUpNonBlank extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
vimState.currentRegisterMode = RegisterMode.LineWise; vimState.currentRegisterMode = RegisterMode.LineWise;
return TextEditor.getFirstNonWhitespaceCharOnLine( return TextEditor.getFirstNonWhitespaceCharOnLine(
vimState.document, vimState.document,
position.getUp(Math.max(count, 1)).line position.getUp(Math.max(count, 1)).line,
); );
} }
} }
@ -790,7 +790,7 @@ class MoveDownUnderscore extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
vimState.currentRegisterMode = RegisterMode.LineWise; vimState.currentRegisterMode = RegisterMode.LineWise;
const pos = position.getDown(Math.max(count - 1, 0)); const pos = position.getDown(Math.max(count - 1, 0));
@ -807,7 +807,7 @@ class MoveToColumn extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
return new Position(position.line, Math.max(0, count - 1)); return new Position(position.line, Math.max(0, count - 1));
} }
@ -824,7 +824,7 @@ function findHelper(
start: Position, start: Position,
char: string, char: string,
count: number, count: number,
direction: 'forward' | 'backward' direction: 'forward' | 'backward',
): Position | undefined { ): Position | undefined {
const line = vimState.document.lineAt(start); const line = vimState.document.lineAt(start);
@ -852,12 +852,12 @@ class MoveFindForward extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
if (configuration.sneakReplacesF) { if (configuration.sneakReplacesF) {
const pos = await new SneakForward( const pos = await new SneakForward(
this.keysPressed.concat('\n'), this.keysPressed.concat('\n'),
this.isRepeat this.isRepeat,
).execActionWithCount(position, vimState, count); ).execActionWithCount(position, vimState, count);
if (vimState.recordedState.operator && !isIMovement(pos)) { if (vimState.recordedState.operator && !isIMovement(pos)) {
return pos.getRight(); return pos.getRight();
@ -892,13 +892,13 @@ class MoveFindBackward extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
if (configuration.sneakReplacesF) { if (configuration.sneakReplacesF) {
return new SneakBackward(this.keysPressed.concat('\n'), this.isRepeat).execActionWithCount( return new SneakBackward(this.keysPressed.concat('\n'), this.isRepeat).execActionWithCount(
position, position,
vimState, vimState,
count count,
); );
} }
@ -922,7 +922,7 @@ function tilHelper(
start: Position, start: Position,
char: string, char: string,
count: number, count: number,
direction: 'forward' | 'backward' direction: 'forward' | 'backward',
) { ) {
const result = findHelper(vimState, start, char, count, direction); const result = findHelper(vimState, start, char, count, direction);
return direction === 'forward' ? result?.getLeft() : result?.getRight(); return direction === 'forward' ? result?.getLeft() : result?.getRight();
@ -935,7 +935,7 @@ class MoveTilForward extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
count ||= 1; count ||= 1;
const toFind = Notation.ToControlCharacter(this.keysPressed[1]); const toFind = Notation.ToControlCharacter(this.keysPressed[1]);
@ -968,7 +968,7 @@ class MoveTilBackward extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
count ||= 1; count ||= 1;
const toFind = Notation.ToControlCharacter(this.keysPressed[1]); const toFind = Notation.ToControlCharacter(this.keysPressed[1]);
@ -997,7 +997,7 @@ class MoveRepeat extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const movement = vimState.lastSemicolonRepeatableMovement; const movement = vimState.lastSemicolonRepeatableMovement;
if (movement) { if (movement) {
@ -1014,7 +1014,7 @@ class MoveRepeatReversed extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const semiColonMovement = vimState.lastSemicolonRepeatableMovement; const semiColonMovement = vimState.lastSemicolonRepeatableMovement;
const commaMovement = vimState.lastCommaRepeatableMovement; const commaMovement = vimState.lastCommaRepeatableMovement;
@ -1040,7 +1040,7 @@ class MoveLineEnd extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
return position.getDown(Math.max(count - 1, 0)).getLineEnd(); return position.getDown(Math.max(count - 1, 0)).getLineEnd();
} }
@ -1089,7 +1089,7 @@ class MoveScreenLineEndNonBlank extends MoveByScreenLine {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
count ||= 1; count ||= 1;
const pos = await super.execActionWithCount(position, vimState, count); const pos = await super.execActionWithCount(position, vimState, count);
@ -1173,7 +1173,7 @@ class MoveUpByScreenLineVisualBlock extends BaseMovement {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
if (position.line > 0) { if (position.line > 0) {
return position.with({ character: vimState.desiredColumn }).getUp(); return position.with({ character: vimState.desiredColumn }).getUp();
@ -1184,7 +1184,7 @@ class MoveUpByScreenLineVisualBlock extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position> { ): Promise<Position> {
vimState.currentRegisterMode = RegisterMode.LineWise; vimState.currentRegisterMode = RegisterMode.LineWise;
return position.getUp(); return position.getUp();
@ -1202,7 +1202,7 @@ class MoveDownByScreenLineVisualBlock extends BaseMovement {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
if (position.line < vimState.document.lineCount - 1) { if (position.line < vimState.document.lineCount - 1) {
return position.with({ character: vimState.desiredColumn }).getDown(); return position.with({ character: vimState.desiredColumn }).getDown();
@ -1213,7 +1213,7 @@ class MoveDownByScreenLineVisualBlock extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position> { ): Promise<Position> {
vimState.currentRegisterMode = RegisterMode.LineWise; vimState.currentRegisterMode = RegisterMode.LineWise;
return position.getDown(); return position.getDown();
@ -1328,7 +1328,7 @@ class MoveNonBlankFirst extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
vimState.currentRegisterMode = RegisterMode.LineWise; vimState.currentRegisterMode = RegisterMode.LineWise;
@ -1349,19 +1349,19 @@ class MoveNonBlankLast extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
vimState.currentRegisterMode = RegisterMode.LineWise; vimState.currentRegisterMode = RegisterMode.LineWise;
let stop: Position; let stop: Position;
if (count === 0) { if (count === 0) {
stop = new Position(vimState.document.lineCount - 1, position.character).obeyStartOfLine( stop = new Position(vimState.document.lineCount - 1, position.character).obeyStartOfLine(
vimState.document vimState.document,
); );
} else { } else {
stop = new Position( stop = new Position(
Math.min(count, vimState.document.lineCount) - 1, Math.min(count, vimState.document.lineCount) - 1,
position.character position.character,
).obeyStartOfLine(vimState.document); ).obeyStartOfLine(vimState.document);
} }
@ -1379,7 +1379,7 @@ class EndOfSpecificLine extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position> { ): Promise<Position> {
const line = count const line = count
? clamp(count - 1, 0, vimState.document.lineCount - 1) ? clamp(count - 1, 0, vimState.document.lineCount - 1)
@ -1397,7 +1397,7 @@ export class MoveWordBegin extends BaseMovement {
position: Position, position: Position,
vimState: VimState, vimState: VimState,
firstIteration: boolean, firstIteration: boolean,
lastIteration: boolean lastIteration: boolean,
): Promise<Position> { ): Promise<Position> {
if ( if (
lastIteration && lastIteration &&
@ -1433,7 +1433,7 @@ export class MoveWordBegin extends BaseMovement {
position: Position, position: Position,
vimState: VimState, vimState: VimState,
firstIteration: boolean, firstIteration: boolean,
lastIteration: boolean lastIteration: boolean,
): Promise<Position> { ): Promise<Position> {
const result = await this.execAction(position, vimState, firstIteration, lastIteration); const result = await this.execAction(position, vimState, firstIteration, lastIteration);
@ -1492,7 +1492,7 @@ class MoveWordEnd extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position> { ): Promise<Position> {
const end = position.nextWordEnd(vimState.document); const end = position.nextWordEnd(vimState.document);
@ -1510,7 +1510,7 @@ class MoveFullWordEnd extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position> { ): Promise<Position> {
return position.nextWordEnd(vimState.document, { wordType: WordType.Big }).getRight(); return position.nextWordEnd(vimState.document, { wordType: WordType.Big }).getRight();
} }
@ -1654,7 +1654,7 @@ abstract class MoveSectionBoundary extends BaseMovement {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const document = vimState.document; const document = vimState.document;
@ -1665,7 +1665,7 @@ abstract class MoveSectionBoundary extends BaseMovement {
position, position,
vimState, vimState,
this.forward, this.forward,
this.begin this.begin,
); );
} }
@ -1736,7 +1736,7 @@ class MoveToMatchingBracket extends BaseMovement {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
position = position.getLeftIfEOL(); position = position.getLeftIfEOL();
@ -1756,7 +1756,7 @@ class MoveToMatchingBracket extends BaseMovement {
new Position(position.line, col), new Position(position.line, col),
lineText[col], lineText[col],
vimState, vimState,
false false,
) || failure ) || failure
); );
} }
@ -1768,7 +1768,7 @@ class MoveToMatchingBracket extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const result = await this.execAction(position, vimState); const result = await this.execAction(position, vimState);
@ -1793,7 +1793,7 @@ class MoveToMatchingBracket extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
// % has a special mode that lets you use it to jump to a percentage of the file // % has a special mode that lets you use it to jump to a percentage of the file
// However, some other bracket motions inherit from this so only do this behavior for % explicitly // However, some other bracket motions inherit from this so only do this behavior for % explicitly
@ -1833,7 +1833,7 @@ export abstract class MoveInsideCharacter extends ExpandingSelection {
position: Position, position: Position,
vimState: VimState, vimState: VimState,
firstIteration: boolean, firstIteration: boolean,
lastIteration: boolean lastIteration: boolean,
): Promise<IMovement> { ): Promise<IMovement> {
const closingChar = PairMatcher.pairings[this.charToMatch].match; const closingChar = PairMatcher.pairings[this.charToMatch].match;
const [selStart, selEnd] = sorted(vimState.cursorStartPosition, position); const [selStart, selEnd] = sorted(vimState.cursorStartPosition, position);
@ -1941,7 +1941,7 @@ export abstract class MoveCurlyBrace extends MoveInsideCharacter {
position: Position, position: Position,
vimState: VimState, vimState: VimState,
firstIteration: boolean, firstIteration: boolean,
lastIteration: boolean lastIteration: boolean,
): Promise<IMovement> { ): Promise<IMovement> {
// curly braces has a special treatment. In case the cursor is before an opening curly brace, // curly braces has a special treatment. In case the cursor is before an opening curly brace,
// and there are no characters before the opening curly brace in the same line, it should jump // and there are no characters before the opening curly brace in the same line, it should jump
@ -1956,7 +1956,7 @@ export abstract class MoveCurlyBrace extends MoveInsideCharacter {
) { ) {
const curlyPos = position.with( const curlyPos = position.with(
position.line, position.line,
position.character + openCurlyBraceIndexFromCursor position.character + openCurlyBraceIndexFromCursor,
); );
vimState.cursorStartPosition = vimState.cursorStopPosition = curlyPos; vimState.cursorStartPosition = vimState.cursorStopPosition = curlyPos;
const movement = await super.execAction(curlyPos, vimState, firstIteration, lastIteration); const movement = await super.execAction(curlyPos, vimState, firstIteration, lastIteration);
@ -2060,7 +2060,7 @@ export abstract class MoveQuoteMatch extends BaseMovement {
public override async execActionWithCount( public override async execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<IMovement> { ): Promise<IMovement> {
// TODO: this is super janky // TODO: this is super janky
return (await super.execActionWithCount(position, vimState, 1)) as IMovement; return (await super.execActionWithCount(position, vimState, 1)) as IMovement;
@ -2080,7 +2080,7 @@ export abstract class MoveQuoteMatch extends BaseMovement {
if (useSmartQuotes()) { if (useSmartQuotes()) {
const quoteMatcher = new SmartQuoteMatcher( const quoteMatcher = new SmartQuoteMatcher(
this.anyQuote ? 'any' : this.charToMatch, this.anyQuote ? 'any' : this.charToMatch,
vimState.document vimState.document,
); );
const res = quoteMatcher.smartSurroundingQuotes(position, this.which); const res = quoteMatcher.smartSurroundingQuotes(position, this.which);
@ -2164,7 +2164,7 @@ export abstract class MoveQuoteMatch extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const result = await this.execAction(position, vimState); const result = await this.execAction(position, vimState);
if (isIMovement(result)) { if (isIMovement(result)) {
@ -2227,7 +2227,7 @@ class MoveToUnclosedRoundBracketBackward extends MoveToMatchingBracket {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const charToMatch = ')'; const charToMatch = ')';
const result = PairMatcher.nextPairedChar(position, charToMatch, vimState, false); const result = PairMatcher.nextPairedChar(position, charToMatch, vimState, false);
@ -2245,7 +2245,7 @@ class MoveToUnclosedRoundBracketForward extends MoveToMatchingBracket {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const charToMatch = '('; const charToMatch = '(';
const result = PairMatcher.nextPairedChar(position, charToMatch, vimState, false); const result = PairMatcher.nextPairedChar(position, charToMatch, vimState, false);
@ -2272,7 +2272,7 @@ class MoveToUnclosedCurlyBracketBackward extends MoveToMatchingBracket {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const charToMatch = '}'; const charToMatch = '}';
const result = PairMatcher.nextPairedChar(position, charToMatch, vimState, false); const result = PairMatcher.nextPairedChar(position, charToMatch, vimState, false);
@ -2290,7 +2290,7 @@ class MoveToUnclosedCurlyBracketForward extends MoveToMatchingBracket {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
const charToMatch = '{'; const charToMatch = '{';
const result = PairMatcher.nextPairedChar(position, charToMatch, vimState, false); const result = PairMatcher.nextPairedChar(position, charToMatch, vimState, false);

View File

@ -77,7 +77,7 @@ export abstract class BaseOperator extends BaseAction {
await this.run( await this.run(
vimState, vimState,
position.getLineBegin(), position.getLineBegin(),
position.getDown(Math.max(0, count - 1)).getLineEnd() position.getDown(Math.max(0, count - 1)).getLineEnd(),
); );
} }
@ -344,7 +344,7 @@ abstract class ChangeCaseOperator extends BaseOperator {
const range = new vscode.Range(start, end); const range = new vscode.Range(start, end);
vimState.recordedState.transformer.replace( vimState.recordedState.transformer.replace(
range, range,
this.transformText(vimState.document.getText(range)) this.transformText(vimState.document.getText(range)),
); );
} }
@ -352,7 +352,7 @@ abstract class ChangeCaseOperator extends BaseOperator {
for (let i = 0; i < vimState.editor.selections.length; i++) { for (let i = 0; i < vimState.editor.selections.length; i++) {
vimState.recordedState.transformer.moveCursor( vimState.recordedState.transformer.moveCursor(
PositionDiff.exactPosition(earlierOf(startPos, endPos)), PositionDiff.exactPosition(earlierOf(startPos, endPos)),
i i,
); );
} }
} else { } else {
@ -495,7 +495,7 @@ class IndentOperatorVisualBlock extends BaseOperator {
if (vimState.isRunningDotCommand && vimState.dotCommandPreviousVisualSelection) { if (vimState.isRunningDotCommand && vimState.dotCommandPreviousVisualSelection) {
const shiftSelectionByNum = Math.abs( const shiftSelectionByNum = Math.abs(
vimState.dotCommandPreviousVisualSelection.end.line - vimState.dotCommandPreviousVisualSelection.end.line -
vimState.dotCommandPreviousVisualSelection.start.line vimState.dotCommandPreviousVisualSelection.start.line,
); );
start = vimState.cursorStartPosition; start = vimState.cursorStartPosition;
@ -534,7 +534,7 @@ class OutdentOperator extends BaseOperator {
await vimState.setCurrentMode(Mode.Normal); await vimState.setCurrentMode(Mode.Normal);
vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine( vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine(
vimState.document, vimState.document,
start.line start.line,
); );
} }
} }
@ -569,7 +569,7 @@ class OutdentOperatorVisualAndVisualLine extends BaseOperator {
await vimState.setCurrentMode(Mode.Normal); await vimState.setCurrentMode(Mode.Normal);
vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine( vimState.cursorStopPosition = TextEditor.getFirstNonWhitespaceCharOnLine(
vimState.document, vimState.document,
start.line start.line,
); );
} }
} }
@ -588,7 +588,7 @@ class OutdentOperatorVisualBlock extends BaseOperator {
if (vimState.isRunningDotCommand && vimState.dotCommandPreviousVisualSelection) { if (vimState.isRunningDotCommand && vimState.dotCommandPreviousVisualSelection) {
const shiftSelectionByNum = Math.abs( const shiftSelectionByNum = Math.abs(
vimState.dotCommandPreviousVisualSelection.end.line - vimState.dotCommandPreviousVisualSelection.end.line -
vimState.dotCommandPreviousVisualSelection.start.line vimState.dotCommandPreviousVisualSelection.start.line,
); );
start = vimState.cursorStartPosition; start = vimState.cursorStartPosition;
@ -611,7 +611,7 @@ class OutdentOperatorVisualBlock extends BaseOperator {
const distToNonBlankChar = currentLineFromStart.match(/\S/)?.index ?? 0; const distToNonBlankChar = currentLineFromStart.match(/\S/)?.index ?? 0;
const outdentDist = Math.min( const outdentDist = Math.min(
distToNonBlankChar, distToNonBlankChar,
tabSize * (vimState.recordedState.count || 1) tabSize * (vimState.recordedState.count || 1),
); );
vimState.recordedState.transformer.addTransformation({ vimState.recordedState.transformer.addTransformation({
@ -654,21 +654,21 @@ export class ChangeOperator extends BaseOperator {
const firstLineIndent = vimState.document.getText( const firstLineIndent = vimState.document.getText(
new vscode.Range( new vscode.Range(
deleteRange.start.getLineBegin(), deleteRange.start.getLineBegin(),
deleteRange.start.getLineBeginRespectingIndent(vimState.document) deleteRange.start.getLineBeginRespectingIndent(vimState.document),
) ),
); );
vimState.recordedState.transformer.replace( vimState.recordedState.transformer.replace(
deleteRange, deleteRange,
firstLineIndent, firstLineIndent,
PositionDiff.exactPosition(new Position(deleteRange.start.line, firstLineIndent.length)) PositionDiff.exactPosition(new Position(deleteRange.start.line, firstLineIndent.length)),
); );
if (vimState.document.languageId !== 'plaintext') { if (vimState.document.languageId !== 'plaintext') {
vimState.recordedState.transformer.vscodeCommand('editor.action.reindentselectedlines'); vimState.recordedState.transformer.vscodeCommand('editor.action.reindentselectedlines');
vimState.recordedState.transformer.moveCursor( vimState.recordedState.transformer.moveCursor(
PositionDiff.endOfLine(), PositionDiff.endOfLine(),
this.multicursorIndex this.multicursorIndex,
); );
} }
} else { } else {
@ -1024,7 +1024,7 @@ class ActionVisualReflowParagraph extends BaseOperator {
// by searching backward for a whitespace character (space or tab). // by searching backward for a whitespace character (space or tab).
let breakpoint = Math.max( let breakpoint = Math.max(
trimmedLine.lastIndexOf(' ', remaining), trimmedLine.lastIndexOf(' ', remaining),
trimmedLine.lastIndexOf('\t', remaining) trimmedLine.lastIndexOf('\t', remaining),
); );
if (breakpoint < 0) { if (breakpoint < 0) {
// Next word is too long to fit on the current line. // Next word is too long to fit on the current line.

View File

@ -59,7 +59,7 @@ class MoveCamelCaseWordEnd extends CamelCaseBaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position> { ): Promise<Position> {
const end = position.nextWordEnd(vimState.document, { wordType: WordType.CamelCase }); const end = position.nextWordEnd(vimState.document, { wordType: WordType.CamelCase });

View File

@ -103,7 +103,7 @@ function getMatchesForString(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
searchString: string, searchString: string,
options?: SearchOptions options?: SearchOptions,
): Match[] { ): Match[] {
switch (searchString) { switch (searchString) {
case '': case '':
@ -114,7 +114,7 @@ function getMatchesForString(
vimState.document, vimState.document,
position, position,
new RegExp(' {1,}', 'g'), new RegExp(' {1,}', 'g'),
options options,
); );
default: default:
// Search all occurences of the character pressed // Search all occurences of the character pressed
@ -131,7 +131,7 @@ function getMatchesForString(
vimState.document, vimState.document,
position, position,
new RegExp(searchString, regexFlags), new RegExp(searchString, regexFlags),
options options,
); );
} }
} }
@ -197,7 +197,7 @@ export class SearchByNCharCommand extends BaseEasyMotionCommand implements EasyM
position, position,
vimState, vimState,
this.removeTrailingLineBreak(this.searchString), this.removeTrailingLineBreak(this.searchString),
{} {},
); );
} }
@ -264,7 +264,7 @@ export abstract class EasyMotionWordMoveCommandBase extends BaseEasyMotionComman
private getMatchesForWord( private getMatchesForWord(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
options?: SearchOptions options?: SearchOptions,
): Match[] { ): Match[] {
const regex = this._options.jumpToAnywhere const regex = this._options.jumpToAnywhere
? new RegExp(configuration.easymotionJumpToAnywhereRegex, 'g') ? new RegExp(configuration.easymotionJumpToAnywhereRegex, 'g')
@ -292,19 +292,19 @@ export abstract class EasyMotionLineMoveCommandBase extends BaseEasyMotionComman
private getMatchesForLineStart( private getMatchesForLineStart(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
options?: SearchOptions options?: SearchOptions,
): Match[] { ): Match[] {
// Search for the beginning of all non whitespace chars on each line before the cursor // Search for the beginning of all non whitespace chars on each line before the cursor
const matches = vimState.easyMotion.sortedSearch( const matches = vimState.easyMotion.sortedSearch(
vimState.document, vimState.document,
position, position,
new RegExp('^.', 'gm'), new RegExp('^.', 'gm'),
options options,
); );
for (const match of matches) { for (const match of matches) {
match.position = TextEditor.getFirstNonWhitespaceCharOnLine( match.position = TextEditor.getFirstNonWhitespaceCharOnLine(
vimState.document, vimState.document,
match.position.line match.position.line,
); );
} }
return matches; return matches;

View File

@ -57,7 +57,7 @@ export class EasyMotion implements IEasyMotion {
*/ */
public static getDecorationType( public static getDecorationType(
length: number, length: number,
decorations?: vscode.DecorationRenderOptions decorations?: vscode.DecorationRenderOptions,
): vscode.TextEditorDecorationType { ): vscode.TextEditorDecorationType {
const cache = this.decorationTypeCache[length]; const cache = this.decorationTypeCache[length];
if (cache) { if (cache) {
@ -112,7 +112,7 @@ export class EasyMotion implements IEasyMotion {
document: vscode.TextDocument, document: vscode.TextDocument,
position: Position, position: Position,
search: string | RegExp = '', search: string | RegExp = '',
options: SearchOptions = {} options: SearchOptions = {},
): Match[] { ): Match[] {
const regex = const regex =
typeof search === 'string' typeof search === 'string'
@ -184,7 +184,7 @@ export class EasyMotion implements IEasyMotion {
private getMarkerColor( private getMarkerColor(
customizedValue: string, customizedValue: string,
themeColorId: string themeColorId: string,
): string | vscode.ThemeColor { ): string | vscode.ThemeColor {
if (customizedValue) { if (customizedValue) {
return customizedValue; return customizedValue;
@ -206,14 +206,14 @@ export class EasyMotion implements IEasyMotion {
private getEasymotionMarkerForegroundColorTwoCharFirst() { private getEasymotionMarkerForegroundColorTwoCharFirst() {
return this.getMarkerColor( return this.getMarkerColor(
configuration.easymotionMarkerForegroundColorTwoCharFirst, configuration.easymotionMarkerForegroundColorTwoCharFirst,
'#ffb400' '#ffb400',
); );
} }
private getEasymotionMarkerForegroundColorTwoCharSecond() { private getEasymotionMarkerForegroundColorTwoCharSecond() {
return this.getMarkerColor( return this.getMarkerColor(
configuration.easymotionMarkerForegroundColorTwoCharSecond, configuration.easymotionMarkerForegroundColorTwoCharSecond,
'#b98300' '#b98300',
); );
} }
@ -319,7 +319,7 @@ export class EasyMotion implements IEasyMotion {
pos.line, pos.line,
pos.character + 1, pos.character + 1,
pos.line, pos.line,
pos.character + 1 pos.character + 1,
); );
const secondCharRenderOptions: vscode.ThemableDecorationInstanceRenderOptions = { const secondCharRenderOptions: vscode.ThemableDecorationInstanceRenderOptions = {
@ -343,7 +343,12 @@ export class EasyMotion implements IEasyMotion {
} }
hiddenChars.push( hiddenChars.push(
new vscode.Range(pos.line, pos.character, pos.line, pos.character + keystroke.length + trim) new vscode.Range(
pos.line,
pos.character,
pos.line,
pos.character + keystroke.length + trim,
),
); );
if (configuration.easymotionDimBackground) { if (configuration.easymotionDimBackground) {
@ -363,7 +368,7 @@ export class EasyMotion implements IEasyMotion {
const prevKeystroke = prevMarker.name.substring(this.accumulation.length); const prevKeystroke = prevMarker.name.substring(this.accumulation.length);
const prevDimPos = prevMarker.position; const prevDimPos = prevMarker.position;
const offsetPrevDimPos = prevDimPos.withColumn( const offsetPrevDimPos = prevDimPos.withColumn(
prevDimPos.character + prevKeystroke.length prevDimPos.character + prevKeystroke.length,
); );
// Don't create dimming ranges in between consecutive markers (the 'after' is in the cases // Don't create dimming ranges in between consecutive markers (the 'after' is in the cases
@ -377,7 +382,7 @@ export class EasyMotion implements IEasyMotion {
offsetPrevDimPos.line, offsetPrevDimPos.line,
offsetPrevDimPos.character, offsetPrevDimPos.character,
pos.line, pos.line,
pos.character pos.character,
), ),
renderOptions: dimmingRenderOptions, renderOptions: dimmingRenderOptions,
}); });
@ -400,7 +405,7 @@ export class EasyMotion implements IEasyMotion {
dimmingZones.push({ dimmingZones.push({
range: new vscode.Range( range: new vscode.Range(
offsetPrevDimPos, offsetPrevDimPos,
new Position(editor.document.lineCount, Number.MAX_VALUE) new Position(editor.document.lineCount, Number.MAX_VALUE),
), ),
renderOptions: dimmingRenderOptions, renderOptions: dimmingRenderOptions,
}); });

View File

@ -81,7 +81,7 @@ export interface IEasyMotion {
document: vscode.TextDocument, document: vscode.TextDocument,
position: Position, position: Position,
search?: string | RegExp, search?: string | RegExp,
options?: SearchOptions options?: SearchOptions,
): Match[]; ): Match[];
updateDecorations(editor: vscode.TextEditor): void; updateDecorations(editor: vscode.TextEditor): void;
clearMarkers(): void; clearMarkers(): void;

View File

@ -32,7 +32,7 @@ class ReplaceOperator extends BaseOperator {
if (register === undefined) { if (register === undefined) {
StatusBar.displayError( StatusBar.displayError(
vimState, vimState,
VimError.fromCode(ErrorCode.NothingInRegister, vimState.recordedState.registerName) VimError.fromCode(ErrorCode.NothingInRegister, vimState.recordedState.registerName),
); );
return; return;
} }

View File

@ -24,7 +24,7 @@ export class SneakForward extends BaseMovement {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
if (!this.isRepeat) { if (!this.isRepeat) {
vimState.lastSemicolonRepeatableMovement = new SneakForward(this.keysPressed, true); vimState.lastSemicolonRepeatableMovement = new SneakForward(this.keysPressed, true);
@ -91,7 +91,7 @@ export class SneakBackward extends BaseMovement {
public override async execAction( public override async execAction(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<Position | IMovement> { ): Promise<Position | IMovement> {
if (!this.isRepeat) { if (!this.isRepeat) {
vimState.lastSemicolonRepeatableMovement = new SneakBackward(this.keysPressed, true); vimState.lastSemicolonRepeatableMovement = new SneakBackward(this.keysPressed, true);

View File

@ -126,7 +126,7 @@ class YankSurroundOperator extends SurroundOperator {
public override async runRepeat( public override async runRepeat(
vimState: VimState, vimState: VimState,
position: Position, position: Position,
count: number count: number,
): Promise<void> { ): Promise<void> {
// we want to act on range: first non whitespace to last non whitespace // we want to act on range: first non whitespace to last non whitespace
await this.run( await this.run(
@ -135,7 +135,7 @@ class YankSurroundOperator extends SurroundOperator {
position position
.getDown(Math.max(0, count - 1)) .getDown(Math.max(0, count - 1))
.getLineEnd() .getLineEnd()
.prevWordEnd(vimState.document) .prevWordEnd(vimState.document),
); );
} }
} }
@ -228,7 +228,7 @@ class CommandSurroundDeleteSurround extends CommandSurround {
const replaceRanges = await SurroundHelper.getReplaceRanges( const replaceRanges = await SurroundHelper.getReplaceRanges(
vimState, vimState,
position, position,
this.multicursorIndex ?? 0 this.multicursorIndex ?? 0,
); );
if (replaceRanges) { if (replaceRanges) {
@ -274,7 +274,7 @@ class CommandSurroundChangeSurround extends CommandSurround {
const replaceRanges = await SurroundHelper.getReplaceRanges( const replaceRanges = await SurroundHelper.getReplaceRanges(
vimState, vimState,
position, position,
this.multicursorIndex ?? 0 this.multicursorIndex ?? 0,
); );
// collect ranges for all cursors // collect ranges for all cursors
@ -520,7 +520,7 @@ class SurroundHelper {
public static async getReplaceRanges( public static async getReplaceRanges(
vimState: VimState, vimState: VimState,
position: Position, position: Position,
multicursorIndex: number multicursorIndex: number,
): Promise<SurroundEdge | undefined> { ): Promise<SurroundEdge | undefined> {
/* so this method is a bit of a dumpster for edge cases and ugly details /* so this method is a bit of a dumpster for edge cases and ugly details
the main idea is this: the main idea is this:
@ -578,7 +578,7 @@ class SurroundHelper {
function checkRemoveSpace(): number { function checkRemoveSpace(): number {
// capiche? // capiche?
const leftSpace = vimState.editor.document.getText( const leftSpace = vimState.editor.document.getText(
new Range(rangeStart.getRight(), rangeStart.getRight(2)) new Range(rangeStart.getRight(), rangeStart.getRight(2)),
); );
const rightSpace = vimState.editor.document.getText(new Range(rangeEnd.getLeft(), rangeEnd)); const rightSpace = vimState.editor.document.getText(new Range(rangeEnd.getLeft(), rangeEnd));
return removeSpace && leftSpace === ' ' && rightSpace === ' ' ? 1 : 0; return removeSpace && leftSpace === ' ' && rightSpace === ' ' ? 1 : 0;

View File

@ -81,7 +81,7 @@ function LastNextObject<T extends MoveInsideCharacter>(type: new () => T, which:
position: Position, position: Position,
vimState: VimState, vimState: VimState,
firstIteration: boolean, firstIteration: boolean,
lastIteration: boolean lastIteration: boolean,
): Promise<IMovement> { ): Promise<IMovement> {
const maybePosition = searchPosition(this.charToFind, vimState.document, position, { const maybePosition = searchPosition(this.charToFind, vimState.document, position, {
direction: which === 'l' ? '<' : '>', direction: which === 'l' ? '<' : '>',
@ -97,7 +97,7 @@ function LastNextObject<T extends MoveInsideCharacter>(type: new () => T, which:
maybePosition, maybePosition,
vimState, vimState,
firstIteration, firstIteration,
lastIteration lastIteration,
); );
if (movement.failed) { if (movement.failed) {
return movement; return movement;

View File

@ -14,7 +14,7 @@ function searchForward(
throughLineBreaks?: boolean; throughLineBreaks?: boolean;
} = { } = {
throughLineBreaks: false, throughLineBreaks: false,
} },
): Position | undefined { ): Position | undefined {
let position = start; let position = start;
for ( for (
@ -41,7 +41,7 @@ function searchBackward(
throughLineBreaks?: boolean; throughLineBreaks?: boolean;
} = { } = {
throughLineBreaks: false, throughLineBreaks: false,
} },
): Position | undefined { ): Position | undefined {
let position = start; let position = start;
for ( for (
@ -66,7 +66,7 @@ export function maybeGetLeft(
count = 1, count = 1,
throughLineBreaks, throughLineBreaks,
dontMove, dontMove,
}: { count?: number; throughLineBreaks?: boolean; dontMove?: boolean } }: { count?: number; throughLineBreaks?: boolean; dontMove?: boolean },
) { ) {
return dontMove return dontMove
? position ? position
@ -80,7 +80,7 @@ export function maybeGetRight(
count = 1, count = 1,
throughLineBreaks, throughLineBreaks,
dontMove, dontMove,
}: { count?: number; throughLineBreaks?: boolean; dontMove?: boolean } }: { count?: number; throughLineBreaks?: boolean; dontMove?: boolean },
) { ) {
return dontMove return dontMove
? position ? position
@ -97,7 +97,7 @@ export function searchPosition(
direction: '>', direction: '>',
includeCursor: true, includeCursor: true,
throughLineBreaks: false, throughLineBreaks: false,
} },
): Position | undefined { ): Position | undefined {
if (flags.direction === '<') { if (flags.direction === '<') {
start = maybeGetLeft(start, { start = maybeGetLeft(start, {

View File

@ -200,7 +200,7 @@ export class SmartQuoteMatcher {
public smartSurroundingQuotes( public smartSurroundingQuotes(
position: Position, position: Position,
which: WhichQuotes which: WhichQuotes,
): { start: Position; stop: Position; lineText: string } | undefined { ): { start: Position; stop: Position; lineText: string } | undefined {
position = this.document.validatePosition(position); position = this.document.validatePosition(position);
const cursorIndex = position.character; const cursorIndex = position.character;
@ -276,7 +276,7 @@ export class SmartQuoteMatcher {
private smartSearch( private smartSearch(
start: number, start: number,
action: SearchAction, action: SearchAction,
quoteMap: QuoteMatch[] quoteMap: QuoteMatch[],
): [number, number] | undefined { ): [number, number] | undefined {
const offset = action.includeCurrent ? 1 : 0; const offset = action.includeCurrent ? 1 : 0;
let cursorPos: number | undefined = start; let cursorPos: number | undefined = start;

View File

@ -217,8 +217,8 @@ export class ExCommandLine extends CommandLine {
public display(cursorChar: string): string { public display(cursorChar: string): string {
return escapeCSSIcons( return escapeCSSIcons(
`:${this.text.substring(0, this.cursorIndex)}${cursorChar}${this.text.substring( `:${this.text.substring(0, this.cursorIndex)}${cursorChar}${this.text.substring(
this.cursorIndex this.cursorIndex,
)}` )}`,
); );
} }
@ -353,8 +353,8 @@ export class SearchCommandLine extends CommandLine {
.get() .get()
.forEach((val) => .forEach((val) =>
SearchCommandLine.previousSearchStates.push( SearchCommandLine.previousSearchStates.push(
new SearchState(SearchDirection.Forward, new Position(0, 0), val, undefined) new SearchState(SearchDirection.Forward, new Position(0, 0), val, undefined),
) ),
); );
} }
@ -397,8 +397,8 @@ export class SearchCommandLine extends CommandLine {
return escapeCSSIcons( return escapeCSSIcons(
`${this.searchState.direction === SearchDirection.Forward ? '/' : '?'}${this.text.substring( `${this.searchState.direction === SearchDirection.Forward ? '/' : '?'}${this.text.substring(
0, 0,
this.cursorIndex this.cursorIndex,
)}${cursorChar}${this.text.substring(this.cursorIndex)}` )}${cursorChar}${this.text.substring(this.cursorIndex)}`,
); );
} }
@ -436,7 +436,7 @@ export class SearchCommandLine extends CommandLine {
vimState, vimState,
vimState.cursorStopPosition, vimState.cursorStopPosition,
SearchDirection.Forward, SearchDirection.Forward,
this.getCurrentMatchRelativeIndex(vimState) this.getCurrentMatchRelativeIndex(vimState),
); );
} }
@ -450,7 +450,7 @@ export class SearchCommandLine extends CommandLine {
vimState, vimState,
vimState.cursorStopPosition, vimState.cursorStopPosition,
SearchDirection.Forward, SearchDirection.Forward,
this.getCurrentMatchRelativeIndex(vimState) this.getCurrentMatchRelativeIndex(vimState),
); );
} }
@ -459,7 +459,7 @@ export class SearchCommandLine extends CommandLine {
this.searchState.getMatchRanges(vimState), this.searchState.getMatchRanges(vimState),
configuration.incsearch && vimState.currentMode === Mode.SearchInProgressMode configuration.incsearch && vimState.currentMode === Mode.SearchInProgressMode
? this.getCurrentMatchRange(vimState)?.index ? this.getCurrentMatchRange(vimState)?.index
: undefined : undefined,
); );
} }
@ -494,8 +494,8 @@ export class SearchCommandLine extends CommandLine {
this.searchState.direction === SearchDirection.Backward this.searchState.direction === SearchDirection.Backward
? ErrorCode.SearchHitTop ? ErrorCode.SearchHitTop
: ErrorCode.SearchHitBottom, : ErrorCode.SearchHitBottom,
this.text this.text,
) ),
); );
return; return;
} }

View File

@ -14,7 +14,7 @@ export class BangCommand extends ExCommand {
(command) => (command) =>
new BangCommand({ new BangCommand({
command, command,
}) }),
); );
protected _arguments: IBangCommandArguments; protected _arguments: IBangCommandArguments;

View File

@ -59,7 +59,7 @@ class AddBreakpointCommand extends ExCommand {
} }
const location = new vscode.Location( const location = new vscode.Location(
file, file,
new vscode.Position(this.addBreakpoint.line - 1, 0) new vscode.Position(this.addBreakpoint.line - 1, 0),
); );
return vscode.debug.addBreakpoints([new vscode.SourceBreakpoint(location)]); return vscode.debug.addBreakpoints([new vscode.SourceBreakpoint(location)]);
} else if (this.addBreakpoint.type === 'func') { } else if (this.addBreakpoint.type === 'func') {
@ -102,7 +102,7 @@ class DeleteBreakpointCommand extends ExCommand {
async execute(vimState: VimState): Promise<void> { async execute(vimState: VimState): Promise<void> {
if (this.delBreakpoint.type === 'byId') { if (this.delBreakpoint.type === 'byId') {
return vscode.debug.removeBreakpoints( return vscode.debug.removeBreakpoints(
vscode.debug.breakpoints.slice(this.delBreakpoint.id - 1, 1) vscode.debug.breakpoints.slice(this.delBreakpoint.id - 1, 1),
); );
} else if (this.delBreakpoint.type === 'all') { } else if (this.delBreakpoint.type === 'all') {
return vscode.debug.removeBreakpoints(vscode.debug.breakpoints); return vscode.debug.removeBreakpoints(vscode.debug.breakpoints);
@ -121,7 +121,7 @@ class DeleteBreakpointCommand extends ExCommand {
.find( .find(
(b) => (b) =>
b.location.uri.toString() === reqUri.toString() && b.location.uri.toString() === reqUri.toString() &&
b.location.range.start.line === reqLine b.location.range.start.line === reqLine,
); );
if (breakpoint) return vscode.debug.removeBreakpoints([breakpoint]); if (breakpoint) return vscode.debug.removeBreakpoints([breakpoint]);
} else if (this.delBreakpoint.type === 'func') { } else if (this.delBreakpoint.type === 'func') {
@ -140,7 +140,7 @@ class DeleteBreakpointCommand extends ExCommand {
.filter( .filter(
(b) => (b) =>
b.location.uri.toString() === location.uri.toString() && b.location.uri.toString() === location.uri.toString() &&
b.location.range.start.line === location.range.start.line b.location.range.start.line === location.range.start.line,
) )
.sort((a, b) => distFromLocationCharacter(a) - distFromLocationCharacter(b))[0]; .sort((a, b) => distFromLocationCharacter(a) - distFromLocationCharacter(b))[0];
if (breakpoint) return vscode.debug.removeBreakpoints([breakpoint]); if (breakpoint) return vscode.debug.removeBreakpoints([breakpoint]);
@ -196,21 +196,21 @@ export class Breakpoints {
seqObj<AddBreakpointFile>( seqObj<AddBreakpointFile>(
['type', string('file')], ['type', string('file')],
['line', optWhitespace.then(numberParser).fallback(1)], ['line', optWhitespace.then(numberParser).fallback(1)],
['file', optWhitespace.then(fileNameParser).fallback('')] ['file', optWhitespace.then(fileNameParser).fallback('')],
), ),
// func // func
seqObj<AddBreakpointFunction>( seqObj<AddBreakpointFunction>(
['type', string('func')], ['type', string('func')],
optWhitespace.then(numberParser).fallback(1), // we don't support line numbers in function names, but Vim does, so we'll allow it. optWhitespace.then(numberParser).fallback(1), // we don't support line numbers in function names, but Vim does, so we'll allow it.
['function', optWhitespace.then(regexp(/\S+/))] ['function', optWhitespace.then(regexp(/\S+/))],
), ),
// expr // expr
seqObj<AddBreakpointExpr>(['type', string('expr')], ['expr', optWhitespace.then(all)]) seqObj<AddBreakpointExpr>(['type', string('expr')], ['expr', optWhitespace.then(all)]),
) ),
) )
.or( .or(
// without arg // without arg
eof.result<DelBreakpointHere>({ type: 'here' }) eof.result<DelBreakpointHere>({ type: 'here' }),
) )
.map((a) => new AddBreakpointCommand(a)), .map((a) => new AddBreakpointCommand(a)),
@ -223,23 +223,23 @@ export class Breakpoints {
seqObj<DelBreakpointFile>( seqObj<DelBreakpointFile>(
['type', string('file')], ['type', string('file')],
['line', optWhitespace.then(numberParser).fallback(1)], ['line', optWhitespace.then(numberParser).fallback(1)],
['file', optWhitespace.then(fileNameParser).fallback('')] ['file', optWhitespace.then(fileNameParser).fallback('')],
), ),
// func // func
seqObj<DelBreakpointFunction>( seqObj<DelBreakpointFunction>(
['type', string('func')], ['type', string('func')],
optWhitespace.then(numberParser).fallback(1), // we don't support line numbers in function names, but Vim does, so we'll allow it. optWhitespace.then(numberParser).fallback(1), // we don't support line numbers in function names, but Vim does, so we'll allow it.
['function', optWhitespace.then(regexp(/\S+/))] ['function', optWhitespace.then(regexp(/\S+/))],
), ),
// all // all
string('*').then(optWhitespace).result<DelAllBreakpoints>({ type: 'all' }), string('*').then(optWhitespace).result<DelAllBreakpoints>({ type: 'all' }),
// by number // by number
numberParser.map((n) => ({ type: 'byId', id: n })) numberParser.map((n) => ({ type: 'byId', id: n })),
) ),
) )
.or( .or(
// without arg // without arg
eof.result<DelBreakpointHere>({ type: 'here' }) eof.result<DelBreakpointHere>({ type: 'here' }),
) )
.map((a) => new DeleteBreakpointCommand(a)), .map((a) => new DeleteBreakpointCommand(a)),

View File

@ -19,7 +19,7 @@ interface IBufferDeleteCommandArguments {
export class BufferDeleteCommand extends ExCommand { export class BufferDeleteCommand extends ExCommand {
public static readonly argParser: Parser<BufferDeleteCommand> = seq( public static readonly argParser: Parser<BufferDeleteCommand> = seq(
bangParser.skip(optWhitespace), bangParser.skip(optWhitespace),
alt(numberParser, fileNameParser).sepBy(whitespace) alt(numberParser, fileNameParser).sepBy(whitespace),
).map(([bang, buffers]) => new BufferDeleteCommand({ bang, buffers })); ).map(([bang, buffers]) => new BufferDeleteCommand({ bang, buffers }));
public readonly arguments: IBufferDeleteCommandArguments; public readonly arguments: IBufferDeleteCommandArguments;
@ -42,7 +42,7 @@ export class BufferDeleteCommand extends ExCommand {
StatusBar.setText( StatusBar.setText(
vimState, vimState,
':bd[elete][!] {bufname} is not yet implemented (PRs are welcome!)', ':bd[elete][!] {bufname} is not yet implemented (PRs are welcome!)',
true true,
); );
continue; continue;
} }

View File

@ -12,7 +12,7 @@ import { bangParser } from '../../vimscript/parserUtils';
// //
export class CloseCommand extends ExCommand { export class CloseCommand extends ExCommand {
public static readonly argParser: Parser<CloseCommand> = bangParser.map( public static readonly argParser: Parser<CloseCommand> = bangParser.map(
(bang) => new CloseCommand(bang) (bang) => new CloseCommand(bang),
); );
public readonly bang: boolean; public readonly bang: boolean;

View File

@ -34,7 +34,7 @@ export class CopyCommand extends ExCommand {
} }
const copiedText = vimState.document.getText( const copiedText = vimState.document.getText(
new Range(new Position(sourceStart, 0), new Position(sourceEnd, 0).getLineEnd()) new Range(new Position(sourceStart, 0), new Position(sourceEnd, 0).getLineEnd()),
); );
let text: string; let text: string;
@ -50,13 +50,13 @@ export class CopyCommand extends ExCommand {
const lines = copiedText.split('\n'); const lines = copiedText.split('\n');
const cursorPosition = new Position( const cursorPosition = new Position(
Math.max(dest + lines.length, 0), Math.max(dest + lines.length, 0),
lines[lines.length - 1].match(/\S/)?.index ?? 0 lines[lines.length - 1].match(/\S/)?.index ?? 0,
); );
vimState.recordedState.transformer.insert( vimState.recordedState.transformer.insert(
position, position,
text, text,
PositionDiff.exactPosition(cursorPosition) PositionDiff.exactPosition(cursorPosition),
); );
} }

View File

@ -23,15 +23,15 @@ export class DeleteCommand extends ExCommand {
seq(any.fallback(undefined), whitespace.then(numberParser).fallback(undefined)).map( seq(any.fallback(undefined), whitespace.then(numberParser).fallback(undefined)).map(
([register, count]) => { ([register, count]) => {
return { register, count }; return { register, count };
} },
) ),
).map( ).map(
({ register, count }) => ({ register, count }) =>
new DeleteCommand({ new DeleteCommand({
register, register,
count, count,
}) }),
) ),
); );
private readonly arguments: IDeleteCommandArguments; private readonly arguments: IDeleteCommandArguments;

View File

@ -21,7 +21,7 @@ interface DigraphQuickPickItem extends vscode.QuickPickItem {
export class DigraphsCommand extends ExCommand { export class DigraphsCommand extends ExCommand {
public static readonly argParser: Parser<DigraphsCommand> = seq( public static readonly argParser: Parser<DigraphsCommand> = seq(
bangParser, bangParser,
whitespace.then(seq(any, any, whitespace.then(numberParser))).many() whitespace.then(seq(any, any, whitespace.then(numberParser))).many(),
).map(([bang, newDigraphs]) => new DigraphsCommand({ bang, newDigraphs })); ).map(([bang, newDigraphs]) => new DigraphsCommand({ bang, newDigraphs }));
private readonly arguments: IDigraphsCommandArguments; private readonly arguments: IDigraphsCommandArguments;
@ -47,7 +47,7 @@ export class DigraphsCommand extends ExCommand {
// TODO: use arguments // TODO: use arguments
const digraphKeyAndContent = this.makeQuickPicks(Object.entries(configuration.digraphs)).concat( const digraphKeyAndContent = this.makeQuickPicks(Object.entries(configuration.digraphs)).concat(
this.makeQuickPicks([...DefaultDigraphs.entries()]) this.makeQuickPicks([...DefaultDigraphs.entries()]),
); );
vscode.window.showQuickPick(digraphKeyAndContent).then(async (val) => { vscode.window.showQuickPick(digraphKeyAndContent).then(async (val) => {

View File

@ -84,28 +84,28 @@ export class FileCommand extends ExCommand {
bangParser, bangParser,
optWhitespace.then(fileOptParser).fallback([]), optWhitespace.then(fileOptParser).fallback([]),
optWhitespace.then(fileCmdParser).fallback(undefined), optWhitespace.then(fileCmdParser).fallback(undefined),
optWhitespace.then(fileNameParser).fallback(undefined) optWhitespace.then(fileNameParser).fallback(undefined),
).map(([bang, opt, cmd, file]) => new FileCommand({ name: 'edit', bang, opt, cmd, file })), ).map(([bang, opt, cmd, file]) => new FileCommand({ name: 'edit', bang, opt, cmd, file })),
enew: bangParser.map((bang) => new FileCommand({ name: 'enew', bang })), enew: bangParser.map((bang) => new FileCommand({ name: 'enew', bang })),
new: seq( new: seq(
optWhitespace.then(fileOptParser).fallback([]), optWhitespace.then(fileOptParser).fallback([]),
optWhitespace.then(fileCmdParser).fallback(undefined), optWhitespace.then(fileCmdParser).fallback(undefined),
optWhitespace.then(fileNameParser).fallback(undefined) optWhitespace.then(fileNameParser).fallback(undefined),
).map(([opt, cmd, file]) => new FileCommand({ name: 'new', opt, cmd, file })), ).map(([opt, cmd, file]) => new FileCommand({ name: 'new', opt, cmd, file })),
split: seq( split: seq(
optWhitespace.then(fileOptParser).fallback([]), optWhitespace.then(fileOptParser).fallback([]),
optWhitespace.then(fileCmdParser).fallback(undefined), optWhitespace.then(fileCmdParser).fallback(undefined),
optWhitespace.then(fileNameParser).fallback(undefined) optWhitespace.then(fileNameParser).fallback(undefined),
).map(([opt, cmd, file]) => new FileCommand({ name: 'split', opt, cmd, file })), ).map(([opt, cmd, file]) => new FileCommand({ name: 'split', opt, cmd, file })),
vnew: seq( vnew: seq(
optWhitespace.then(fileOptParser).fallback([]), optWhitespace.then(fileOptParser).fallback([]),
optWhitespace.then(fileCmdParser).fallback(undefined), optWhitespace.then(fileCmdParser).fallback(undefined),
optWhitespace.then(fileNameParser).fallback(undefined) optWhitespace.then(fileNameParser).fallback(undefined),
).map(([opt, cmd, file]) => new FileCommand({ name: 'vnew', opt, cmd, file })), ).map(([opt, cmd, file]) => new FileCommand({ name: 'vnew', opt, cmd, file })),
vsplit: seq( vsplit: seq(
optWhitespace.then(fileOptParser).fallback([]), optWhitespace.then(fileOptParser).fallback([]),
optWhitespace.then(fileCmdParser).fallback(undefined), optWhitespace.then(fileCmdParser).fallback(undefined),
optWhitespace.then(fileNameParser).fallback(undefined) optWhitespace.then(fileNameParser).fallback(undefined),
).map(([opt, cmd, file]) => new FileCommand({ name: 'vsplit', opt, cmd, file })), ).map(([opt, cmd, file]) => new FileCommand({ name: 'vsplit', opt, cmd, file })),
}; };
@ -231,7 +231,7 @@ export class FileCommand extends ExCommand {
: undefined; : undefined;
if (lineNumber !== undefined && lineNumber >= 0) { if (lineNumber !== undefined && lineNumber >= 0) {
vscode.window.activeTextEditor!.revealRange( vscode.window.activeTextEditor!.revealRange(
new vscode.Range(new vscode.Position(lineNumber, 0), new vscode.Position(lineNumber, 0)) new vscode.Range(new vscode.Position(lineNumber, 0), new vscode.Position(lineNumber, 0)),
); );
} }
await hidePreviousEditor(); await hidePreviousEditor();

View File

@ -7,7 +7,7 @@ import { bangParser } from '../../vimscript/parserUtils';
export class FileInfoCommand extends ExCommand { export class FileInfoCommand extends ExCommand {
public static readonly argParser: Parser<FileInfoCommand> = seq( public static readonly argParser: Parser<FileInfoCommand> = seq(
bangParser, bangParser,
optWhitespace.then(all) optWhitespace.then(all),
).map(([bang, fileName]) => new FileInfoCommand({ bang, fileName })); ).map(([bang, fileName]) => new FileInfoCommand({ bang, fileName }));
private args: { private args: {

View File

@ -23,7 +23,7 @@ const historyTypeParser: Parser<HistoryCommandType> = alt(
alt(nameAbbrevParser('e', 'xpr'), string('=')).result(HistoryCommandType.Expr), alt(nameAbbrevParser('e', 'xpr'), string('=')).result(HistoryCommandType.Expr),
alt(nameAbbrevParser('i', 'nput'), string('@')).result(HistoryCommandType.Input), alt(nameAbbrevParser('i', 'nput'), string('@')).result(HistoryCommandType.Input),
alt(nameAbbrevParser('d', 'ebug'), string('>')).result(HistoryCommandType.Debug), alt(nameAbbrevParser('d', 'ebug'), string('>')).result(HistoryCommandType.Debug),
nameAbbrevParser('a', 'll').result(HistoryCommandType.All) nameAbbrevParser('a', 'll').result(HistoryCommandType.All),
); );
export interface IHistoryCommandArguments { export interface IHistoryCommandArguments {
@ -51,7 +51,7 @@ export class HistoryCommand extends ExCommand {
case HistoryCommandType.Search: case HistoryCommandType.Search:
await new CommandShowSearchHistory(SearchDirection.Forward).exec( await new CommandShowSearchHistory(SearchDirection.Forward).exec(
vimState.cursorStopPosition, vimState.cursorStopPosition,
vimState vimState,
); );
break; break;
// TODO: Implement these // TODO: Implement these

View File

@ -38,9 +38,9 @@ export class LeftCommand extends ExCommand {
lines lines
.map( .map(
(line) => (line) =>
' '.repeat(this.args.indent) + line.text.slice(line.firstNonWhitespaceCharacterIndex) ' '.repeat(this.args.indent) + line.text.slice(line.firstNonWhitespaceCharacterIndex),
) )
.join('\n') .join('\n'),
); );
} }
} }
@ -79,12 +79,12 @@ export class RightCommand extends ExCommand {
const indent = ' '.repeat( const indent = ' '.repeat(
Math.max( Math.max(
0, 0,
this.args.width - (line.text.length - line.firstNonWhitespaceCharacterIndex) this.args.width - (line.text.length - line.firstNonWhitespaceCharacterIndex),
) ),
); );
return indent + line.text.slice(line.firstNonWhitespaceCharacterIndex); return indent + line.text.slice(line.firstNonWhitespaceCharacterIndex);
}) })
.join('\n') .join('\n'),
); );
} }
} }
@ -123,12 +123,12 @@ export class CenterCommand extends ExCommand {
const indent = ' '.repeat( const indent = ' '.repeat(
Math.max( Math.max(
0, 0,
this.args.width - (line.text.length - line.firstNonWhitespaceCharacterIndex) this.args.width - (line.text.length - line.firstNonWhitespaceCharacterIndex),
) / 2 ) / 2,
); );
return indent + line.text.slice(line.firstNonWhitespaceCharacterIndex); return indent + line.text.slice(line.firstNonWhitespaceCharacterIndex);
}) })
.join('\n') .join('\n'),
); );
} }
} }

View File

@ -79,11 +79,11 @@ export class DeleteMarksCommand extends ExCommand {
seq(regexp(/[0-9]/).skip(string('-')), regexp(/[0-9]/)).map(([start, end]) => { seq(regexp(/[0-9]/).skip(string('-')), regexp(/[0-9]/)).map(([start, end]) => {
return { start, end }; return { start, end };
}), }),
noneOf('-') noneOf('-'),
) ),
)
.many()
) )
.many(),
),
).map((marks) => new DeleteMarksCommand(marks)); ).map((marks) => new DeleteMarksCommand(marks));
private args: DeleteMarksArgs; private args: DeleteMarksArgs;

View File

@ -43,7 +43,7 @@ export class MoveCommand extends ExCommand {
// copy // copy
const copiedText = vimState.document.getText( const copiedText = vimState.document.getText(
new Range(new Position(sourceStart, 0), new Position(sourceEnd, 0).getLineEnd()) new Range(new Position(sourceStart, 0), new Position(sourceEnd, 0).getLineEnd()),
); );
let text: string; let text: string;
@ -62,12 +62,12 @@ export class MoveCommand extends ExCommand {
// make the cursor position at the beginning of the endline. // make the cursor position at the beginning of the endline.
cursorPosition = new Position( cursorPosition = new Position(
Math.max(dest, 0), Math.max(dest, 0),
lines[lines.length - 1].match(/\S/)?.index ?? 0 lines[lines.length - 1].match(/\S/)?.index ?? 0,
); );
} else { } else {
cursorPosition = new Position( cursorPosition = new Position(
Math.max(dest + lines.length, 0), Math.max(dest + lines.length, 0),
lines[lines.length - 1].match(/\S/)?.index ?? 0 lines[lines.length - 1].match(/\S/)?.index ?? 0,
); );
} }
// delete // delete
@ -89,7 +89,7 @@ export class MoveCommand extends ExCommand {
vimState.recordedState.transformer.insert( vimState.recordedState.transformer.insert(
position, position,
text, text,
PositionDiff.exactPosition(cursorPosition) PositionDiff.exactPosition(cursorPosition),
); );
} }

View File

@ -31,8 +31,8 @@ export class PutExCommand extends ExCommand {
optWhitespace optWhitespace
.then(any) .then(any)
.map((x) => ({ register: x })) .map((x) => ({ register: x }))
.fallback({ register: undefined }) .fallback({ register: undefined }),
) ),
).map(([bang, register]) => new PutExCommand({ bang, ...register })); ).map(([bang, register]) => new PutExCommand({ bang, ...register }));
public readonly arguments: IPutCommandArguments; public readonly arguments: IPutCommandArguments;
@ -53,7 +53,7 @@ export class PutExCommand extends ExCommand {
vimState, vimState,
this.arguments.register, this.arguments.register,
this.arguments.fromExpression, this.arguments.fromExpression,
0 0,
); );
} }

View File

@ -17,14 +17,14 @@ export interface IQuitCommandArguments {
// //
export class QuitCommand extends ExCommand { export class QuitCommand extends ExCommand {
public static readonly argParser: (quitAll: boolean) => Parser<QuitCommand> = ( public static readonly argParser: (quitAll: boolean) => Parser<QuitCommand> = (
quitAll: boolean quitAll: boolean,
) => ) =>
bangParser.map( bangParser.map(
(bang) => (bang) =>
new QuitCommand({ new QuitCommand({
bang, bang,
quitAll, quitAll,
}) }),
); );
public override isRepeatableWithDot = false; public override isRepeatableWithDot = false;

View File

@ -5,10 +5,9 @@ import { ExCommand } from '../../vimscript/exCommand';
import { fileNameParser, FileOpt, fileOptParser } from '../../vimscript/parserUtils'; import { fileNameParser, FileOpt, fileOptParser } from '../../vimscript/parserUtils';
import { all, alt, optWhitespace, Parser, seq, string, whitespace } from 'parsimmon'; import { all, alt, optWhitespace, Parser, seq, string, whitespace } from 'parsimmon';
export type IReadCommandArguments = export type IReadCommandArguments = {
| {
opt: FileOpt; opt: FileOpt;
} & ({ cmd: string } | { file: string } | {}); } & ({ cmd: string } | { file: string } | {});
// //
// Implements :read and :read! // Implements :read and :read!
@ -28,10 +27,10 @@ export class ReadCommand extends ExCommand {
}), }),
fileNameParser.map((file) => { fileNameParser.map((file) => {
return { file }; return { file };
}) }),
),
) )
) .fallback(undefined),
.fallback(undefined)
).map(([opt, other]) => new ReadCommand({ opt, ...other })); ).map(([opt, other]) => new ReadCommand({ opt, ...other }));
private readonly arguments: IReadCommandArguments; private readonly arguments: IReadCommandArguments;
@ -49,7 +48,7 @@ export class ReadCommand extends ExCommand {
if (textToInsert) { if (textToInsert) {
vimState.recordedState.transformer.insert( vimState.recordedState.transformer.insert(
vimState.cursorStopPosition.getLineEnd(), vimState.cursorStopPosition.getLineEnd(),
'\n' + textToInsert '\n' + textToInsert,
); );
} }
} }

View File

@ -10,7 +10,7 @@ import { any, optWhitespace, Parser } from 'parsimmon';
export class RegisterCommand extends ExCommand { export class RegisterCommand extends ExCommand {
public static readonly argParser: Parser<RegisterCommand> = optWhitespace.then( public static readonly argParser: Parser<RegisterCommand> = optWhitespace.then(
any.sepBy(optWhitespace).map((registers) => new RegisterCommand(registers)) any.sepBy(optWhitespace).map((registers) => new RegisterCommand(registers)),
); );
private readonly registers: string[]; private readonly registers: string[];
@ -61,7 +61,7 @@ export class RegisterCommand extends ExCommand {
} else { } else {
const currentRegisterKeys = Register.getKeys() const currentRegisterKeys = Register.getKeys()
.filter( .filter(
(reg) => reg !== '_' && (this.registers.length === 0 || this.registers.includes(reg)) (reg) => reg !== '_' && (this.registers.length === 0 || this.registers.includes(reg)),
) )
.sort((reg1: string, reg2: string) => this.regSortOrder(reg1) - this.regSortOrder(reg2)); .sort((reg1: string, reg2: string) => this.regSortOrder(reg1) - this.regSortOrder(reg2));
const registerKeyAndContent = new Array<vscode.QuickPickItem>(); const registerKeyAndContent = new Array<vscode.QuickPickItem>();

View File

@ -22,13 +22,13 @@ interface UpdatedLineSegment {
export class RetabCommand extends ExCommand { export class RetabCommand extends ExCommand {
public static readonly argParser: Parser<RetabCommand> = seq( public static readonly argParser: Parser<RetabCommand> = seq(
bangParser, bangParser,
optWhitespace.then(numberParser).fallback(undefined) optWhitespace.then(numberParser).fallback(undefined),
).map( ).map(
([replaceSpaces, newTabstop]) => ([replaceSpaces, newTabstop]) =>
new RetabCommand({ new RetabCommand({
replaceSpaces, replaceSpaces,
newTabstop, newTabstop,
}) }),
); );
private readonly arguments: IRetabCommandArguments; private readonly arguments: IRetabCommandArguments;
@ -88,7 +88,7 @@ export class RetabCommand extends ExCommand {
retabLineSegment( retabLineSegment(
segment: string, segment: string,
start: number, start: number,
tabstop = configuration.tabstop tabstop = configuration.tabstop,
): UpdatedLineSegment { ): UpdatedLineSegment {
const retab = this.arguments.replaceSpaces || this.hasTabs(segment); const retab = this.arguments.replaceSpaces || this.hasTabs(segment);

View File

@ -102,7 +102,7 @@ const setOperationParser: Parser<SetOperation> = whitespace
option, option,
source, source,
}; };
} },
), ),
seq(optionParser.skip(oneOf('=:')), valueParser).map(([option, value]) => { seq(optionParser.skip(oneOf('=:')), valueParser).map(([option, value]) => {
return { return {
@ -137,14 +137,14 @@ const setOperationParser: Parser<SetOperation> = whitespace
type: 'show_or_set', type: 'show_or_set',
option, option,
}; };
}) }),
) ),
) )
.fallback({ type: 'show_or_set', option: undefined }); .fallback({ type: 'show_or_set', option: undefined });
export class SetCommand extends ExCommand { export class SetCommand extends ExCommand {
public static readonly argParser: Parser<SetCommand> = setOperationParser.map( public static readonly argParser: Parser<SetCommand> = setOperationParser.map(
(operation) => new SetCommand(operation) (operation) => new SetCommand(operation),
); );
private readonly operation: SetOperation; private readonly operation: SetOperation;
@ -225,7 +225,7 @@ export class SetCommand extends ExCommand {
// TODO: Could also be {option}:{value} // TODO: Could also be {option}:{value}
throw VimError.fromCode( throw VimError.fromCode(
ErrorCode.NumberRequiredAfterEqual, ErrorCode.NumberRequiredAfterEqual,
`${option}=${this.operation.value}` `${option}=${this.operation.value}`,
); );
} }
configuration[option] = value; configuration[option] = value;
@ -242,7 +242,7 @@ export class SetCommand extends ExCommand {
if (isNaN(value)) { if (isNaN(value)) {
throw VimError.fromCode( throw VimError.fromCode(
ErrorCode.NumberRequiredAfterEqual, ErrorCode.NumberRequiredAfterEqual,
`${option}+=${this.operation.value}` `${option}+=${this.operation.value}`,
); );
} }
configuration[option] = currentValue + value; configuration[option] = currentValue + value;
@ -259,7 +259,7 @@ export class SetCommand extends ExCommand {
if (isNaN(value)) { if (isNaN(value)) {
throw VimError.fromCode( throw VimError.fromCode(
ErrorCode.NumberRequiredAfterEqual, ErrorCode.NumberRequiredAfterEqual,
`${option}^=${this.operation.value}` `${option}^=${this.operation.value}`,
); );
} }
configuration[option] = currentValue * value; configuration[option] = currentValue * value;
@ -276,7 +276,7 @@ export class SetCommand extends ExCommand {
if (isNaN(value)) { if (isNaN(value)) {
throw VimError.fromCode( throw VimError.fromCode(
ErrorCode.NumberRequiredAfterEqual, ErrorCode.NumberRequiredAfterEqual,
`${option}-=${this.operation.value}` `${option}-=${this.operation.value}`,
); );
} }
configuration[option] = currentValue - value; configuration[option] = currentValue - value;

View File

@ -25,8 +25,8 @@ export class ShiftCommand extends ExCommand {
.map((shifts) => shifts.length + 1) .map((shifts) => shifts.length + 1)
.skip(optWhitespace), .skip(optWhitespace),
// `:> 2` indents 2 lines // `:> 2` indents 2 lines
numberParser.fallback(undefined) numberParser.fallback(undefined),
) ),
) )
.map(([depth, numLines]) => new ShiftCommand({ dir, depth, numLines })); .map(([depth, numLines]) => new ShiftCommand({ dir, depth, numLines }));

View File

@ -21,7 +21,7 @@ export interface ISortCommandArguments {
export class SortCommand extends ExCommand { export class SortCommand extends ExCommand {
public static readonly argParser: Parser<SortCommand> = seq( public static readonly argParser: Parser<SortCommand> = seq(
bangParser, bangParser,
optWhitespace.then(oneOf('bfilnorux').many()) optWhitespace.then(oneOf('bfilnorux').many()),
).map( ).map(
([bang, flags]) => ([bang, flags]) =>
new SortCommand({ new SortCommand({
@ -29,7 +29,7 @@ export class SortCommand extends ExCommand {
ignoreCase: flags.includes('i'), ignoreCase: flags.includes('i'),
unique: flags.includes('u'), unique: flags.includes('u'),
numeric: flags.includes('n'), numeric: flags.includes('n'),
}) }),
); );
private readonly arguments: ISortCommandArguments; private readonly arguments: ISortCommandArguments;
@ -82,7 +82,7 @@ export class SortCommand extends ExCommand {
sortedLines = originalLines.sort( sortedLines = originalLines.sort(
(a: string, b: string) => (a: string, b: string) =>
(NumericString.parse(a, NumericStringRadix.Dec)?.num.value ?? Number.MAX_VALUE) - (NumericString.parse(a, NumericStringRadix.Dec)?.num.value ?? Number.MAX_VALUE) -
(NumericString.parse(b, NumericStringRadix.Dec)?.num.value ?? Number.MAX_VALUE) (NumericString.parse(b, NumericStringRadix.Dec)?.num.value ?? Number.MAX_VALUE),
); );
} else if (this.arguments.ignoreCase) { } else if (this.arguments.ignoreCase) {
sortedLines = originalLines.sort((a: string, b: string) => a.localeCompare(b)); sortedLines = originalLines.sort((a: string, b: string) => a.localeCompare(b));
@ -101,7 +101,7 @@ export class SortCommand extends ExCommand {
range: new vscode.Range(startLine, 0, endLine, lastLineLength), range: new vscode.Range(startLine, 0, endLine, lastLineLength),
text: sortedContent, text: sortedContent,
diff: PositionDiff.exactPosition( diff: PositionDiff.exactPosition(
new vscode.Position(startLine, sortedLines[0].match(/\S/)?.index ?? 0) new vscode.Position(startLine, sortedLines[0].match(/\S/)?.index ?? 0),
), ),
}); });
} }

View File

@ -136,18 +136,18 @@ const replaceStringParser = (delimiter: string): Parser<ReplaceString> =>
} else { } else {
return { type: 'string' as const, value: `\\${escaped}` }; return { type: 'string' as const, value: `\\${escaped}` };
} }
}) }),
), ),
string('&').result({ type: 'capture_group' as const, group: '&' }), string('&').result({ type: 'capture_group' as const, group: '&' }),
string('~').result({ type: 'prev_replace_string' as const }), string('~').result({ type: 'prev_replace_string' as const }),
noneOf(delimiter).map((value) => ({ type: 'string', value })) noneOf(delimiter).map((value) => ({ type: 'string', value })),
) )
.many() .many()
.map((components) => new ReplaceString(components)); .map((components) => new ReplaceString(components));
const substituteFlagsParser: Parser<SubstituteFlags> = seq( const substituteFlagsParser: Parser<SubstituteFlags> = seq(
string('&').fallback(undefined), string('&').fallback(undefined),
oneOf('cegiInp#lr').many() oneOf('cegiInp#lr').many(),
).map(([amp, flagChars]) => { ).map(([amp, flagChars]) => {
const flags: SubstituteFlags = {}; const flags: SubstituteFlags = {};
if (amp === '&') { if (amp === '&') {
@ -228,11 +228,11 @@ export class SubstituteCommand extends ExCommand {
Pattern.parser({ direction: SearchDirection.Forward, delimiter }), Pattern.parser({ direction: SearchDirection.Forward, delimiter }),
replaceStringParser(delimiter), replaceStringParser(delimiter),
string(delimiter).then(substituteFlagsParser).fallback({}), string(delimiter).then(substituteFlagsParser).fallback({}),
countParser countParser,
).map( ).map(
([pattern, replace, flags, count]) => ([pattern, replace, flags, count]) =>
new SubstituteCommand({ pattern, replace, flags, count }) new SubstituteCommand({ pattern, replace, flags, count }),
) ),
), ),
// :s[ubstitute] [flags] [count] // :s[ubstitute] [flags] [count]
@ -243,9 +243,9 @@ export class SubstituteCommand extends ExCommand {
replace: new ReplaceString([]), replace: new ReplaceString([]),
flags, flags,
count, count,
}) }),
) ),
) ),
); );
public readonly arguments: ISubstituteCommandArguments; public readonly arguments: ISubstituteCommandArguments;
@ -265,7 +265,7 @@ export class SubstituteCommand extends ExCommand {
public getSubstitutionDecorations( public getSubstitutionDecorations(
vimState: VimState, vimState: VimState,
lineRange = new LineRange(new Address({ type: 'current_line' })) lineRange = new LineRange(new Address({ type: 'current_line' })),
): SearchDecorations { ): SearchDecorations {
const substitutionAppend: DecorationOptions[] = []; const substitutionAppend: DecorationOptions[] = [];
const substitutionReplace: DecorationOptions[] = []; const substitutionReplace: DecorationOptions[] = [];
@ -298,7 +298,7 @@ export class SubstituteCommand extends ExCommand {
if (showReplacements) { if (showReplacements) {
const contentText = formatDecorationText( const contentText = formatDecorationText(
replace.resolve(match.groups), replace.resolve(match.groups),
vimState.editor.options.tabSize as number vimState.editor.options.tabSize as number,
); );
subsArr.push({ subsArr.push({
@ -320,7 +320,7 @@ export class SubstituteCommand extends ExCommand {
*/ */
private async replaceMatchRange( private async replaceMatchRange(
vimState: VimState, vimState: VimState,
match: PatternMatch match: PatternMatch,
): Promise<number | undefined> { ): Promise<number | undefined> {
if (this.arguments.flags.printCount) { if (this.arguments.flags.printCount) {
return 0; return 0;
@ -346,7 +346,7 @@ export class SubstituteCommand extends ExCommand {
private async confirmReplacement( private async confirmReplacement(
vimState: VimState, vimState: VimState,
match: PatternMatch, match: PatternMatch,
replaceText: string replaceText: string,
): Promise<boolean> { ): Promise<boolean> {
const cancellationToken = new CancellationTokenSource(); const cancellationToken = new CancellationTokenSource();
const validSelections: readonly string[] = ['y', 'n', 'a', 'q', 'l']; const validSelections: readonly string[] = ['y', 'n', 'a', 'q', 'l'];
@ -355,8 +355,8 @@ export class SubstituteCommand extends ExCommand {
`Replace with ${formatDecorationText( `Replace with ${formatDecorationText(
replaceText, replaceText,
vimState.editor.options.tabSize as number, vimState.editor.options.tabSize as number,
'\\n' '\\n',
)} (${validSelections.join('/')})?` )} (${validSelections.join('/')})?`,
); );
const newConfirmationSearchHighlights = const newConfirmationSearchHighlights =
@ -367,7 +367,7 @@ export class SubstituteCommand extends ExCommand {
vimState.editor.setDecorations(decoration.searchMatch, [ensureVisible(match.range)]); vimState.editor.setDecorations(decoration.searchMatch, [ensureVisible(match.range)]);
vimState.editor.setDecorations( vimState.editor.setDecorations(
decoration.confirmedSubstitution, decoration.confirmedSubstitution,
this.confirmedSubstitutions ?? [] this.confirmedSubstitutions ?? [],
); );
await window.showInputBox( await window.showInputBox(
{ {
@ -382,7 +382,7 @@ export class SubstituteCommand extends ExCommand {
return prompt; return prompt;
}, },
}, },
cancellationToken.token cancellationToken.token,
); );
if (selection === 'q' || selection === 'l' || !selection) { if (selection === 'q' || selection === 'l' || !selection) {
@ -402,7 +402,7 @@ export class SubstituteCommand extends ExCommand {
before: { before: {
contentText: formatDecorationText( contentText: formatDecorationText(
replaceText, replaceText,
vimState.editor.options.tabSize as number vimState.editor.options.tabSize as number,
), ),
}, },
}, },
@ -481,7 +481,7 @@ export class SubstituteCommand extends ExCommand {
lineRange: new LineRange( lineRange: new LineRange(
new Address({ type: 'number', num: start + 1 }), new Address({ type: 'number', num: start + 1 }),
',', ',',
new Address({ type: 'number', num: end + 1 }) new Address({ type: 'number', num: end + 1 }),
), ),
}) ?? []; }) ?? [];
@ -539,7 +539,7 @@ export class SubstituteCommand extends ExCommand {
document: vimState.document, document: vimState.document,
position: cursor, position: cursor,
}), }),
Jump.fromStateNow(vimState) Jump.fromStateNow(vimState),
); );
vimState.recordedState.transformer.moveCursor(PositionDiff.exactPosition(cursor), 0); vimState.recordedState.transformer.moveCursor(PositionDiff.exactPosition(cursor), 0);
} }
@ -556,7 +556,7 @@ export class SubstituteCommand extends ExCommand {
SearchDirection.Forward, SearchDirection.Forward,
vimState.cursorStopPosition, vimState.cursorStopPosition,
pattern?.patternString, pattern?.patternString,
{} {},
); );
} }
} }
@ -565,21 +565,21 @@ export class SubstituteCommand extends ExCommand {
if (substitutions === 0) { if (substitutions === 0) {
StatusBar.displayError( StatusBar.displayError(
vimState, vimState,
VimError.fromCode(ErrorCode.PatternNotFound, this.arguments.pattern?.patternString) VimError.fromCode(ErrorCode.PatternNotFound, this.arguments.pattern?.patternString),
); );
} else if (this.arguments.flags.printCount) { } else if (this.arguments.flags.printCount) {
StatusBar.setText( StatusBar.setText(
vimState, vimState,
`${substitutions} match${substitutions > 1 ? 'es' : ''} on ${lines} line${ `${substitutions} match${substitutions > 1 ? 'es' : ''} on ${lines} line${
lines > 1 ? 's' : '' lines > 1 ? 's' : ''
}` }`,
); );
} else if (substitutions > configuration.report) { } else if (substitutions > configuration.report) {
StatusBar.setText( StatusBar.setText(
vimState, vimState,
`${substitutions} substitution${substitutions > 1 ? 's' : ''} on ${lines} line${ `${substitutions} substitution${substitutions > 1 ? 's' : ''} on ${lines} line${
lines > 1 ? 's' : '' lines > 1 ? 's' : ''
}` }`,
); );
} }
} }

View File

@ -79,31 +79,31 @@ export class TabCommand extends ExCommand {
bnext: seq( bnext: seq(
bangParser, bangParser,
optWhitespace.then(fileCmdParser).fallback(undefined), optWhitespace.then(fileCmdParser).fallback(undefined),
optWhitespace.then(numberParser).fallback(undefined) optWhitespace.then(numberParser).fallback(undefined),
).map(([bang, cmd, count]) => { ).map(([bang, cmd, count]) => {
return new TabCommand({ type: TabCommandType.Next, bang, cmd, count }); return new TabCommand({ type: TabCommandType.Next, bang, cmd, count });
}), }),
bprev: seq( bprev: seq(
bangParser, bangParser,
optWhitespace.then(fileCmdParser).fallback(undefined), optWhitespace.then(fileCmdParser).fallback(undefined),
optWhitespace.then(numberParser).fallback(undefined) optWhitespace.then(numberParser).fallback(undefined),
).map(([bang, cmd, count]) => { ).map(([bang, cmd, count]) => {
return new TabCommand({ type: TabCommandType.Previous, bang, cmd, count }); return new TabCommand({ type: TabCommandType.Previous, bang, cmd, count });
}), }),
tabclose: seq(bangParser, optWhitespace.then(numberParser).fallback(undefined)).map( tabclose: seq(bangParser, optWhitespace.then(numberParser).fallback(undefined)).map(
([bang, count]) => { ([bang, count]) => {
return new TabCommand({ type: TabCommandType.Close, bang, count }); return new TabCommand({ type: TabCommandType.Close, bang, count });
} },
), ),
tabonly: seq(bangParser, optWhitespace.then(numberParser).fallback(undefined)).map( tabonly: seq(bangParser, optWhitespace.then(numberParser).fallback(undefined)).map(
([bang, count]) => { ([bang, count]) => {
return new TabCommand({ type: TabCommandType.Only, bang, count }); return new TabCommand({ type: TabCommandType.Only, bang, count });
} },
), ),
tabnew: seq( tabnew: seq(
optWhitespace.then(fileOptParser).fallback([]), optWhitespace.then(fileOptParser).fallback([]),
optWhitespace.then(fileCmdParser).fallback(undefined), optWhitespace.then(fileCmdParser).fallback(undefined),
regexp(/\S+/).fallback(undefined) regexp(/\S+/).fallback(undefined),
).map(([opt, cmd, file]) => { ).map(([opt, cmd, file]) => {
return new TabCommand({ return new TabCommand({
type: TabCommandType.New, type: TabCommandType.New,
@ -116,10 +116,10 @@ export class TabCommand extends ExCommand {
.then( .then(
seq( seq(
alt<'right' | 'left'>(string('+').result('right'), string('-').result('left')).fallback( alt<'right' | 'left'>(string('+').result('right'), string('-').result('left')).fallback(
undefined undefined,
),
numberParser.fallback(undefined),
), ),
numberParser.fallback(undefined)
)
) )
.map(([direction, count]) => new TabCommand({ type: TabCommandType.Move, direction, count })), .map(([direction, count]) => new TabCommand({ type: TabCommandType.Move, direction, count })),
}; };
@ -142,7 +142,7 @@ export class TabCommand extends ExCommand {
if (this.arguments.count !== undefined && this.arguments.count >= 0) { if (this.arguments.count !== undefined && this.arguments.count >= 0) {
await vscode.commands.executeCommand( await vscode.commands.executeCommand(
'workbench.action.openEditorAtIndex', 'workbench.action.openEditorAtIndex',
this.arguments.count this.arguments.count,
); );
} }
break; break;
@ -172,7 +172,7 @@ export class TabCommand extends ExCommand {
await this.executeCommandWithCount( await this.executeCommandWithCount(
this.arguments.count || 1, this.arguments.count || 1,
'workbench.action.previousEditorInGroup' 'workbench.action.previousEditorInGroup',
); );
break; break;
case TabCommandType.First: case TabCommandType.First:

View File

@ -10,7 +10,7 @@ import { bangParser } from '../../vimscript/parserUtils';
// //
export class WallCommand extends ExCommand { export class WallCommand extends ExCommand {
public static readonly argParser: Parser<WallCommand> = bangParser.map( public static readonly argParser: Parser<WallCommand> = bangParser.map(
(bang) => new WallCommand(bang) (bang) => new WallCommand(bang),
); );
private readonly bang: boolean; private readonly bang: boolean;

View File

@ -8,13 +8,12 @@ import { ExCommand } from '../../vimscript/exCommand';
import { all, alt, optWhitespace, Parser, regexp, seq, string } from 'parsimmon'; import { all, alt, optWhitespace, Parser, regexp, seq, string } from 'parsimmon';
import { bangParser, fileNameParser, FileOpt, fileOptParser } from '../../vimscript/parserUtils'; import { bangParser, fileNameParser, FileOpt, fileOptParser } from '../../vimscript/parserUtils';
export type IWriteCommandArguments = export type IWriteCommandArguments = {
| {
bang: boolean; bang: boolean;
opt: FileOpt; opt: FileOpt;
bgWrite: boolean; bgWrite: boolean;
file?: string; file?: string;
} & ({ cmd: string } | {}); } & ({ cmd: string } | {});
// //
// Implements :write // Implements :write
@ -32,9 +31,9 @@ export class WriteCommand extends ExCommand {
}), }),
fileNameParser.map((file) => { fileNameParser.map((file) => {
return { file }; return { file };
}) }),
// TODO: Support `:help :w_a` ('>>') // TODO: Support `:help :w_a` ('>>')
).fallback({}) ).fallback({}),
).map(([bang, opt, other]) => new WriteCommand({ bang, opt, bgWrite: true, ...other })); ).map(([bang, opt, other]) => new WriteCommand({ bang, opt, bgWrite: true, ...other }));
public override isRepeatableWithDot = false; public override isRepeatableWithDot = false;
@ -107,7 +106,7 @@ export class WriteCommand extends ExCommand {
`File "${fileName}" already exists. Do you want to overwrite it?`, `File "${fileName}" already exists. Do you want to overwrite it?`,
{ modal: true }, { modal: true },
'Yes', 'Yes',
'No' 'No',
); );
if (confirmOverwrite === 'No') { if (confirmOverwrite === 'No') {
@ -124,7 +123,7 @@ export class WriteCommand extends ExCommand {
vimState, vimState,
`"${fileName}" ${fileExists ? '' : '[New]'} ${vimState.document.lineCount}L ${ `"${fileName}" ${fileExists ? '' : '[New]'} ${vimState.document.lineCount}L ${
vimState.document.getText().length vimState.document.getText().length
}C written` }C written`,
); );
} catch (e) { } catch (e) {
StatusBar.setText(vimState, e.message); StatusBar.setText(vimState, e.message);
@ -139,13 +138,13 @@ export class WriteCommand extends ExCommand {
vimState, vimState,
`"${path.basename(vimState.document.fileName)}" ${vimState.document.lineCount}L ${ `"${path.basename(vimState.document.fileName)}" ${vimState.document.lineCount}L ${
vimState.document.getText().length vimState.document.getText().length
}C written` }C written`,
); );
} else { } else {
Logger.warn(':w failed'); Logger.warn(':w failed');
// TODO: What's the right thing to do here? // TODO: What's the right thing to do here?
} }
}) }),
); );
} }

View File

@ -19,7 +19,7 @@ export class WriteQuitCommand extends ExCommand {
public static readonly argParser: Parser<WriteQuitCommand> = seq( public static readonly argParser: Parser<WriteQuitCommand> = seq(
bangParser.skip(optWhitespace), bangParser.skip(optWhitespace),
fileOptParser.skip(optWhitespace), fileOptParser.skip(optWhitespace),
fileNameParser.fallback(undefined) fileNameParser.fallback(undefined),
).map(([bang, opt, file]) => new WriteQuitCommand(file ? { bang, opt, file } : { bang, opt })); ).map(([bang, opt, file]) => new WriteQuitCommand(file ? { bang, opt, file } : { bang, opt }));
public override isRepeatableWithDot = false; public override isRepeatableWithDot = false;

View File

@ -17,7 +17,7 @@ export interface IWriteQuitAllCommandArguments {
export class WriteQuitAllCommand extends ExCommand { export class WriteQuitAllCommand extends ExCommand {
public static readonly argParser: Parser<WriteQuitAllCommand> = seq( public static readonly argParser: Parser<WriteQuitAllCommand> = seq(
bangParser, bangParser,
whitespace.then(fileOptParser).fallback([]) whitespace.then(fileOptParser).fallback([]),
).map(([bang, fileOpt]) => new WriteQuitAllCommand({ bang, fileOpt })); ).map(([bang, fileOpt]) => new WriteQuitAllCommand({ bang, fileOpt }));
public override isRepeatableWithDot = false; public override isRepeatableWithDot = false;

View File

@ -21,15 +21,15 @@ export class YankCommand extends ExCommand {
seq(any.fallback(undefined), whitespace.then(numberParser).fallback(undefined)).map( seq(any.fallback(undefined), whitespace.then(numberParser).fallback(undefined)).map(
([register, count]) => { ([register, count]) => {
return { register, count }; return { register, count };
} },
) ),
).map( ).map(
({ register, count }) => ({ register, count }) =>
new YankCommand({ new YankCommand({
register, register,
count, count,
}) }),
) ),
); );
private readonly arguments: YankCommandArguments; private readonly arguments: YankCommandArguments;

View File

@ -23,7 +23,7 @@ const RangeExpression: Expression = {
optWhitespace, optWhitespace,
['step', string(',').then(optWhitespace).then(integerParser).fallback(1)], ['step', string(',').then(optWhitespace).then(integerParser).fallback(1)],
optWhitespace, optWhitespace,
string(')') string(')'),
).map(({ start, end, step }): string => { ).map(({ start, end, step }): string => {
const numbers = range(start, end, step); const numbers = range(start, end, step);
if (numbers.length === 0) { if (numbers.length === 0) {
@ -42,5 +42,5 @@ export const expressionParser = seqObj<{ register: string; fromExpression: strin
optWhitespace, optWhitespace,
['register', EXPRESSION_REGISTER], ['register', EXPRESSION_REGISTER],
optWhitespace, optWhitespace,
['fromExpression', altExpressions] ['fromExpression', altExpressions],
); );

View File

@ -42,7 +42,7 @@ export class PairMatcher {
stackHeight: number, stackHeight: number,
isNextMatchForward: boolean, isNextMatchForward: boolean,
vimState: VimState, vimState: VimState,
allowCurrentPosition: boolean allowCurrentPosition: boolean,
): Position | undefined { ): Position | undefined {
let lineNumber = position.line; let lineNumber = position.line;
const linePosition = position.character; const linePosition = position.character;
@ -139,7 +139,7 @@ export class PairMatcher {
position: Position, position: Position,
charToMatch: string, charToMatch: string,
vimState: VimState, vimState: VimState,
allowCurrentPosition: boolean allowCurrentPosition: boolean,
): Position | undefined { ): Position | undefined {
/** /**
* We do a fairly basic implementation that only tracks the state of the type of * We do a fairly basic implementation that only tracks the state of the type of
@ -169,7 +169,7 @@ export class PairMatcher {
stackHeight, stackHeight,
pairing.isNextMatchForward, pairing.isNextMatchForward,
vimState, vimState,
allowCurrentPosition allowCurrentPosition,
); );
} }
} }

View File

@ -78,7 +78,7 @@ export class TagMatcher {
const firstNonWhitespacePositionOnLine = TextEditor.getFirstNonWhitespaceCharOnLine( const firstNonWhitespacePositionOnLine = TextEditor.getFirstNonWhitespaceCharOnLine(
vimState.document, vimState.document,
vimState.cursorStartPosition.line vimState.cursorStartPosition.line,
); );
/** /**
@ -109,7 +109,7 @@ export class TagMatcher {
const nodeSurrounding = this.determineRelevantTag( const nodeSurrounding = this.determineRelevantTag(
tagsSurrounding, tagsSurrounding,
startPosOffset, startPosOffset,
vimState.cursorStartPosition.compareTo(vimState.cursorStopPosition) !== 0 vimState.cursorStartPosition.compareTo(vimState.cursorStopPosition) !== 0,
); );
if (!nodeSurrounding) { if (!nodeSurrounding) {
@ -140,7 +140,7 @@ export class TagMatcher {
determineRelevantTag( determineRelevantTag(
tagsSurrounding: MatchedTag[], tagsSurrounding: MatchedTag[],
adjustedStartPosOffset: number, adjustedStartPosOffset: number,
selectionActive: boolean selectionActive: boolean,
): MatchedTag | undefined { ): MatchedTag | undefined {
const relevantTag = tagsSurrounding[0]; const relevantTag = tagsSurrounding[0];

View File

@ -163,7 +163,7 @@ declare module 'vscode' {
*/ */
prevWordStart( prevWordStart(
document: vscode.TextDocument, document: vscode.TextDocument,
args?: { wordType?: WordType; inclusive?: boolean } args?: { wordType?: WordType; inclusive?: boolean },
): Position; ): Position;
/** /**
@ -174,7 +174,7 @@ declare module 'vscode' {
*/ */
nextWordStart( nextWordStart(
document: vscode.TextDocument, document: vscode.TextDocument,
args?: { wordType?: WordType; inclusive?: boolean } args?: { wordType?: WordType; inclusive?: boolean },
): Position; ): Position;
/** /**
@ -192,7 +192,7 @@ declare module 'vscode' {
*/ */
nextWordEnd( nextWordEnd(
document: vscode.TextDocument, document: vscode.TextDocument,
args?: { wordType?: WordType; inclusive?: boolean } args?: { wordType?: WordType; inclusive?: boolean },
): Position; ): Position;
getSentenceBegin(args: { forward: boolean }): Position; getSentenceBegin(args: { forward: boolean }): Position;
@ -264,7 +264,7 @@ Position.prototype.add = function (
this: Position, this: Position,
document: vscode.TextDocument, document: vscode.TextDocument,
diff: PositionDiff, diff: PositionDiff,
boundsCheck = true boundsCheck = true,
): Position { ): Position {
if (diff.type === PositionDiffType.ExactPosition) { if (diff.type === PositionDiffType.ExactPosition) {
return new Position(diff.line, diff.character); return new Position(diff.line, diff.character);
@ -318,7 +318,7 @@ Position.prototype.getLeft = function (this: Position, count = 1): Position {
Position.prototype.getRight = function (this: Position, count = 1): Position { Position.prototype.getRight = function (this: Position, count = 1): Position {
return new Position( return new Position(
this.line, this.line,
Math.min(this.character + count, TextEditor.getLineLength(this.line)) Math.min(this.character + count, TextEditor.getLineLength(this.line)),
); );
}; };
@ -348,7 +348,7 @@ Position.prototype.getUp = function (this: Position, count = 1): Position {
*/ */
Position.prototype.getLeftThroughLineBreaks = function ( Position.prototype.getLeftThroughLineBreaks = function (
this: Position, this: Position,
includeEol = true includeEol = true,
): Position { ): Position {
if (!this.isLineBeginning()) { if (!this.isLineBeginning()) {
return this.getLeft(); return this.getLeft();
@ -368,7 +368,7 @@ Position.prototype.getLeftThroughLineBreaks = function (
Position.prototype.getRightThroughLineBreaks = function ( Position.prototype.getRightThroughLineBreaks = function (
this: Position, this: Position,
includeEol = false includeEol = false,
): Position { ): Position {
if (this.isAtDocumentEnd()) { if (this.isAtDocumentEnd()) {
return this; return this;
@ -389,7 +389,7 @@ Position.prototype.getRightThroughLineBreaks = function (
Position.prototype.getOffsetThroughLineBreaks = function ( Position.prototype.getOffsetThroughLineBreaks = function (
this: Position, this: Position,
offset: number offset: number,
): Position { ): Position {
let pos = new Position(this.line, this.character); let pos = new Position(this.line, this.character);
@ -409,7 +409,7 @@ Position.prototype.getOffsetThroughLineBreaks = function (
Position.prototype.prevWordStart = function ( Position.prototype.prevWordStart = function (
this: Position, this: Position,
document: vscode.TextDocument, document: vscode.TextDocument,
args?: { wordType?: WordType; inclusive?: boolean } args?: { wordType?: WordType; inclusive?: boolean },
): Position { ): Position {
return prevWordStart(document, this, args?.wordType ?? WordType.Normal, args?.inclusive ?? false); return prevWordStart(document, this, args?.wordType ?? WordType.Normal, args?.inclusive ?? false);
}; };
@ -417,7 +417,7 @@ Position.prototype.prevWordStart = function (
Position.prototype.nextWordStart = function ( Position.prototype.nextWordStart = function (
this: Position, this: Position,
document: vscode.TextDocument, document: vscode.TextDocument,
args?: { wordType?: WordType; inclusive?: boolean } args?: { wordType?: WordType; inclusive?: boolean },
): Position { ): Position {
return nextWordStart(document, this, args?.wordType ?? WordType.Normal, args?.inclusive ?? false); return nextWordStart(document, this, args?.wordType ?? WordType.Normal, args?.inclusive ?? false);
}; };
@ -425,7 +425,7 @@ Position.prototype.nextWordStart = function (
Position.prototype.prevWordEnd = function ( Position.prototype.prevWordEnd = function (
this: Position, this: Position,
document: vscode.TextDocument, document: vscode.TextDocument,
args?: { wordType?: WordType } args?: { wordType?: WordType },
): Position { ): Position {
return prevWordEnd(document, this, args?.wordType ?? WordType.Normal); return prevWordEnd(document, this, args?.wordType ?? WordType.Normal);
}; };
@ -433,14 +433,14 @@ Position.prototype.prevWordEnd = function (
Position.prototype.nextWordEnd = function ( Position.prototype.nextWordEnd = function (
this: Position, this: Position,
document: vscode.TextDocument, document: vscode.TextDocument,
args?: { wordType?: WordType; inclusive?: boolean } args?: { wordType?: WordType; inclusive?: boolean },
): Position { ): Position {
return nextWordEnd(document, this, args?.wordType ?? WordType.Normal, args?.inclusive ?? false); return nextWordEnd(document, this, args?.wordType ?? WordType.Normal, args?.inclusive ?? false);
}; };
Position.prototype.getSentenceBegin = function ( Position.prototype.getSentenceBegin = function (
this: Position, this: Position,
args: { forward: boolean } args: { forward: boolean },
): Position { ): Position {
return getSentenceBegin(this, args); return getSentenceBegin(this, args);
}; };
@ -462,7 +462,7 @@ Position.prototype.getLineBegin = function (this: Position): Position {
*/ */
Position.prototype.getLineBeginRespectingIndent = function ( Position.prototype.getLineBeginRespectingIndent = function (
this: Position, this: Position,
document: vscode.TextDocument document: vscode.TextDocument,
): Position { ): Position {
if (!configuration.autoindent) { if (!configuration.autoindent) {
return this.getLineBegin(); return this.getLineBegin();
@ -508,7 +508,7 @@ Position.prototype.advancePositionByText = function (this: Position, text: strin
} else { } else {
return new Position( return new Position(
this.line + newlines.length, this.line + newlines.length,
text.length - (newlines[newlines.length - 1] + 1) text.length - (newlines[newlines.length - 1] + 1),
); );
} }
}; };
@ -529,7 +529,7 @@ Position.prototype.isLineEnd = function (this: Position): boolean {
Position.prototype.isFirstWordOfLine = function ( Position.prototype.isFirstWordOfLine = function (
this: Position, this: Position,
document: vscode.TextDocument document: vscode.TextDocument,
): boolean { ): boolean {
return ( return (
TextEditor.getFirstNonWhitespaceCharOnLine(document, this.line).character === this.character TextEditor.getFirstNonWhitespaceCharOnLine(document, this.line).character === this.character
@ -550,7 +550,7 @@ Position.prototype.isAtDocumentEnd = function (this: Position): boolean {
*/ */
Position.prototype.isInLeadingWhitespace = function ( Position.prototype.isInLeadingWhitespace = function (
this: Position, this: Position,
document: vscode.TextDocument document: vscode.TextDocument,
): boolean { ): boolean {
return /^\s+$/.test(document.getText(new vscode.Range(this.getLineBegin(), this))); return /^\s+$/.test(document.getText(new vscode.Range(this.getLineBegin(), this)));
}; };
@ -560,7 +560,7 @@ Position.prototype.isInLeadingWhitespace = function (
*/ */
Position.prototype.obeyStartOfLine = function ( Position.prototype.obeyStartOfLine = function (
this: Position, this: Position,
document: vscode.TextDocument document: vscode.TextDocument,
): Position { ): Position {
return configuration.startofline return configuration.startofline
? TextEditor.getFirstNonWhitespaceCharOnLine(document, this.line) ? TextEditor.getFirstNonWhitespaceCharOnLine(document, this.line)

View File

@ -63,7 +63,7 @@ export class NumericString {
// Return parse result and offset of suffix // Return parse result and offset of suffix
public static parse( public static parse(
input: string, input: string,
targetRadix?: NumericStringRadix targetRadix?: NumericStringRadix,
): { num: NumericString; suffixOffset: number } | undefined { ): { num: NumericString; suffixOffset: number } | undefined {
const filteredMatchings = const filteredMatchings =
targetRadix !== undefined targetRadix !== undefined
@ -149,7 +149,7 @@ export class NumericString {
prefix: string, prefix: string,
suffix: string, suffix: string,
negative: boolean, negative: boolean,
isCapital: boolean isCapital: boolean,
) { ) {
this.value = value; this.value = value;
this.radix = radix; this.radix = radix;

View File

@ -29,7 +29,7 @@ const documentsStartingWith = (startingFileName: string) => {
const linesWithoutIndentation = ( const linesWithoutIndentation = (
document: vscode.TextDocument, document: vscode.TextDocument,
lineToStartScanFrom: number, lineToStartScanFrom: number,
scanAboveFirst: boolean scanAboveFirst: boolean,
): Array<{ sortPriority: number; text: string }> => { ): Array<{ sortPriority: number; text: string }> => {
const distanceFromStartLine = (line: number) => { const distanceFromStartLine = (line: number) => {
let sortPriority = scanAboveFirst ? lineToStartScanFrom - line : line - lineToStartScanFrom; let sortPriority = scanAboveFirst ? lineToStartScanFrom - line : line - lineToStartScanFrom;
@ -68,7 +68,7 @@ const linesWithoutIndentation = (
const getCompletionsForText = ( const getCompletionsForText = (
text: string, text: string,
currentFileName: string, currentFileName: string,
currentPosition: Position currentPosition: Position,
): string[] | null => { ): string[] | null => {
const matchedLines: string[] = []; const matchedLines: string[] = [];
@ -115,10 +115,10 @@ const getCompletionsForText = (
*/ */
export const getCompletionsForCurrentLine = ( export const getCompletionsForCurrentLine = (
position: Position, position: Position,
document: vscode.TextDocument document: vscode.TextDocument,
): string[] | null => { ): string[] | null => {
const currentLineText = document.getText( const currentLineText = document.getText(
new vscode.Range(TextEditor.getFirstNonWhitespaceCharOnLine(document, position.line), position) new vscode.Range(TextEditor.getFirstNonWhitespaceCharOnLine(document, position.line), position),
); );
return getCompletionsForText(currentLineText, document.fileName, position); return getCompletionsForText(currentLineText, document.fileName, position);
@ -160,8 +160,8 @@ export const lineCompletionProvider = {
vimState.recordedState.transformer.delete( vimState.recordedState.transformer.delete(
new vscode.Range( new vscode.Range(
TextEditor.getFirstNonWhitespaceCharOnLine(vimState.document, position.line), TextEditor.getFirstNonWhitespaceCharOnLine(vimState.document, position.line),
position.getLineEnd() position.getLineEnd(),
) ),
); );
vimState.recordedState.transformer.addTransformation({ vimState.recordedState.transformer.addTransformation({

View File

@ -544,7 +544,7 @@ function overlapSetting(args: {
this.getConfiguration('editor').update( this.getConfiguration('editor').update(
args.settingName, args.settingName,
value, value,
vscode.ConfigurationTarget.Global vscode.ConfigurationTarget.Global,
); );
}, },
enumerable: true, enumerable: true,

View File

@ -124,7 +124,7 @@ export class Remapper implements IRemapper {
Logger.trace( Logger.trace(
`trying to find matching remap. keys=${keys}. mode=${ `trying to find matching remap. keys=${keys}. mode=${
Mode[vimState.currentMode] Mode[vimState.currentMode]
}. keybindings=${this.configKey}.` }. keybindings=${this.configKey}.`,
); );
let remapping: IKeyRemapping | undefined = this.findMatchingRemap(userDefinedRemappings, keys); let remapping: IKeyRemapping | undefined = this.findMatchingRemap(userDefinedRemappings, keys);
@ -206,11 +206,11 @@ export class Remapper implements IRemapper {
keys.push(SpecialKeys.TimeoutFinished); // include the '<TimeoutFinished>' key keys.push(SpecialKeys.TimeoutFinished); // include the '<TimeoutFinished>' key
Logger.trace( Logger.trace(
`${this.configKey}. timeout finished, handling timed out buffer keys without allowing a new timeout.` `${this.configKey}. timeout finished, handling timed out buffer keys without allowing a new timeout.`,
); );
} }
Logger.trace( Logger.trace(
`${this.configKey}. potential remap broken. resending keys without allowing a potential remap on first key. keys=${keys}` `${this.configKey}. potential remap broken. resending keys without allowing a potential remap on first key. keys=${keys}`,
); );
this.hasPotentialRemap = false; this.hasPotentialRemap = false;
vimState.recordedState.allowPotentialRemapOnFirstKey = false; vimState.recordedState.allowPotentialRemapOnFirstKey = false;
@ -229,7 +229,7 @@ export class Remapper implements IRemapper {
} catch (e) { } catch (e) {
if (e instanceof ForceStopRemappingError) { if (e instanceof ForceStopRemappingError) {
Logger.trace( Logger.trace(
`${this.configKey}. Stopped the remapping in the middle, ignoring the rest. Reason: ${e.message}` `${this.configKey}. Stopped the remapping in the middle, ignoring the rest. Reason: ${e.message}`,
); );
} }
} finally { } finally {
@ -266,12 +266,12 @@ export class Remapper implements IRemapper {
this.hasAmbiguousRemap = remapping; this.hasAmbiguousRemap = remapping;
Logger.trace( Logger.trace(
`${this.configKey}. ambiguous match found. before=${remapping.before}. after=${remapping.after}. command=${remapping.commands}. waiting for other key or timeout to finish.` `${this.configKey}. ambiguous match found. before=${remapping.before}. after=${remapping.after}. command=${remapping.commands}. waiting for other key or timeout to finish.`,
); );
} else { } else {
this.hasPotentialRemap = true; this.hasPotentialRemap = true;
Logger.trace( Logger.trace(
`${this.configKey}. potential remap found. waiting for other key or timeout to finish.` `${this.configKey}. potential remap found. waiting for other key or timeout to finish.`,
); );
} }
@ -333,7 +333,7 @@ export class Remapper implements IRemapper {
remapState.mapDepth++; remapState.mapDepth++;
Logger.trace( Logger.trace(
`${this.configKey}. match found. before=${remapping.before}. after=${remapping.after}. command=${remapping.commands}. remainingKeys=${remainingKeys}. mapDepth=${remapState.mapDepth}.` `${this.configKey}. match found. before=${remapping.before}. after=${remapping.after}. command=${remapping.commands}. remainingKeys=${remainingKeys}. mapDepth=${remapState.mapDepth}.`,
); );
let remapFailed = false; let remapFailed = false;
@ -377,12 +377,12 @@ export class Remapper implements IRemapper {
} }
Logger.trace( Logger.trace(
`${this.configKey}. Stopped the remapping in the middle, ignoring the rest. Reason: ${e.message}` `${this.configKey}. Stopped the remapping in the middle, ignoring the rest. Reason: ${e.message}`,
); );
} else { } else {
// If some other error happens during the remapping handling it should stop the remap and rethrow // If some other error happens during the remapping handling it should stop the remap and rethrow
Logger.trace( Logger.trace(
`${this.configKey}. error found in the middle of remapping, ignoring the rest of the remap. error: ${e}` `${this.configKey}. error found in the middle of remapping, ignoring the rest of the remap. error: ${e}`,
); );
throw e; throw e;
} }
@ -440,7 +440,7 @@ export class Remapper implements IRemapper {
await modeHandler.handleMultipleKeyEvents(remainingKeys); await modeHandler.handleMultipleKeyEvents(remainingKeys);
} catch (e) { } catch (e) {
Logger.trace( Logger.trace(
`${this.configKey}. Stopped the remapping in the middle, ignoring the rest. Reason: ${e.message}` `${this.configKey}. Stopped the remapping in the middle, ignoring the rest. Reason: ${e.message}`,
); );
} finally { } finally {
remapState.isCurrentlyPerformingRecursiveRemapping = false; remapState.isCurrentlyPerformingRecursiveRemapping = false;
@ -466,7 +466,7 @@ export class Remapper implements IRemapper {
private async handleRemapping( private async handleRemapping(
remapping: IKeyRemapping, remapping: IKeyRemapping,
modeHandler: ModeHandler, modeHandler: ModeHandler,
skipFirstCharacter: boolean skipFirstCharacter: boolean,
) { ) {
const { vimState, remapState } = modeHandler; const { vimState, remapState } = modeHandler;
@ -531,7 +531,7 @@ export class Remapper implements IRemapper {
protected findMatchingRemap( protected findMatchingRemap(
userDefinedRemappings: Map<string, IKeyRemapping>, userDefinedRemappings: Map<string, IKeyRemapping>,
inputtedKeys: string[] inputtedKeys: string[],
): IKeyRemapping | undefined { ): IKeyRemapping | undefined {
if (userDefinedRemappings.size === 0) { if (userDefinedRemappings.size === 0) {
return undefined; return undefined;
@ -563,7 +563,7 @@ export class Remapper implements IRemapper {
* @param remappings * @param remappings
*/ */
protected static getRemappedKeysLengthRange( protected static getRemappedKeysLengthRange(
remappings: ReadonlyMap<string, IKeyRemapping> remappings: ReadonlyMap<string, IKeyRemapping>,
): [number, number] { ): [number, number] {
if (remappings.size === 0) { if (remappings.size === 0) {
return [0, 0]; return [0, 0];
@ -581,7 +581,7 @@ export class Remapper implements IRemapper {
protected static hasPotentialRemap( protected static hasPotentialRemap(
keys: string[], keys: string[],
remappings: ReadonlyMap<string, IKeyRemapping>, remappings: ReadonlyMap<string, IKeyRemapping>,
countRemapAsPotential: boolean = false countRemapAsPotential: boolean = false,
): boolean { ): boolean {
const keysAsString = keys.join(''); const keysAsString = keys.join('');
const re = /^<([^>]+)>/; const re = /^<([^>]+)>/;

View File

@ -28,7 +28,7 @@ export class RemappingValidator implements IConfigurationValidator {
// because we process keybindings backwards in next loop, user mapping will override // because we process keybindings backwards in next loop, user mapping will override
for (const pluginMapping of PluginDefaultMappings.getPluginDefaultMappings( for (const pluginMapping of PluginDefaultMappings.getPluginDefaultMappings(
modeKeyBindingsKey, modeKeyBindingsKey,
config config,
)) { )) {
// note concat(all mappings) does not work somehow // note concat(all mappings) does not work somehow
keybindings.push(pluginMapping); keybindings.push(pluginMapping);
@ -59,13 +59,13 @@ export class RemappingValidator implements IConfigurationValidator {
// normalize // normalize
if (remapping.before) { if (remapping.before) {
remapping.before.forEach( remapping.before.forEach(
(key, idx) => (remapping.before[idx] = Notation.NormalizeKey(key, config.leader)) (key, idx) => (remapping.before[idx] = Notation.NormalizeKey(key, config.leader)),
); );
} }
if (remapping.after) { if (remapping.after) {
remapping.after.forEach( remapping.after.forEach(
(key, idx) => (remapping.after![idx] = Notation.NormalizeKey(key, config.leader)) (key, idx) => (remapping.after![idx] = Notation.NormalizeKey(key, config.leader)),
); );
} }
@ -159,7 +159,7 @@ export class RemappingValidator implements IConfigurationValidator {
private async getCommandMap(): Promise<Map<string, boolean>> { private async getCommandMap(): Promise<Map<string, boolean>> {
if (this.commandMap == null) { if (this.commandMap == null) {
this.commandMap = new Map( this.commandMap = new Map(
(await vscode.commands.getCommands(true)).map((x) => [x, true] as [string, boolean]) (await vscode.commands.getCommands(true)).map((x) => [x, true] as [string, boolean]),
); );
} }
return this.commandMap; return this.commandMap;

View File

@ -320,7 +320,7 @@ export class VimrcImpl {
// Don't remove a mapping present in settings.json; those are more specific to VSCodeVim. // Don't remove a mapping present in settings.json; those are more specific to VSCodeVim.
_.remove( _.remove(
remaps, remaps,
(r) => r.source === 'vimrc' && _.isEqual(r.before, remap.keyRemapping.before) (r) => r.source === 'vimrc' && _.isEqual(r.before, remap.keyRemapping.before),
); );
}); });
return true; return true;

View File

@ -139,7 +139,7 @@ class VimrcKeyRemappingBuilderImpl {
*/ */
public async build( public async build(
line: string, line: string,
vscodeCommands: string[] vscodeCommands: string[],
): Promise<IVimrcKeyRemapping | undefined> { ): Promise<IVimrcKeyRemapping | undefined> {
const matches = VimrcKeyRemappingBuilderImpl.KEY_REMAPPING_REG_EX.exec(line); const matches = VimrcKeyRemappingBuilderImpl.KEY_REMAPPING_REG_EX.exec(line);
if (!matches || matches.length < 4) { if (!matches || matches.length < 4) {

View File

@ -189,7 +189,7 @@ class HistoryStep {
current = DocumentChange.replace( current = DocumentChange.replace(
first.start, first.start,
first.before + second.before.slice(intersectLength), first.before + second.before.slice(intersectLength),
first.after.slice(0, first.after.length - intersectLength) + second.after first.after.slice(0, first.after.length - intersectLength) + second.after,
); );
} else { } else {
merged.push(current); merged.push(current);
@ -448,12 +448,12 @@ export class HistoryTracker {
if (ch === '\n') { if (ch === '\n') {
newMark.position = new Position( newMark.position = new Position(
Math.max(newMark.position.line - 1, 0), Math.max(newMark.position.line - 1, 0),
newMark.position.character newMark.position.character,
); );
} else if (pos.line === newMark.position.line) { } else if (pos.line === newMark.position.line) {
newMark.position = new Position( newMark.position = new Position(
newMark.position.line, newMark.position.line,
Math.max(newMark.position.character - 1, 0) Math.max(newMark.position.character - 1, 0),
); );
} }
} }
@ -476,12 +476,12 @@ export class HistoryTracker {
if (ch === '\n') { if (ch === '\n') {
newMark.position = new Position( newMark.position = new Position(
newMark.position.line + 1, newMark.position.line + 1,
newMark.position.character newMark.position.character,
); );
} else if (pos.line === newMark.position.line) { } else if (pos.line === newMark.position.line) {
newMark.position = new Position( newMark.position = new Position(
newMark.position.line, newMark.position.line,
newMark.position.character + 1 newMark.position.character + 1,
); );
} }
} }
@ -610,7 +610,7 @@ export class HistoryTracker {
this.undoStack.removeMarks(markNames); this.undoStack.removeMarks(markNames);
HistoryStep.globalMarks = HistoryStep.globalMarks.filter( HistoryStep.globalMarks = HistoryStep.globalMarks.filter(
(mark) => mark.name === '' || !markNames.includes(mark.name) (mark) => mark.name === '' || !markNames.includes(mark.name),
); );
} }
@ -686,7 +686,7 @@ export class HistoryTracker {
this.undoStack.pushChange( this.undoStack.pushChange(
added added
? DocumentChange.insert(currentPosition, text) ? DocumentChange.insert(currentPosition, text)
: DocumentChange.delete(currentPosition, text) : DocumentChange.delete(currentPosition, text),
); );
} }
@ -762,7 +762,9 @@ export class HistoryTracker {
const changes = step.changes.length === 1 ? `1 change` : `${step.changes.length} changes`; const changes = step.changes.length === 1 ? `1 change` : `${step.changes.length} changes`;
StatusBar.setText( StatusBar.setText(
this.vimState, this.vimState,
`${changes}; before #${this.undoStack.getCurrentHistoryStepIndex() + 1} ${step.howLongAgo()}` `${changes}; before #${
this.undoStack.getCurrentHistoryStepIndex() + 1
} ${step.howLongAgo()}`,
); );
return step.cursorStart; return step.cursorStart;
@ -789,7 +791,7 @@ export class HistoryTracker {
const changes = step.changes.length === 1 ? `1 change` : `${step.changes.length} changes`; const changes = step.changes.length === 1 ? `1 change` : `${step.changes.length} changes`;
StatusBar.setText( StatusBar.setText(
this.vimState, this.vimState,
`${changes}; after #${this.undoStack.getCurrentHistoryStepIndex()} ${step.howLongAgo()}` `${changes}; after #${this.undoStack.getCurrentHistoryStepIndex()} ${step.howLongAgo()}`,
); );
return step.cursorStart; return step.cursorStart;
@ -836,7 +838,7 @@ export class HistoryTracker {
// Modify & replace the change to avoid undoing the newline embedded in the change // Modify & replace the change to avoid undoing the newline embedded in the change
change = DocumentChange.insert( change = DocumentChange.insert(
new Position(change.start.line + 1, 0), new Position(change.start.line + 1, 0),
change.after.slice(change.after.lastIndexOf('\n')) change.after.slice(change.after.lastIndexOf('\n')),
); );
done = true; done = true;
} else if (newlines.length > 0 || change.start.line !== undoLine) { } else if (newlines.length > 0 || change.start.line !== undoLine) {

View File

@ -132,7 +132,7 @@ export class JumpTracker {
} else { } else {
// Get jump file from visible editors // Get jump file from visible editors
const editor: vscode.TextEditor = vscode.window.visibleTextEditors.filter( const editor: vscode.TextEditor = vscode.window.visibleTextEditors.filter(
(e) => e.document.fileName === jump.fileName (e) => e.document.fileName === jump.fileName,
)[0]; )[0];
if (editor) { if (editor) {
@ -158,7 +158,7 @@ export class JumpTracker {
private async jumpThroughHistory( private async jumpThroughHistory(
getJump: (j: Jump) => Jump, getJump: (j: Jump) => Jump,
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<void> { ): Promise<void> {
let jump = new Jump({ let jump = new Jump({
document: vimState.document, document: vimState.document,
@ -326,13 +326,14 @@ export class JumpTracker {
new Jump({ new Jump({
document: jump.document, document: jump.document,
position: newPosition, position: newPosition,
}) }),
); );
} }
private clearJumpsOnSameLine(jump: Jump): void { private clearJumpsOnSameLine(jump: Jump): void {
this._jumps = this._jumps.filter( this._jumps = this._jumps.filter(
(j) => j === jump || !(j.fileName === jump.fileName && j.position.line === jump.position.line) (j) =>
j === jump || !(j.fileName === jump.fileName && j.position.line === jump.position.line),
); );
} }

View File

@ -39,7 +39,7 @@ export function isVisualMode(mode: Mode): mode is Mode.Visual | Mode.VisualLine
* This means SearchInProgess and CommandlineInProgress modes. * This means SearchInProgess and CommandlineInProgress modes.
*/ */
export function isStatusBarMode( export function isStatusBarMode(
mode: Mode mode: Mode,
): mode is Mode.CommandlineInProgress | Mode.SearchInProgressMode { ): mode is Mode.CommandlineInProgress | Mode.SearchInProgressMode {
return [Mode.SearchInProgressMode, Mode.CommandlineInProgress].includes(mode); return [Mode.SearchInProgressMode, Mode.CommandlineInProgress].includes(mode);
} }

View File

@ -111,7 +111,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
public static async create( public static async create(
handlerMap: IModeHandlerMap, handlerMap: IModeHandlerMap,
textEditor: vscode.TextEditor textEditor: vscode.TextEditor,
): Promise<ModeHandler> { ): Promise<ModeHandler> {
const modeHandler = new ModeHandler(handlerMap, textEditor); const modeHandler = new ModeHandler(handlerMap, textEditor);
await modeHandler.vimState.load(); await modeHandler.vimState.load();
@ -152,7 +152,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
} }
this.vimState.cursors = selections.map(({ active, anchor }) => this.vimState.cursors = selections.map(({ active, anchor }) =>
active.isBefore(anchor) ? new Cursor(anchor.getLeft(), active) : new Cursor(anchor, active) active.isBefore(anchor) ? new Cursor(anchor.getLeft(), active) : new Cursor(anchor, active),
); );
} }
@ -195,7 +195,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
Logger.debug( Logger.debug(
`Selection change: ${selection.anchor.toString()}, ${selection.active}, SelectionsLength: ${ `Selection change: ${selection.anchor.toString()}, ${selection.active}, SelectionsLength: ${
e.selections.length e.selections.length
}` }`,
); );
// If our previous cursors are not included on any of the current selections, then a snippet // If our previous cursors are not included on any of the current selections, then a snippet
@ -220,8 +220,8 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
new Cursor( new Cursor(
// Adjust the cursor positions because cursors & selections don't match exactly // Adjust the cursor positions because cursors & selections don't match exactly
sel.anchor.isAfter(sel.active) ? sel.anchor.getLeft() : sel.anchor, sel.anchor.isAfter(sel.active) ? sel.anchor.getLeft() : sel.anchor,
sel.active sel.active,
) ),
); );
if ( if (
e.selections.some((s) => !s.anchor.isEqual(s.active)) && e.selections.some((s) => !s.anchor.isEqual(s.active)) &&
@ -288,7 +288,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
const cursorEnd = laterOf( const cursorEnd = laterOf(
this.vimState.cursorStartPosition, this.vimState.cursorStartPosition,
this.vimState.cursorStopPosition this.vimState.cursorStopPosition,
); );
if (e.textEditor.document.validatePosition(cursorEnd).isBefore(cursorEnd)) { if (e.textEditor.document.validatePosition(cursorEnd).isBefore(cursorEnd)) {
// The document changed such that our cursor position is now out of bounds, possibly by // The document changed such that our cursor position is now out of bounds, possibly by
@ -317,7 +317,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
Logger.debug( Logger.debug(
`Selections: Changing Cursors from selection handler... ${selection.anchor.toString()}, ${ `Selections: Changing Cursors from selection handler... ${selection.anchor.toString()}, ${
selection.active selection.active
}` }`,
); );
this.vimState.cursorStopPosition = selection.active; this.vimState.cursorStopPosition = selection.active;
this.vimState.cursorStartPosition = selection.anchor; this.vimState.cursorStartPosition = selection.anchor;
@ -492,7 +492,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
) { ) {
handledAsRemap = await this.remappers.sendKey( handledAsRemap = await this.remappers.sendKey(
this.vimState.recordedState.commandList, this.vimState.recordedState.commandList,
this this,
); );
} }
@ -666,7 +666,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
// Push document content change to the stack // Push document content change to the stack
lastAction.addChanges( lastAction.addChanges(
this.vimState.historyTracker.currentContentChanges, this.vimState.historyTracker.currentContentChanges,
this.vimState.cursorStopPosition this.vimState.cursorStopPosition,
); );
this.vimState.historyTracker.currentContentChanges = []; this.vimState.historyTracker.currentContentChanges = [];
recordedState.actionsRun.push(action); recordedState.actionsRun.push(action);
@ -676,7 +676,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
// This means we are already in Insert Mode but there is still not DocumentContentChangeAction in stack // This means we are already in Insert Mode but there is still not DocumentContentChangeAction in stack
this.vimState.historyTracker.currentContentChanges = []; this.vimState.historyTracker.currentContentChanges = [];
const newContentChange = new DocumentContentChangeAction( const newContentChange = new DocumentContentChangeAction(
this.vimState.cursorStopPosition this.vimState.cursorStopPosition,
); );
newContentChange.keysPressed.push(key); newContentChange.keysPressed.push(key);
recordedState.actionsRun.push(newContentChange); recordedState.actionsRun.push(newContentChange);
@ -707,7 +707,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
if (action.isJump) { if (action.isJump) {
globalState.jumpTracker.recordJump( globalState.jumpTracker.recordJump(
Jump.fromStateBefore(this.vimState), Jump.fromStateBefore(this.vimState),
Jump.fromStateNow(this.vimState) Jump.fromStateNow(this.vimState),
); );
} }
@ -723,7 +723,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
// position instead of the position sent to VSCode. // position instead of the position sent to VSCode.
if (this.vimState.currentMode === Mode.Visual) { if (this.vimState.currentMode === Mode.Visual) {
this.vimState.cursors = this.vimState.cursors.map((c) => this.vimState.cursors = this.vimState.cursors.map((c) =>
c.start.isBefore(c.stop) ? c.withNewStop(c.stop.getLeftThroughLineBreaks(true)) : c c.start.isBefore(c.stop) ? c.withNewStop(c.stop.getLeftThroughLineBreaks(true)) : c,
); );
} }
@ -733,8 +733,8 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
(c) => (c) =>
new Cursor( new Cursor(
this.vimState.document.validatePosition(c.start), this.vimState.document.validatePosition(c.start),
this.vimState.document.validatePosition(c.stop) this.vimState.document.validatePosition(c.stop),
) ),
); );
let ranRepeatableAction = false; let ranRepeatableAction = false;
@ -851,9 +851,9 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
this.vimState.cursors = this.vimState.cursors.map((c) => this.vimState.cursors = this.vimState.cursors.map((c) =>
c.start.isBeforeOrEqual(c.stop) c.start.isBeforeOrEqual(c.stop)
? c.withNewStop( ? c.withNewStop(
c.stop.isLineEnd() ? c.stop.getRightThroughLineBreaks() : c.stop.getRight() c.stop.isLineEnd() ? c.stop.getRightThroughLineBreaks() : c.stop.getRight(),
) )
: c : c,
); );
} }
@ -895,7 +895,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
// If we're in Normal mode, collapse each cursor down to one character // If we're in Normal mode, collapse each cursor down to one character
if (this.currentMode === Mode.Normal) { if (this.currentMode === Mode.Normal) {
this.vimState.cursors = this.vimState.cursors.map( this.vimState.cursors = this.vimState.cursors.map(
(cursor) => new Cursor(cursor.stop, cursor.stop) (cursor) => new Cursor(cursor.stop, cursor.stop),
); );
} }
@ -929,7 +929,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
isVisualMode(this.vimState.currentMode) && currentLineLength > 0 ? 1 : 0; isVisualMode(this.vimState.currentMode) && currentLineLength > 0 ? 1 : 0;
if (cursor.start.character >= currentStartLineLength) { if (cursor.start.character >= currentStartLineLength) {
cursor = cursor.withNewStart( cursor = cursor.withNewStart(
cursor.start.withColumn(Math.max(currentStartLineLength - 1, 0)) cursor.start.withColumn(Math.max(currentStartLineLength - 1, 0)),
); );
} }
@ -982,14 +982,14 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
const result = await movement.execActionWithCount( const result = await movement.execActionWithCount(
cursorPosition, cursorPosition,
this.vimState, this.vimState,
recordedState.count recordedState.count,
); );
// We also need to update the specific cursor, in case the cursor position was modified inside // We also need to update the specific cursor, in case the cursor position was modified inside
// the handling functions (e.g. 'it') // the handling functions (e.g. 'it')
this.vimState.cursors[i] = new Cursor( this.vimState.cursors[i] = new Cursor(
this.vimState.cursorStartPosition, this.vimState.cursorStartPosition,
this.vimState.cursorStopPosition this.vimState.cursorStopPosition,
); );
this.vimState.cursorStartPosition = oldCursorPositionStart; this.vimState.cursorStartPosition = oldCursorPositionStart;
@ -1094,7 +1094,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
const resultingCursor = new Cursor( const resultingCursor = new Cursor(
this.vimState.cursorStartPosition, this.vimState.cursorStartPosition,
this.vimState.cursorStopPosition this.vimState.cursorStopPosition,
); );
resultingCursors.push(resultingCursor); resultingCursors.push(resultingCursor);
@ -1118,7 +1118,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
if (this.vimState.lastVisualSelection) { if (this.vimState.lastVisualSelection) {
this.vimState.dotCommandPreviousVisualSelection = new vscode.Selection( this.vimState.dotCommandPreviousVisualSelection = new vscode.Selection(
this.vimState.lastVisualSelection.start, this.vimState.lastVisualSelection.start,
this.vimState.lastVisualSelection.end this.vimState.lastVisualSelection.end,
); );
} }
@ -1198,7 +1198,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
} }
// If there are no decorations from the command line, get decorations for previous SearchState // If there are no decorations from the command line, get decorations for previous SearchState
decorations = getDecorationsForSearchMatchRanges( decorations = getDecorationsForSearchMatchRanges(
globalState.searchState.getMatchRanges(this.vimState) globalState.searchState.getMatchRanges(this.vimState),
); );
this.searchDecorationCacheKey = { this.searchDecorationCacheKey = {
searchString: globalState.searchState.searchString, searchString: globalState.searchState.searchString,
@ -1209,16 +1209,16 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
this.vimState.editor.setDecorations( this.vimState.editor.setDecorations(
decoration.searchHighlight, decoration.searchHighlight,
decorations?.searchHighlight ?? [] decorations?.searchHighlight ?? [],
); );
this.vimState.editor.setDecorations(decoration.searchMatch, decorations?.searchMatch ?? []); this.vimState.editor.setDecorations(decoration.searchMatch, decorations?.searchMatch ?? []);
this.vimState.editor.setDecorations( this.vimState.editor.setDecorations(
decoration.substitutionAppend, decoration.substitutionAppend,
decorations?.substitutionAppend ?? [] decorations?.substitutionAppend ?? [],
); );
this.vimState.editor.setDecorations( this.vimState.editor.setDecorations(
decoration.substitutionReplace, decoration.substitutionReplace,
decorations?.substitutionReplace ?? [] decorations?.substitutionReplace ?? [],
); );
} }
@ -1226,7 +1226,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
args: { drawSelection: boolean; revealRange: boolean } = { args: { drawSelection: boolean; revealRange: boolean } = {
drawSelection: true, drawSelection: true,
revealRange: true, revealRange: true,
} },
): Promise<void> { ): Promise<void> {
// Draw selection (or cursor) // Draw selection (or cursor)
if (args.drawSelection) { if (args.drawSelection) {
@ -1275,8 +1275,8 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
selections.push( selections.push(
new vscode.Selection( new vscode.Selection(
this.vimState.document.validatePosition(line.start), this.vimState.document.validatePosition(line.start),
this.vimState.document.validatePosition(line.end) this.vimState.document.validatePosition(line.end),
) ),
); );
} }
break; break;
@ -1312,12 +1312,12 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
? // Forwards Selection ? // Forwards Selection
new vscode.Selection( new vscode.Selection(
earlierOf(s.anchor, previousSelection.anchor), earlierOf(s.anchor, previousSelection.anchor),
laterOf(s.active, previousSelection.active) laterOf(s.active, previousSelection.active),
) )
: // Backwards Selection : // Backwards Selection
new vscode.Selection( new vscode.Selection(
laterOf(s.anchor, previousSelection.anchor), laterOf(s.anchor, previousSelection.anchor),
earlierOf(s.active, previousSelection.active) earlierOf(s.active, previousSelection.active),
); );
} else { } else {
combinedSelections.push(s); combinedSelections.push(s);
@ -1338,7 +1338,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
selections.some( selections.some(
(s, i) => (s, i) =>
!s.anchor.isEqual(this.vimState.editor.selections[i].anchor) || !s.anchor.isEqual(this.vimState.editor.selections[i].anchor) ||
!s.active.isEqual(this.vimState.editor.selections[i].active) !s.active.isEqual(this.vimState.editor.selections[i].active),
); );
if (willTriggerChange) { if (willTriggerChange) {
@ -1346,13 +1346,13 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
(hash, s) => (hash, s) =>
hash + hash +
`[${s.anchor.line}, ${s.anchor.character}; ${s.active.line}, ${s.active.character}]`, `[${s.anchor.line}, ${s.anchor.character}; ${s.active.line}, ${s.active.character}]`,
'' '',
); );
this.selectionsChanged.ourSelections.push(selectionsHash); this.selectionsChanged.ourSelections.push(selectionsHash);
Logger.trace( Logger.trace(
`Adding selection change to be ignored! (total: ${ `Adding selection change to be ignored! (total: ${
this.selectionsChanged.ourSelections.length this.selectionsChanged.ourSelections.length
}) Hash: ${selectionsHash}, Selections: ${selections[0].anchor.toString()}, ${selections[0].active.toString()}` }) Hash: ${selectionsHash}, Selections: ${selections[0].anchor.toString()}, ${selections[0].active.toString()}`,
); );
} }
@ -1419,7 +1419,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
*/ */
this.vimState.editor.revealRange( this.vimState.editor.revealRange(
new vscode.Range(cursorToTrack.stop, cursorToTrack.stop), new vscode.Range(cursorToTrack.stop, cursorToTrack.stop),
revealType revealType,
); );
} }
} }
@ -1430,7 +1430,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
if (!cursorStyle) { if (!cursorStyle) {
const cursorType = getCursorType( const cursorType = getCursorType(
this.vimState, this.vimState,
this.vimState.currentModeIncludingPseudoModes this.vimState.currentModeIncludingPseudoModes,
); );
cursorStyle = getCursorStyle(cursorType); cursorStyle = getCursorStyle(cursorType);
if ( if (
@ -1529,7 +1529,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
this.vimState.editor.setDecorations( this.vimState.editor.setDecorations(
decoration.insertModeVirtualCharacter, decoration.insertModeVirtualCharacter,
iModeVirtualCharDecorationOptions iModeVirtualCharDecorationOptions,
); );
// OperatorPendingMode half block cursor // OperatorPendingMode half block cursor
@ -1556,7 +1556,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
this.vimState.editor.setDecorations(decoration.operatorPendingModeCursor, opCursorDecorations); this.vimState.editor.setDecorations(decoration.operatorPendingModeCursor, opCursorDecorations);
this.vimState.editor.setDecorations( this.vimState.editor.setDecorations(
decoration.operatorPendingModeCursorChar, decoration.operatorPendingModeCursorChar,
opCursorCharDecorations opCursorCharDecorations,
); );
for (const markDecoration of decoration.allMarkDecorations()) { for (const markDecoration of decoration.allMarkDecorations()) {
@ -1597,7 +1597,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
? [ ? [
new vscode.Range( new vscode.Range(
TextEditor.getDocumentBegin(), TextEditor.getDocumentBegin(),
TextEditor.getDocumentEnd(this.vimState.document) TextEditor.getDocumentEnd(this.vimState.document),
), ),
] ]
: []; : [];
@ -1629,7 +1629,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
// Tell VSCode that the cursor position changed, so it updates its highlights for `editor.occurrencesHighlight`. // Tell VSCode that the cursor position changed, so it updates its highlights for `editor.occurrencesHighlight`.
const range = new vscode.Range( const range = new vscode.Range(
this.vimState.cursorStartPosition, this.vimState.cursorStartPosition,
this.vimState.cursorStopPosition this.vimState.cursorStopPosition,
); );
if (!/\s+/.test(this.vimState.document.getText(range))) { if (!/\s+/.test(this.vimState.document.getText(range))) {
vscode.commands.executeCommand('editor.action.wordHighlight.trigger'); vscode.commands.executeCommand('editor.action.wordHighlight.trigger');
@ -1652,7 +1652,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
this.vimState.cursorStopPosition, this.vimState.cursorStopPosition,
key, key,
this.vimState, this.vimState,
false false,
); );
if (result !== undefined) { if (result !== undefined) {
if (this.vimState.cursorStopPosition.isEqual(result)) { if (this.vimState.cursorStopPosition.isEqual(result)) {
@ -1664,7 +1664,7 @@ export class ModeHandler implements vscode.Disposable, IModeHandler {
this.vimState.cursorStopPosition.getLeft(), this.vimState.cursorStopPosition.getLeft(),
key, key,
this.vimState, this.vimState,
false false,
); );
if (result !== undefined) { if (result !== undefined) {
if (this.vimState.cursorStopPosition.getLeft(2).isEqual(result)) { if (this.vimState.cursorStopPosition.getLeft(2).isEqual(result)) {

View File

@ -21,7 +21,7 @@ export class NeovimWrapper implements vscode.Disposable {
async run( async run(
vimState: VimState, vimState: VimState,
command: string command: string,
): Promise<{ statusBarText: string; error: boolean }> { ): Promise<{ statusBarText: string; error: boolean }> {
if (!this.nvim) { if (!this.nvim) {
this.nvim = await this.startNeovim(vimState.document); this.nvim = await this.startNeovim(vimState.document);
@ -137,7 +137,7 @@ export class NeovimWrapper implements vscode.Disposable {
const [rangeStart, rangeEnd] = sorted( const [rangeStart, rangeEnd] = sorted(
vimState.cursorStartPosition, vimState.cursorStartPosition,
vimState.cursorStopPosition vimState.cursorStopPosition,
); );
await this.nvim.callFunction('setpos', [ await this.nvim.callFunction('setpos', [
'.', '.',
@ -189,18 +189,18 @@ export class NeovimWrapper implements vscode.Disposable {
await TextEditor.replace( await TextEditor.replace(
vimState.editor, vimState.editor,
new vscode.Range(0, 0, lineCount - 1, TextEditor.getLineLength(lineCount - 1)), new vscode.Range(0, 0, lineCount - 1, TextEditor.getLineLength(lineCount - 1)),
fixedLines.join('\n') fixedLines.join('\n'),
); );
Logger.debug(`${lines.length} lines in nvim. ${lineCount} in editor.`); Logger.debug(`${lines.length} lines in nvim. ${lineCount} in editor.`);
const [row, character] = ((await this.nvim.callFunction('getpos', ['.'])) as number[]).slice( const [row, character] = ((await this.nvim.callFunction('getpos', ['.'])) as number[]).slice(
1, 1,
3 3,
); );
vimState.editor.selection = new vscode.Selection( vimState.editor.selection = new vscode.Selection(
new Position(row - 1, character), new Position(row - 1, character),
new Position(row - 1, character) new Position(row - 1, character),
); );
if (configuration.expandtab) { if (configuration.expandtab) {

View File

@ -92,7 +92,7 @@ export async function mkdirAsync(path: string, options: any): Promise<void> {
export async function writeFileAsync( export async function writeFileAsync(
path: string, path: string,
content: string, content: string,
encoding: BufferEncoding encoding: BufferEncoding,
): Promise<void> { ): Promise<void> {
return vscode.workspace.fs.writeFile(vscode.Uri.parse(path), Buffer.from(content)); return vscode.workspace.fs.writeFile(vscode.Uri.parse(path), Buffer.from(content));
} }

View File

@ -12,7 +12,7 @@ export class HistoryBase {
constructor( constructor(
context: vscode.ExtensionContext, context: vscode.ExtensionContext,
historyFileName: string, historyFileName: string,
extensionStoragePath: string extensionStoragePath: string,
) { ) {
this.context = context; this.context = context;
this.historyFileName = historyFileName; this.historyFileName = historyFileName;

View File

@ -101,7 +101,7 @@ export async function mkdirAsync(path: string, options: any): Promise<void> {
export async function writeFileAsync( export async function writeFileAsync(
path: string, path: string,
content: string, content: string,
encoding: BufferEncoding encoding: BufferEncoding,
): Promise<void> { ): Promise<void> {
await promisify(fs.writeFile)(path, content, encoding); await promisify(fs.writeFile)(path, content, encoding);
} }

View File

@ -16,7 +16,7 @@ export class HistoryBase {
constructor( constructor(
context: vscode.ExtensionContext, context: vscode.ExtensionContext,
historyFileName: string, historyFileName: string,
extensionStoragePath: string extensionStoragePath: string,
) { ) {
this.historyFileName = historyFileName; this.historyFileName = historyFileName;
this.extensionStoragePath = extensionStoragePath; this.extensionStoragePath = extensionStoragePath;

View File

@ -55,7 +55,7 @@ export class Register {
vimState: VimState, vimState: VimState,
content: RegisterContent, content: RegisterContent,
multicursorIndex?: number, multicursorIndex?: number,
copyToUnnamed?: boolean copyToUnnamed?: boolean,
): void { ): void {
const register = vimState.recordedState.registerName; const register = vimState.recordedState.registerName;
@ -119,7 +119,7 @@ export class Register {
vimState: VimState, vimState: VimState,
register: string, register: string,
content: RegisterContent, content: RegisterContent,
multicursorIndex: number multicursorIndex: number,
): void { ): void {
if (multicursorIndex === 0 || !Register.registers.has(register)) { if (multicursorIndex === 0 || !Register.registers.has(register)) {
Register.registers.set(register, []); Register.registers.set(register, []);
@ -148,7 +148,7 @@ export class Register {
vimState: VimState, vimState: VimState,
register: string, register: string,
content: RegisterContent, content: RegisterContent,
multicursorIndex: number multicursorIndex: number,
): void { ): void {
if (!Register.registers.has(register)) { if (!Register.registers.has(register)) {
Register.registers.set(register, []); Register.registers.set(register, []);
@ -192,7 +192,7 @@ export class Register {
*/ */
public static setReadonlyRegister( public static setReadonlyRegister(
register: '.' | '%' | ':' | '#' | '/', register: '.' | '%' | ':' | '#' | '/',
content: RegisterContent content: RegisterContent,
) { ) {
Register.registers.set(register, [ Register.registers.set(register, [
{ {
@ -269,7 +269,7 @@ export class Register {
*/ */
public static async get( public static async get(
register: string, register: string,
multicursorIndex = 0 multicursorIndex = 0,
): Promise<IRegisterContent | undefined> { ): Promise<IRegisterContent | undefined> {
if (!Register.isValidRegister(register)) { if (!Register.isValidRegister(register)) {
throw new Error(`Invalid register ${register}`); throw new Error(`Invalid register ${register}`);
@ -329,7 +329,7 @@ export class Register {
version: REGISTER_FORMAT_VERSION, version: REGISTER_FORMAT_VERSION,
registers: serializableRegisters, registers: serializableRegisters,
}), }),
'utf8' 'utf8',
); );
}); });
} }
@ -345,7 +345,7 @@ export class Register {
if (parsed.version === REGISTER_FORMAT_VERSION) { if (parsed.version === REGISTER_FORMAT_VERSION) {
Register.registers = new Map(parsed.registers); Register.registers = new Map(parsed.registers);
} }
} },
); );
}); });
} else { } else {

View File

@ -29,7 +29,7 @@ export class SearchState {
direction: SearchDirection, direction: SearchDirection,
startPosition: Position, startPosition: Position,
searchString = '', searchString = '',
{ ignoreSmartcase = false } = {} { ignoreSmartcase = false } = {},
) { ) {
this._searchString = searchString; this._searchString = searchString;
@ -124,13 +124,13 @@ export class SearchState {
vimState: VimState, vimState: VimState,
startPosition: Position, startPosition: Position,
direction = SearchDirection.Forward, direction = SearchDirection.Forward,
relativeIndex = 0 relativeIndex = 0,
): IndexedPosition | undefined { ): IndexedPosition | undefined {
const nextMatch = this.getNextSearchMatchRange( const nextMatch = this.getNextSearchMatchRange(
vimState, vimState,
startPosition, startPosition,
direction, direction,
relativeIndex relativeIndex,
); );
if (nextMatch === undefined) { if (nextMatch === undefined) {
return undefined; return undefined;
@ -155,7 +155,7 @@ export class SearchState {
vimState: VimState, vimState: VimState,
fromPosition: Position, fromPosition: Position,
direction = SearchDirection.Forward, direction = SearchDirection.Forward,
relativeIndex = 0 relativeIndex = 0,
): IndexedRange | undefined { ): IndexedRange | undefined {
const matchRanges = this.recalculateSearchRanges(vimState); const matchRanges = this.recalculateSearchRanges(vimState);

View File

@ -26,7 +26,7 @@ interface IBaseMovement {
execActionWithCount( execActionWithCount(
position: Position, position: Position,
vimState: VimState, vimState: VimState,
count: number count: number,
): Promise<Position | IMovement>; ): Promise<Position | IMovement>;
} }
@ -256,7 +256,7 @@ export class VimState implements vscode.Disposable {
mode, mode,
replaceState: new ReplaceState( replaceState: new ReplaceState(
this.cursors.map((cursor) => cursor.stop), this.cursors.map((cursor) => cursor.stop),
this.recordedState.count this.recordedState.count,
), ),
} }
: mode === Mode.CommandlineInProgress : mode === Mode.CommandlineInProgress
@ -275,7 +275,7 @@ export class VimState implements vscode.Disposable {
mode, mode,
highSurrogate: undefined, highSurrogate: undefined,
} }
: { mode } : { mode },
); );
} }

View File

@ -21,7 +21,7 @@ class StatusBarImpl implements vscode.Disposable {
this.statusBarItem = vscode.window.createStatusBarItem( this.statusBarItem = vscode.window.createStatusBarItem(
'primary', 'primary',
vscode.StatusBarAlignment.Left, vscode.StatusBarAlignment.Left,
Number.MIN_SAFE_INTEGER // Furthest right on the left Number.MIN_SAFE_INTEGER, // Furthest right on the left
); );
this.statusBarItem.name = 'Vim Command Line'; this.statusBarItem.name = 'Vim Command Line';
this.statusBarItem.show(); this.statusBarItem.show();
@ -29,7 +29,7 @@ class StatusBarImpl implements vscode.Disposable {
this.recordedStateStatusBarItem = vscode.window.createStatusBarItem( this.recordedStateStatusBarItem = vscode.window.createStatusBarItem(
'showcmd', 'showcmd',
vscode.StatusBarAlignment.Right, vscode.StatusBarAlignment.Right,
Number.MAX_SAFE_INTEGER // Furthest left on the right Number.MAX_SAFE_INTEGER, // Furthest left on the right
); );
this.recordedStateStatusBarItem.name = 'Vim Pending Command Keys'; this.recordedStateStatusBarItem.name = 'Vim Pending Command Keys';
this.recordedStateStatusBarItem.show(); this.recordedStateStatusBarItem.show();

View File

@ -21,7 +21,7 @@ export class TextEditor {
editor: vscode.TextEditor, editor: vscode.TextEditor,
text: string, text: string,
at?: Position, at?: Position,
letVSCodeHandleKeystrokes?: boolean letVSCodeHandleKeystrokes?: boolean,
): Promise<void> { ): Promise<void> {
// If we insert "blah(" with default:type, VSCode will insert the closing ). // If we insert "blah(" with default:type, VSCode will insert the closing ).
// We *probably* don't want that to happen if we're inserting a lot of text. // We *probably* don't want that to happen if we're inserting a lot of text.
@ -46,7 +46,7 @@ export class TextEditor {
static async replace( static async replace(
editor: vscode.TextEditor, editor: vscode.TextEditor,
range: vscode.Range, range: vscode.Range,
text: string text: string,
): Promise<boolean> { ): Promise<boolean> {
return editor.edit((editBuilder) => { return editor.edit((editBuilder) => {
editBuilder.replace(range, text); editBuilder.replace(range, text);
@ -190,7 +190,7 @@ export class TextEditor {
*/ */
public static getFirstNonWhitespaceCharOnLine( public static getFirstNonWhitespaceCharOnLine(
document: vscode.TextDocument, document: vscode.TextDocument,
line: number line: number,
): Position { ): Position {
line = clamp(line, 0, document.lineCount - 1); line = clamp(line, 0, document.lineCount - 1);
return new Position(line, document.lineAt(line).firstNonWhitespaceCharacterIndex); return new Position(line, document.lineAt(line).firstNonWhitespaceCharacterIndex);
@ -205,7 +205,7 @@ export class TextEditor {
public static *iterateLinesInBlock( public static *iterateLinesInBlock(
vimState: VimState, vimState: VimState,
cursor?: Cursor, cursor?: Cursor,
options: { reverse?: boolean } = { reverse: false } options: { reverse?: boolean } = { reverse: false },
): Iterable<{ line: string; start: Position; end: Position }> { ): Iterable<{ line: string; start: Position; end: Position }> {
const { reverse } = options; const { reverse } = options;
@ -243,7 +243,7 @@ export class TextEditor {
*/ */
public static *iterateWords( public static *iterateWords(
document: vscode.TextDocument, document: vscode.TextDocument,
start: Position start: Position,
): Iterable<{ start: Position; end: Position; word: string }> { ): Iterable<{ start: Position; end: Position; word: string }> {
const text = document.lineAt(start).text; const text = document.lineAt(start).text;
if (/\s/.test(text[start.character])) { if (/\s/.test(text[start.character])) {

View File

@ -18,7 +18,7 @@ export function getSentenceEnd(pos: Position): Position {
for (let currentLine = pos.line; currentLine <= paragraphEnd.line; currentLine++) { for (let currentLine = pos.line; currentLine <= paragraphEnd.line; currentLine++) {
const allPositions = getAllPositions(TextEditor.getLine(currentLine).text, sentenceEndRegex); const allPositions = getAllPositions(TextEditor.getLine(currentLine).text, sentenceEndRegex);
const newCharacter = allPositions.find( const newCharacter = allPositions.find(
(index) => index > pos.character || currentLine !== pos.line (index) => index > pos.character || currentLine !== pos.line,
); );
if (newCharacter !== undefined) { if (newCharacter !== undefined) {
@ -59,7 +59,7 @@ function getNextSentenceBegin(pos: Position): Position {
for (let currentLine = pos.line; currentLine <= paragraphEnd.line; currentLine++) { for (let currentLine = pos.line; currentLine <= paragraphEnd.line; currentLine++) {
const endPositions = getAllEndPositions(TextEditor.getLine(currentLine).text, sentenceEndRegex); const endPositions = getAllEndPositions(TextEditor.getLine(currentLine).text, sentenceEndRegex);
const newCharacter = endPositions.find( const newCharacter = endPositions.find(
(index) => index > pos.character || currentLine !== pos.line (index) => index > pos.character || currentLine !== pos.line,
); );
if (newCharacter !== undefined) { if (newCharacter !== undefined) {
@ -73,7 +73,7 @@ function getNextSentenceBegin(pos: Position): Position {
function getFirstNonWhitespaceInParagraph( function getFirstNonWhitespaceInParagraph(
pos: Position, pos: Position,
paragraphEnd: Position, paragraphEnd: Position,
inclusive: boolean inclusive: boolean,
): Position { ): Position {
// If the cursor is at an empty line, it's the end of a paragraph and the begin of another paragraph // If the cursor is at an empty line, it's the end of a paragraph and the begin of another paragraph
// Find the first non-whitespace character. // Find the first non-whitespace character.
@ -86,7 +86,7 @@ function getFirstNonWhitespaceInParagraph(
(index) => (index) =>
(index > pos.character && !inclusive) || (index > pos.character && !inclusive) ||
(index >= pos.character && inclusive) || (index >= pos.character && inclusive) ||
currentLine !== pos.line currentLine !== pos.line,
); );
if (newCharacter !== undefined) { if (newCharacter !== undefined) {

View File

@ -26,7 +26,7 @@ export abstract class TextObject extends BaseMovement {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<IMovement> { ): Promise<IMovement> {
const res = await this.execAction(position, vimState); const res = await this.execAction(position, vimState);
// Since we need to handle leading spaces, we cannot use MoveWordBegin.execActionForOperator // Since we need to handle leading spaces, we cannot use MoveWordBegin.execActionForOperator
@ -135,7 +135,7 @@ export class SelectABigWord extends TextObject {
stop = position.getLineEnd(); stop = position.getLineEnd();
} else if ( } else if (
(nextWord.isEqual( (nextWord.isEqual(
TextEditor.getFirstNonWhitespaceCharOnLine(vimState.document, nextWord.line) TextEditor.getFirstNonWhitespaceCharOnLine(vimState.document, nextWord.line),
) || ) ||
nextWord.isLineEnd()) && nextWord.isLineEnd()) &&
vimState.recordedState.count === 0 vimState.recordedState.count === 0
@ -190,7 +190,7 @@ export class SelectAnExpandingBlock extends ExpandingSelection {
position: Position, position: Position,
vimState: VimState, vimState: VimState,
firstIteration: boolean, firstIteration: boolean,
lastIteration: boolean lastIteration: boolean,
): Promise<IMovement> { ): Promise<IMovement> {
const blocks = [ const blocks = [
new MoveAroundDoubleQuotes(), new MoveAroundDoubleQuotes(),
@ -208,7 +208,7 @@ export class SelectAnExpandingBlock extends ExpandingSelection {
const cursorPos = new Position(position.line, position.character); const cursorPos = new Position(position.line, position.character);
const cursorStartPos = new Position( const cursorStartPos = new Position(
vimState.cursorStartPosition.line, vimState.cursorStartPosition.line,
vimState.cursorStartPosition.character vimState.cursorStartPosition.character,
); );
ranges.push(await block.execAction(cursorPos, vimState, firstIteration, lastIteration)); ranges.push(await block.execAction(cursorPos, vimState, firstIteration, lastIteration));
vimState.cursorStartPosition = cursorStartPos; vimState.cursorStartPosition = cursorStartPos;
@ -223,7 +223,7 @@ export class SelectAnExpandingBlock extends ExpandingSelection {
for (const iMotion of ranges) { for (const iMotion of ranges) {
const currentSelectedRange = new Cursor( const currentSelectedRange = new Cursor(
vimState.cursorStartPosition, vimState.cursorStartPosition,
vimState.cursorStopPosition vimState.cursorStopPosition,
); );
if (iMotion.failed) { if (iMotion.failed) {
continue; continue;
@ -266,11 +266,11 @@ export class SelectAnExpandingBlock extends ExpandingSelection {
// revert relevant state changes // revert relevant state changes
vimState.cursorStartPosition = new Position( vimState.cursorStartPosition = new Position(
smallestRange.start.line, smallestRange.start.line,
smallestRange.start.character smallestRange.start.character,
); );
vimState.cursorStopPosition = new Position( vimState.cursorStopPosition = new Position(
smallestRange.stop.line, smallestRange.stop.line,
smallestRange.stop.character smallestRange.stop.character,
); );
vimState.recordedState.operatorPositionDiff = undefined; vimState.recordedState.operatorPositionDiff = undefined;
return { return {
@ -609,13 +609,13 @@ abstract class IndentObjectMatch extends TextObject {
vimState.document, vimState.document,
firstValidLineNumber, firstValidLineNumber,
cursorIndent, cursorIndent,
-1 -1,
); );
let endLineNumber = IndentObjectMatch.findRangeStartOrEnd( let endLineNumber = IndentObjectMatch.findRangeStartOrEnd(
vimState.document, vimState.document,
firstValidLineNumber, firstValidLineNumber,
cursorIndent, cursorIndent,
1 1,
); );
// Adjust the start line as needed. // Adjust the start line as needed.
@ -664,7 +664,7 @@ abstract class IndentObjectMatch extends TextObject {
public override async execActionForOperator( public override async execActionForOperator(
position: Position, position: Position,
vimState: VimState vimState: VimState,
): Promise<IMovement> { ): Promise<IMovement> {
return this.execAction(position, vimState); return this.execAction(position, vimState);
} }
@ -689,7 +689,7 @@ abstract class IndentObjectMatch extends TextObject {
document: TextDocument, document: TextDocument,
startIndex: number, startIndex: number,
cursorIndent: number, cursorIndent: number,
step: -1 | 1 step: -1 | 1,
): number { ): number {
let i = startIndex; let i = startIndex;
let ret = startIndex; let ret = startIndex;
@ -796,12 +796,12 @@ abstract class SelectArgument extends TextObject {
SelectInnerArgument.findLeftArgumentBoundary( SelectInnerArgument.findLeftArgumentBoundary(
vimState.document, vimState.document,
leftSearchStartPosition, leftSearchStartPosition,
true true,
) === undefined || ) === undefined ||
SelectInnerArgument.findRightArgumentBoundary( SelectInnerArgument.findRightArgumentBoundary(
vimState.document, vimState.document,
rightSearchStartPosition, rightSearchStartPosition,
true true,
) === undefined ) === undefined
) { ) {
return failure; return failure;
@ -809,7 +809,7 @@ abstract class SelectArgument extends TextObject {
const leftArgumentBoundary = SelectInnerArgument.findLeftArgumentBoundary( const leftArgumentBoundary = SelectInnerArgument.findLeftArgumentBoundary(
vimState.document, vimState.document,
leftSearchStartPosition leftSearchStartPosition,
); );
if (leftArgumentBoundary === undefined) { if (leftArgumentBoundary === undefined) {
return failure; return failure;
@ -817,7 +817,7 @@ abstract class SelectArgument extends TextObject {
const rightArgumentBoundary = SelectInnerArgument.findRightArgumentBoundary( const rightArgumentBoundary = SelectInnerArgument.findRightArgumentBoundary(
vimState.document, vimState.document,
rightSearchStartPosition rightSearchStartPosition,
); );
if (rightArgumentBoundary === undefined) { if (rightArgumentBoundary === undefined) {
return failure; return failure;
@ -828,10 +828,10 @@ abstract class SelectArgument extends TextObject {
if (this.selectAround) { if (this.selectAround) {
const isLeftOnOpening: boolean = SelectArgument.openingDelimiterCharacters().includes( const isLeftOnOpening: boolean = SelectArgument.openingDelimiterCharacters().includes(
TextEditor.getCharAt(vimState.document, leftArgumentBoundary) TextEditor.getCharAt(vimState.document, leftArgumentBoundary),
); );
const isRightOnClosing: boolean = SelectArgument.closingDelimiterCharacters().includes( const isRightOnClosing: boolean = SelectArgument.closingDelimiterCharacters().includes(
TextEditor.getCharAt(vimState.document, rightArgumentBoundary) TextEditor.getCharAt(vimState.document, rightArgumentBoundary),
); );
// Edge-case: // Edge-case:
@ -903,7 +903,7 @@ abstract class SelectArgument extends TextObject {
private static findLeftArgumentBoundary( private static findLeftArgumentBoundary(
document: TextDocument, document: TextDocument,
position: Position, position: Position,
ignoreSeparators: boolean = false ignoreSeparators: boolean = false,
): Position | undefined { ): Position | undefined {
let delimiterPosition: Position | undefined; let delimiterPosition: Position | undefined;
let walkingPosition = position; let walkingPosition = position;
@ -944,7 +944,7 @@ abstract class SelectArgument extends TextObject {
private static findRightArgumentBoundary( private static findRightArgumentBoundary(
document: TextDocument, document: TextDocument,
position: Position, position: Position,
ignoreSeparators: boolean = false ignoreSeparators: boolean = false,
): Position | undefined { ): Position | undefined {
let delimiterPosition: Position | undefined; let delimiterPosition: Position | undefined;
let walkingPosition = position; let walkingPosition = position;

View File

@ -36,7 +36,7 @@ function regexForWordType(wordType: WordType): RegExp {
export function getWordLeftInText( export function getWordLeftInText(
text: string, text: string,
pos: number, pos: number,
wordType: WordType wordType: WordType,
): number | undefined { ): number | undefined {
return getWordLeftOnLine(text, pos, wordType); return getWordLeftOnLine(text, pos, wordType);
} }
@ -44,7 +44,7 @@ export function getWordLeftInText(
export function getWordRightInText( export function getWordRightInText(
text: string, text: string,
pos: number, pos: number,
wordType: WordType wordType: WordType,
): number | undefined { ): number | undefined {
return getAllPositions(text, regexForWordType(wordType)).find((index) => index > pos); return getAllPositions(text, regexForWordType(wordType)).find((index) => index > pos);
} }
@ -53,7 +53,7 @@ export function prevWordStart(
document: TextDocument, document: TextDocument,
pos: Position, pos: Position,
wordType: WordType, wordType: WordType,
inclusive: boolean = false inclusive: boolean = false,
): Position { ): Position {
for (let currentLine = pos.line; currentLine >= 0; currentLine--) { for (let currentLine = pos.line; currentLine >= 0; currentLine--) {
const newCharacter = getWordLeftOnLine( const newCharacter = getWordLeftOnLine(
@ -61,7 +61,7 @@ export function prevWordStart(
pos.character, pos.character,
wordType, wordType,
currentLine !== pos.line, currentLine !== pos.line,
inclusive inclusive,
); );
if (newCharacter !== undefined) { if (newCharacter !== undefined) {
@ -77,7 +77,7 @@ function getWordLeftOnLine(
pos: number, pos: number,
wordType: WordType, wordType: WordType,
forceFirst: boolean = false, forceFirst: boolean = false,
inclusive: boolean = false inclusive: boolean = false,
): number | undefined { ): number | undefined {
return getAllPositions(text, regexForWordType(wordType)) return getAllPositions(text, regexForWordType(wordType))
.reverse() .reverse()
@ -88,18 +88,18 @@ export function nextWordStart(
document: TextDocument, document: TextDocument,
pos: Position, pos: Position,
wordType: WordType, wordType: WordType,
inclusive: boolean = false inclusive: boolean = false,
): Position { ): Position {
for (let currentLine = pos.line; currentLine < document.lineCount; currentLine++) { for (let currentLine = pos.line; currentLine < document.lineCount; currentLine++) {
const positions = getAllPositions( const positions = getAllPositions(
document.lineAt(currentLine).text, document.lineAt(currentLine).text,
regexForWordType(wordType) regexForWordType(wordType),
); );
const newCharacter = positions.find( const newCharacter = positions.find(
(index) => (index) =>
(index > pos.character && !inclusive) || (index > pos.character && !inclusive) ||
(index >= pos.character && inclusive) || (index >= pos.character && inclusive) ||
currentLine !== pos.line currentLine !== pos.line,
); );
if (newCharacter !== undefined) { if (newCharacter !== undefined) {
@ -114,18 +114,18 @@ export function nextWordEnd(
document: TextDocument, document: TextDocument,
pos: Position, pos: Position,
wordType: WordType, wordType: WordType,
inclusive: boolean = false inclusive: boolean = false,
): Position { ): Position {
for (let currentLine = pos.line; currentLine < document.lineCount; currentLine++) { for (let currentLine = pos.line; currentLine < document.lineCount; currentLine++) {
const positions = getAllEndPositions( const positions = getAllEndPositions(
document.lineAt(currentLine).text, document.lineAt(currentLine).text,
regexForWordType(wordType) regexForWordType(wordType),
); );
const newCharacter = positions.find( const newCharacter = positions.find(
(index) => (index) =>
(index > pos.character && !inclusive) || (index > pos.character && !inclusive) ||
(index >= pos.character && inclusive) || (index >= pos.character && inclusive) ||
currentLine !== pos.line currentLine !== pos.line,
); );
if (newCharacter !== undefined) { if (newCharacter !== undefined) {
@ -140,7 +140,7 @@ export function prevWordEnd(document: TextDocument, pos: Position, wordType: Wor
for (let currentLine = pos.line; currentLine > -1; currentLine--) { for (let currentLine = pos.line; currentLine > -1; currentLine--) {
let positions = getAllEndPositions( let positions = getAllEndPositions(
document.lineAt(currentLine).text, document.lineAt(currentLine).text,
regexForWordType(wordType) regexForWordType(wordType),
); );
// if one line is empty, use the 0 position as the default value // if one line is empty, use the 0 position as the default value
if (positions.length === 0) { if (positions.length === 0) {

View File

@ -33,7 +33,7 @@ export interface IModeHandler {
export async function executeTransformations( export async function executeTransformations(
modeHandler: IModeHandler, modeHandler: IModeHandler,
transformations: Transformation[] transformations: Transformation[],
) { ) {
if (transformations.length === 0) { if (transformations.length === 0) {
return; return;
@ -42,14 +42,14 @@ export async function executeTransformations(
const vimState = modeHandler.vimState; const vimState = modeHandler.vimState;
const textTransformations: TextTransformations[] = transformations.filter((x) => const textTransformations: TextTransformations[] = transformations.filter((x) =>
isTextTransformation(x) isTextTransformation(x),
) as any; ) as any;
const multicursorTextTransformations: InsertTextVSCodeTransformation[] = transformations.filter( const multicursorTextTransformations: InsertTextVSCodeTransformation[] = transformations.filter(
(x) => isMultiCursorTextTransformation(x) (x) => isMultiCursorTextTransformation(x),
) as any; ) as any;
const otherTransformations = transformations.filter( const otherTransformations = transformations.filter(
(x) => !isTextTransformation(x) && !isMultiCursorTextTransformation(x) (x) => !isTextTransformation(x) && !isMultiCursorTextTransformation(x),
); );
const accumulatedPositionDifferences: { [key: number]: PositionDiff[] } = {}; const accumulatedPositionDifferences: { [key: number]: PositionDiff[] } = {};
@ -186,7 +186,7 @@ export async function executeTransformations(
vimState.recordedState = new RecordedState(); vimState.recordedState = new RecordedState();
if (transformation.register === ':') { if (transformation.register === ':') {
await new ExCommandLine(recordedMacro.commandString, vimState.currentMode).run( await new ExCommandLine(recordedMacro.commandString, vimState.currentMode).run(
vimState vimState,
); );
} else if (transformation.replay === 'contentChange') { } else if (transformation.replay === 'contentChange') {
await modeHandler.runMacro(recordedMacro); await modeHandler.runMacro(recordedMacro);
@ -207,7 +207,7 @@ export async function executeTransformations(
await executeTransformations( await executeTransformations(
modeHandler, modeHandler,
vimState.recordedState.transformer.transformations vimState.recordedState.transformer.transformations,
); );
globalState.lastInvokedMacro = recordedMacro; globalState.lastInvokedMacro = recordedMacro;
@ -274,9 +274,9 @@ export async function executeTransformations(
(cursor, diff) => (cursor, diff) =>
new Cursor( new Cursor(
cursor.start.add(vimState.document, diff), cursor.start.add(vimState.document, diff),
cursor.stop.add(vimState.document, diff) cursor.stop.add(vimState.document, diff),
), ),
Cursor.FromVSCodeSelection(sel) Cursor.FromVSCodeSelection(sel),
); );
}); });

View File

@ -234,7 +234,7 @@ const getRangeFromTextTransformation = (transformation: TextTransformations): Ra
case 'insertText': case 'insertText':
return new Range( return new Range(
transformation.position, transformation.position,
transformation.position.advancePositionByText(transformation.text) transformation.position.advancePositionByText(transformation.text),
); );
case 'replaceText': case 'replaceText':
// TODO: Do we need to do the same sort of thing here as for insertText? // TODO: Do we need to do the same sort of thing here as for insertText?
@ -249,7 +249,7 @@ const getRangeFromTextTransformation = (transformation: TextTransformations): Ra
}; };
export function overlappingTransformations( export function overlappingTransformations(
transformations: TextTransformations[] transformations: TextTransformations[],
): [TextTransformations, TextTransformations] | undefined { ): [TextTransformations, TextTransformations] | undefined {
for (let i = 0; i < transformations.length; i++) { for (let i = 0; i < transformations.length; i++) {
for (let j = i + 1; j < transformations.length; j++) { for (let j = i + 1; j < transformations.length; j++) {

View File

@ -3,7 +3,7 @@ import { promisify } from 'util';
export function exec( export function exec(
command: string, command: string,
options?: child_process.ExecOptions options?: child_process.ExecOptions,
): child_process.PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer }> { ): child_process.PromiseWithChild<{ stdout: string | Buffer; stderr: string | Buffer }> {
return promisify(child_process.exec)(command, options); return promisify(child_process.exec)(command, options);
} }

View File

@ -46,7 +46,7 @@ export function ensureVisible(range: Range): DecorationOptions {
export function formatDecorationText( export function formatDecorationText(
text: string, text: string,
tabsize: number, tabsize: number,
newlineReplacement: string | ((substring: string, ...args: any[]) => string) = '\u23ce' // "⏎" RETURN SYMBOL newlineReplacement: string | ((substring: string, ...args: any[]) => string) = '\u23ce', // "⏎" RETURN SYMBOL
) { ) {
// surround with zero-width space to prevent trimming // surround with zero-width space to prevent trimming
return `\u200b${text return `\u200b${text
@ -62,7 +62,7 @@ export function formatDecorationText(
*/ */
export function getDecorationsForSearchMatchRanges( export function getDecorationsForSearchMatchRanges(
ranges: Range[], ranges: Range[],
currentMatchIndex?: number currentMatchIndex?: number,
): SearchDecorations { ): SearchDecorations {
const searchHighlight: DecorationOptions[] = []; const searchHighlight: DecorationOptions[] = [];
const searchMatch: DecorationOptions[] = []; const searchMatch: DecorationOptions[] = [];

View File

@ -109,7 +109,7 @@ interface PathDetails {
export function getPathDetails( export function getPathDetails(
partialPath: string, partialPath: string,
currentUri: vscode.Uri, currentUri: vscode.Uri,
isRemote: boolean isRemote: boolean,
): PathDetails { ): PathDetails {
let isWindows: boolean; let isWindows: boolean;
if (currentUri.scheme === 'untitled') { if (currentUri.scheme === 'untitled') {
@ -150,7 +150,7 @@ export function getPathDetails(
// path will return /home/user for example even 'vscode-remote' is used on windows // path will return /home/user for example even 'vscode-remote' is used on windows
// as we relied of our isWindows detection // as we relied of our isWindows detection
separatePath(isWindows ? currentUri.fsPath : currentUri.path, p.sep)[0], separatePath(isWindows ? currentUri.fsPath : currentUri.path, p.sep)[0],
dirName dirName,
); );
} }
@ -179,7 +179,7 @@ export function resolveUri(
absolutePath: string, absolutePath: string,
sep: string, sep: string,
currentUri: vscode.Uri, currentUri: vscode.Uri,
isRemote: boolean isRemote: boolean,
) { ) {
const isWindows = sep === path.win32.sep; const isWindows = sep === path.win32.sep;
if (isWindows && !/^(\\\\.+\\)|([a-zA-Z]:\\)/.test(absolutePath)) { if (isWindows && !/^(\\\\.+\\)|([a-zA-Z]:\\)/.test(absolutePath)) {
@ -221,7 +221,7 @@ export async function readDirectory(
sep: string, sep: string,
currentUri: vscode.Uri, currentUri: vscode.Uri,
isRemote: boolean, isRemote: boolean,
addCurrentAndUp: boolean addCurrentAndUp: boolean,
) { ) {
try { try {
const directoryUri = resolveUri(absolutePath, sep, currentUri, isRemote); const directoryUri = resolveUri(absolutePath, sep, currentUri, isRemote);

View File

@ -63,7 +63,7 @@ export function reportFileInfo(position: Position, vimState: VimState) {
vimState, vimState,
`"${fileName}"${modified} ${doc.lineCount} line${ `"${fileName}"${modified} ${doc.lineCount} line${
doc.lineCount > 1 ? 's' : '' doc.lineCount > 1 ? 's' : ''
} --${progress}%--` } --${progress}%--`,
); );
} }
} }

View File

@ -625,7 +625,7 @@ class UnimplementedCommand extends ExCommand {
StatusBar.setText( StatusBar.setText(
vimState, vimState,
`Command :${this.name} is not yet implemented (PRs are welcome!)`, `Command :${this.name} is not yet implemented (PRs are welcome!)`,
true true,
); );
} }
@ -642,7 +642,7 @@ export class NoOpCommand extends ExCommand {
function nameParser( function nameParser(
name: [string, string], name: [string, string],
argParser: ArgParser | undefined argParser: ArgParser | undefined,
): Parser<Parser<ExCommand>> { ): Parser<Parser<ExCommand>> {
argParser ??= all.result(new UnimplementedCommand(name[1] ? `${name[0]}[${name[1]}]` : name[0])); argParser ??= all.result(new UnimplementedCommand(name[1] ? `${name[0]}[${name[1]}]` : name[0]));
@ -654,7 +654,7 @@ function nameParser(
export const commandNameParser: Parser<Parser<ExCommand> | undefined> = alt( export const commandNameParser: Parser<Parser<ExCommand> | undefined> = alt(
...[...builtinExCommands] ...[...builtinExCommands]
.reverse() .reverse()
.map(([name, argParser]) => nameParser(name, argParser?.skip(optWhitespace))) .map(([name, argParser]) => nameParser(name, argParser?.skip(optWhitespace))),
); );
export const exCommandParser: Parser<{ lineRange: LineRange | undefined; command: ExCommand }> = export const exCommandParser: Parser<{ lineRange: LineRange | undefined; command: ExCommand }> =
@ -665,14 +665,14 @@ export const exCommandParser: Parser<{ lineRange: LineRange | undefined; command
LineRange.parser.fallback(undefined), LineRange.parser.fallback(undefined),
optWhitespace, optWhitespace,
commandNameParser.fallback(undefined), commandNameParser.fallback(undefined),
all all,
) ),
) )
.map(([lineRange, whitespace, parseArgs, args]) => { .map(([lineRange, whitespace, parseArgs, args]) => {
if (parseArgs === undefined) { if (parseArgs === undefined) {
throw VimError.fromCode( throw VimError.fromCode(
ErrorCode.NotAnEditorCommand, ErrorCode.NotAnEditorCommand,
`${lineRange?.toString() ?? ''}${whitespace}${args}` `${lineRange?.toString() ?? ''}${whitespace}${args}`,
); );
} }
const result = seq(parseArgs, optWhitespace.then(all)).parse(args); const result = seq(parseArgs, optWhitespace.then(all)).parse(args);

View File

@ -22,5 +22,5 @@ const escapedParser = string('\\')
export const keystrokesExpressionParser: Parser<string[]> = alt( export const keystrokesExpressionParser: Parser<string[]> = alt(
escapedParser, escapedParser,
specialCharacterParser, specialCharacterParser,
noneOf('"') noneOf('"'),
).many(); ).many();

View File

@ -92,7 +92,7 @@ const lineSpecifierParser: Parser<LineSpecifier> = alt(
}), }),
string('\\/').result({ type: 'last_search_pattern_next' }), string('\\/').result({ type: 'last_search_pattern_next' }),
string('\\?').result({ type: 'last_search_pattern_prev' }), string('\\?').result({ type: 'last_search_pattern_prev' }),
string('\\&').result({ type: 'last_substitute_pattern_next' }) string('\\&').result({ type: 'last_substitute_pattern_next' }),
); );
const offsetParser: Parser<number> = alt( const offsetParser: Parser<number> = alt(
@ -100,7 +100,7 @@ const offsetParser: Parser<number> = alt(
string('-') string('-')
.then(numberParser.fallback(1)) .then(numberParser.fallback(1))
.map((num) => -num), .map((num) => -num),
numberParser numberParser,
) )
.skip(optWhitespace) .skip(optWhitespace)
.atLeast(1) .atLeast(1)
@ -117,7 +117,7 @@ export class Address {
public static parser: Parser<Address> = alt( public static parser: Parser<Address> = alt(
seq(lineSpecifierParser.skip(optWhitespace), offsetParser.fallback(0)), seq(lineSpecifierParser.skip(optWhitespace), offsetParser.fallback(0)),
seq(succeed({ type: 'current_line' as const }), offsetParser) seq(succeed({ type: 'current_line' as const }), offsetParser),
).map(([specifier, offset]) => { ).map(([specifier, offset]) => {
return new Address(specifier, offset); return new Address(specifier, offset);
}); });
@ -155,13 +155,13 @@ export class Address {
case 'pattern_next': case 'pattern_next':
const m = this.specifier.pattern.nextMatch( const m = this.specifier.pattern.nextMatch(
vimState.document, vimState.document,
vimState.cursorStopPosition vimState.cursorStopPosition,
); );
if (m === undefined) { if (m === undefined) {
// TODO: throw proper errors for nowrapscan // TODO: throw proper errors for nowrapscan
throw VimError.fromCode( throw VimError.fromCode(
ErrorCode.PatternNotFound, ErrorCode.PatternNotFound,
this.specifier.pattern.patternString this.specifier.pattern.patternString,
); );
} else { } else {
return m.start.line; return m.start.line;
@ -175,13 +175,13 @@ export class Address {
const nextMatch = globalState.searchState.getNextSearchMatchPosition( const nextMatch = globalState.searchState.getNextSearchMatchPosition(
vimState, vimState,
vimState.cursorStopPosition, vimState.cursorStopPosition,
SearchDirection.Forward SearchDirection.Forward,
); );
if (nextMatch === undefined) { if (nextMatch === undefined) {
// TODO: throw proper errors for nowrapscan // TODO: throw proper errors for nowrapscan
throw VimError.fromCode( throw VimError.fromCode(
ErrorCode.PatternNotFound, ErrorCode.PatternNotFound,
globalState.searchState.searchString globalState.searchState.searchString,
); );
} }
return nextMatch.pos.line; return nextMatch.pos.line;
@ -192,13 +192,13 @@ export class Address {
const prevMatch = globalState.searchState.getNextSearchMatchPosition( const prevMatch = globalState.searchState.getNextSearchMatchPosition(
vimState, vimState,
vimState.cursorStopPosition, vimState.cursorStopPosition,
SearchDirection.Backward SearchDirection.Backward,
); );
if (prevMatch === undefined) { if (prevMatch === undefined) {
// TODO: throw proper errors for nowrapscan // TODO: throw proper errors for nowrapscan
throw VimError.fromCode( throw VimError.fromCode(
ErrorCode.PatternNotFound, ErrorCode.PatternNotFound,
globalState.searchState.searchString globalState.searchState.searchString,
); );
} }
return prevMatch.pos.line; return prevMatch.pos.line;
@ -211,12 +211,12 @@ export class Address {
SearchDirection.Forward, SearchDirection.Forward,
vimState.cursorStopPosition, vimState.cursorStopPosition,
globalState.substituteState.searchPattern.patternString, globalState.substituteState.searchPattern.patternString,
{} {},
) )
: undefined; : undefined;
const match = searchState?.getNextSearchMatchPosition( const match = searchState?.getNextSearchMatchPosition(
vimState, vimState,
vimState.cursorStopPosition vimState.cursorStopPosition,
); );
if (match === undefined) { if (match === undefined) {
// TODO: throw proper errors for nowrapscan // TODO: throw proper errors for nowrapscan
@ -283,8 +283,8 @@ export class LineRange {
Address.parser.skip(optWhitespace), Address.parser.skip(optWhitespace),
seq( seq(
alt(string(','), string(';')).skip(optWhitespace), alt(string(','), string(';')).skip(optWhitespace),
Address.parser.fallback(undefined) Address.parser.fallback(undefined),
).fallback(undefined) ).fallback(undefined),
).map(([start, sepEnd]) => { ).map(([start, sepEnd]) => {
if (sepEnd) { if (sepEnd) {
const [sep, end] = sepEnd; const [sep, end] = sepEnd;
@ -295,11 +295,11 @@ export class LineRange {
seq( seq(
// without the start line // without the start line
alt(string(','), string(';')).skip(optWhitespace), alt(string(','), string(';')).skip(optWhitespace),
Address.parser.fallback(undefined) Address.parser.fallback(undefined),
).map((sepEnd) => { ).map((sepEnd) => {
const [sep, end] = sepEnd; const [sep, end] = sepEnd;
return new LineRange(new Address({ type: 'current_line' }), sep, end); return new LineRange(new Address({ type: 'current_line' }), sep, end);
}) }),
); );
public resolve(vimState: VimState): { start: number; end: number } { public resolve(vimState: VimState): { start: number; end: number } {

View File

@ -29,9 +29,9 @@ export const fileNameParser: Parser<string> = alt<string>(
// TODO: anything else that needs escaping? // TODO: anything else that needs escaping?
return `\\${escaped}`; return `\\${escaped}`;
} }
}) }),
), ),
regexp(/\S/) regexp(/\S/),
) )
.atLeast(1) .atLeast(1)
.map((chars) => chars.join('')); .map((chars) => chars.join(''));
@ -50,10 +50,10 @@ export const fileOptParser: Parser<FileOpt> = string('++')
alt(string('bin'), string('binary')).result('bin'), alt(string('bin'), string('binary')).result('bin'),
alt(string('nobin'), string('nobinary')).result('nobin'), alt(string('nobin'), string('nobinary')).result('nobin'),
string('bad'), string('bad'),
string('edit') string('edit'),
),
string('=').then(regexp(/\S+/)).fallback(undefined),
), ),
string('=').then(regexp(/\S+/)).fallback(undefined)
)
) )
.sepBy(whitespace) .sepBy(whitespace)
.desc('[++opt]'); .desc('[++opt]');
@ -80,8 +80,8 @@ export const fileCmdParser: Parser<FileCmd | undefined> = string('+')
// TODO: Ex command // TODO: Ex command
// lazy(() => exCommandParser), // lazy(() => exCommandParser),
// Last line // Last line
succeed({ type: 'last_line' }) succeed({ type: 'last_line' }),
) ),
) )
.fallback(undefined) .fallback(undefined)
.desc('[+cmd]'); .desc('[+cmd]');

View File

@ -15,7 +15,7 @@ export function searchStringParser(args: {
}> { }> {
return seq( return seq(
Pattern.parser(args), Pattern.parser(args),
lazy(() => SearchOffset.parser.fallback(undefined)) lazy(() => SearchOffset.parser.fallback(undefined)),
).map(([pattern, offset]) => { ).map(([pattern, offset]) => {
return { pattern, offset }; return { pattern, offset };
}); });
@ -75,7 +75,7 @@ export class Pattern {
} }
| { | {
lineRange: LineRange; lineRange: LineRange;
} },
): PatternMatch[] { ): PatternMatch[] {
if (this.emptyBranch) { if (this.emptyBranch) {
// HACK: This pattern matches each character, but for purposes of perf when highlighting, merge them. // HACK: This pattern matches each character, but for purposes of perf when highlighting, merge them.
@ -109,7 +109,7 @@ export class Pattern {
// TODO: This is not exactly how Vim implements in-selection search (\%V), see :help \%V for more info. // TODO: This is not exactly how Vim implements in-selection search (\%V), see :help \%V for more info.
const searchRange = new Range( const searchRange = new Range(
vimState.lastVisualSelection.start, vimState.lastVisualSelection.start,
vimState.lastVisualSelection.end vimState.lastVisualSelection.end,
); );
haystack = vimState.document.getText(searchRange); haystack = vimState.document.getText(searchRange);
searchOffset = vimState.document.offsetAt(vimState.lastVisualSelection.start); searchOffset = vimState.document.offsetAt(vimState.lastVisualSelection.start);
@ -142,7 +142,7 @@ export class Pattern {
const matchRange = new Range( const matchRange = new Range(
vimState.document.positionAt(searchOffset + match.index), vimState.document.positionAt(searchOffset + match.index),
vimState.document.positionAt(searchOffset + match.index + match[0].length) vimState.document.positionAt(searchOffset + match.index + match[0].length),
); );
if ( if (
!this.inSelection && !this.inSelection &&
@ -231,12 +231,12 @@ export class Pattern {
string('\\') string('\\')
.then(any.fallback(undefined)) .then(any.fallback(undefined))
.map((escaped) => '\\' + (escaped ?? '\\')), .map((escaped) => '\\' + (escaped ?? '\\')),
noneOf(']') noneOf(']'),
) )
.many() .many()
.wrap(string('['), string(']')) .wrap(string('['), string(']'))
.map((result) => '[' + result.join('') + ']'), .map((result) => '[' + result.join('') + ']'),
noneOf(delimiter) noneOf(delimiter),
).many(), ).many(),
string(delimiter).fallback(undefined), string(delimiter).fallback(undefined),
(leadingBar, atoms, delim) => { (leadingBar, atoms, delim) => {
@ -267,7 +267,7 @@ export class Pattern {
closed: delim !== undefined, closed: delim !== undefined,
emptyBranch, emptyBranch,
}; };
} },
).map(({ patternString, caseOverride, inSelection, closed, emptyBranch }) => { ).map(({ patternString, caseOverride, inSelection, closed, emptyBranch }) => {
const ignoreCase = Pattern.getIgnoreCase(patternString, { const ignoreCase = Pattern.getIgnoreCase(patternString, {
caseOverride, caseOverride,
@ -279,14 +279,14 @@ export class Pattern {
Pattern.compileRegex(patternString, ignoreCase), Pattern.compileRegex(patternString, ignoreCase),
inSelection ?? false, inSelection ?? false,
closed, closed,
emptyBranch emptyBranch,
); );
}); });
} }
private static getIgnoreCase( private static getIgnoreCase(
patternString: string, patternString: string,
flags: { caseOverride?: boolean; ignoreSmartcase: boolean } flags: { caseOverride?: boolean; ignoreSmartcase: boolean },
): boolean { ): boolean {
if (flags.caseOverride !== undefined) { if (flags.caseOverride !== undefined) {
return flags.caseOverride; return flags.caseOverride;
@ -302,7 +302,7 @@ export class Pattern {
regex: RegExp, regex: RegExp,
inSelection: boolean, inSelection: boolean,
closed: boolean, closed: boolean,
emptyBranch: boolean emptyBranch: boolean,
) { ) {
this.patternString = patternString; this.patternString = patternString;
this.direction = direction; this.direction = direction;
@ -348,14 +348,14 @@ export class SearchOffset {
new SearchOffset({ new SearchOffset({
type, type,
delta: sign === '-' ? -num : num, delta: sign === '-' ? -num : num,
}) }),
), ),
seq(searchOffsetTypeParser, oneOf('+-')).map( seq(searchOffsetTypeParser, oneOf('+-')).map(
([type, sign]) => ([type, sign]) =>
new SearchOffset({ new SearchOffset({
type, type,
delta: sign === '-' ? -1 : 1, delta: sign === '-' ? -1 : 1,
}) }),
), ),
seq(searchOffsetTypeParser).map(([type]) => new SearchOffset({ type, delta: 0 })), seq(searchOffsetTypeParser).map(([type]) => new SearchOffset({ type, delta: 0 })),
string(';/') string(';/')
@ -377,7 +377,7 @@ export class SearchOffset {
pattern, pattern,
offset, offset,
}); });
}) }),
); );
public constructor(data: SearchOffsetData) { public constructor(data: SearchOffsetData) {

View File

@ -97,7 +97,7 @@ suite('bang (!) cmd_line', () => {
test('! can read from both stdout and stderr', async () => { test('! can read from both stdout and stderr', async () => {
await modeHandler.handleMultipleKeyEvents( await modeHandler.handleMultipleKeyEvents(
':.!echo "stdout" && >&2 echo "stderr"\n'.split('') ':.!echo "stdout" && >&2 echo "stderr"\n'.split(''),
); );
assertEqualLines(['stdout', 'stderr']); assertEqualLines(['stdout', 'stderr']);
}); });

View File

@ -29,11 +29,11 @@ suite('Breakpoints command', () => {
const breakpoint = vscode.debug.breakpoints[0] as vscode.SourceBreakpoint; const breakpoint = vscode.debug.breakpoints[0] as vscode.SourceBreakpoint;
assert.strictEqual( assert.strictEqual(
breakpoint.location.uri.fsPath, breakpoint.location.uri.fsPath,
modeHandler.vimState.editor.document.uri.fsPath modeHandler.vimState.editor.document.uri.fsPath,
); );
assert.strictEqual( assert.strictEqual(
breakpoint.location.range.start.line, breakpoint.location.range.start.line,
modeHandler.vimState.cursorStartPosition.line modeHandler.vimState.cursorStartPosition.line,
); );
}); });
@ -48,11 +48,11 @@ suite('Breakpoints command', () => {
test('test "here" is redundant', async () => { test('test "here" is redundant', async () => {
assert.deepStrictEqual( assert.deepStrictEqual(
exCommandParser.tryParse(':breaka here'), exCommandParser.tryParse(':breaka here'),
exCommandParser.tryParse(':breaka') exCommandParser.tryParse(':breaka'),
); );
assert.deepStrictEqual( assert.deepStrictEqual(
exCommandParser.tryParse(':breakd here'), exCommandParser.tryParse(':breakd here'),
exCommandParser.tryParse(':breakd') exCommandParser.tryParse(':breakd'),
); );
}); });
}); });

View File

@ -35,7 +35,7 @@ suite('cursor location', () => {
assert.strictEqual( assert.strictEqual(
statusBarAfterCursorMovement.trim(), statusBarAfterCursorMovement.trim(),
':tes|t', ':tes|t',
'Command Tab Completion Failed' 'Command Tab Completion Failed',
); );
}); });
@ -59,7 +59,7 @@ suite('cursor location', () => {
assert.strictEqual( assert.strictEqual(
statusBarAfterCursorMovement.trim(), statusBarAfterCursorMovement.trim(),
'/tes|t', '/tes|t',
'Command Tab Completion Failed' 'Command Tab Completion Failed',
); );
}); });
}); });

View File

@ -59,7 +59,7 @@ suite.skip(':only command', () => {
assert.strictEqual( assert.strictEqual(
vscode.window.visibleTextEditors.length, vscode.window.visibleTextEditors.length,
1, 1,
'Did not reduce to single editor' 'Did not reduce to single editor',
); );
assert.strictEqual(await isPanelVisible(), false, 'Panel is still visible'); assert.strictEqual(await isPanelVisible(), false, 'Panel is still visible');
}); });

View File

@ -28,7 +28,7 @@ suite('Smile command', () => {
assert.strictEqual( assert.strictEqual(
vscode.window.visibleTextEditors.length, vscode.window.visibleTextEditors.length,
1, 1,
':smile did not create a new untitled file' ':smile did not create a new untitled file',
); );
}); });

View File

@ -24,7 +24,7 @@ suite('Horizontal split', () => {
assert.strictEqual( assert.strictEqual(
vscode.window.visibleTextEditors.length, vscode.window.visibleTextEditors.length,
2, 2,
'Editor did not split in 1 sec' 'Editor did not split in 1 sec',
); );
}); });
} }

Some files were not shown because too many files have changed in this diff Show More