Add vim keys to the solve page's editor
Test and publish the site / test (push) Successful in 51s
Test and publish the site / publish (push) Successful in 1m16s

A Vim checkbox in the toolbar turns on @replit/codemirror-vim, off by
default and remembered in this browser like the split. A status line
under the editor shows the mode and the command being typed, and :w
saves as Save does. Run, Submit and Save keep their Ctrl keys in every
mode, since the page's keymap is at the highest precedence.

The vim extension sits in a Compartment, so turning it on or off keeps
the text and its history; the states kept for the other languages are
brought up to date when they are swapped back in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-20 14:00:29 +01:00
co-authored by Claude Opus 5.5
parent 20d2e05798
commit 2ea9980d58
5 changed files with 93 additions and 1 deletions
+1
View File
@@ -203,6 +203,7 @@ The "Review my explanation" panel (admin only) takes a recording of the admin ex
- **The runner is its own service.** The site holds the Claude, Gitea and S3 secrets and shares `app-network` with the database, so it never runs code. `cmd/usacorunner` does, in a container with no environment, on an `internal` network that only the site joins, read-only apart from an exec-able `/tmp` tmpfs, with memory, CPU and pids limits, all capabilities dropped and tini as PID 1 to reap orphans. The site posts to it (`runner.Client`, `RUNNER_URL`); the browser never sees it. - **The runner is its own service.** The site holds the Claude, Gitea and S3 secrets and shares `app-network` with the database, so it never runs code. `cmd/usacorunner` does, in a container with no environment, on an `internal` network that only the site joins, read-only apart from an exec-able `/tmp` tmpfs, with memory, CPU and pids limits, all capabilities dropped and tini as PID 1 to reap orphans. The site posts to it (`runner.Client`, `RUNNER_URL`); the browser never sees it.
- **Runs copy the CLI.** The same g++ flags as `lib/common.sh` (`-DLOCAL`, with the repo root's `debugging.h` and `leetcode.h`, and a LeetCode problem's `driver.h`, sent along), the program runs in a directory holding `<io>.in` with that file also on stdin, `<io>.out` is its output if it wrote one, and outputs compare as `usaco test` does, ignoring trailing whitespace and trailing blank lines. Unlike the CLI there are limits: CPU time (2 s by default; TLE), 512 MB of address space, 64 MB files, a wall clock, and 60 s for a whole request, which keeps it synchronous under nginx's 120 s. - **Runs copy the CLI.** The same g++ flags as `lib/common.sh` (`-DLOCAL`, with the repo root's `debugging.h` and `leetcode.h`, and a LeetCode problem's `driver.h`, sent along), the program runs in a directory holding `<io>.in` with that file also on stdin, `<io>.out` is its output if it wrote one, and outputs compare as `usaco test` does, ignoring trailing whitespace and trailing blank lines. Unlike the CLI there are limits: CPU time (2 s by default; TLE), 512 MB of address space, 64 MB files, a wall clock, and 60 s for a whole request, which keeps it synchronous under nginx's 120 s.
- **Autocomplete** is in the browser (`web/src/completions.js`), since `@codemirror/lang-cpp` has none. C++ completes keywords, the STL, every name in the file (the template's macros show what they expand to, typedefs what they alias), members after `.` and `->`, and snippets (`for`, `forr`, `foreach`, `lambda`, `dfs`, `sortby`...). Python adds the contest standard library (`heapq`, `bisect`, `collections`...) and members after `.` to lang-python's builtins and local names. Nothing knows types, so members are the common ones plus those already used in the file; clangd would, but it would need a session per editor next to the runner. - **Autocomplete** is in the browser (`web/src/completions.js`), since `@codemirror/lang-cpp` has none. C++ completes keywords, the STL, every name in the file (the template's macros show what they expand to, typedefs what they alias), members after `.` and `->`, and snippets (`for`, `forr`, `foreach`, `lambda`, `dfs`, `sortby`...). Python adds the contest standard library (`heapq`, `bisect`, `collections`...) and members after `.` to lang-python's builtins and local names. Nothing knows types, so members are the common ones plus those already used in the file; clangd would, but it would need a session per editor next to the runner.
- **Vim keys** are a checkbox in the toolbar (`@replit/codemirror-vim`), off by default and remembered in the browser. A status line under the editor shows the mode and the command being typed, and `:w` saves as Save does. Run and Submit keep their Ctrl+Enter keys in every mode.
- **Evaluate** has Claude judge the code in the editor, as a strong competitive programmer would before submitting (`internal/evaluate`). It first runs the saved tests on the runner, as Submit does, and gives Claude their verdicts, with the input, expected output and actual output of up to three failing tests. It answers with a verdict (looks correct, misses edge cases, wrong, too slow, unfinished), complexity against the constraints, issues tied to source lines and a counterexample it has traced. The page marks the issues in the editor next to the lint's, and keeps a mark on its line for as long as that line's text is unchanged. The counterexample can be loaded as the custom input. It is a job the page polls, like explanations, and costs about the same. Nothing is committed: the result lives in the server's memory until the next evaluation or a restart. A statement it had to fetch is not saved either. - **Evaluate** has Claude judge the code in the editor, as a strong competitive programmer would before submitting (`internal/evaluate`). It first runs the saved tests on the runner, as Submit does, and gives Claude their verdicts, with the input, expected output and actual output of up to three failing tests. It answers with a verdict (looks correct, misses edge cases, wrong, too slow, unfinished), complexity against the constraints, issues tied to source lines and a counterexample it has traced. The page marks the issues in the editor next to the lint's, and keeps a mark on its line for as long as that line's text is unchanged. The counterexample can be loaded as the custom input. It is a job the page polls, like explanations, and costs about the same. Nothing is committed: the result lives in the server's memory until the next evaluation or a restart. A statement it had to fetch is not saved either.
- **Lint.** C++ is g++'s warnings plus clang-tidy with the repo's `.clang-tidy` (bugprone, performance and a few readability checks, tuned so `template.cpp` is clean); the runner embeds a copy, and a test keeps the two equal. Python is `compile()` for syntax errors plus ruff (`E4,E7,E9,F,B`). A missing tool is skipped. The runner image precompiles `bits/stdc++.h` for g++ and clang-tidy (`internal/runner/pch.go`), which on the production host takes a build from about 4 s to 0.6 s and a clang-tidy pass from over 30 s to about 4 s (with Alpine 3.24's clang-tidy 22). - **Lint.** C++ is g++'s warnings plus clang-tidy with the repo's `.clang-tidy` (bugprone, performance and a few readability checks, tuned so `template.cpp` is clean); the runner embeds a copy, and a test keeps the two equal. Python is `compile()` for syntax errors plus ruff (`E4,E7,E9,F,B`). A missing tool is skipped. The runner image precompiles `bits/stdc++.h` for g++ and clang-tidy (`internal/runner/pch.go`), which on the production host takes a build from about 4 s to 0.6 s and a clang-tidy pass from over 30 s to about 4 s (with Alpine 3.24's clang-tidy 22).
+23
View File
@@ -17,6 +17,7 @@
"@codemirror/state": "^6.7.6", "@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.13", "@codemirror/view": "^6.43.13",
"@lezer/highlight": "^1.2.5", "@lezer/highlight": "^1.2.5",
"@replit/codemirror-vim": "^6.4.0",
"@vscode/markdown-it-katex": "^1.1.2", "@vscode/markdown-it-katex": "^1.1.2",
"codemirror": "^6.0.2", "codemirror": "^6.0.2",
"dompurify": "^3.4.17", "dompurify": "^3.4.17",
@@ -749,6 +750,28 @@
"node": "^22.20 || ^24.12 || >=25" "node": "^22.20 || ^24.12 || >=25"
} }
}, },
"node_modules/@replit/codemirror-vim": {
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/@replit/codemirror-vim/-/codemirror-vim-6.4.0.tgz",
"integrity": "sha512-t9UMDNhkmeAkl0uRbiJVotv97bGD6mf4GyJJoEbrjUqa/Pov0s9eL+4AaI0Xto3OGri17i9qwIpT0JbVlVXt8A==",
"license": "MIT",
"dependencies": {
"@replit/codemirror-vim-core": "^0.1.0"
},
"peerDependencies": {
"@codemirror/commands": "6.x.x",
"@codemirror/language": "6.x.x",
"@codemirror/search": "6.x.x",
"@codemirror/state": "6.x.x",
"@codemirror/view": "6.x.x"
}
},
"node_modules/@replit/codemirror-vim-core": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/@replit/codemirror-vim-core/-/codemirror-vim-core-0.1.0.tgz",
"integrity": "sha512-1i6EBKpcNfDKvTmTh6N6g9lL6udD5t+uFNh4JCqozRnVlvUGOps7h/QzS2ne4zcvPUjvApKpmcP7Grc3fNbZiQ==",
"license": "MIT"
},
"node_modules/@rolldown/pluginutils": { "node_modules/@rolldown/pluginutils": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+1
View File
@@ -21,6 +21,7 @@
"@codemirror/state": "^6.7.6", "@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.13", "@codemirror/view": "^6.43.13",
"@lezer/highlight": "^1.2.5", "@lezer/highlight": "^1.2.5",
"@replit/codemirror-vim": "^6.4.0",
"@vscode/markdown-it-katex": "^1.1.2", "@vscode/markdown-it-katex": "^1.1.2",
"codemirror": "^6.0.2", "codemirror": "^6.0.2",
"dompurify": "^3.4.17", "dompurify": "^3.4.17",
+34 -1
View File
@@ -17,10 +17,15 @@
* *
* Completions come from basicSetup's autocompletion with sources of our own * Completions come from basicSetup's autocompletion with sources of our own
* (completions.js), since lang-cpp has none. * (completions.js), since lang-cpp has none.
*
* Vim keys (@replit/codemirror-vim) sit in a Compartment, unlike the
* language: turning them on or off keeps the text and its history. The
* states put aside for the other languages are brought up to date when
* they are swapped back in.
*/ */
import { onBeforeUnmount, onMounted, ref, watch } from "vue"; import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { basicSetup } from "codemirror"; import { basicSetup } from "codemirror";
import { EditorState, Prec } from "@codemirror/state"; import { Compartment, EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view"; import { EditorView, keymap } from "@codemirror/view";
import { indentWithTab } from "@codemirror/commands"; import { indentWithTab } from "@codemirror/commands";
import { HighlightStyle, indentUnit, syntaxHighlighting } from "@codemirror/language"; import { HighlightStyle, indentUnit, syntaxHighlighting } from "@codemirror/language";
@@ -28,6 +33,7 @@ import { lintGutter, setDiagnostics } from "@codemirror/lint";
import { cpp } from "@codemirror/lang-cpp"; import { cpp } from "@codemirror/lang-cpp";
import { python } from "@codemirror/lang-python"; import { python } from "@codemirror/lang-python";
import { tags as t } from "@lezer/highlight"; import { tags as t } from "@lezer/highlight";
import { CodeMirror, vim } from "@replit/codemirror-vim";
import { cppCompletions, pythonCompletions } from "@/completions"; import { cppCompletions, pythonCompletions } from "@/completions";
const props = defineProps({ const props = defineProps({
@@ -36,6 +42,7 @@ const props = defineProps({
// The server's: 1-based line/col, endLine/endCol optional. // The server's: 1-based line/col, endLine/endCol optional.
diagnostics: { type: Array, default: () => [] }, diagnostics: { type: Array, default: () => [] },
label: { type: String, default: "Code" }, label: { type: String, default: "Code" },
vim: { type: Boolean, default: false },
}); });
const emit = defineEmits(["update:modelValue", "run", "submit", "save"]); const emit = defineEmits(["update:modelValue", "run", "submit", "save"]);
@@ -107,10 +114,27 @@ const theme = EditorView.theme(
".cm-completionIcon": { opacity: "0.55" }, ".cm-completionIcon": { opacity: "0.55" },
".cm-tooltip.cm-completionInfo": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "4px 8px" }, ".cm-tooltip.cm-completionInfo": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "4px 8px" },
".cm-snippetField": { backgroundColor: "rgba(0, 0, 0, 0.05)" }, ".cm-snippetField": { backgroundColor: "rgba(0, 0, 0, 0.05)" },
// The vim extension's own theme is at the highest precedence, so these
// win on specificity (the cursor layer) instead.
".cm-vimCursorLayer .cm-fat-cursor": { background: "#9ec5f4", color: "var(--color-ink)" },
"&:not(.cm-focused) .cm-vimCursorLayer .cm-fat-cursor": { background: "none", outline: "1px solid #5598e7" },
".cm-panels-bottom": { borderTop: "1px solid var(--color-line-soft)" },
".cm-vim-panel": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "2px 12px" },
".cm-vim-panel input": { fontFamily: "inherit", fontSize: "inherit", color: "var(--color-ink)" },
}, },
{ dark: false }, { dark: false },
); );
// The status line shows the mode and the command being typed; vim must
// come before basicSetup's keymaps, which then work in insert mode.
const vimKeys = new Compartment();
const vimExtension = (on) => (on ? vim({ status: true }) : []);
// :w is vim's save, which calls CodeMirror.commands.save if there is one.
// It is global, so it finds the editor's own handler through the view.
const savers = new WeakMap();
CodeMirror.commands.save = (cm) => savers.get(cm.cm6)?.();
// The page also listens for these on the window, for when the editor is not // The page also listens for these on the window, for when the editor is not
// focused; stopping them here keeps one press from running twice, and keeps // focused; stopping them here keeps one press from running twice, and keeps
// basicSetup's Mod-Enter (insert a blank line) out of the way. // basicSetup's Mod-Enter (insert a blank line) out of the way.
@@ -131,6 +155,7 @@ function newState(doc, lang) {
doc, doc,
extensions: [ extensions: [
pageKeys, pageKeys,
vimKeys.of(vimExtension(props.vim)),
basicSetup, basicSetup,
keymap.of([indentWithTab]), keymap.of([indentWithTab]),
(LANGS[lang] || (() => []))(), (LANGS[lang] || (() => []))(),
@@ -174,6 +199,7 @@ function pushDiagnostics() {
onMounted(() => { onMounted(() => {
view = new EditorView({ state: newState(props.modelValue, props.lang), parent: host.value }); view = new EditorView({ state: newState(props.modelValue, props.lang), parent: host.value });
savers.set(view, () => emit("save"));
states.set(props.lang, view.state); states.set(props.lang, view.state);
}); });
onBeforeUnmount(() => view?.destroy()); onBeforeUnmount(() => view?.destroy());
@@ -190,6 +216,7 @@ watch(
states.set(oldLang, view.state); states.set(oldLang, view.state);
const kept = states.get(lang); const kept = states.get(lang);
view.setState(kept && kept.doc.toString() === value ? kept : newState(value, lang)); view.setState(kept && kept.doc.toString() === value ? kept : newState(value, lang));
syncVim();
pushDiagnostics(); pushDiagnostics();
} else if (value !== view.state.doc.toString()) { } else if (value !== view.state.doc.toString()) {
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } }); view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
@@ -198,6 +225,12 @@ watch(
); );
watch(() => props.diagnostics, () => view && pushDiagnostics()); watch(() => props.diagnostics, () => view && pushDiagnostics());
function syncVim() {
const on = vimKeys.get(view.state).length > 0;
if (on !== props.vim) view.dispatch({ effects: vimKeys.reconfigure(vimExtension(props.vim)) });
}
watch(() => props.vim, () => view && syncVim());
// Puts the cursor at the start of a line's code and shows it. // Puts the cursor at the start of a line's code and shows it.
function goto(line) { function goto(line) {
if (!view) return; if (!view) return;
+34
View File
@@ -414,6 +414,29 @@ onUnmounted(() => {
flushDraft(); flushDraft();
}); });
// ---- vim keys ----
// Off by default, and remembered in this browser like the split.
const VIM_KEY = "usaco:solve:vim";
const vimMode = ref(readVim());
function readVim() {
try {
return localStorage.getItem(VIM_KEY) === "1";
} catch {
return false;
}
}
watch(vimMode, (on) => {
try {
if (on) localStorage.setItem(VIM_KEY, "1");
else localStorage.removeItem(VIM_KEY);
} catch {
// As in readDraft.
}
editor.value?.focus();
});
// ---- the divider between the panes ---- // ---- the divider between the panes ----
// A share of the width, remembered in this browser. // A share of the width, remembered in this browser.
const SPLIT_KEY = "usaco:solve:split"; const SPLIT_KEY = "usaco:solve:split";
@@ -543,6 +566,9 @@ watch(() => props.name, load, { immediate: true });
<button class="btn" type="button" :disabled="busy || !dirty" @click="reset"> <button class="btn" type="button" :disabled="busy || !dirty" @click="reset">
Reset to {{ current.saved ? "saved" : "starter" }} Reset to {{ current.saved ? "saved" : "starter" }}
</button> </button>
<label class="check" title="Vim keys in the editor (:w saves)">
<input v-model="vimMode" type="checkbox" /> Vim
</label>
<span class="grow"></span> <span class="grow"></span>
<button <button
class="btn" class="btn"
@@ -601,6 +627,7 @@ watch(() => props.name, load, { immediate: true });
:lang="lang" :lang="lang"
:diagnostics="editorDiagnostics" :diagnostics="editorDiagnostics"
:label="`${LANG_LABELS[lang] || lang} solution`" :label="`${LANG_LABELS[lang] || lang} solution`"
:vim="vimMode"
@run="run('custom')" @run="run('custom')"
@submit="run('tests')" @submit="run('tests')"
@save="save" @save="save"
@@ -753,6 +780,13 @@ h2 {
opacity: 0.5; opacity: 0.5;
cursor: default; cursor: default;
} }
.check {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.9rem;
cursor: pointer;
}
.grow { .grow {
flex: 1; flex: 1;
} }