preview_lines #4

Merged
Fabel merged 4 commits from preview_lines into develop 2024-10-09 18:00:32 +00:00
2 changed files with 266 additions and 214 deletions

View File

@ -4,7 +4,7 @@
"displayName": "Fabelous Autocoder", "displayName": "Fabelous Autocoder",
"description": "A simple to use Ollama autocompletion Plugin", "description": "A simple to use Ollama autocompletion Plugin",
"icon": "icon.png", "icon": "icon.png",
"publisher": "fabel", "publisher": "Falko Habel",
"license": "CC BY-ND 4.0", "license": "CC BY-ND 4.0",
"bugs": { "bugs": {
"url": "https://gitea.fabelous.app/fabel/Fabelous-Autocoder/issues" "url": "https://gitea.fabelous.app/fabel/Fabelous-Autocoder/issues"
@ -90,7 +90,6 @@
"type": "boolean", "type": "boolean",
"default": true, "default": true,
"description": "Ollama continues autocompletion after what is previewed inline. Disabling disables that feature as some may find it irritating. Multiline completion is still accessible through the shortcut even after disabling." "description": "Ollama continues autocompletion after what is previewed inline. Disabling disables that feature as some may find it irritating. Multiline completion is still accessible through the shortcut even after disabling."
}, },
"fabelous-autocoder.temperature": { "fabelous-autocoder.temperature": {
"type": "number", "type": "number",
@ -104,15 +103,38 @@
}, },
"fabelous-autocoder.top p": { "fabelous-autocoder.top p": {
"type": "number", "type": "number",
"default": 1,
"description": "Top p sampling for the model." "description": "Top p sampling for the model."
},
"fabelous-autocoder.enableLineByLineAcceptance": {
"type": "boolean",
"default": false,
"description": "Enable line-by-line acceptance of the generated code."
} }
} }
}, },
"keybindings": [
{
"command": "fabelous-autocoder.handleTab",
"key": "tab",
"when": "editorTextFocus && !editorTabMovesFocus"
},
{
"command": "fabelous-autocoder.handleBackspace",
"key": "backspace",
"when": "editorTextFocus"
}
],
"commands": [ "commands": [
{ {
"command": "fabelous-autocoder.autocomplete", "command": "fabelous-autocoder.autocomplete",
"title": "Fabelous Autocompletion" "title": "Fabelous Autocompletion"
}] },
{
"command": "fabelous-autocoder.handleTab",
"title": "Handle Tab"
}
]
}, },
"scripts": { "scripts": {
"vscode:prepublish": "npm run compile", "vscode:prepublish": "npm run compile",

View File

@ -91,6 +91,7 @@ class CompletionManager {
private document: vscode.TextDocument; private document: vscode.TextDocument;
private startPosition: vscode.Position; private startPosition: vscode.Position;
private completionText: string; private completionText: string;
private insertedLineCount: number = 0; // Track the number of inserted lines
constructor(textEditor: vscode.TextEditor, startPosition: vscode.Position, completionText: string) { constructor(textEditor: vscode.TextEditor, startPosition: vscode.Position, completionText: string) {
this.textEditor = textEditor; this.textEditor = textEditor;
@ -100,24 +101,36 @@ class CompletionManager {
} }
public async showPreview() { public async showPreview() {
this.completionText = '\n' + this.completionText; if (!previewDecorationType) {
const completionLines = this.completionText.split('\n'); createPreviewDecorationType();
}
const emptyLine = ''; // Empty line for spacing const completionLines = this.completionText.split('\n').length;
const previewLines = [emptyLine, ...completionLines, emptyLine];
const previewRanges: vscode.DecorationOptions[] = previewLines.map((line, index) => { // Adjust the start position to line after the original start position
const actualLineNumber = this.startPosition.line + index; const adjustedStartPosition = this.startPosition.translate(0, 0);
const totalLines = this.textEditor.document.lineCount;
const lineNumber = Math.min(totalLines - 1, actualLineNumber); // Step 1: Insert blank lines to make space for the preview
const edit = new vscode.WorkspaceEdit();
const linePadding = '\n'.repeat(completionLines + 1); // Include extra line break for visual separation
edit.insert(this.document.uri, adjustedStartPosition, linePadding);
await vscode.workspace.applyEdit(edit);
this.insertedLineCount = completionLines + 1;
// Step 2: Apply decorations
const previewRanges: vscode.DecorationOptions[] = this.completionText.split('\n').map((line, index) => {
const lineNumber = adjustedStartPosition.line + index + 1; // Start preview one line later
return { return {
range: new vscode.Range( range: new vscode.Range(
new vscode.Position(lineNumber, 0), new vscode.Position(lineNumber, 0),
new vscode.Position(lineNumber, Number.MAX_VALUE) new vscode.Position(lineNumber, 0)
), ),
renderOptions: { renderOptions: {
after: { after: {
contentText: line.length > 0 ? ` ${line}` : '', contentText: line,
color: '#888888',
fontStyle: 'italic',
}, },
}, },
}; };
@ -126,27 +139,91 @@ class CompletionManager {
this.textEditor.setDecorations(previewDecorationType, previewRanges); this.textEditor.setDecorations(previewDecorationType, previewRanges);
} }
public async acceptCompletion() { public async acceptCompletion() {
const edit = new vscode.WorkspaceEdit(); const edit = new vscode.WorkspaceEdit();
const startLine = Math.max(0, this.startPosition.line - 1); const completionLines = this.completionText.split('\n');
const range = new vscode.Range( const numberOfLines = completionLines.length;
new vscode.Position(startLine, 0),
this.startPosition.translate(0, Number.MAX_VALUE) // Ensure the start position is never negative
const safeStartPosition = new vscode.Position(Math.max(0, this.startPosition.line - 1), 0);
// Prepare the range to replace
const rangeToReplace = new vscode.Range(
safeStartPosition,
this.startPosition.translate(numberOfLines, 0)
); );
edit.replace(this.document.uri, range, this.completionText);
// Construct the content to insert
const contentToInsert = (safeStartPosition.line === 0 ? '' : '\n') + this.completionText + '\n';
edit.replace(this.document.uri, rangeToReplace, contentToInsert);
await vscode.workspace.applyEdit(edit); await vscode.workspace.applyEdit(edit);
// Clear the preview decorations
this.clearPreview(); this.clearPreview();
// Set activeCompletionManager to null
activeCompletionManager = null;
// Calculate the new cursor position from the inserted content
const lastCompletionLine = completionLines[completionLines.length - 1];
const newPosition = new vscode.Position(
this.startPosition.line + numberOfLines - 1,
lastCompletionLine.length
);
// Set the new cursor position
this.textEditor.selection = new vscode.Selection(newPosition, newPosition);
} }
public clearPreview() { public clearPreview() {
this.textEditor.setDecorations(previewDecorationType, []); this.textEditor.setDecorations(previewDecorationType, []); // Remove all preview decorations
} }
public declineCompletion() { public async declineCompletion() {
this.clearPreview(); this.clearPreview(); // Clear the preview decorations
try {
const document = this.textEditor.document;
const currentPosition = this.textEditor.selection.active;
// Calculate the range of lines to remove
const startLine = this.startPosition.line + 1;
const endLine = currentPosition.line;
if (endLine > startLine) {
const workspaceEdit = new vscode.WorkspaceEdit();
// Create a range from start of startLine to end of endLine
const range = new vscode.Range(
new vscode.Position(startLine, 0),
new vscode.Position(endLine, document.lineAt(endLine).text.length)
);
// Delete the range
workspaceEdit.delete(document.uri, range);
// Apply the edit
await vscode.workspace.applyEdit(workspaceEdit);
// Move the cursor back to the original position
this.textEditor.selection = new vscode.Selection(this.startPosition, this.startPosition);
console.log(`Lines ${startLine + 1} to ${endLine + 1} removed successfully`);
activeCompletionManager = null;
} else {
console.log('No lines to remove');
}
} catch (error) {
console.error('Error declining completion:', error);
vscode.window.showErrorMessage(`Error removing lines: ${error}`);
}
} }
} }
async function autocompleteCommand(textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, ...args: any[]) { async function autocompleteCommand(textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, ...args: any[]) {
const cancellationTokenSource = new vscode.CancellationTokenSource(); const cancellationTokenSource = new vscode.CancellationTokenSource();
const cancellationToken = cancellationTokenSource.token; const cancellationToken = cancellationTokenSource.token;
@ -173,49 +250,6 @@ async function autocompleteCommand(textEditor: vscode.TextEditor, edit: vscode.T
await completionManager.showPreview(); await completionManager.showPreview();
activeCompletionManager = completionManager; activeCompletionManager = completionManager;
let isDisposed = false;
const dispose = () => {
if (!isDisposed) {
console.log('Disposing listeners');
disposable.dispose();
typeDisposable.dispose();
activeCompletionManager = null;
isDisposed = true;
}
};
const disposable = vscode.Disposable.from(
vscode.window.onDidChangeTextEditorSelection(async (event) => {
if (event.textEditor !== textEditor) return;
if (event.kind === vscode.TextEditorSelectionChangeKind.Keyboard) {
console.log('Accepting completion');
await completionManager.acceptCompletion();
dispose();
}
}),
vscode.window.onDidChangeActiveTextEditor(() => {
console.log('Active editor changed, clearing preview');
completionManager.clearPreview();
dispose();
}),
vscode.workspace.onDidChangeTextDocument((event) => {
if (event.document === document) {
console.log('Document changed, clearing preview');
completionManager.clearPreview();
dispose();
}
})
);
const typeDisposable = vscode.commands.registerCommand('type', async (args) => {
if (args.text === '\b') { // Backspace key
console.log('Declining completion');
completionManager.declineCompletion();
dispose();
}
});
} catch (err: any) { } catch (err: any) {
console.error('Error in autocompleteCommand:', err); console.error('Error in autocompleteCommand:', err);
@ -225,24 +259,19 @@ async function autocompleteCommand(textEditor: vscode.TextEditor, edit: vscode.T
} }
} }
async function acceptCompletion() { async function handleTab() {
if (activeCompletionManager) { if (activeCompletionManager) {
await activeCompletionManager.acceptCompletion(); await activeCompletionManager.acceptCompletion();
const editor = vscode.window.activeTextEditor; } else {
if (editor) { await vscode.commands.executeCommand('tab');
const lastLine = editor.document.lineAt(editor.document.lineCount - 1);
const newPosition = new vscode.Position(lastLine.lineNumber, lastLine.text.length);
editor.selection = new vscode.Selection(newPosition, newPosition);
}
activeCompletionManager = null;
} }
} }
async function handleTab() { async function handleBackspace() {
if (activeCompletionManager) { if (activeCompletionManager) {
await acceptCompletion(); await activeCompletionManager.declineCompletion();
} else { } else {
await vscode.commands.executeCommand('tab'); await vscode.commands.executeCommand('deleteLeft');
} }
} }
@ -289,10 +318,11 @@ export function activate(context: vscode.ExtensionContext) {
vscode.workspace.onDidChangeConfiguration(updateConfig), vscode.workspace.onDidChangeConfiguration(updateConfig),
vscode.languages.registerCompletionItemProvider('*', { provideCompletionItems }, ...config.completionKeys), vscode.languages.registerCompletionItemProvider('*', { provideCompletionItems }, ...config.completionKeys),
vscode.commands.registerTextEditorCommand('fabelous-autocoder.autocomplete', autocompleteCommand), vscode.commands.registerTextEditorCommand('fabelous-autocoder.autocomplete', autocompleteCommand),
vscode.commands.registerCommand('fabelous-autocoder.acceptCompletion', acceptCompletion), vscode.commands.registerCommand('fabelous-autocoder.handleTab', handleTab),
vscode.commands.registerCommand('fabelous-autocoder.handleTab', handleTab) vscode.commands.registerCommand('fabelous-autocoder.handleBackspace', handleBackspace) // Add this line
); );
} }
export function deactivate() {} export function deactivate() {}