Skip to content

Commit

Permalink
Enhance context gathering in Jupyter notebooks by including text from…
Browse files Browse the repository at this point in the history
… all cells

Signed-off-by: Tal Wertheimer <[email protected]>
  • Loading branch information
Tal Wertheimer authored and Tal Wertheimer committed Dec 13, 2023
1 parent 16c2111 commit ed1e8f7
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/runCompletion.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CancellationToken, Position, Range, TextDocument } from "vscode";
import * as vscode from "vscode";
import {
autocomplete,
AutocompleteParams,
Expand All @@ -14,6 +15,29 @@ import {
import languages from "./globals/languages";
import { getSDKPath } from "./languages";

function calculateContextForJupyterNotebook(
notebookEditor: vscode.window.NotebookEditor,
documentUri: vscode.Uri
): { before: string; after: string } {
const cells = notebookEditor.notebook.getCells();

const index = cells.findIndex(
(cell) => cell.document.uri.toString() === documentUri.toString()
);
const before = cells
.slice(0, index)
.map((cell) => cell.document.getText())
.join("\n");
const after = cells
.slice(index + 1)
.map((cell) => cell.document.getText())
.join("\n");
return {
before,
after,
};
}

export default async function runCompletion({
document,
position,
Expand All @@ -36,6 +60,7 @@ export default async function runCompletion({
const afterEndOffset = offset + CHAR_LIMIT;
const beforeStart = document.positionAt(beforeStartOffset);
const afterEnd = document.positionAt(afterEndOffset);

const requestData = {
filename: getFileNameWithExtension(document),
before:
Expand All @@ -51,6 +76,16 @@ export default async function runCompletion({
indentation_size: getTabSize(),
sdk_path: getSDKPath(document.languageId),
};
const notebookEditor = vscode.window.activeNotebookEditor;

if (notebookEditor) {
const { before, after } = calculateContextForJupyterNotebook(
notebookEditor,
document.uri
);
requestData.before = [before, requestData.before].join("\n");
requestData.after = [requestData.after, after].join("\n");
}

const isEmptyLine = document.lineAt(position.line).text.trim().length === 0;

Expand Down
10 changes: 10 additions & 0 deletions src/vscode.proposed.inlineCompletions.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,16 @@ declare module "vscode" {
* Be aware that this API will not ever be finalized.
*/
export namespace window {
export const activeNotebookEditor: NotebookEditor | undefined;

class NotebookEditor {
notebook: {
getCells: () => {
document: TextDocument;
}[];
};
}

export function getInlineCompletionItemController<
T extends InlineCompletionItem
>(provider: InlineCompletionItemProvider<T>): InlineCompletionController<T>;
Expand Down

0 comments on commit ed1e8f7

Please sign in to comment.