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]>
263 lines
11 KiB
Vue
263 lines
11 KiB
Vue
<script setup>
|
|
/**
|
|
* The solve page's editor: CodeMirror 6 behind a v-model, in the paper
|
|
* palette (the colours are CodeBlock's highlight.js ones, so code reads the
|
|
* same in both).
|
|
*
|
|
* Each language keeps its own EditorState, rather than one state whose
|
|
* language sits in a Compartment: reconfiguring a shared state would give
|
|
* the two languages one undo history, so Ctrl+Z after a switch would bring
|
|
* back the other language's code. With a state each, switching back also
|
|
* restores the cursor and history where they were.
|
|
*
|
|
* Diagnostics come in as a prop, already fetched by the page (its lint call
|
|
* is remote and debounced by the page), and are pushed with setDiagnostics
|
|
* rather than through a linter() source the editor would schedule itself.
|
|
* CodeMirror maps them through later edits until the next set arrives.
|
|
*
|
|
* Completions come from basicSetup's autocompletion with sources of our own
|
|
* (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 { basicSetup } from "codemirror";
|
|
import { Compartment, EditorState, Prec } from "@codemirror/state";
|
|
import { EditorView, keymap } from "@codemirror/view";
|
|
import { indentWithTab } from "@codemirror/commands";
|
|
import { HighlightStyle, indentUnit, syntaxHighlighting } from "@codemirror/language";
|
|
import { lintGutter, setDiagnostics } from "@codemirror/lint";
|
|
import { cpp } from "@codemirror/lang-cpp";
|
|
import { python } from "@codemirror/lang-python";
|
|
import { tags as t } from "@lezer/highlight";
|
|
import { CodeMirror, vim } from "@replit/codemirror-vim";
|
|
import { cppCompletions, pythonCompletions } from "@/completions";
|
|
|
|
const props = defineProps({
|
|
modelValue: { type: String, required: true },
|
|
lang: { type: String, required: true },
|
|
// The server's: 1-based line/col, endLine/endCol optional.
|
|
diagnostics: { type: Array, default: () => [] },
|
|
label: { type: String, default: "Code" },
|
|
vim: { type: Boolean, default: false },
|
|
});
|
|
const emit = defineEmits(["update:modelValue", "run", "submit", "save"]);
|
|
|
|
// The workspace's styles: clang-format's two spaces for C++, PEP 8's four.
|
|
const LANGS = {
|
|
cpp: () => [cpp(), cppCompletions(), indentUnit.of(" ")],
|
|
c: () => [cpp(), cppCompletions(), indentUnit.of(" ")],
|
|
python: () => [python(), pythonCompletions(), indentUnit.of(" ")],
|
|
};
|
|
|
|
const highlight = HighlightStyle.define([
|
|
{ tag: t.comment, color: "#6a737d", fontStyle: "italic" },
|
|
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.definitionKeyword, t.moduleKeyword, t.modifier, t.self], color: "#a3268d" },
|
|
{ tag: [t.typeName, t.className, t.namespace, t.standard(t.typeName)], color: "#0b6e99" },
|
|
{ tag: [t.string, t.special(t.string), t.character, t.escape], color: "#1a7f37" },
|
|
{ tag: [t.number, t.bool, t.null, t.atom, t.literal], color: "#b35900" },
|
|
{
|
|
tag: [t.function(t.variableName), t.function(t.definition(t.variableName)), t.function(t.propertyName)],
|
|
color: "#5a3fc0",
|
|
},
|
|
{ tag: [t.processingInstruction, t.meta, t.special(t.name)], color: "#8250df" },
|
|
{ tag: t.invalid, color: "var(--color-ink-danger)" },
|
|
]);
|
|
|
|
const theme = EditorView.theme(
|
|
{
|
|
"&": {
|
|
height: "100%",
|
|
fontSize: "0.8125rem",
|
|
color: "var(--color-ink-soft)",
|
|
backgroundColor: "var(--color-paper)",
|
|
},
|
|
// The wrapper draws focus, and the site's global :focus-visible ring
|
|
// would otherwise land on the contenteditable inside.
|
|
"&.cm-focused": { outline: "none" },
|
|
".cm-content:focus-visible": { outline: "none" },
|
|
".cm-scroller": { fontFamily: "var(--font-mono)", lineHeight: "1.55" },
|
|
".cm-content": { caretColor: "var(--color-ink)", padding: "12px 0" },
|
|
".cm-cursor, .cm-dropCursor": { borderLeftColor: "var(--color-ink)" },
|
|
".cm-gutters": {
|
|
backgroundColor: "var(--color-paper)",
|
|
color: "var(--color-ink-faint)",
|
|
borderRight: "1px solid var(--color-line-soft)",
|
|
},
|
|
".cm-lineNumbers .cm-gutterElement": { padding: "0 10px 0 12px" },
|
|
".cm-activeLine": { backgroundColor: "rgba(0, 0, 0, 0.03)" },
|
|
".cm-activeLineGutter": { backgroundColor: "transparent", color: "var(--color-ink)" },
|
|
"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":
|
|
{ backgroundColor: "#d7e6fb" },
|
|
".cm-selectionMatch": { backgroundColor: "#eef3e2" },
|
|
"&.cm-focused .cm-matchingBracket": { backgroundColor: "var(--color-paper-shade)", outline: "1px solid var(--color-line)" },
|
|
".cm-tooltip": {
|
|
border: "1px solid var(--color-line)",
|
|
borderRadius: "4px",
|
|
backgroundColor: "var(--color-paper)",
|
|
color: "var(--color-ink)",
|
|
},
|
|
".cm-diagnostic": { fontFamily: "var(--font-mono)", fontSize: "0.8rem" },
|
|
".cm-diagnostic-error": { borderLeftColor: "var(--color-ink-danger)" },
|
|
".cm-diagnostic-warning": { borderLeftColor: "var(--color-solving)" },
|
|
".cm-diagnostic-info": { borderLeftColor: "var(--color-ink-faint)" },
|
|
".cm-diagnosticSource": { color: "var(--color-ink-muted)" },
|
|
".cm-panels": { backgroundColor: "var(--color-paper-tint)", color: "var(--color-ink)" },
|
|
".cm-tooltip.cm-tooltip-autocomplete > ul": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", maxHeight: "16em" },
|
|
".cm-tooltip.cm-tooltip-autocomplete > ul > li": { padding: "1px 8px 1px 4px" },
|
|
".cm-tooltip-autocomplete ul li[aria-selected]": { backgroundColor: "#d7e6fb", color: "var(--color-ink)" },
|
|
".cm-completionMatchedText": { textDecoration: "none", fontWeight: "600" },
|
|
".cm-completionDetail": { color: "var(--color-ink-muted)", fontStyle: "normal", marginLeft: "1em" },
|
|
".cm-completionIcon": { opacity: "0.55" },
|
|
".cm-tooltip.cm-completionInfo": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "4px 8px" },
|
|
".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 },
|
|
);
|
|
|
|
// 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
|
|
// focused; stopping them here keeps one press from running twice, and keeps
|
|
// basicSetup's Mod-Enter (insert a blank line) out of the way.
|
|
const pageKeys = Prec.highest(
|
|
keymap.of([
|
|
{ key: "Mod-Shift-Enter", run: () => (emit("submit"), true), stopPropagation: true },
|
|
{ key: "Mod-Enter", run: () => (emit("run"), true), stopPropagation: true },
|
|
{ key: "Mod-s", run: () => (emit("save"), true), preventDefault: true, stopPropagation: true },
|
|
]),
|
|
);
|
|
|
|
const host = ref(null);
|
|
let view = null;
|
|
const states = new Map();
|
|
|
|
function newState(doc, lang) {
|
|
return EditorState.create({
|
|
doc,
|
|
extensions: [
|
|
pageKeys,
|
|
vimKeys.of(vimExtension(props.vim)),
|
|
basicSetup,
|
|
keymap.of([indentWithTab]),
|
|
(LANGS[lang] || (() => []))(),
|
|
syntaxHighlighting(highlight),
|
|
lintGutter(),
|
|
theme,
|
|
EditorView.contentAttributes.of({ "aria-label": props.label }),
|
|
EditorView.updateListener.of((u) => {
|
|
if (u.docChanged) emit("update:modelValue", u.state.doc.toString());
|
|
}),
|
|
],
|
|
});
|
|
}
|
|
|
|
// The server's positions as document offsets. Columns are taken as
|
|
// characters; anything past the end of a line or the document is clamped,
|
|
// since the source may have moved on since the lint ran. Without an end
|
|
// the mark covers the word at the start, or the rest of the line.
|
|
function toDiagnostic(d, doc) {
|
|
const lineAt = (n) => doc.line(Math.min(Math.max(n || 1, 1), doc.lines));
|
|
const at = (lineNo, col) => {
|
|
const line = lineAt(lineNo);
|
|
return line.from + Math.min(Math.max((col || 1) - 1, 0), line.length);
|
|
};
|
|
const from = at(d.line, d.col);
|
|
let to = d.endLine > 0 ? at(d.endLine, d.endCol || 1) : from;
|
|
if (to <= from) {
|
|
const line = doc.lineAt(from);
|
|
const word = /^\w+/.exec(line.text.slice(from - line.from));
|
|
to = word ? from + word[0].length : line.to;
|
|
}
|
|
const severity = ["error", "warning", "info"].includes(d.severity) ? d.severity : "info";
|
|
const source = [d.source, d.rule].filter(Boolean).join(" ");
|
|
return { from, to, severity, message: d.message, ...(source ? { source } : {}) };
|
|
}
|
|
|
|
function pushDiagnostics() {
|
|
const doc = view.state.doc;
|
|
view.dispatch(setDiagnostics(view.state, props.diagnostics.map((d) => toDiagnostic(d, doc))));
|
|
}
|
|
|
|
onMounted(() => {
|
|
view = new EditorView({ state: newState(props.modelValue, props.lang), parent: host.value });
|
|
savers.set(view, () => emit("save"));
|
|
states.set(props.lang, view.state);
|
|
});
|
|
onBeforeUnmount(() => view?.destroy());
|
|
|
|
// The page sets the language and its source in one go, so they are watched
|
|
// together: a new language swaps in that language's state; a new value in
|
|
// the same language (Reset, Save's commit) replaces the text as an edit,
|
|
// so Ctrl+Z can bring the old text back.
|
|
watch(
|
|
() => [props.lang, props.modelValue],
|
|
([lang, value], [oldLang]) => {
|
|
if (!view) return;
|
|
if (lang !== oldLang) {
|
|
states.set(oldLang, view.state);
|
|
const kept = states.get(lang);
|
|
view.setState(kept && kept.doc.toString() === value ? kept : newState(value, lang));
|
|
syncVim();
|
|
pushDiagnostics();
|
|
} else if (value !== view.state.doc.toString()) {
|
|
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
|
|
}
|
|
},
|
|
);
|
|
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.
|
|
function goto(line) {
|
|
if (!view) return;
|
|
const l = view.state.doc.line(Math.min(Math.max(line, 1), view.state.doc.lines));
|
|
const at = l.from + (/^\s*/.exec(l.text)?.[0].length || 0);
|
|
view.dispatch({ selection: { anchor: at }, effects: EditorView.scrollIntoView(at, { y: "center" }) });
|
|
view.focus();
|
|
}
|
|
|
|
defineExpose({ focus: () => view?.focus(), goto });
|
|
</script>
|
|
|
|
<template>
|
|
<div ref="host" class="editor"></div>
|
|
</template>
|
|
|
|
<style scoped>
|
|
.editor {
|
|
height: 100%;
|
|
min-height: 0;
|
|
border: 1px solid var(--color-line-soft);
|
|
border-radius: 6px;
|
|
overflow: hidden;
|
|
background: var(--color-paper);
|
|
}
|
|
.editor:focus-within {
|
|
border-color: var(--color-ink-muted);
|
|
}
|
|
</style>
|