Skip to content

feat: improve handling of prepend #37

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

Merged
merged 6 commits into from
Jun 27, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
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
4 changes: 2 additions & 2 deletions language-configuration.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
],
"folding": {
"markers": {
"start": "// PREPEND -- DO NOT EDIT",
"end": "// END PREPEND"
"start": "// PREPEND",
"end": "// END PREPEND -- DO NOT EDIT PREPEND"
}
},
"wordPattern": "[_$a-zA-Z][_$a-zA-Z0-9]*",
Expand Down
14 changes: 6 additions & 8 deletions src/commands/showPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { FRONTEND_ELEMENT_ID } from "../constants";
import { client, SOURCE_ACADEMY_ICON_URI } from "../extension";
import _ from "lodash";
import { treeDataProvider } from "../treeview";
import { codeRemovePrepend, getNumPrependLines } from "../utils/editorUtils";

let panel: vscode.WebviewPanel | null = null;
// This needs to be a reference to active
Expand Down Expand Up @@ -55,13 +56,8 @@ async function handleMessage(
const info = context.globalState.get("info") ?? {};
if (activeEditor.uri) {
// TODO: Write our own wrapper to set nested keys easily, removing lodash
// @ts-ignore
_.set(info, `["${activeEditor.uri}"].chapter`, message.chapter ?? 1);
// TODO: message.prepend can be undefined in runtime, investigate
const nPrependLines =
message.prepend && message.prepend !== ""
? message.prepend.split("\n").length + 2 // account for start/end markers
: 0;
const nPrependLines = getNumPrependLines(message.prepend);
_.set(info, `["${activeEditor.uri}"].prepend`, nPrependLines);
context.globalState.update("info", info);
client.sendRequest("source/publishInfo", info);
Expand All @@ -82,8 +78,10 @@ async function handleMessage(
`EXTENSION: Editor ${editor.assessmentName}_${editor.questionId} is no longer active, skipping onChange`,
);
}
const message = Messages.Text(workspaceLocation, code);
console.log(`Sending message: ${JSON.stringify(message)}`);
const message = Messages.Text(
workspaceLocation,
codeRemovePrepend(code),
);
sendToFrontend(panel, message);
});
break;
Expand Down
99 changes: 48 additions & 51 deletions src/utils/editor.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// TODO: Move this file to src/features/editor/editor.ts
import * as vscode from "vscode";

import config from "../utils/config";
import Messages, { VscWorkspaceLocation } from "./messages";
import path from "path";
import { sendToFrontendWrapped } from "../commands/showPanel";
import { canonicaliseLocation } from "./misc";
import { codeAddPrepend, codeRemovePrepend } from "./editorUtils";

export class Editor {
editor?: vscode.TextEditor;
Expand Down Expand Up @@ -60,58 +62,53 @@ export class Editor {
const uri = vscode.Uri.file(filePath);
self.uri = uri.toString();

const contents =
prepend !== ""
? [
"// PREPEND -- DO NOT EDIT",
prepend,
"// END PREPEND",
initialCode,
].join("\n")
: initialCode;

await vscode.workspace.fs.readFile(vscode.Uri.file(filePath)).then(
(value) => {
if (value.toString() !== contents) {
self.log(
"EXTENSION: Conflict detected between local and remote, prompting user to choose one",
const contents = codeAddPrepend(initialCode, prepend);

await vscode.workspace.fs
.readFile(vscode.Uri.file(filePath))
.then((value) => value.toString())
.then(
(localCode) => {
if (localCode !== contents) {
self.log(
"EXTENSION: Conflict detected between local and remote, prompting user to choose one",
);
vscode.window
.showInformationMessage(
[
"The local file differs from the version on the Source Academy servers.",
"Discard the local file and use the one on the server?",
].join(" "),
{ modal: true },
"Yes",
)
.then(async (answer) => {
// By default the code displayed is the local one
if (answer === "Yes") {
self.log("EXTENSION: Saving program from server to file");
await vscode.workspace.fs.writeFile(
uri,
new TextEncoder().encode(contents),
);
} else if (answer === undefined) {
// Modal cancelled
const message = Messages.Text(
self.workspaceLocation,
codeRemovePrepend(localCode),
);
sendToFrontendWrapped(message);
}
});
}
},
async () => {
self.log(`Opening file failed, creating at ${filePath}`);
await vscode.workspace.fs.writeFile(
uri,
new TextEncoder().encode(contents),
);
vscode.window
.showInformationMessage(
[
"The local file differs from the version on the Source Academy servers.",
"Discard the local file and use the one on the server?",
].join(" "),
{ modal: true },
"Yes",
)
.then(async (answer) => {
// By default the code displayed is the local one
if (answer === "Yes") {
self.log("EXTENSION: Saving program from server to file");
await vscode.workspace.fs.writeFile(
uri,
new TextEncoder().encode(contents),
);
} else if (answer === undefined) {
// Modal cancelled
const message = Messages.Text(
self.workspaceLocation,
value.toString(),
);
sendToFrontendWrapped(message);
}
});
}
},
async () => {
self.log(`Opening file failed, creating at ${filePath}`);
await vscode.workspace.fs.writeFile(
uri,
new TextEncoder().encode(contents),
);
},
);
},
);

const editor = await vscode.window.showTextDocument(uri, {
preview: false,
Expand Down
44 changes: 44 additions & 0 deletions src/utils/editorUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// TODO: Move this file to src/features/editor/utils.ts

// ================================================================================
// Prepend
// ================================================================================

// If this is edited, also change folding.markers.{start,end} in language-configuration.json
const PREPEND_MARKER_START = "// PREPEND";
const PREPEND_MARKER_END = "// END PREPEND -- DO NOT EDIT PREPEND";

export function codeAddPrepend(code: string, prepend: string) {
if (prepend === "") {
return code;
}
return [
PREPEND_MARKER_START,
prepend,
PREPEND_MARKER_END,
"", // Visual separation between prepend and code
code,
].join("\n");
}

export function getNumPrependLines(prepend: string) {
if (prepend === "") {
return 0;
}
return prepend.split("\n").length + 3; // account for start/end markers
}

export function codeRemovePrepend(code: string) {
const lines = code.split("\n");
const start = lines.indexOf(PREPEND_MARKER_START);
const end = lines.indexOf(PREPEND_MARKER_END);

if (start === -1 || end === -1 || end < start) {
return code;
}

// If line spacing between prepend and code accidentally removed, do not delete code!
const skip = end + (lines[end + 1] === "" ? 1 : 0);

return lines.slice(skip + 1).join("\n");
}