Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tab completion on vim command line #3639

Merged
merged 32 commits into from
May 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
7d3a164
added tab support for commands in command mode
keith-ferney Feb 21, 2019
d16fcc0
Merge branch 'master' of https://github.com/VSCodeVim/Vim
keith-guru Mar 1, 2019
21a5790
missed a file in merge
keith-guru Mar 1, 2019
0f75563
add cursor to search mode and update tab completion
keith-guru Mar 1, 2019
cf6a8fc
file completion on tab support #745
keith-guru Mar 8, 2019
143f909
Merge branch 'master' of https://github.com/VSCodeVim/Vim
keith-guru Mar 13, 2019
0fd486f
file completion
keith-guru Mar 13, 2019
54883b0
fix missed merge conflicts
keith-guru Mar 22, 2019
ddc54a0
Merge branch 'master' of https://github.com/VSCodeVim/Vim
keith-guru Mar 22, 2019
cf24961
add path symbols to tab autocomplete '~/', './', '../', '/'
keith-guru Mar 22, 2019
02d987d
Merge branch 'master' of https://github.com/VSCodeVim/Vim
keith-guru Mar 29, 2019
e6e1a8b
replace var with let/const
keith-guru Apr 1, 2019
39fab9b
Merge branch 'master' of https://github.com/VSCodeVim/Vim
keith-guru Apr 2, 2019
819b9b4
tab completion optimizations and refactors
keith-guru Apr 3, 2019
7c184c3
Merge branch 'master' of https://github.com/VSCodeVim/Vim
keith-guru Apr 3, 2019
e44fb7f
fix esc in search mode conflict
keith-guru Apr 3, 2019
cfe8159
Merge branch 'master' into master
keith-guru Apr 16, 2019
233cf3e
Merge branch 'master' of https://github.com/VSCodeVim/Vim
keith-guru Apr 26, 2019
959bdd5
remove tabCompletion.ts because it had the wrong name format
keith-guru Apr 26, 2019
dbe0fa1
add command line tab completion tests
keith-guru Apr 26, 2019
26bc4f1
Merge branch 'master' of github.com:keith-ferney/Vim
keith-guru Apr 26, 2019
6da8f80
tab completion test add space after comma's
keith-guru Apr 26, 2019
2b69c74
tab completion test equal instead of not equal
keith-guru Apr 26, 2019
0365e2d
remove console log
keith-guru Apr 26, 2019
ab8c120
added cursor location test and moved GetTrimmed from statusBar to act…
keith-guru May 2, 2019
542f11e
moved absolute path calculation to path util and created more verbose…
keith-guru May 3, 2019
a6a679c
remove console.log from cursorLoaction.test.ts
keith-guru May 3, 2019
763b81f
Merge branch 'master' of https://github.com/VSCodeVim/Vim
keith-guru May 6, 2019
764ed45
missed a merge conflict
keith-guru May 6, 2019
0a8103d
rename AbsolutePathFromRelativePath to GetAbsolutePath, update the co…
keith-guru May 6, 2019
a500e4d
Merge branch 'master' of https://github.com/VSCodeVim/Vim
keith-guru May 9, 2019
435df91
revert changes to package-lock.json
keith-guru May 9, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
"type": "gulp",
"task": "default",
"problemMatcher": "$tsc-watch"
},
{
"type": "gulp",
"task": "build",
"problemMatcher": []
}
]
}
157 changes: 144 additions & 13 deletions src/actions/commands/actions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';

import { RecordedState } from '../../state/recordedState';
import { ReplaceState } from '../../state/replaceState';
Expand All @@ -24,6 +27,9 @@ import { BaseAction } from './../base';
import { commandLine } from './../../cmd_line/commandLine';
import * as operator from './../operator';
import { Jump } from '../../jumps/jump';
import { commandParsers } from '../../cmd_line/subparser';
import { StatusBar } from '../../statusBar';
import { GetAbsolutePath } from '../../util/path';
import {
ReportLinesChanged,
ReportClear,
Expand Down Expand Up @@ -540,6 +546,13 @@ class CommandEsc extends BaseCommand {
vimState.cursors = vimState.cursors.map(x => x.withNewStop(x.stop.getLeft()));
}

if (vimState.currentMode === ModeName.SearchInProgressMode) {
vimState.statusBarCursorCharacterPos = 0;
if (vimState.globalState.searchState) {
vimState.cursorStopPosition = vimState.globalState.searchState.searchCursorStartPosition;
}
}

if (vimState.currentMode === ModeName.Normal && vimState.isMultiCursor) {
vimState.isMultiCursor = false;
}
Expand Down Expand Up @@ -889,7 +902,14 @@ class CommandInsertInSearchMode extends BaseCommand {
if (searchState.searchString.length === 0) {
return new CommandEscInSearchMode().exec(position, vimState);
}
searchState.searchString = searchState.searchString.slice(0, -1);
if (vimState.statusBarCursorCharacterPos === 0) {
return vimState;
}

searchState.searchString =
searchState.searchString.slice(0, vimState.statusBarCursorCharacterPos - 1) +
searchState.searchString.slice(vimState.statusBarCursorCharacterPos);
vimState.statusBarCursorCharacterPos = Math.max(vimState.statusBarCursorCharacterPos - 1, 0);
} else if (key === '\n') {
await vimState.setCurrentMode(vimState.globalState.searchState!.previousMode);

Expand All @@ -906,6 +926,7 @@ class CommandInsertInSearchMode extends BaseCommand {
const nextMatch = searchState.getNextSearchMatchPosition(vimState.cursorStopPosition);
vimState.cursorStopPosition = nextMatch.pos;

vimState.statusBarCursorCharacterPos = 0;
Register.putByKey(searchState.searchString, '/', undefined, true);

ReportSearch(nextMatch.index, searchState.matchRanges.length, vimState);
Expand All @@ -920,6 +941,7 @@ class CommandInsertInSearchMode extends BaseCommand {
if (prevSearchList[vimState.globalState.searchStateIndex] !== undefined) {
searchState.searchString =
prevSearchList[vimState.globalState.searchStateIndex].searchString;
vimState.statusBarCursorCharacterPos = searchState.searchString.length;
}
} else if (key === '<down>') {
vimState.globalState.searchStateIndex += 1;
Expand All @@ -938,8 +960,12 @@ class CommandInsertInSearchMode extends BaseCommand {
searchState.searchString =
prevSearchList[vimState.globalState.searchStateIndex].searchString;
}
vimState.statusBarCursorCharacterPos = searchState.searchString.length;
} else {
searchState.searchString += this.keysPressed[0];
let modifiedString = searchState.searchString.split('');
modifiedString.splice(vimState.statusBarCursorCharacterPos, 0, key);
searchState.searchString = modifiedString.join('');
vimState.statusBarCursorCharacterPos += key.length;
}

return vimState;
Expand All @@ -965,6 +991,7 @@ class CommandEscInSearchMode extends BaseCommand {
: undefined;

await vimState.setCurrentMode(searchState.previousMode);
vimState.statusBarCursorCharacterPos = 0;

return vimState;
}
Expand Down Expand Up @@ -1852,10 +1879,120 @@ class CommandShowCommandLine extends BaseCommand {
}
}

@RegisterAction
class CommandNavigateInCommandlineOrSearchMode extends BaseCommand {
modes = [ModeName.CommandlineInProgress, ModeName.SearchInProgressMode];
keys = [['<left>'], ['<right>']];
runsOnceForEveryCursor() {
return this.keysPressed[0] === '\n';
}

private getTrimmedStatusBarText() {
// first regex removes the : / and | from the string
// second regex removes a single space from the end of the string
let trimmedStatusBarText = StatusBar.Get()
.replace(/^(?:\/|\:)(.*)(?:\|)(.*)/, '$1$2')
.replace(/(.*) $/, '$1');
return trimmedStatusBarText;
}

public async exec(position: Position, vimState: VimState): Promise<VimState> {
const key = this.keysPressed[0];
const searchState = vimState.globalState.searchState!;
let statusBarText = this.getTrimmedStatusBarText();
if (key === '<right>') {
vimState.statusBarCursorCharacterPos = Math.min(
vimState.statusBarCursorCharacterPos + 1,
statusBarText.length
);
} else if (key === '<left>') {
vimState.statusBarCursorCharacterPos = Math.max(vimState.statusBarCursorCharacterPos - 1, 0);
}
return vimState;
}
}
@RegisterAction
class CommandTabInCommandline extends BaseCommand {
modes = [ModeName.CommandlineInProgress];
keys = ['<tab>'];
runsOnceForEveryCursor() {
return this.keysPressed[0] === '\n';
}

private autoComplete(completionItems: any, vimState: VimState) {
if (commandLine.lastKeyPressed !== '<tab>') {
if (/ /g.test(vimState.currentCommandlineText)) {
// The regex here will match any text after the space or any text after the last / if it is present
const search = <RegExpExecArray>(
/(?:.* .*\/|.* )(.*)/g.exec(vimState.currentCommandlineText)
);
commandLine.autoCompleteText = search[1];
commandLine.autoCompleteIndex = 0;
} else {
commandLine.autoCompleteText = vimState.currentCommandlineText;
commandLine.autoCompleteIndex = 0;
}
}

completionItems = completionItems.filter(completionItem =>
completionItem.startsWith(commandLine.autoCompleteText)
);

if (
jpoon marked this conversation as resolved.
Show resolved Hide resolved
commandLine.lastKeyPressed === '<tab>' &&
commandLine.autoCompleteIndex < completionItems.length
) {
commandLine.autoCompleteIndex += 1;
}
if (commandLine.autoCompleteIndex >= completionItems.length) {
jpoon marked this conversation as resolved.
Show resolved Hide resolved
jpoon marked this conversation as resolved.
Show resolved Hide resolved
commandLine.autoCompleteIndex = 0;
}

let result = completionItems[commandLine.autoCompleteIndex];
if (result === vimState.currentCommandlineText) {
result = completionItems[++commandLine.autoCompleteIndex % completionItems.length];
}

if (result !== undefined && !/ /g.test(vimState.currentCommandlineText)) {
vimState.currentCommandlineText = result;
vimState.statusBarCursorCharacterPos = result.length;
} else if (result !== undefined) {
const searchArray = <RegExpExecArray>/(.* .*\/|.* )/g.exec(vimState.currentCommandlineText);
vimState.currentCommandlineText = searchArray[0] + result;
vimState.statusBarCursorCharacterPos = vimState.currentCommandlineText.length;
}
return vimState;
}

public async exec(position: Position, vimState: VimState): Promise<VimState> {
const key = this.keysPressed[0];

if (!/ /g.test(vimState.currentCommandlineText)) {
// Command completion
const commands = Object.keys(commandParsers).sort();
vimState = this.autoComplete(commands, vimState);
} else {
// File Completion
let completeFiles: fs.Dirent[];
const search = <RegExpExecArray>/.* (.*\/)/g.exec(vimState.currentCommandlineText);
let searchString = search !== null ? search[1] : '';

let fullPath = GetAbsolutePath(searchString);

completeFiles = fs.readdirSync(fullPath, { withFileTypes: true });

vimState = this.autoComplete(completeFiles, vimState);
}

commandLine.lastKeyPressed = key;
return vimState;
}
}

@RegisterAction
class CommandInsertInCommandline extends BaseCommand {
modes = [ModeName.CommandlineInProgress];
keys = [['<character>'], ['<up>'], ['<down>'], ['<left>'], ['<right>'], ['<C-h>']];
keys = [['<character>'], ['<up>'], ['<down>'], ['<C-h>']];
runsOnceForEveryCursor() {
return this.keysPressed[0] === '\n';
}
Expand Down Expand Up @@ -1911,20 +2048,14 @@ class CommandInsertInCommandline extends BaseCommand {
}

vimState.statusBarCursorCharacterPos = vimState.currentCommandlineText.length;
} else if (key === '<right>') {
vimState.statusBarCursorCharacterPos = Math.min(
vimState.statusBarCursorCharacterPos + 1,
vimState.currentCommandlineText.length
);
} else if (key === '<left>') {
vimState.statusBarCursorCharacterPos = Math.max(vimState.statusBarCursorCharacterPos - 1, 0);
} else {
} else if (key !== '<tab>') {
let modifiedString = vimState.currentCommandlineText.split('');
modifiedString.splice(vimState.statusBarCursorCharacterPos, 0, this.keysPressed[0]);
modifiedString.splice(vimState.statusBarCursorCharacterPos, 0, key);
vimState.currentCommandlineText = modifiedString.join('');
vimState.statusBarCursorCharacterPos += 1;
vimState.statusBarCursorCharacterPos += key.length;
}

commandLine.lastKeyPressed = key;
return vimState;
}
}
Expand Down
17 changes: 17 additions & 0 deletions src/cmd_line/commandLine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,23 @@ class CommandLine {
*/
private _commandLineHistoryIndex: number = 0;

/**
* for checking the last pressed key in command mode
*/
public lastKeyPressed = '';

/**
* for checking the last pressed key in command mode
*
*/
public autoCompleteIndex = 0;

/**
* for checking the last pressed key in command mode
*
*/
public autoCompleteText = '';

public get commandlineHistoryIndex(): number {
return this._commandLineHistoryIndex;
}
Expand Down
6 changes: 5 additions & 1 deletion src/mode/modes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ export class SearchInProgressMode extends Mode {
}
const leadingChar =
vimState.globalState.searchState.searchDirection === SearchDirection.Forward ? '/' : '?';
return `${leadingChar}${vimState.globalState.searchState!.searchString}`;

let stringWithCursor = vimState.globalState.searchState!.searchString.split('');
stringWithCursor.splice(vimState.statusBarCursorCharacterPos, 0, '|');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As per your comment in the Get() method, isn't the pipe removed?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah it is mainly doing that for the search I should probably move the trimming happening in the Get() method to a different method eg GetTrimmed() since it is not just getting the status bar text.


return `${leadingChar}${stringWithCursor.join('')}`;
}

getStatusBarCommandText(vimState: VimState): string {
Expand Down
5 changes: 5 additions & 0 deletions src/statusBar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ class StatusBarImpl implements vscode.Disposable {
this._statusBarItem.dispose();
}

public Get() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:( why on earth did we do pascal case for this file? what idiot did that (fyi. it was me).

let text = this._statusBarItem.text;
return text;
}

private UpdateText(text: string) {
this._statusBarItem.text = text || '';
}
Expand Down
28 changes: 28 additions & 0 deletions src/util/path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as vscode from 'vscode';
import * as path from 'path';
import untildify = require('untildify');
import { parseTabOnlyCommandArgs } from '../cmd_line/subparsers/tab';

/**
* Given relative path, calculate absolute path.
*/
export function GetAbsolutePath(partialPath: string): string {
const editorFilePath = vscode.window.activeTextEditor!.document.uri.fsPath;
let basePath: string;

if (partialPath.startsWith('/')) {
basePath = '/';
} else if (partialPath.startsWith('~/')) {
basePath = <string>untildify(partialPath);
partialPath = '';
} else if (partialPath.startsWith('./')) {
basePath = path.dirname(editorFilePath);
partialPath = partialPath.replace('./', '');
} else if (partialPath.startsWith('../')) {
basePath = path.dirname(editorFilePath) + '/';
} else {
basePath = path.dirname(editorFilePath);
}

return basePath + partialPath;
}
59 changes: 59 additions & 0 deletions test/cmd_line/cursorLocation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import * as vscode from 'vscode';
import * as assert from 'assert';

import { getAndUpdateModeHandler } from '../../extension';
import { commandLine } from '../../src/cmd_line/commandLine';
import { ModeHandler } from '../../src/mode/modeHandler';
import { createRandomFile, setupWorkspace, cleanUpWorkspace } from '../testUtils';
import { StatusBar } from '../../src/statusBar';

suite('cursor location', () => {
let modeHandler: ModeHandler;

suiteSetup(async () => {
await setupWorkspace();
modeHandler = await getAndUpdateModeHandler();
});

suiteTeardown(cleanUpWorkspace);

test('cursor location in command line', async () => {
await modeHandler.handleMultipleKeyEvents([
':',
't',
'e',
's',
't',
'<right>',
'<right>',
'<right>',
'<left>',
]);

const statusBarAfterCursorMovement = StatusBar.Get();
await modeHandler.handleKeyEvent('<Esc>');

const statusBarAfterEsc = StatusBar.Get();
assert.equal(statusBarAfterCursorMovement.trim(), ':tes|t', 'Command Tab Completion Failed');
});

test('cursor location in search', async () => {
await modeHandler.handleMultipleKeyEvents([
'/',
't',
'e',
's',
't',
'<right>',
'<right>',
'<right>',
'<left>',
]);

const statusBarAfterCursorMovement = StatusBar.Get();

await modeHandler.handleKeyEvent('<Esc>');
const statusBarAfterEsc = StatusBar.Get();
assert.equal(statusBarAfterCursorMovement.trim(), '/tes|t', 'Command Tab Completion Failed');
});
});
Loading