offline-tex-editor 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. offline_tex_editor/__init__.py +2 -0
  2. offline_tex_editor/__main__.py +3 -0
  3. offline_tex_editor/gitapi.py +250 -0
  4. offline_tex_editor/index.html +132 -0
  5. offline_tex_editor/latexlog.py +205 -0
  6. offline_tex_editor/project.py +403 -0
  7. offline_tex_editor/server.py +923 -0
  8. offline_tex_editor/static/app.css +231 -0
  9. offline_tex_editor/static/app.js +72 -0
  10. offline_tex_editor/static/compile.js +83 -0
  11. offline_tex_editor/static/complete.js +159 -0
  12. offline_tex_editor/static/diffview.js +72 -0
  13. offline_tex_editor/static/editor.js +230 -0
  14. offline_tex_editor/static/files.js +181 -0
  15. offline_tex_editor/static/git.js +120 -0
  16. offline_tex_editor/static/package.json +5 -0
  17. offline_tex_editor/static/panels.js +83 -0
  18. offline_tex_editor/static/pdfview.js +254 -0
  19. offline_tex_editor/static/textindex.js +45 -0
  20. offline_tex_editor/static/tools.js +72 -0
  21. offline_tex_editor/static/util.js +57 -0
  22. offline_tex_editor/vendor/README.md +29 -0
  23. offline_tex_editor/vendor/codemirror/LICENSE +21 -0
  24. offline_tex_editor/vendor/codemirror/addon/dialog/dialog.min.css +1 -0
  25. offline_tex_editor/vendor/codemirror/addon/dialog/dialog.min.js +1 -0
  26. offline_tex_editor/vendor/codemirror/addon/edit/matchbrackets.min.js +1 -0
  27. offline_tex_editor/vendor/codemirror/addon/search/jump-to-line.min.js +1 -0
  28. offline_tex_editor/vendor/codemirror/addon/search/search.min.js +1 -0
  29. offline_tex_editor/vendor/codemirror/addon/search/searchcursor.min.js +1 -0
  30. offline_tex_editor/vendor/codemirror/addon/selection/active-line.min.js +1 -0
  31. offline_tex_editor/vendor/codemirror/codemirror.min.css +1 -0
  32. offline_tex_editor/vendor/codemirror/codemirror.min.js +1 -0
  33. offline_tex_editor/vendor/codemirror/mode/markdown/markdown.min.js +1 -0
  34. offline_tex_editor/vendor/codemirror/mode/python/python.min.js +1 -0
  35. offline_tex_editor/vendor/codemirror/mode/stex/stex.min.js +1 -0
  36. offline_tex_editor/vendor/pdfjs/LICENSE +177 -0
  37. offline_tex_editor/vendor/pdfjs/pdf.min.mjs +21 -0
  38. offline_tex_editor/vendor/pdfjs/pdf.worker.min.mjs +21 -0
  39. offline_tex_editor-0.2.0.dist-info/METADATA +193 -0
  40. offline_tex_editor-0.2.0.dist-info/RECORD +44 -0
  41. offline_tex_editor-0.2.0.dist-info/WHEEL +5 -0
  42. offline_tex_editor-0.2.0.dist-info/entry_points.txt +2 -0
  43. offline_tex_editor-0.2.0.dist-info/licenses/LICENSE +21 -0
  44. offline_tex_editor-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,254 @@
1
+ // The PDF preview: rendering with a text layer, find in PDF, SyncTeX both ways, page number, zoom, splitter.
2
+ import * as pdfjsLib from '../vendor/pdfjs/pdf.min.mjs';
3
+ import { $, el, app, state, store, api, setStatus } from './util.js';
4
+ import { normalize, indexText, findAll, matchSpans } from './textindex.js';
5
+
6
+ pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('../vendor/pdfjs/pdf.worker.min.mjs', import.meta.url).href;
7
+ // isEvalSupported: false keeps pdf.js from compiling fonts to code, a defence against malicious PDFs (such as one
8
+ // pulled in by \includegraphics). The page's Content-Security-Policy forbids eval anyway.
9
+ const OPEN = { isEvalSupported: false };
10
+
11
+ const pdf = { mtime: null, rendering: false, failures: 0 };
12
+ app.pdf = pdf;
13
+ let zoom = store.get('zoom', 1.0);
14
+
15
+ // The PDF on screen: pages, their elements and scales, and per page the draw promise, the indexed text and the
16
+ // text layer's spans. A recompile builds a new view, so work for an old one checks `v === view` and stops.
17
+ let view = null;
18
+ function newView(doc, pages, els, scales) {
19
+ const v = { doc, pages, els, scales, drawn: new Map(), text: new Map(), textReady: [], textDivs: [], painted: [] };
20
+ v.draw = i => { if (!v.drawn.has(i)) v.drawn.set(i, drawPage(v, i).catch(() => {})); return v.drawn.get(i); };
21
+ return v;
22
+ }
23
+
24
+ async function drawPage(v, i) {
25
+ const page = v.pages[i], scale = v.scales[i], vp = page.getViewport({ scale }), dpr = window.devicePixelRatio || 1;
26
+ const c = el('canvas');
27
+ c.width = vp.width * dpr; c.height = vp.height * dpr; c.style.width = vp.width + 'px'; c.style.height = vp.height + 'px';
28
+ await page.render({ canvasContext: c.getContext('2d'), viewport: page.getViewport({ scale: scale * dpr }) }).promise;
29
+ // Text layer: transparent text over the image, so the PDF's text can be selected, copied and searched.
30
+ const t = await pageText(v, i), tl = el('div', { className: 'textLayer' });
31
+ tl.style.setProperty('--scale-factor', scale);
32
+ const layer = new pdfjsLib.TextLayer({ textContentSource: t.content, container: tl, viewport: vp });
33
+ await layer.render();
34
+ v.els[i].replaceChildren(c, tl, ...v.els[i].querySelectorAll('.mark'));
35
+ v.textDivs[i] = layer.textDivs; // textDivs[k] is the span for t.content.items[k]
36
+ paintFind(v, i);
37
+ }
38
+
39
+ function pageText(v, i) {
40
+ if (!v.text.has(i)) v.text.set(i, v.pages[i].getTextContent().then(content => {
41
+ const t = { content, ...indexText(content.items) }; v.textReady[i] = t; return t;
42
+ }));
43
+ return v.text.get(i);
44
+ }
45
+
46
+ export async function loadPdf() {
47
+ if (pdf.rendering) return;
48
+ pdf.rendering = true;
49
+ const wrap = $('pdfWrap'), keepTop = wrap.scrollTop / Math.max(1, wrap.scrollHeight);
50
+ try {
51
+ const res = await fetch('/pdf?t=' + Date.now());
52
+ if (!res.ok) { pdf.rendering = false; if (res.status === 404 && !view) $('pdfEmpty').textContent = 'No PDF yet — press Recompile.'; return; }
53
+ const data = await res.arrayBuffer();
54
+ const doc = await pdfjsLib.getDocument({ data, ...OPEN }).promise;
55
+ const box = $('pdf'), frag = document.createDocumentFragment(), els = [], scales = [], pages = [];
56
+ const avail = wrap.clientWidth - 28;
57
+ // 1) lay out every page (cheap), 2) draw the pages near the old scroll position before swapping,
58
+ // 3) swap, 4) draw the rest in the background.
59
+ for (let i = 1; i <= doc.numPages; i++) {
60
+ const page = await doc.getPage(i), base = page.getViewport({ scale: 1 });
61
+ const scale = (avail / base.width) * zoom, vp = page.getViewport({ scale });
62
+ const div = el('div', { className: 'page', dataset: { page: i } });
63
+ div.style.width = vp.width + 'px'; div.style.height = vp.height + 'px';
64
+ frag.appendChild(div); els.push(div); scales.push(scale); pages.push(page);
65
+ }
66
+ const v = newView(doc, pages, els, scales);
67
+ const totalH = scales.reduce((a, s, i) => a + pages[i].getViewport({ scale: s }).height + 12, 12);
68
+ let y = 12, first = 0; const target = keepTop * totalH;
69
+ for (let i = 0; i < pages.length; i++) { const h = pages[i].getViewport({ scale: scales[i] }).height + 12; if (y + h > target) { first = i; break; } y += h; }
70
+ const near = [first, first + 1, first + 2].filter(i => i < pages.length);
71
+ for (const i of near) await v.draw(i);
72
+ const old = view;
73
+ box.replaceChildren(frag); view = v;
74
+ wrap.scrollTop = keepTop * wrap.scrollHeight;
75
+ $('pageCount').textContent = doc.numPages; updatePageNum();
76
+ const s = await api('/api/status'); pdf.mtime = s.pdf_mtime; pdf.failures = 0;
77
+ pdf.rendering = false;
78
+ old?.doc.destroy(); // free the previous document in the pdf.js worker
79
+ if (find.query) runFind(false); // same search on the new PDF, without moving the view
80
+ for (let i = 0; i < pages.length; i++) if (view === v) await v.draw(i);
81
+ } catch (e) {
82
+ // A PDF being replaced at this moment can fail to parse; the next poll retries. Report repeated failures only.
83
+ if (++pdf.failures >= 3) { console.error('PDF render failed', e); setStatus('PDF render failed: ' + e.message, 'err'); }
84
+ }
85
+ pdf.rendering = false;
86
+ }
87
+
88
+ // The main document changed: forget the old PDF.
89
+ export function resetPdf() {
90
+ view?.doc.destroy(); view = null; pdf.mtime = null;
91
+ $('pdf').replaceChildren(el('div', { id: 'pdfEmpty' }, 'No PDF yet.'));
92
+ $('pageCount').textContent = '–'; $('pageNum').value = '–';
93
+ }
94
+
95
+ // First page of a PDF file, for the file preview.
96
+ export async function renderPdfPage(url) {
97
+ const doc = await pdfjsLib.getDocument({ url, ...OPEN }).promise;
98
+ try {
99
+ const page = await doc.getPage(1), base = page.getViewport({ scale: 1 });
100
+ const scale = Math.min(2, (Math.min(900, $('previewBody').clientWidth - 32)) / base.width), dpr = window.devicePixelRatio || 1;
101
+ const vp = page.getViewport({ scale: scale * dpr }), c = el('canvas');
102
+ c.width = vp.width; c.height = vp.height; c.style.width = vp.width / dpr + 'px';
103
+ await page.render({ canvasContext: c.getContext('2d'), viewport: vp }).promise;
104
+ return c;
105
+ } finally { setTimeout(() => doc.destroy(), 0); }
106
+ }
107
+
108
+ $('zoomIn').onclick = () => { zoom = Math.min(4, zoom * 1.15); store.set('zoom', zoom); loadPdf(); };
109
+ $('zoomOut').onclick = () => { zoom = Math.max(0.3, zoom / 1.15); store.set('zoom', zoom); loadPdf(); };
110
+ let resizeT; window.addEventListener('resize', () => { clearTimeout(resizeT); resizeT = setTimeout(loadPdf, 300); });
111
+
112
+ // ---------- page number ----------
113
+ const pageEls = () => view ? view.els : [];
114
+ function updatePageNum() {
115
+ const els = pageEls();
116
+ if (!els.length || document.activeElement === $('pageNum')) return;
117
+ const wrap = $('pdfWrap'), mid = wrap.scrollTop + wrap.clientHeight / 2;
118
+ let cur = 1;
119
+ for (let i = 0; i < els.length; i++) { if (els[i].offsetTop <= mid) cur = i + 1; else break; }
120
+ $('pageNum').value = cur;
121
+ }
122
+ let pageT; $('pdfWrap').addEventListener('scroll', () => { if (!pageT) pageT = requestAnimationFrame(() => { pageT = 0; updatePageNum(); }); });
123
+ $('pageNum').addEventListener('keydown', ev => {
124
+ if (ev.key === 'Enter') {
125
+ const n = parseInt($('pageNum').value, 10), els = pageEls();
126
+ if (n >= 1 && n <= els.length) $('pdfWrap').scrollTop = els[n - 1].offsetTop - 12;
127
+ $('pageNum').blur();
128
+ } else if (ev.key === 'Escape') $('pageNum').blur();
129
+ });
130
+ $('pageNum').addEventListener('focus', () => $('pageNum').select());
131
+ $('pageNum').addEventListener('blur', updatePageNum);
132
+
133
+ // ---------- SyncTeX: PDF -> source (double-click), source -> PDF (button / Ctrl+J) ----------
134
+ $('pdf').addEventListener('dblclick', async ev => {
135
+ const div = ev.target.closest('.page'); if (!div || !view) return;
136
+ window.getSelection().removeAllRanges(); // the double-click also selected a word in the text layer
137
+ const i = +div.dataset.page, rect = div.getBoundingClientRect(), s = view.scales[i - 1];
138
+ const x = (ev.clientX - rect.left) / s, y = (ev.clientY - rect.top) / s;
139
+ const r = await api(`/api/synctex/edit?page=${i}&x=${x.toFixed(1)}&y=${y.toFixed(1)}`);
140
+ if (r.ok && r.path) app.openFile(r.path, r.line, { flash: true }); else setStatus(r.error || 'no source for that spot', 'err');
141
+ });
142
+ export async function syncToPdf() {
143
+ if (!state.current || !view) return;
144
+ const line = app.cm.getCursor().line + 1;
145
+ const r = await api(`/api/synctex/view?path=${encodeURIComponent(state.current)}&line=${line}`);
146
+ if (!r.ok) return setStatus(r.error || 'no PDF location (compile first?)', 'err');
147
+ const div = view.els[r.page - 1]; if (!div) return;
148
+ const y = r.y * view.scales[r.page - 1];
149
+ $('pdfWrap').scrollTop = div.offsetTop + y - $('pdfWrap').clientHeight / 3;
150
+ const m = el('div', { className: 'mark' }); m.style.top = (y - 14) + 'px'; div.appendChild(m);
151
+ setTimeout(() => { m.style.opacity = 0; }, 900); setTimeout(() => m.remove(), 2200);
152
+ }
153
+ $('syncBtn').onclick = syncToPdf;
154
+
155
+ // ---------- splitter ----------
156
+ (() => {
157
+ const main = document.querySelector('main'); let drag = false;
158
+ const side = () => $('side').getBoundingClientRect().width;
159
+ const setCols = f => { main.style.gridTemplateColumns = `${side()}px ${f}fr 6px ${1 - f}fr`; };
160
+ const saved = store.get('split', null); if (saved) setCols(saved);
161
+ $('split').onmousedown = () => { drag = true; document.body.style.userSelect = 'none'; };
162
+ window.addEventListener('mouseup', () => { if (drag) { drag = false; document.body.style.userSelect = ''; loadPdf(); } });
163
+ window.addEventListener('mousemove', e => { if (!drag) return;
164
+ const r = main.getBoundingClientRect(), s = side(), f = Math.min(.8, Math.max(.2, (e.clientX - r.left - s) / (r.width - s - 6)));
165
+ setCols(f); store.set('split', f); app.cm.refresh(); });
166
+ })();
167
+
168
+ // ---------- find in PDF ----------
169
+ const find = { query: '', matches: [], cur: -1, view: null, run: 0 };
170
+
171
+ // Wrap this page's matches in highlight spans inside the text layer, after undoing the previous paint.
172
+ function paintFind(v, i) {
173
+ const divs = v.textDivs[i], t = v.textReady[i]; if (!divs || !t) return;
174
+ for (const k of v.painted[i] || []) divs[k].textContent = t.content.items[k].str;
175
+ const ranges = new Map();
176
+ if (find.view === v) find.matches.forEach((m, n) => {
177
+ if (m.page !== i) return;
178
+ for (const [k, [a, b]] of matchSpans(t.map, m.start, m.end)) { if (!ranges.has(k)) ranges.set(k, []); ranges.get(k).push([a, b, n === find.cur]); }
179
+ });
180
+ for (const [k, rs] of ranges) {
181
+ const s = t.content.items[k].str, parts = []; let pos = 0;
182
+ rs.sort((x, y) => x[0] - y[0]);
183
+ for (const [a, b, cur] of rs) {
184
+ if (a < pos) continue;
185
+ if (a > pos) parts.push(document.createTextNode(s.slice(pos, a)));
186
+ parts.push(el('span', { className: cur ? 'hl cur' : 'hl' }, s.slice(a, b))); pos = b;
187
+ }
188
+ if (pos < s.length) parts.push(document.createTextNode(s.slice(pos)));
189
+ divs[k].replaceChildren(...parts);
190
+ }
191
+ v.painted[i] = [...ranges.keys()];
192
+ }
193
+ function showFindCount() {
194
+ const n = find.matches.length, c = $('findCount');
195
+ c.textContent = !find.query ? '' : n ? `${find.cur + 1} of ${n}` : 'No results';
196
+ c.className = find.query && !n ? 'none' : '';
197
+ }
198
+ // Search every page. jump: the query changed, so select the first match from the visible page on and scroll to
199
+ // it; otherwise (a recompile) keep the current match number and leave the view where it is.
200
+ async function runFind(jump) {
201
+ const v = view, q = normalize($('findInput').value).trim(), run = ++find.run, prev = find.cur;
202
+ const prevView = find.view, prevPages = new Set(find.matches.map(m => m.page));
203
+ const matches = [];
204
+ if (v && q) for (let i = 0; i < v.pages.length; i++) {
205
+ const t = await pageText(v, i);
206
+ if (run !== find.run || v !== view) return; // a newer search or a new PDF took over
207
+ for (const m of findAll(t.text, q)) matches.push({ page: i, ...m });
208
+ }
209
+ Object.assign(find, { query: q, matches, view: v });
210
+ const visible = (parseInt($('pageNum').value, 10) || 1) - 1;
211
+ find.cur = !matches.length ? -1 : jump ? Math.max(0, matches.findIndex(m => m.page >= visible)) : Math.min(Math.max(prev, 0), matches.length - 1);
212
+ if (prevView === v) prevPages.forEach(i => paintFind(v, i)); // clear the old highlights
213
+ if (v) new Set(matches.map(m => m.page)).forEach(i => paintFind(v, i));
214
+ showFindCount();
215
+ if (jump && matches.length) gotoMatch(find.cur);
216
+ }
217
+ async function gotoMatch(n) {
218
+ const v = find.view, total = find.matches.length; if (!v || v !== view || !total) return;
219
+ const old = find.matches[find.cur]; find.cur = (n + total) % total;
220
+ const m = find.matches[find.cur]; showFindCount();
221
+ if (old && old.page !== m.page) paintFind(v, old.page);
222
+ await v.draw(m.page); if (v !== view) return;
223
+ paintFind(v, m.page);
224
+ const e = v.els[m.page].querySelector('.hl.cur'), wrap = $('pdfWrap'); if (!e) return;
225
+ const r = e.getBoundingClientRect(), w = wrap.getBoundingClientRect();
226
+ if (r.top < w.top + 50 || r.bottom > w.bottom - 20) wrap.scrollTop += r.top - w.top - wrap.clientHeight / 3;
227
+ if (r.left < w.left || r.right > w.right) wrap.scrollLeft += r.left - w.left - wrap.clientWidth / 3;
228
+ }
229
+ export function openFind() {
230
+ $('pdfFind').hidden = false; $('findInput').focus(); $('findInput').select();
231
+ if ($('findInput').value.trim() && !find.query) runFind(true);
232
+ }
233
+ function closeFind() {
234
+ $('pdfFind').hidden = true; find.run++;
235
+ const v = find.view, pages = new Set(find.matches.map(m => m.page));
236
+ Object.assign(find, { query: '', matches: [], cur: -1 });
237
+ if (v) pages.forEach(i => paintFind(v, i));
238
+ showFindCount();
239
+ }
240
+ let findT;
241
+ $('findInput').addEventListener('input', () => { clearTimeout(findT); findT = setTimeout(() => runFind(true), 200); });
242
+ $('findInput').addEventListener('keydown', e => {
243
+ if (e.key === 'Enter') {
244
+ e.preventDefault(); clearTimeout(findT);
245
+ if (normalize($('findInput').value).trim() !== find.query || find.view !== view) return runFind(true);
246
+ gotoMatch(find.cur + (e.shiftKey ? -1 : 1));
247
+ } else if (e.key === 'Escape') { e.preventDefault(); closeFind(); }
248
+ });
249
+ $('findNext').onclick = () => gotoMatch(find.cur + 1);
250
+ $('findPrev').onclick = () => gotoMatch(find.cur - 1);
251
+ $('findClose').onclick = closeFind;
252
+ $('findBtn').onclick = openFind;
253
+
254
+ Object.assign(app, { loadPdf, resetPdf, renderPdfPage, syncToPdf, openFind });
@@ -0,0 +1,45 @@
1
+ // Searchable text of a PDF page, from pdf.js text items. Pure functions, tested with `node --test tests/`.
2
+ //
3
+ // The text is lower-cased, compatibility characters are expanded (NFKC, so "fi" and math italic letters match plain
4
+ // text), runs of white space become one space, and line ends are joined, dropping the hyphen of a word broken
5
+ // across lines, so "exam-" + "ple" matches "example". map[n] = [item, from, to] gives the characters of text item
6
+ // `item` that produced text[n]; null for a space inserted at a line end.
7
+
8
+ export const normalize = s => s.normalize('NFKC').toLowerCase().replace(/\s+/g, ' ');
9
+
10
+ export function indexText(items) {
11
+ let text = '';
12
+ const map = [];
13
+ const add = (ch, src) => {
14
+ if (/\s/.test(ch)) { if (!text || text.endsWith(' ')) return; ch = ' '; }
15
+ text += ch; map.push(src);
16
+ };
17
+ items.forEach((it, k) => {
18
+ let o = 0;
19
+ for (const cp of it.str || '') { for (const ch of normalize(cp)) add(ch, [k, o, o + cp.length]); o += cp.length; }
20
+ if (it.hasEOL) {
21
+ if (text.endsWith('-') && /\p{L}/u.test(text.slice(-2, -1))) { text = text.slice(0, -1); map.pop(); }
22
+ else add(' ', null);
23
+ }
24
+ });
25
+ return { text, map };
26
+ }
27
+
28
+ // Every match of an already-normalized query: [{ start, end }] offsets into `text`.
29
+ export function findAll(text, q) {
30
+ const out = [];
31
+ if (!q) return out;
32
+ for (let at = text.indexOf(q); at !== -1; at = text.indexOf(q, at + q.length)) out.push({ start: at, end: at + q.length });
33
+ return out;
34
+ }
35
+
36
+ // The characters of each text item that the match [start, end) covers: Map item -> [from, to].
37
+ export function matchSpans(map, start, end) {
38
+ const out = new Map();
39
+ for (let n = start; n < end; n++) {
40
+ const src = map[n]; if (!src) continue;
41
+ const [k, a, b] = src, r = out.get(k);
42
+ if (r) { r[0] = Math.min(r[0], a); r[1] = Math.max(r[1], b); } else out.set(k, [a, b]);
43
+ }
44
+ return out;
45
+ }
@@ -0,0 +1,72 @@
1
+ // The ⚙ popover: main document, engine, compile only one chapter, draft mode, spell check, word count, shortcuts.
2
+ import { $, el, app, state, project, api, post, setStatus, store } from './util.js';
3
+
4
+ const SOURCES = {
5
+ default: 'the default. To use XeLaTeX or LuaLaTeX, put "% !TEX program = xelatex" (or lualatex) on the first line of the main file.',
6
+ '% !TEX program': 'set by "% !TEX program" in the main file.',
7
+ latexmkrc: "chosen by the project's latexmkrc ($pdf_mode).",
8
+ '--engine': 'set with --engine when the editor was started.',
9
+ };
10
+
11
+ export async function refreshSettings() {
12
+ const s = await api('/api/settings');
13
+ if (!s.ok) return;
14
+ state.settings = s;
15
+ project.main = s.main; $('mainDoc').textContent = s.main;
16
+ const roots = s.roots.includes(s.main) ? s.roots : [s.main, ...s.roots];
17
+ $('mainSelect').replaceChildren(...roots.map(r => el('option', { value: r, selected: r === s.main }, r)));
18
+ $('onlySelect').replaceChildren(el('option', { value: '' }, 'Whole document'),
19
+ ...s.includes.map(i => el('option', { value: i, selected: i === s.only }, i)));
20
+ $('onlySelect').disabled = !s.includes.length;
21
+ $('onlySelect').title = s.includes.length ? 'Compile just one \\include\'d file; page numbers and references of the others are kept'
22
+ : 'The main document has no \\include{…} files';
23
+ $('draftChk').checked = !!s.draft;
24
+ $('engineNote').textContent = `Engine: ${s.engine || 'from latexmkrc'}, ${SOURCES[s.engine_source] || s.engine_source}`;
25
+ $('shellNote').textContent = s.shell_escape
26
+ ? 'Shell escape is on (--shell-escape): this project can run programs when it compiles.'
27
+ : 'Shell escape is off. Packages such as minted (before v3) or svg need --shell-escape.';
28
+ const missing = Object.entries(s.tools).filter(([, ok]) => !ok).map(([t]) => t);
29
+ if (missing.length) $('shellNote').textContent += ` Not installed: ${missing.join(', ')}.`;
30
+ }
31
+
32
+ async function change(body, what) {
33
+ const r = await post('/api/settings', body);
34
+ if (!r.ok) { setStatus(r.error, 'err'); return refreshSettings(); }
35
+ await refreshSettings();
36
+ setStatus(what, 'ok');
37
+ return r;
38
+ }
39
+ $('mainSelect').onchange = async () => {
40
+ const r = await change({ main: $('mainSelect').value }, `main document: ${$('mainSelect').value}`);
41
+ if (!r) return;
42
+ app.resetPdf(); app.renderFiles(); app.refreshOutline(); app.compile();
43
+ };
44
+ $('onlySelect').onchange = async () => { if (await change({ only: $('onlySelect').value || null }, $('onlySelect').value ? `compiling only ${$('onlySelect').value}` : 'compiling the whole document')) app.compile(); };
45
+ $('draftChk').onchange = async () => { if (await change({ draft: $('draftChk').checked }, $('draftChk').checked ? 'draft mode: images are boxes' : 'draft mode off')) app.compile(); };
46
+ $('spellChk').onchange = () => app.setSpellcheck($('spellChk').checked);
47
+ $('spellChk').checked = store.get('spellcheck', false);
48
+
49
+ $('wcBtn').onclick = async () => {
50
+ $('wcNote').textContent = 'counting…';
51
+ const r = await api('/api/wordcount');
52
+ $('wcNote').textContent = r.ok ? `in ${project.main} and the files it includes` : '';
53
+ if (!r.ok) { $('wcOut').replaceChildren(el('div', { className: 'note' }, r.error)); return; }
54
+ const rows = [['Words in text', r.text], ['Words in headings', r.headers], ['Words in captions and the like', r.outside],
55
+ ['Headings', r.n_headers], ['Figures and tables', r.floats], ['Inline formulas', r.math_inline], ['Displayed formulas', r.math_display]];
56
+ $('wcOut').replaceChildren(el('table', {}, ...rows.filter(([, v]) => v !== undefined).map(([k, v]) => el('tr', {}, el('td', {}, k), el('td', {}, String(v))))));
57
+ };
58
+
59
+ // ---------- open and close ----------
60
+ export function openTools() {
61
+ const t = $('tools'), r = $('toolsBtn').getBoundingClientRect();
62
+ t.hidden = false;
63
+ t.style.top = (r.bottom + 6) + 'px';
64
+ t.style.left = Math.max(8, Math.min(innerWidth - t.offsetWidth - 8, r.right - t.offsetWidth)) + 'px';
65
+ $('toolsBtn').setAttribute('aria-expanded', 'true');
66
+ refreshSettings();
67
+ }
68
+ export function closeTools() { $('tools').hidden = true; $('toolsBtn').setAttribute('aria-expanded', 'false'); }
69
+ $('toolsBtn').onclick = () => $('tools').hidden ? openTools() : closeTools();
70
+ document.addEventListener('mousedown', e => { if (!$('tools').hidden && !$('tools').contains(e.target) && e.target !== $('toolsBtn')) closeTools(); });
71
+
72
+ Object.assign(app, { refreshSettings, openTools, closeTools });
@@ -0,0 +1,57 @@
1
+ // Shared helpers and state. Modules register their public functions on `app` (app.openFile, app.compile, …) and
2
+ // call each other through it, so there are no import cycles and the start-up order does not matter.
3
+ export const app = {};
4
+ export const state = { current: null, lastResult: null, settings: null };
5
+ export const project = { root: '', main: 'main.tex', files: [], assets: [] };
6
+
7
+ export const $ = id => document.getElementById(id);
8
+
9
+ // el('div', { className: 'x', onclick }, child, 'text', …)
10
+ export function el(tag, props, ...children) {
11
+ const e = document.createElement(tag);
12
+ if (props) for (const [k, v] of Object.entries(props)) {
13
+ if (k === 'dataset') Object.assign(e.dataset, v); else if (v !== undefined && v !== null) e[k] = v;
14
+ }
15
+ e.append(...children.filter(c => c !== null && c !== undefined && c !== false));
16
+ return e;
17
+ }
18
+
19
+ export const store = {
20
+ get(k, d) { try { const v = localStorage.getItem(k); return v === null ? d : JSON.parse(v); } catch { return d; } },
21
+ set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} },
22
+ };
23
+ // Per-project settings: every project is served from the same origin, so key them by the project root.
24
+ export const pkey = k => `${k}@${project.root}`;
25
+
26
+ export async function api(url, opts) {
27
+ try {
28
+ const r = await fetch(url, opts);
29
+ const j = await r.json().catch(() => ({}));
30
+ return { ...j, ok: r.ok, status: r.status }; // the HTTP outcome wins over any "ok" in the reply
31
+ } catch (e) {
32
+ return { ok: false, status: 0, error: 'the editor server is not reachable' };
33
+ }
34
+ }
35
+ // Every POST is JSON: the server refuses anything else, so another site cannot forge one without a CORS preflight.
36
+ export const post = (url, body) => api(url, { method: 'POST', headers: { 'Content-Type': 'application/json' },
37
+ body: JSON.stringify(body || {}) });
38
+
39
+ export function setStatus(text, cls, title) {
40
+ const s = $('status'); s.textContent = text; s.className = cls || ''; s.title = title || text;
41
+ }
42
+
43
+ export function debounce(fn, ms) {
44
+ let t;
45
+ return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };
46
+ }
47
+
48
+ export const dirOf = p => p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '';
49
+ export const baseName = p => p.slice(p.lastIndexOf('/') + 1);
50
+
51
+ // A button that asks for a second click before doing something destructive (instead of a blocking dialog).
52
+ export function confirmClick(button, question, action, ms = 4000) {
53
+ if (button.dataset.armed) { delete button.dataset.armed; button.textContent = button.dataset.label; button.classList.remove('danger'); action(); return; }
54
+ button.dataset.label = button.textContent; button.dataset.armed = '1';
55
+ button.textContent = question; button.classList.add('danger');
56
+ setTimeout(() => { if (button.dataset.armed) { delete button.dataset.armed; button.textContent = button.dataset.label; button.classList.remove('danger'); } }, ms);
57
+ }
@@ -0,0 +1,29 @@
1
+ # Vendored libraries
2
+
3
+ Bundled so the editor works fully offline. Files are unmodified copies from cdnjs; licenses from the npm packages.
4
+
5
+ | Library | Version | License | Source |
6
+ |---|---|---|---|
7
+ | CodeMirror | 5.65.16 | MIT (`codemirror/LICENSE`) | https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/ |
8
+ | pdf.js | 4.10.38 | Apache-2.0 (`pdfjs/LICENSE`) | https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/ (`pdf.min.mjs`, `pdf.worker.min.mjs`); identical to `build/` in the npm package `pdfjs-dist@4.10.38` |
9
+
10
+ To update, download the same file list at the new version, check it against the npm package, and replace this table and the checksums below (`sha256sum` from this folder; CI checks them). Before choosing a pdf.js version, check its security advisories (github.com/mozilla/pdf.js/security/advisories): 4.10.38 is outside the ranges of CVE-2024-4367 (<= 4.1.392) and CVE-2026-16633 (5.6.83 to 6.2.107).
11
+
12
+ ## SHA-256
13
+
14
+ ```
15
+ a69862c96bb9201693e29c78d041f9085a79785cafaf80a9cb3d228c6f99f828 ./codemirror/addon/dialog/dialog.min.css
16
+ b11516c9c96f4d593f4427d4d70cddcb3520ebe6c19048cd62db641250ea2dc4 ./codemirror/addon/dialog/dialog.min.js
17
+ f359c5f395a2a08191557d40b61ef8c3893803da9019171cc44b8d9c8c7d4a3a ./codemirror/addon/edit/matchbrackets.min.js
18
+ 98d3a590d2d60037ead413dc70aae17b05da6bde62528d2365a540fde4852887 ./codemirror/addon/search/jump-to-line.min.js
19
+ 59c16a8249700b3b6d6c23693e09fb7fbec58c13e330c7815008e77b91da025e ./codemirror/addon/search/search.min.js
20
+ 0b5f19d72d5febca9b2bb3d471489eadd92ff2c18d29fef5335bbb536cba6692 ./codemirror/addon/search/searchcursor.min.js
21
+ bbca0b4ba03a94163a1eaa604b45ef038c12d8572b7cc16a41dd287b40cc998c ./codemirror/addon/selection/active-line.min.js
22
+ 11077112ab6955d29fe41085c62365c7d4a2f00a570c7475e2aec2a8cbc85fc4 ./codemirror/codemirror.min.css
23
+ f102bb61fb2ac45c3a611847edd9948faad0ab22a83a2dfa9974be5031079b15 ./codemirror/codemirror.min.js
24
+ 6d31310a4719d151d198b604864fa7cb7dcaa5013888863585e06d7c7085f3d8 ./codemirror/mode/markdown/markdown.min.js
25
+ 6d19a4ba8b05a354935ceebf490582faffa047c86c4715a2b504b14319eb6399 ./codemirror/mode/python/python.min.js
26
+ ebc5cb8e191cf20207a2477db7dc4ffb08329e9e40d3487b9113ae1c68eafa53 ./codemirror/mode/stex/stex.min.js
27
+ 27fc2a057a00f92a4334ad06e17dbd7259912954e9fb7f76400bcca5fd190a9c ./pdfjs/pdf.min.mjs
28
+ 1baa1844c89c80a5b2797c916e75ab29254be46d8e9cb53cb6364d7aad84be36 ./pdfjs/pdf.worker.min.mjs
29
+ ```
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (C) 2017 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1 @@
1
+ .CodeMirror-dialog{position:absolute;left:0;right:0;background:inherit;z-index:15;padding:.1em .8em;overflow:hidden;color:inherit}.CodeMirror-dialog-top{border-bottom:1px solid #eee;top:0}.CodeMirror-dialog-bottom{border-top:1px solid #eee;bottom:0}.CodeMirror-dialog input{border:none;outline:0;background:0 0;width:20em;color:inherit;font-family:monospace}.CodeMirror-dialog button{font-size:70%}
@@ -0,0 +1 @@
1
+ !function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(s){function f(e,o,n){var e=e.getWrapperElement(),t=e.appendChild(document.createElement("div"));return t.className=n?"CodeMirror-dialog CodeMirror-dialog-bottom":"CodeMirror-dialog CodeMirror-dialog-top","string"==typeof o?t.innerHTML=o:t.appendChild(o),s.addClass(e,"dialog-opened"),t}function p(e,o){e.state.currentNotificationClose&&e.state.currentNotificationClose(),e.state.currentNotificationClose=o}s.defineExtension("openDialog",function(e,o,n){n=n||{},p(this,null);var t=f(this,e,n.bottom),i=!1,r=this;function u(e){"string"==typeof e?l.value=e:i||(i=!0,s.rmClass(t.parentNode,"dialog-opened"),t.parentNode.removeChild(t),r.focus(),n.onClose&&n.onClose(t))}var l=t.getElementsByTagName("input")[0];return l?(l.focus(),n.value&&(l.value=n.value,!1!==n.selectValueOnOpen&&l.select()),n.onInput&&s.on(l,"input",function(e){n.onInput(e,l.value,u)}),n.onKeyUp&&s.on(l,"keyup",function(e){n.onKeyUp(e,l.value,u)}),s.on(l,"keydown",function(e){n&&n.onKeyDown&&n.onKeyDown(e,l.value,u)||((27==e.keyCode||!1!==n.closeOnEnter&&13==e.keyCode)&&(l.blur(),s.e_stop(e),u()),13==e.keyCode&&o(l.value,e))}),!1!==n.closeOnBlur&&s.on(t,"focusout",function(e){null!==e.relatedTarget&&u()})):(e=t.getElementsByTagName("button")[0])&&(s.on(e,"click",function(){u(),r.focus()}),!1!==n.closeOnBlur&&s.on(e,"blur",u),e.focus()),u}),s.defineExtension("openConfirm",function(e,o,n){p(this,null);var t=f(this,e,n&&n.bottom),i=t.getElementsByTagName("button"),r=!1,u=this,l=1;function a(){r||(r=!0,s.rmClass(t.parentNode,"dialog-opened"),t.parentNode.removeChild(t),u.focus())}i[0].focus();for(var c=0;c<i.length;++c){var d=i[c];!function(o){s.on(d,"click",function(e){s.e_preventDefault(e),a(),o&&o(u)})}(o[c]),s.on(d,"blur",function(){--l,setTimeout(function(){l<=0&&a()},200)}),s.on(d,"focus",function(){++l})}}),s.defineExtension("openNotification",function(e,o){p(this,r);var n,t=f(this,e,o&&o.bottom),i=!1,e=o&&void 0!==o.duration?o.duration:5e3;function r(){i||(i=!0,clearTimeout(n),s.rmClass(t.parentNode,"dialog-opened"),t.parentNode.removeChild(t))}return s.on(t,"click",function(e){s.e_preventDefault(e),r()}),e&&(n=setTimeout(r,e)),r})});
@@ -0,0 +1 @@
1
+ !function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],t):t(CodeMirror)}(function(r){var u=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),k=r.Pos,p={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<","<":">>",">":"<<"};function y(t){return t&&t.bracketRegex||/[(){}[\]]/}function f(t,e,n){var r=t.getLineHandle(e.line),i=e.ch-1,c=n&&n.afterCursor,a=(null==c&&(c=/(^| )cm-fat-cursor($| )/.test(t.getWrapperElement().className)),y(n)),c=!c&&0<=i&&a.test(r.text.charAt(i))&&p[r.text.charAt(i)]||a.test(r.text.charAt(i+1))&&p[r.text.charAt(++i)];if(!c)return null;a=">"==c.charAt(1)?1:-1;if(n&&n.strict&&0<a!=(i==e.ch))return null;r=t.getTokenTypeAt(k(e.line,i+1)),t=o(t,k(e.line,i+(0<a?1:0)),a,r,n);return null==t?null:{from:k(e.line,i),to:t&&t.pos,match:t&&t.ch==c.charAt(0),forward:0<a}}function o(t,e,n,r,i){for(var c=i&&i.maxScanLineLength||1e4,a=i&&i.maxScanLines||1e3,o=[],h=y(i),l=0<n?Math.min(e.line+a,t.lastLine()+1):Math.max(t.firstLine()-1,e.line-a),s=e.line;s!=l;s+=n){var u=t.getLine(s);if(u){var f=0<n?0:u.length-1,m=0<n?u.length:-1;if(!(u.length>c))for(s==e.line&&(f=e.ch-(n<0?1:0));f!=m;f+=n){var g=u.charAt(f);if(h.test(g)&&(void 0===r||(t.getTokenTypeAt(k(s,f+1))||"")==(r||""))){var d=p[g];if(d&&">"==d.charAt(1)==0<n)o.push(g);else{if(!o.length)return{pos:k(s,f),ch:g};o.pop()}}}}}return s-n!=(0<n?t.lastLine():t.firstLine())&&null}function e(t,e,n){for(var r=t.state.matchBrackets.maxHighlightLineLength||1e3,i=n&&n.highlightNonMatching,c=[],a=t.listSelections(),o=0;o<a.length;o++){var h,l=a[o].empty()&&f(t,a[o].head,n);l&&(l.match||!1!==i)&&t.getLine(l.from.line).length<=r&&(h=l.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket",c.push(t.markText(l.from,k(l.from.line,l.from.ch+1),{className:h})),l.to&&t.getLine(l.to.line).length<=r&&c.push(t.markText(l.to,k(l.to.line,l.to.ch+1),{className:h})))}if(c.length){u&&t.state.focused&&t.focus();function s(){t.operation(function(){for(var t=0;t<c.length;t++)c[t].clear()})}if(!e)return s;setTimeout(s,800)}}function i(t){t.operation(function(){t.state.matchBrackets.currentlyHighlighted&&(t.state.matchBrackets.currentlyHighlighted(),t.state.matchBrackets.currentlyHighlighted=null),t.state.matchBrackets.currentlyHighlighted=e(t,!1,t.state.matchBrackets)})}function c(t){t.state.matchBrackets&&t.state.matchBrackets.currentlyHighlighted&&(t.state.matchBrackets.currentlyHighlighted(),t.state.matchBrackets.currentlyHighlighted=null)}r.defineOption("matchBrackets",!1,function(t,e,n){n&&n!=r.Init&&(t.off("cursorActivity",i),t.off("focus",i),t.off("blur",c),c(t)),e&&(t.state.matchBrackets="object"==typeof e?e:{},t.on("cursorActivity",i),t.on("focus",i),t.on("blur",c))}),r.defineExtension("matchBrackets",function(){e(this,!0)}),r.defineExtension("findMatchingBracket",function(t,e,n){return f(this,t,e=!n&&"boolean"!=typeof e?e:n?(n.strict=e,n):e?{strict:!0}:null)}),r.defineExtension("scanForBracket",function(t,e,n,r){return o(this,t,e,n,r)})});
@@ -0,0 +1 @@
1
+ !function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror"),require("../dialog/dialog")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../dialog/dialog"],e):e(CodeMirror)}(function(e){"use strict";function l(e,o){var r=Number(o);return/^[-+]/.test(o)?e.getCursor().line+r:r-1}e.defineOption("search",{bottom:!1}),e.commands.jumpToLine=function(t){var e,o,r,s,i,n=t.getCursor();i=(i=e=t).phrase("Jump to line:")+' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">'+i.phrase("(Use line:column or scroll% syntax)")+"</span>",o=t.phrase("Jump to line:"),r=n.line+1+":"+n.ch,s=function(e){var o,r;e&&((o=/^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(e))?t.setCursor(l(t,o[1]),Number(o[2])):(o=/^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(e))?(r=Math.round(t.lineCount()*Number(o[1])/100),/^[-+]/.test(o[1])&&(r=n.line+r+1),t.setCursor(r-1,n.ch)):(o=/^\s*\:?\s*([\+\-]?\d+)\s*/.exec(e))&&t.setCursor(l(t,o[1]),n.ch))},e.openDialog?e.openDialog(i,s,{value:r,selectValueOnOpen:!0,bottom:e.options.search.bottom}):s(prompt(o,r))},e.keyMap.default["Alt-G"]="jumpToLine"});
@@ -0,0 +1 @@
1
+ !function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror"),require("./searchcursor"),require("../dialog/dialog")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./searchcursor","../dialog/dialog"],e):e(CodeMirror)}(function(f){"use strict";function r(){this.posFrom=this.posTo=this.lastQuery=this.query=null,this.overlay=null}function p(e){return e.state.search||(e.state.search=new r)}function n(e){return"string"==typeof e&&e==e.toLowerCase()}function d(e,r,o){return e.getSearchCursor(r,o,{caseFold:n(r),multiline:!0})}function m(e,r,o,t,n){e.openDialog?e.openDialog(r,n,{value:t,selectValueOnOpen:!0,bottom:e.options.search.bottom}):n(prompt(o,t))}function h(e){return e.replace(/\\([nrt\\])/g,function(e,r){return"n"==r?"\n":"r"==r?"\r":"t"==r?"\t":"\\"==r?"\\":e})}function a(e){var r=e.match(/^\/(.*)\/([a-z]*)$/);if(r)try{e=new RegExp(r[1],-1==r[2].indexOf("i")?"":"i")}catch(e){}else e=h(e);return e=("string"==typeof e?""==e:e.test(""))?/x^/:e}function y(e,r,o){var t;r.queryText=o,r.query=a(o),e.removeOverlay(r.overlay,n(r.query)),r.overlay=(t=r.query,o=n(r.query),"string"==typeof t?t=new RegExp(t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),o?"gi":"g"):t.global||(t=new RegExp(t.source,t.ignoreCase?"gi":"g")),{token:function(e){t.lastIndex=e.pos;var r=t.exec(e.string);if(r&&r.index==e.pos)return e.pos+=r[0].length||1,"searching";r?e.pos=r.index:e.skipToEnd()}}),e.addOverlay(r.overlay),e.showMatchesOnScrollbar&&(r.annotate&&(r.annotate.clear(),r.annotate=null),r.annotate=e.showMatchesOnScrollbar(r.query,n(r.query)))}function o(n,r,e,o){var t=p(n);if(t.query)return g(n,r);var a,i,s,c,l,u=n.getSelection()||t.lastQuery;u instanceof RegExp&&"x^"==u.source&&(u=null),e&&n.openDialog?(a=null,i=function(e,r){f.e_stop(r),e&&(e!=t.queryText&&(y(n,t,e),t.posFrom=t.posTo=n.getCursor()),a&&(a.style.opacity=1),g(n,r.shiftKey,function(e,r){var o;r.line<3&&document.querySelector&&(o=n.display.wrapper.querySelector(".CodeMirror-dialog"))&&o.getBoundingClientRect().bottom-4>n.cursorCoords(r,"window").top&&((a=o).style.opacity=.4)}))},e=C(s=n),c=u,l=function(e,r){var o=f.keyName(e),t=n.getOption("extraKeys"),t=t&&t[o]||f.keyMap[n.getOption("keyMap")][o];"findNext"==t||"findPrev"==t||"findPersistentNext"==t||"findPersistentPrev"==t?(f.e_stop(e),y(n,p(n),r),n.execCommand(t)):"find"!=t&&"findPersistent"!=t||(f.e_stop(e),i(r,e))},s.openDialog(e,i,{value:c,selectValueOnOpen:!0,closeOnEnter:!1,onClose:function(){v(s)},onKeyDown:l,bottom:s.options.search.bottom}),o&&u&&(y(n,t,u),g(n,r))):m(n,C(n),"Search for:",u,function(e){e&&!t.query&&n.operation(function(){y(n,t,e),t.posFrom=t.posTo=n.getCursor(),g(n,r)})})}function g(o,t,n){o.operation(function(){var e=p(o),r=d(o,e.query,t?e.posFrom:e.posTo);(r.find(t)||(r=d(o,e.query,t?f.Pos(o.lastLine()):f.Pos(o.firstLine(),0))).find(t))&&(o.setSelection(r.from(),r.to()),o.scrollIntoView({from:r.from(),to:r.to()},20),e.posFrom=r.from(),e.posTo=r.to(),n&&n(r.from(),r.to()))})}function v(r){r.operation(function(){var e=p(r);e.lastQuery=e.query,e.query&&(e.query=e.queryText=null,r.removeOverlay(e.overlay),e.annotate&&(e.annotate.clear(),e.annotate=null))})}function x(e,r){var o,t=e?document.createElement(e):document.createDocumentFragment();for(o in r)t[o]=r[o];for(var n=2;n<arguments.length;n++){var a=arguments[n];t.appendChild("string"==typeof a?document.createTextNode(a):a)}return t}function C(e){var r=x("label",{className:"CodeMirror-search-label"},e.phrase("Search:"),x("input",{type:"text",style:"width: 10em",className:"CodeMirror-search-field",id:"CodeMirror-search-field"}));return r.setAttribute("for","CodeMirror-search-field"),x("",null,r," ",x("span",{style:"color: #666",className:"CodeMirror-search-hint"},e.phrase("(Use /re/ syntax for regexp search)")))}function b(r,t,n){r.operation(function(){for(var o,e=d(r,t);e.findNext();)"string"!=typeof t?(o=r.getRange(e.from(),e.to()).match(t),e.replace(n.replace(/\$(\d)/g,function(e,r){return o[r]}))):e.replace(n)})}function t(u,e){var r,o,t;u.getOption("readOnly")||(r=u.getSelection()||p(u).lastQuery,t=x("",null,x("span",{className:"CodeMirror-search-label"},o=e?u.phrase("Replace all:"):u.phrase("Replace:")),(t=u,x("",null," ",x("input",{type:"text",style:"width: 10em",className:"CodeMirror-search-field"})," ",x("span",{style:"color: #666",className:"CodeMirror-search-hint"},t.phrase("(Use /re/ syntax for regexp search)"))))),m(u,t,o,r,function(l){l&&(l=a(l),m(u,x("",null,x("span",{className:"CodeMirror-search-label"},u.phrase("With:"))," ",x("input",{type:"text",style:"width: 10em",className:"CodeMirror-search-field"})),u.phrase("Replace with:"),"",function(a){var i,s,c;a=h(a),e?b(u,l,a):(v(u),i=d(u,l,u.getCursor("from")),c=function(o){i.replace("string"==typeof l?a:a.replace(/\$(\d)/g,function(e,r){return o[r]})),s()},(s=function(){var e,r,o,t,n=i.from();!(e=i.findNext())&&(i=d(u,l),!(e=i.findNext())||n&&i.from().line==n.line&&i.from().ch==n.ch)||(u.setSelection(i.from(),i.to()),u.scrollIntoView({from:i.from(),to:i.to()}),t=x("",null,x("span",{className:"CodeMirror-search-label"},(t=n=u).phrase("Replace?"))," ",x("button",{},t.phrase("Yes"))," ",x("button",{},t.phrase("No"))," ",x("button",{},t.phrase("All"))," ",x("button",{},t.phrase("Stop"))),r=u.phrase("Replace?"),o=[function(){c(e)},s,function(){b(u,l,a)}],n.openConfirm?n.openConfirm(t,o):confirm(r)&&o[0]())})())}))}))}f.defineOption("search",{bottom:!1}),f.commands.find=function(e){v(e),o(e)},f.commands.findPersistent=function(e){v(e),o(e,!1,!0)},f.commands.findPersistentNext=function(e){o(e,!1,!0,!0)},f.commands.findPersistentPrev=function(e){o(e,!0,!0,!0)},f.commands.findNext=o,f.commands.findPrev=function(e){o(e,!0)},f.commands.clearSearch=v,f.commands.replace=t,f.commands.replaceAll=function(e){t(e,!0)}});
@@ -0,0 +1 @@
1
+ !function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],t):t(CodeMirror)}(function(r){"use strict";var p,v,x=r.Pos;function m(t,e){for(var n,i=null!=(i=(n=t).flags)?i:(n.ignoreCase?"i":"")+(n.global?"g":"")+(n.multiline?"m":""),r=i,o=0;o<e.length;o++)-1==r.indexOf(e.charAt(o))&&(r+=e.charAt(o));return i==r?t:new RegExp(t.source,r)}function d(t){return/\\s|\\n|\n|\\W|\\D|\[\^/.test(t.source)}function a(t,e,n){e=m(e,"g");for(var i=n.line,r=n.ch,o=t.lastLine();i<=o;i++,r=0){e.lastIndex=r;var h=t.getLine(i),h=e.exec(h);if(h)return{from:x(i,h.index),to:x(i,h.index+h[0].length),match:h}}}function o(t,e,n){if(!d(e))return a(t,e,n);e=m(e,"gm");for(var i=1,r=n.line,o=t.lastLine();r<=o;){for(var h=0;h<i&&!(o<r);h++)var l=t.getLine(r++),c=null==c?l:c+"\n"+l;i*=2,e.lastIndex=n.ch;var s,f,g,u=e.exec(c);if(u)return g=c.slice(0,u.index).split("\n"),s=u[0].split("\n"),f=n.line+g.length-1,g=g[g.length-1].length,{from:x(f,g),to:x(f+s.length-1,1==s.length?g+s[0].length:s[s.length-1].length),match:u}}}function L(t,e,n){for(var i,r=0;r<=t.length;){e.lastIndex=r;var o=e.exec(t);if(!o)break;var h=o.index+o[0].length;if(h>t.length-n)break;(!i||h>i.index+i[0].length)&&(i=o),r=o.index+1}return i}function O(t,e,n){e=m(e,"g");for(var i=n.line,r=n.ch,o=t.firstLine();o<=i;i--,r=-1){var h=t.getLine(i),h=L(h,e,r<0?0:h.length-r);if(h)return{from:x(i,h.index),to:x(i,h.index+h[0].length),match:h}}}function h(t,e,n){if(!d(e))return O(t,e,n);e=m(e,"gm");for(var i=1,r=t.getLine(n.line).length-n.ch,o=n.line,h=t.firstLine();h<=o;){for(var l=0;l<i&&h<=o;l++)var c=t.getLine(o--),s=null==s?c:c+"\n"+s;i*=2;var f,g,u,a=L(s,e,r);if(a)return u=s.slice(0,a.index).split("\n"),f=a[0].split("\n"),g=o+u.length,u=u[u.length-1].length,{from:x(g,u),to:x(g+f.length-1,1==f.length?u+f[0].length:f[f.length-1].length),match:a}}}function y(t,e,n,i){if(t.length==e.length)return n;for(var r=0,o=n+Math.max(0,t.length-e.length);;){if(r==o)return r;var h=r+o>>1,l=i(t.slice(0,h)).length;if(l==n)return h;n<l?o=h:r=1+h}}function l(t,e,n,i){if(!e.length)return null;var r=i?p:v,o=r(e).split(/\r|\n\r?/);t:for(var h=n.line,l=n.ch,c=t.lastLine()+1-o.length;h<=c;h++,l=0){var s=t.getLine(h).slice(l),f=r(s);if(1==o.length){var g=f.indexOf(o[0]);if(-1==g);else return n=y(s,f,g,r)+l,{from:x(h,y(s,f,g,r)+l),to:x(h,y(s,f,g+o[0].length,r)+l)}}else{g=f.length-o[0].length;if(f.slice(g)==o[0]){for(var u=1;u<o.length-1;u++)if(r(t.getLine(h+u))!=o[u])continue t;var a=t.getLine(h+o.length-1),m=r(a),d=o[o.length-1];if(m.slice(0,d.length)==d)return{from:x(h,y(s,f,g,r)+l),to:x(h+o.length-1,y(a,m,d.length,r))}}}}}function c(t,e,n,i){if(!e.length)return null;var r=i?p:v,o=r(e).split(/\r|\n\r?/);t:for(var h=n.line,l=n.ch,c=t.firstLine()-1+o.length;c<=h;h--,l=-1){var s=t.getLine(h),f=r(s=-1<l?s.slice(0,l):s);if(1==o.length){var g=f.lastIndexOf(o[0]);if(-1!=g)return{from:x(h,y(s,f,g,r)),to:x(h,y(s,f,g+o[0].length,r))}}else{g=o[o.length-1];if(f.slice(0,g.length)==g){for(var u=1,n=h-o.length+1;u<o.length-1;u++)if(r(t.getLine(n+u))!=o[u])continue t;var a=t.getLine(h+1-o.length),m=r(a);if(m.slice(m.length-o[0].length)==o[0])return{from:x(h+1-o.length,y(a,m,a.length-o[0].length,r)),to:x(h,y(s,f,g.length,r))}}}}}function i(n,i,t,e){var r;this.atOccurrence=!1,this.afterEmptyMatch=!1,this.doc=n,t=t?n.clipPos(t):x(0,0),this.pos={from:t,to:t},"object"==typeof e?r=e.caseFold:(r=e,e=null),"string"==typeof i?(null==r&&(r=!1),this.matches=function(t,e){return(t?c:l)(n,i,e,r)}):(i=m(i,"gm"),e&&!1===e.multiline?this.matches=function(t,e){return(t?O:a)(n,i,e)}:this.matches=function(t,e){return(t?h:o)(n,i,e)})}v=String.prototype.normalize?(p=function(t){return t.normalize("NFD").toLowerCase()},function(t){return t.normalize("NFD")}):(p=function(t){return t.toLowerCase()},function(t){return t}),i.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(t){var e=this.doc.clipPos(t?this.pos.from:this.pos.to);if(this.afterEmptyMatch&&this.atOccurrence&&(e=x(e.line,e.ch),t?(e.ch--,e.ch<0&&(e.line--,e.ch=(this.doc.getLine(e.line)||"").length)):(e.ch++,e.ch>(this.doc.getLine(e.line)||"").length&&(e.ch=0,e.line++)),0!=r.cmpPos(e,this.doc.clipPos(e))))return this.atOccurrence=!1;var e=this.matches(t,e);return this.afterEmptyMatch=e&&0==r.cmpPos(e.from,e.to),e?(this.pos=e,this.atOccurrence=!0,this.pos.match||!0):(e=x(t?this.doc.firstLine():this.doc.lastLine()+1,0),this.pos={from:e,to:e},this.atOccurrence=!1)},from:function(){if(this.atOccurrence)return this.pos.from},to:function(){if(this.atOccurrence)return this.pos.to},replace:function(t,e){this.atOccurrence&&(t=r.splitLines(t),this.doc.replaceRange(t,this.pos.from,this.pos.to,e),this.pos.to=x(this.pos.from.line+t.length-1,t[t.length-1].length+(1==t.length?this.pos.from.ch:0)))}},r.defineExtension("getSearchCursor",function(t,e,n){return new i(this.doc,t,e,n)}),r.defineDocExtension("getSearchCursor",function(t,e,n){return new i(this,t,e,n)}),r.defineExtension("selectMatches",function(t,e){for(var n=[],i=this.getSearchCursor(t,this.getCursor("from"),e);i.findNext()&&!(0<r.cmpPos(i.to(),this.getCursor("to")));)n.push({anchor:i.from(),head:i.to()});n.length&&this.setSelections(n,0)})});
@@ -0,0 +1 @@
1
+ !function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(i){"use strict";var a="CodeMirror-activeline",s="CodeMirror-activeline-background",c="CodeMirror-activeline-gutter";function l(e){for(var t=0;t<e.state.activeLines.length;t++)e.removeLineClass(e.state.activeLines[t],"wrap",a),e.removeLineClass(e.state.activeLines[t],"background",s),e.removeLineClass(e.state.activeLines[t],"gutter",c)}function o(t,e){for(var n=[],i=0;i<e.length;i++){var o=e[i],r=t.getOption("styleActiveLine");("object"==typeof r&&r.nonEmpty?o.anchor.line==o.head.line:o.empty())&&(r=t.getLineHandleVisualStart(o.head.line),n[n.length-1]!=r&&n.push(r))}!function(e,t){if(e.length==t.length){for(var n=0;n<e.length;n++)if(e[n]!=t[n])return;return 1}}(t.state.activeLines,n)&&t.operation(function(){l(t);for(var e=0;e<n.length;e++)t.addLineClass(n[e],"wrap",a),t.addLineClass(n[e],"background",s),t.addLineClass(n[e],"gutter",c);t.state.activeLines=n})}function r(e,t){o(e,t.ranges)}i.defineOption("styleActiveLine",!1,function(e,t,n){n=n!=i.Init&&n;t!=n&&(n&&(e.off("beforeSelectionChange",r),l(e),delete e.state.activeLines),t&&(e.state.activeLines=[],o(e,e.listSelections()),e.on("beforeSelectionChange",r)))})});
@@ -0,0 +1 @@
1
+ .CodeMirror{font-family:monospace;height:300px;color:#000;direction:ltr}.CodeMirror-lines{padding:4px 0}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{padding:0 4px}.CodeMirror-gutter-filler,.CodeMirror-scrollbar-filler{background-color:#fff}.CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;white-space:nowrap}.CodeMirror-guttermarker{color:#000}.CodeMirror-guttermarker-subtle{color:#999}.CodeMirror-cursor{border-left:1px solid #000;border-right:none;width:0}.CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.cm-fat-cursor .CodeMirror-cursor{width:auto;border:0!important;background:#7e7}.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.cm-fat-cursor .CodeMirror-line::selection,.cm-fat-cursor .CodeMirror-line>span::selection,.cm-fat-cursor .CodeMirror-line>span>span::selection{background:0 0}.cm-fat-cursor .CodeMirror-line::-moz-selection,.cm-fat-cursor .CodeMirror-line>span::-moz-selection,.cm-fat-cursor .CodeMirror-line>span>span::-moz-selection{background:0 0}.cm-fat-cursor{caret-color:transparent}@-moz-keyframes blink{50%{background-color:transparent}}@-webkit-keyframes blink{50%{background-color:transparent}}@keyframes blink{50%{background-color:transparent}}.cm-tab{display:inline-block;text-decoration:inherit}.CodeMirror-rulers{position:absolute;left:0;right:0;top:-50px;bottom:0;overflow:hidden}.CodeMirror-ruler{border-left:1px solid #ccc;top:0;bottom:0;position:absolute}.cm-s-default .cm-header{color:#00f}.cm-s-default .cm-quote{color:#090}.cm-negative{color:#d44}.cm-positive{color:#292}.cm-header,.cm-strong{font-weight:700}.cm-em{font-style:italic}.cm-link{text-decoration:underline}.cm-strikethrough{text-decoration:line-through}.cm-s-default .cm-keyword{color:#708}.cm-s-default .cm-atom{color:#219}.cm-s-default .cm-number{color:#164}.cm-s-default .cm-def{color:#00f}.cm-s-default .cm-variable-2{color:#05a}.cm-s-default .cm-type,.cm-s-default .cm-variable-3{color:#085}.cm-s-default .cm-comment{color:#a50}.cm-s-default .cm-string{color:#a11}.cm-s-default .cm-string-2{color:#f50}.cm-s-default .cm-meta{color:#555}.cm-s-default .cm-qualifier{color:#555}.cm-s-default .cm-builtin{color:#30a}.cm-s-default .cm-bracket{color:#997}.cm-s-default .cm-tag{color:#170}.cm-s-default .cm-attribute{color:#00c}.cm-s-default .cm-hr{color:#999}.cm-s-default .cm-link{color:#00c}.cm-s-default .cm-error{color:red}.cm-invalidchar{color:red}.CodeMirror-composing{border-bottom:2px solid}div.CodeMirror span.CodeMirror-matchingbracket{color:#0b0}div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#a22}.CodeMirror-matchingtag{background:rgba(255,150,0,.3)}.CodeMirror-activeline-background{background:#e8f2ff}.CodeMirror{position:relative;overflow:hidden;background:#fff}.CodeMirror-scroll{overflow:scroll!important;margin-bottom:-50px;margin-right:-50px;padding-bottom:50px;height:100%;outline:0;position:relative;z-index:0}.CodeMirror-sizer{position:relative;border-right:50px solid transparent}.CodeMirror-gutter-filler,.CodeMirror-hscrollbar,.CodeMirror-scrollbar-filler,.CodeMirror-vscrollbar{position:absolute;z-index:6;display:none;outline:0}.CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.CodeMirror-scrollbar-filler{right:0;bottom:0}.CodeMirror-gutter-filler{left:0;bottom:0}.CodeMirror-gutters{position:absolute;left:0;top:0;min-height:100%;z-index:3}.CodeMirror-gutter{white-space:normal;height:100%;display:inline-block;vertical-align:top;margin-bottom:-50px}.CodeMirror-gutter-wrapper{position:absolute;z-index:4;background:0 0!important;border:none!important}.CodeMirror-gutter-background{position:absolute;top:0;bottom:0;z-index:4}.CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.CodeMirror-gutter-wrapper ::selection{background-color:transparent}.CodeMirror-gutter-wrapper ::-moz-selection{background-color:transparent}.CodeMirror-lines{cursor:text;min-height:1px}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:0 0;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible;-webkit-tap-highlight-color:transparent;-webkit-font-variant-ligatures:contextual;font-variant-ligatures:contextual}.CodeMirror-wrap pre.CodeMirror-line,.CodeMirror-wrap pre.CodeMirror-line-like{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.CodeMirror-linewidget{position:relative;z-index:2;padding:.1px}.CodeMirror-rtl pre{direction:rtl}.CodeMirror-code{outline:0}.CodeMirror-gutter,.CodeMirror-gutters,.CodeMirror-linenumber,.CodeMirror-scroll,.CodeMirror-sizer{-moz-box-sizing:content-box;box-sizing:content-box}.CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.CodeMirror-cursor{position:absolute;pointer-events:none}.CodeMirror-measure pre{position:static}div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}div.CodeMirror-dragcursors{visibility:visible}.CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.CodeMirror-selected{background:#d9d9d9}.CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.CodeMirror-crosshair{cursor:crosshair}.CodeMirror-line::selection,.CodeMirror-line>span::selection,.CodeMirror-line>span>span::selection{background:#d7d4f0}.CodeMirror-line::-moz-selection,.CodeMirror-line>span::-moz-selection,.CodeMirror-line>span>span::-moz-selection{background:#d7d4f0}.cm-searching{background-color:#ffa;background-color:rgba(255,255,0,.4)}.cm-force-border{padding-right:.1px}@media print{.CodeMirror div.CodeMirror-cursors{visibility:hidden}}.cm-tab-wrap-hack:after{content:''}span.CodeMirror-selectedtext{background:0 0}