A Real Code Editor
Built on CodeMirror 6: click, drag and select exactly where you point, line numbers, current-line highlight, bracket matching, auto-indent and Tab / Shift+Tab.
Ctrl / ⌘ + Enter to run
A real code editor, live execution and 165 hands-on lessons across 10 languages,
from your first print() to data structures. Nothing to install. Your progress saves in this browser.
A complete coding lab in one page: a professional editor, four execution engines, and a structured curriculum that takes you from first syntax to working with real data structures.
Built on CodeMirror 6: click, drag and select exactly where you point, line numbers, current-line highlight, bracket matching, auto-indent and Tab / Shift+Tab.
Ctrl / ⌘ + Enter to runPython runs on WebAssembly, JavaScript in a sandboxed worker, HTML and CSS in a live preview, and six compiled languages on a cloud judge.
Output + timing consoleStage 1 is complete in all 10 languages, and Python also has Stage 2. Every lesson has a plain-English explanation, a runnable example and a challenge to try.
More stages in developmentLessons you finish are ticked off and remembered in your browser, along with your edits and the last lesson you opened. No account needed.
Stored locallyFind any topic in a second: search lesson titles and explanations, or filter by stage, and jump straight into the example.
Instant searchThe workspace adapts from wide desktop screens down to a 375px phone, with touch-friendly selection in the editor and a resizable console.
Responsive IDEEach language is routed to the engine that suits it best. Four of them run completely inside your browser.
ce.judge0.com to be compiled. Don't put passwords or personal data in your programs.Stage 1 (15 lessons) is ready in every language, and Python also has Stage 2. Your progress ring fills as you complete lessons.
Read the lesson on the left, edit and run the code on the right. Switch to scratch for free practice.
Press Run (or Ctrl/⌘ + Enter) to execute your code.$1').replace(/\*\*([^*]+)\*\*/g, '$1');
}
function toast(msg) {
const t = $('#toast'); t.textContent = msg; t.classList.add('show');
clearTimeout(toast._t); toast._t = setTimeout(() => t.classList.remove('show'), 1800);
}
const pad2 = n => String(n).padStart(2, '0');
const fileName = (lang, n) => LANGS[lang].file && n == null ? LANGS[lang].file : (n == null ? 'scratch.' + LANGS[lang].ext : `lesson-${pad2(n)}.${LANGS[lang].ext}`);
/* ============================================================
Editor: CodeMirror 6 (from esm.sh), plain textarea fallback
============================================================ */
const CM_BASE = 'https://esm.sh/';
let CM = null;
const langExtCache = {};
async function loadCM() {
const [view, state, commands, language, autocomplete, search, highlight] = await Promise.all([
import(CM_BASE + '@codemirror/view@6'),
import(CM_BASE + '@codemirror/state@6'),
import(CM_BASE + '@codemirror/commands@6'),
import(CM_BASE + '@codemirror/language@6'),
import(CM_BASE + '@codemirror/autocomplete@6'),
import(CM_BASE + '@codemirror/search@6'),
import(CM_BASE + '@lezer/highlight@1'),
]);
return { ...view, ...state, ...commands, ...language, ...autocomplete, ...search, tags: highlight.tags };
}
const LANG_LOADERS = {
python: async () => (await import(CM_BASE + '@codemirror/lang-python@6')).python(),
javascript: async () => (await import(CM_BASE + '@codemirror/lang-javascript@6')).javascript(),
html: async () => (await import(CM_BASE + '@codemirror/lang-html@6')).html(),
css: async () => (await import(CM_BASE + '@codemirror/lang-css@6')).css(),
go: async () => (await import(CM_BASE + '@codemirror/lang-go@6')).go(),
c: async () => (await import(CM_BASE + '@codemirror/lang-cpp@6')).cpp(),
cpp: async () => (await import(CM_BASE + '@codemirror/lang-cpp@6')).cpp(),
java: async () => (await import(CM_BASE + '@codemirror/lang-java@6')).java(),
php: async () => (await import(CM_BASE + '@codemirror/lang-php@6')).php(),
ruby: async () => CM.StreamLanguage.define((await import(CM_BASE + '@codemirror/legacy-modes@6/mode/ruby')).ruby),
};
async function langExt(lang) {
if (!langExtCache[lang]) langExtCache[lang] = LANG_LOADERS[lang]().catch(e => { console.warn('Language mode failed', lang, e); delete langExtCache[lang]; return []; });
return langExtCache[lang];
}
const editor = {
view: null, fallback: null, langComp: null, listeners: [],
onChange(fn) { this.listeners.push(fn); },
emit() { this.listeners.forEach(f => f()); },
get value() { return this.view ? this.view.state.doc.toString() : this.fallback.value; },
set(text, lang) {
if (this.view) {
this.view.setState(this.makeState(text));
this.applyLang(lang);
} else {
this.fallback.value = text; this.fallback.scrollTop = 0; this.fallback.scrollLeft = 0; this.updateCursor();
}
},
async applyLang(lang) {
if (!this.view) return;
const want = lang; this._lang = lang;
const ext = await langExt(lang);
if (this._lang !== want || !this.view) return;
this.view.dispatch({ effects: this.langComp.reconfigure(ext) });
},
focus() { this.view ? this.view.focus() : this.fallback.focus(); },
updateCursor() {
let line = 1, col = 1, sel = 0;
if (this.view) {
const st = this.view.state, r = st.selection.main, l = st.doc.lineAt(r.head);
line = l.number; col = r.head - l.from + 1; sel = Math.abs(r.to - r.from);
} else {
const t = this.fallback, before = t.value.slice(0, t.selectionStart).split('\n');
line = before.length; col = before[before.length - 1].length + 1; sel = Math.abs(t.selectionEnd - t.selectionStart);
}
$('#sbCursor').textContent = `Ln ${line}, Col ${col}` + (sel ? ` (${sel} selected)` : '');
},
makeState(text) {
const C = CM;
return C.EditorState.create({
doc: text,
extensions: [
C.lineNumbers(), C.highlightActiveLineGutter(), C.highlightSpecialChars(), C.history(), C.foldGutter(),
C.drawSelection(), C.dropCursor(), C.EditorState.allowMultipleSelections.of(true), C.indentOnInput(),
C.syntaxHighlighting(cmHighlight, { fallback: true }), C.bracketMatching(), C.closeBrackets(),
C.autocompletion({ activateOnTyping: true }), C.rectangularSelection(), C.crosshairCursor(),
C.highlightActiveLine(), C.highlightSelectionMatches(),
C.indentUnit.of(' '), C.EditorState.tabSize.of(4),
C.keymap.of([
{ key: 'Mod-Enter', run: () => { runCode(); return true; } },
{ key: 'Shift-Enter', run: () => { runCode(); return true; } },
...C.closeBracketsKeymap, ...C.defaultKeymap, ...C.searchKeymap, ...C.historyKeymap,
...C.foldKeymap, ...C.completionKeymap, C.indentWithTab,
]),
this.langComp.of([]),
cmTheme,
C.EditorView.updateListener.of(u => { if (u.docChanged) this.emit(); if (u.selectionSet || u.docChanged) this.updateCursor(); }),
C.EditorView.contentAttributes.of({ 'aria-label': 'Code editor', autocapitalize: 'off', autocorrect: 'off', spellcheck: 'false' }),
],
});
},
};
let cmTheme, cmHighlight;
function buildCMTheme() {
const C = CM, t = C.tags;
cmTheme = C.EditorView.theme({
'&': { color: '#e2e8f0', backgroundColor: '#020617', fontSize: '14px', height: '100%' },
'.cm-scroller': { fontFamily: "'Fira Code', ui-monospace, Menlo, Consolas, monospace", lineHeight: '1.65', overflow: 'auto' },
'.cm-content': { caretColor: '#38bdf8', padding: '12px 0' },
'.cm-line': { padding: '0 16px 0 10px' },
'&.cm-focused .cm-cursor': { borderLeftColor: '#38bdf8', borderLeftWidth: '2px' },
'.cm-cursor': { borderLeftColor: '#38bdf8', borderLeftWidth: '2px' },
'.cm-selectionBackground, ::selection': { backgroundColor: 'rgba(56, 189, 248, 0.28) !important' },
'&.cm-focused .cm-selectionBackground': { backgroundColor: 'rgba(56, 189, 248, 0.32) !important' },
'.cm-activeLine': { backgroundColor: 'rgba(56, 189, 248, 0.07)', boxShadow: 'inset 2px 0 0 #38bdf8' },
'.cm-gutters': { backgroundColor: '#010409', color: '#475569', borderRight: '1px solid #1e293b' },
'.cm-lineNumbers .cm-gutterElement': { padding: '0 10px 0 14px', minWidth: '44px' },
'.cm-activeLineGutter': { backgroundColor: 'rgba(56, 189, 248, 0.1)', color: '#38bdf8' },
'.cm-foldGutter .cm-gutterElement': { color: '#334155', padding: '0 4px' },
'.cm-matchingBracket': { backgroundColor: 'rgba(56, 189, 248, 0.2)', outline: '1px solid rgba(56,189,248,.5)', color: '#fff !important' },
'.cm-selectionMatch': { backgroundColor: 'rgba(129, 140, 248, 0.2)' },
'.cm-tooltip': { backgroundColor: '#0a1329', border: '1px solid #24365e', borderRadius: '8px', overflow: 'hidden' },
'.cm-tooltip-autocomplete > ul > li[aria-selected]': { backgroundColor: 'rgba(56,189,248,.2)', color: '#fff' },
'.cm-panels': { backgroundColor: '#040917', color: '#e2e8f0', borderColor: '#1e293b' },
'.cm-panels input, .cm-panels button': { fontSize: '13px' },
'.cm-searchMatch': { backgroundColor: 'rgba(251,191,36,.25)' },
}, { dark: true });
cmHighlight = C.HighlightStyle.define([
{ tag: [t.keyword, t.controlKeyword, t.moduleKeyword, t.operatorKeyword, t.definitionKeyword, t.modifier], color: '#f472b6', fontWeight: '500' },
{ tag: [t.string, t.special(t.string), t.regexp, t.character], color: '#34d399' },
{ tag: [t.number, t.bool, t.null, t.atom], color: '#fbbf24' },
{ tag: [t.comment, t.lineComment, t.blockComment, t.docComment], color: '#64748b', fontStyle: 'italic' },
{ tag: [t.function(t.variableName), t.function(t.propertyName)], color: '#7dd3fc' },
{ tag: [t.definition(t.variableName), t.definition(t.function(t.variableName))], color: '#e0f2fe' },
{ tag: [t.typeName, t.className, t.namespace, t.standard(t.variableName)], color: '#a78bfa' },
{ tag: [t.propertyName, t.attributeName], color: '#93c5fd' },
{ tag: [t.tagName], color: '#f472b6' },
{ tag: [t.attributeValue], color: '#34d399' },
{ tag: [t.operator, t.punctuation, t.bracket], color: '#94a3b8' },
{ tag: [t.meta, t.processingInstruction, t.self], color: '#22d3ee' },
{ tag: t.invalid, color: '#f43f5e' },
]);
}
function mountFallback() {
const host = $('#editorHost');
host.innerHTML = '';
const ta = host.querySelector('textarea');
editor.fallback = ta;
ta.addEventListener('input', () => editor.emit());
['keyup', 'click', 'select'].forEach(ev => ta.addEventListener(ev, () => editor.updateCursor()));
ta.addEventListener('keydown', e => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); runCode(); return; }
if (e.key === 'Tab') {
e.preventDefault();
const s = ta.selectionStart, en = ta.selectionEnd, v = ta.value;
const ls = v.lastIndexOf('\n', s - 1) + 1;
if (s === en && !e.shiftKey) { document.execCommand('insertText', false, ' '); return; }
const block = v.slice(ls, en);
const out = e.shiftKey ? block.replace(/^( {1,4}|\t)/gm, '') : block.replace(/^/gm, ' ');
ta.setSelectionRange(ls, en); document.execCommand('insertText', false, out);
ta.setSelectionRange(ls, ls + out.length);
} else if (e.key === 'Enter' && !e.shiftKey) {
const s = ta.selectionStart, v = ta.value, ls = v.lastIndexOf('\n', s - 1) + 1;
const line = v.slice(ls, s), base = (line.match(/^[ \t]*/) || [''])[0];
const extra = /(:|\{|\(|\[|\bdo|\bthen)\s*$/.test(line) ? ' ' : '';
e.preventDefault(); document.execCommand('insertText', false, '\n' + base + extra);
}
});
}
async function initEditor() {
try {
CM = await Promise.race([loadCM(), new Promise((_, rej) => setTimeout(() => rej(new Error('Editor CDN timed out')), 15000))]);
buildCMTheme();
editor.langComp = new CM.Compartment();
const host = $('#editorHost'); host.innerHTML = '';
editor.view = new CM.EditorView({ state: editor.makeState(''), parent: host });
} catch (e) {
console.warn('CodeMirror unavailable, using plain editor:', e);
CM = null; editor.view = null; mountFallback();
}
}
/* ============================================================
App state
============================================================ */
const last = store.get('last', {});
const state = {
lang: LANGS[last.lang] ? last.lang : 'python',
idx: {}, // current lesson index per language
tab: 'lesson', // 'lesson' | 'scratch'
stageFilter: 0,
query: '',
};
LANG_KEYS.forEach(k => { const i = (last.idx || {})[k]; state.idx[k] = Number.isInteger(i) && LESSONS[k] && i < LESSONS[k].length ? i : 0; });
const lessonOf = (lang = state.lang) => LESSONS[lang][state.idx[lang]];
const editKey = (lang, n) => `edit.${lang}.${n}`;
function saveLast() { store.set('last', { lang: state.lang, idx: state.idx }); }
const SCRATCH_DEFAULT = {
python: '# Free practice: write any Python here\nnumbers = [12, 45, 68, 23, 89, 34]\nprint("Sum:", sum(numbers))\nprint("Average:", round(sum(numbers) / len(numbers), 2))\nprint("Max:", max(numbers))\n',
javascript: '// Free practice: write any JavaScript here\nconst numbers = [12, 45, 68, 23, 89, 34];\nconst sum = numbers.reduce((a, n) => a + n, 0);\nconsole.log("Sum:", sum);\nconsole.log("Average:", (sum / numbers.length).toFixed(2));\nconsole.log("Max:", Math.max(...numbers));\n',
html: '\n\n\n \n\n\n Edit me: the preview updates as you type.
\n\n\n', css: '/* Free practice: this CSS styles the demo page in Preview */\nbody {\n font-family: system-ui, sans-serif;\n background: #070d1e;\n color: #e2e8f0;\n padding: 24px;\n}\n\n.card {\n background: #0a1329;\n border: 1px solid #38bdf8;\n border-radius: 12px;\n padding: 20px;\n}\n', go: 'package main\n\nimport "fmt"\n\nfunc main() {\n numbers := []int{12, 45, 68, 23, 89, 34}\n sum := 0\n for _, n := range numbers {\n sum += n\n }\n fmt.Println("Sum:", sum)\n fmt.Printf("Average: %.2f\\n", float64(sum)/float64(len(numbers)))\n}\n', c: '#includeThis page is styled by your CSS.
\nCards are boxes with padding, a border and rounded corners.
\n \n${inlineMd(p.replace(/\n/g, ' '))}
`).join(''); $('#tryBox').hidden = !l.tryIt; $('#tryText').innerHTML = inlineMd(l.tryIt || ''); const sh = $('#stdinHint'); if (l.stdin) { sh.hidden = false; sh.innerHTML = `This lesson reads input. The Input tab has been filled with:${esc(l.stdin.replace(/\n/g, ' ⏎ '))}`; }
else sh.hidden = true;
$('#lessonBody').scrollTop = 0;
updateLessonMeta();
};
const body = $('#lessonBody');
if (dir && !reduceMotion) {
body.style.setProperty('--dir', dir);
body.classList.remove('swap-in'); body.classList.add('swap-out');
setTimeout(() => { paint(); body.classList.remove('swap-out'); void body.offsetWidth; body.classList.add('swap-in'); }, 170);
} else paint();
if (l.stdin) { $('#stdinArea').value = l.stdin; updateStdinCount(); }
$('#paneTitle').textContent = `${LANGS[lang].name} · Lesson ${l.n}`;
$('#prevBtn').disabled = state.idx[lang] === 0;
$('#nextBtn').disabled = state.idx[lang] === list.length - 1;
renderLessonList();
}
function updateLessonMeta() {
const lang = state.lang, l = lessonOf(), total = LESSONS[lang].length, done = (progress[lang] || []).length;
const d = isDone(lang, l.n);
$('#doneBadge').hidden = !d;
$('#doneBtn').classList.toggle('is-done', d);
$('#doneLbl').textContent = d ? 'Completed' : 'Mark complete';
$('#progressText').textContent = `${done} / ${total}`;
$('#progressBar').style.setProperty('--w', (done / total * 100) + '%');
$('#sbLesson').textContent = `Lesson ${l.n}/${total} · ${done} done`;
renderLangCards();
}
function goLesson(i, dir) {
const list = LESSONS[state.lang];
if (i < 0 || i >= list.length) return;
state.idx[state.lang] = i; state.tab = 'lesson';
renderLesson(dir ?? (i > state.idx[state.lang] ? 1 : -1));
loadEditor(); saveLast(); resetConsole();
if (LANGS[state.lang].kind === 'web') schedulePreview(0);
}
/* ---------- Lesson list drawer ---------- */
function buildStageFilter() {
const box = $('#stageFilter');
const maxStage = LESSONS[state.lang].at(-1).stage;
state.stageFilter = 0;
const btns = [``];
STAGES.forEach(s => btns.push(``));
box.innerHTML = btns.join('');
if (box._wired) return; box._wired = true;
box.addEventListener('click', e => {
const b = e.target.closest('.sf-btn'); if (!b || b.disabled) return;
state.stageFilter = +b.dataset.s;
$$('.sf-btn', box).forEach(x => x.setAttribute('aria-pressed', x === b));
renderLessonList();
});
}
function highlightMatch(text, q) {
if (!q) return esc(text);
const i = text.toLowerCase().indexOf(q);
if (i < 0) return esc(text);
return esc(text.slice(0, i)) + '' + esc(text.slice(i, i + q.length)) + '' + esc(text.slice(i + q.length));
}
function renderLessonList() {
const lang = state.lang, q = state.query.trim().toLowerCase();
const items = LESSONS[lang].filter(l => (!state.stageFilter || l.stage === state.stageFilter) &&
(!q || l.title.toLowerCase().includes(q) || l.text.toLowerCase().includes(q) || l.code.toLowerCase().includes(q)));
$('#drawerTitle').textContent = `${LANGS[lang].name} · ${items.length} lesson${items.length === 1 ? '' : 's'}`;
if (!items.length) { $('#lessonList').innerHTML = `${s.desc}
${live ? `● ${count} lessons · ${langs.length === LANG_KEYS.length ? 'all languages' : langs.map(k => LANGS[k].name).join(', ')}` : '○ In development'}