M2.2: PHP highlighting, syntax colour tokens and editor.reveal
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f13a49064d
commit
6c75c08d70
25 changed files with 1044 additions and 33 deletions
|
|
@ -5,7 +5,8 @@
|
|||
*
|
||||
* Save, save all and close run through the global keymap and the
|
||||
* palette (`commands/store.ts`): the area supplies their behaviour with the
|
||||
* active buffer as context and says when they can run.
|
||||
* active buffer as context and says when they can run. It also supplies the
|
||||
* UI command `editor.reveal` (`reveal.ts`).
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted } from "vue";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
|
|
@ -14,6 +15,7 @@ import { useEditorStore } from "../../stores/editor";
|
|||
import ClosePrompt from "./ClosePrompt.vue";
|
||||
import CodeEditor from "./CodeEditor.vue";
|
||||
import EditorTabs from "./EditorTabs.vue";
|
||||
import { reveal, REVEAL_COMMAND } from "./reveal";
|
||||
|
||||
const editor = useEditorStore();
|
||||
const commands = useCommandsStore();
|
||||
|
|
@ -28,6 +30,7 @@ onMounted(() => {
|
|||
commands.provide("file.save", { run: async () => { await editor.save(); }, enabled: hasActive }),
|
||||
commands.provide("file.saveAll", { run: () => editor.saveAll(), enabled: () => editor.tabs.length > 0 }),
|
||||
commands.provide("buffer.close", { run: () => editor.requestClose(), enabled: hasActive }),
|
||||
commands.provide(REVEAL_COMMAND, { run: (params) => reveal(editor, params) }),
|
||||
];
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -212,3 +212,25 @@ export function diffDocs(from: Text, to: Text): ChangeSet {
|
|||
a.length,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The CodeMirror position of an engine `{line, column}` position.
|
||||
*
|
||||
* Engine lines are split at the same breaks CodeMirror recognises, and a
|
||||
* `\r\n` counts as one break on both sides, so line numbers carry over
|
||||
* unchanged; the column counts UTF-16 code units inside the line, which is
|
||||
* the same in both. A line past the end selects the last line, a column past
|
||||
* the line's end (into a `\r\n`, say) its end, and negative or fractional
|
||||
* values are clamped and truncated (non-finite ones count as 0). Converting the result back with
|
||||
* {@link EngineText.toEngine} yields the engine offset.
|
||||
*
|
||||
* @param doc - the CodeMirror document.
|
||||
* @param line - 0-based line.
|
||||
* @param column - 0-based column in UTF-16 code units.
|
||||
* @returns the position in `doc`.
|
||||
*/
|
||||
export function positionOf(doc: Text, line: number, column: number): number {
|
||||
const whole = (n: number): number => (Number.isFinite(n) ? Math.max(Math.trunc(n), 0) : 0);
|
||||
const target = doc.line(Math.min(whole(line) + 1, doc.lines));
|
||||
return target.from + Math.min(whole(column), target.length);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
/**
|
||||
* CodeMirror extensions of the Lutra editor: the basic setup (line numbers,
|
||||
* history, selection, brackets, search) without a language (PHP comes in
|
||||
* M2), and a theme that takes every colour from `--lt-*` tokens, including
|
||||
* history, selection, brackets, search), the file's language and syntax
|
||||
* highlighting (`language.ts`), and a theme that takes every colour from
|
||||
* `--lt-*` tokens, including the syntax tokens (`--lt-syntax-*`) and
|
||||
* the editor tokens (`--lt-editor-selection-bg`, `--lt-editor-active-line-bg`,
|
||||
* `--lt-editor-cursor`, `--lt-editor-gutter-bg`, `--lt-editor-gutter-fg`,
|
||||
* `--lt-editor-match-bg`, `--lt-font-size-editor`).
|
||||
|
|
@ -9,6 +10,25 @@
|
|||
import { EditorView } from "@codemirror/view";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { basicSetup } from "codemirror";
|
||||
import { languageExtensions, type SYNTAX_CLASS, type SyntaxToken } from "./language";
|
||||
|
||||
/**
|
||||
* Colours of the highlight classes (`language.ts`), one `--lt-syntax-*`
|
||||
* token each, spelled out so the theme tests can check every token name.
|
||||
*/
|
||||
const syntaxColours: Record<`.${typeof SYNTAX_CLASS}${SyntaxToken}`, { color: string }> = {
|
||||
".lt-syntax-keyword": { color: "var(--lt-syntax-keyword)" },
|
||||
".lt-syntax-string": { color: "var(--lt-syntax-string)" },
|
||||
".lt-syntax-number": { color: "var(--lt-syntax-number)" },
|
||||
".lt-syntax-comment": { color: "var(--lt-syntax-comment)" },
|
||||
".lt-syntax-variable": { color: "var(--lt-syntax-variable)" },
|
||||
".lt-syntax-function": { color: "var(--lt-syntax-function)" },
|
||||
".lt-syntax-type": { color: "var(--lt-syntax-type)" },
|
||||
".lt-syntax-constant": { color: "var(--lt-syntax-constant)" },
|
||||
".lt-syntax-tag": { color: "var(--lt-syntax-tag)" },
|
||||
".lt-syntax-attribute": { color: "var(--lt-syntax-attribute)" },
|
||||
".lt-syntax-operator": { color: "var(--lt-syntax-operator)" },
|
||||
};
|
||||
|
||||
/** Editor theme built from theme tokens only. */
|
||||
export const lutraEditorTheme: Extension = EditorView.theme({
|
||||
|
|
@ -80,9 +100,15 @@ export const lutraEditorTheme: Extension = EditorView.theme({
|
|||
color: "var(--lt-fg)",
|
||||
border: "1px solid var(--lt-border)",
|
||||
},
|
||||
...syntaxColours,
|
||||
});
|
||||
|
||||
/** Every extension of an editor state. */
|
||||
export function editorExtensions(): Extension {
|
||||
return [basicSetup, lutraEditorTheme];
|
||||
/**
|
||||
* Every extension of an editor state.
|
||||
*
|
||||
* @param path - the file's path, which picks the language; plain text when
|
||||
* omitted or unknown.
|
||||
*/
|
||||
export function editorExtensions(path = ""): Extension {
|
||||
return [basicSetup, lutraEditorTheme, languageExtensions(path)];
|
||||
}
|
||||
|
|
|
|||
167
ui/src/components/editor/language.ts
Normal file
167
ui/src/components/editor/language.ts
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
/**
|
||||
* Language support of an editor tab, picked once from the file extension
|
||||
* when the tab opens.
|
||||
*
|
||||
* Every parser is a Lezer grammar from the `@codemirror/lang-*` packages
|
||||
* (MIT). PHP files use `@codemirror/lang-php`, which also parses the HTML
|
||||
* (with its CSS and JavaScript) around `<?php … ?>` blocks. Unknown
|
||||
* extensions stay plain text. The colours come from {@link lutraHighlighting}.
|
||||
*/
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { syntaxHighlighting } from "@codemirror/language";
|
||||
import { tagHighlighter, tags } from "@lezer/highlight";
|
||||
import { css } from "@codemirror/lang-css";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { json } from "@codemirror/lang-json";
|
||||
import { markdown } from "@codemirror/lang-markdown";
|
||||
import { php } from "@codemirror/lang-php";
|
||||
import { yaml } from "@codemirror/lang-yaml";
|
||||
|
||||
/** Languages the editor knows. */
|
||||
export type LanguageId = "php" | "html" | "css" | "javascript" | "typescript" | "json" | "yaml" | "markdown";
|
||||
|
||||
/** Language by lower-case file extension (without the dot). */
|
||||
const BY_EXTENSION: Readonly<Record<string, LanguageId>> = {
|
||||
php: "php",
|
||||
phtml: "php",
|
||||
php3: "php",
|
||||
php4: "php",
|
||||
php5: "php",
|
||||
php7: "php",
|
||||
php8: "php",
|
||||
phps: "php",
|
||||
inc: "php",
|
||||
html: "html",
|
||||
htm: "html",
|
||||
css: "css",
|
||||
js: "javascript",
|
||||
mjs: "javascript",
|
||||
cjs: "javascript",
|
||||
jsx: "javascript",
|
||||
ts: "typescript",
|
||||
mts: "typescript",
|
||||
cts: "typescript",
|
||||
tsx: "typescript",
|
||||
json: "json",
|
||||
yaml: "yaml",
|
||||
yml: "yaml",
|
||||
md: "markdown",
|
||||
markdown: "markdown",
|
||||
};
|
||||
|
||||
/**
|
||||
* The language of a file.
|
||||
*
|
||||
* @param path - the file's path; only the extension after the last `.` of
|
||||
* the file name counts, case-insensitively.
|
||||
* @returns the language, or null for plain text.
|
||||
*/
|
||||
export function languageOf(path: string): LanguageId | null {
|
||||
const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
|
||||
const dot = name.lastIndexOf(".");
|
||||
if (dot <= 0) {
|
||||
return null;
|
||||
}
|
||||
return BY_EXTENSION[name.slice(dot + 1).toLowerCase()] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The CodeMirror support of a language.
|
||||
*
|
||||
* @param id - the language.
|
||||
*/
|
||||
function supportOf(id: LanguageId): Extension {
|
||||
switch (id) {
|
||||
case "php":
|
||||
return php();
|
||||
case "html":
|
||||
return html();
|
||||
case "css":
|
||||
return css();
|
||||
case "javascript":
|
||||
return javascript({ jsx: true });
|
||||
case "typescript":
|
||||
return javascript({ jsx: true, typescript: true });
|
||||
case "json":
|
||||
return json();
|
||||
case "yaml":
|
||||
return yaml();
|
||||
case "markdown":
|
||||
return markdown();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Highlight class prefix: a highlighted span carries `lt-syntax-<token>`,
|
||||
* and the editor theme colours it with the token `--lt-syntax-<token>`.
|
||||
*/
|
||||
export const SYNTAX_CLASS = "lt-syntax-";
|
||||
|
||||
/** Syntax token names, as `SYNTAX_TOKENS` in `crates/engine/src/theme.rs`. */
|
||||
export const SYNTAX_TOKENS = [
|
||||
"keyword",
|
||||
"string",
|
||||
"number",
|
||||
"comment",
|
||||
"variable",
|
||||
"function",
|
||||
"type",
|
||||
"constant",
|
||||
"tag",
|
||||
"attribute",
|
||||
"operator",
|
||||
] as const;
|
||||
|
||||
/** A syntax token name. */
|
||||
export type SyntaxToken = (typeof SYNTAX_TOKENS)[number];
|
||||
|
||||
/**
|
||||
* Lezer highlight tags and the token each one is drawn with. A tag that is
|
||||
* not listed falls back to its parent (`tags.controlKeyword` to
|
||||
* `tags.keyword`, `tags.function(tags.variableName)` to
|
||||
* `tags.variableName`); one without a listed ancestor keeps the text colour.
|
||||
*/
|
||||
const TAG_TOKENS: readonly [SyntaxToken, Parameters<typeof tagHighlighter>[0][number]["tag"]][] = [
|
||||
["keyword", [tags.keyword, tags.modifier, tags.self, tags.heading]],
|
||||
["string", [tags.string, tags.regexp, tags.character, tags.link, tags.url]],
|
||||
["number", [tags.number]],
|
||||
["comment", [tags.comment, tags.meta]],
|
||||
["variable", [tags.variableName, tags.propertyName, tags.labelName]],
|
||||
[
|
||||
"function",
|
||||
[
|
||||
tags.function(tags.variableName),
|
||||
tags.function(tags.propertyName),
|
||||
tags.function(tags.definition(tags.variableName)),
|
||||
tags.macroName,
|
||||
],
|
||||
],
|
||||
["type", [tags.typeName, tags.className, tags.namespace]],
|
||||
[
|
||||
"constant",
|
||||
[tags.bool, tags.null, tags.atom, tags.constant(tags.variableName), tags.constant(tags.propertyName), tags.escape],
|
||||
],
|
||||
["tag", [tags.tagName, tags.angleBracket, tags.processingInstruction]],
|
||||
["attribute", [tags.attributeName]],
|
||||
["operator", [tags.operator, tags.derefOperator]],
|
||||
];
|
||||
|
||||
/**
|
||||
* Highlighting that marks spans with `lt-syntax-<token>` classes only, so
|
||||
* every colour comes from a theme token.
|
||||
*/
|
||||
export const lutraHighlighting: Extension = syntaxHighlighting(
|
||||
tagHighlighter(TAG_TOKENS.map(([token, tag]) => ({ tag, class: `${SYNTAX_CLASS}${token}` }))),
|
||||
);
|
||||
|
||||
/**
|
||||
* Editor extensions for a file: its language support (if any) and the
|
||||
* Lutra highlighting.
|
||||
*
|
||||
* @param path - the file's path.
|
||||
*/
|
||||
export function languageExtensions(path: string): Extension {
|
||||
const id = languageOf(path);
|
||||
return id === null ? [] : [supportOf(id), lutraHighlighting];
|
||||
}
|
||||
88
ui/src/components/editor/reveal.ts
Normal file
88
ui/src/components/editor/reveal.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
/**
|
||||
* The UI command `editor.reveal {path, line, column}`: shows a position in
|
||||
* the editor. It opens the file (`file.open`) unless a tab has it,
|
||||
* activates the tab, places the cursor and scrolls it to the centre.
|
||||
*
|
||||
* Positions follow the C3 contract: `line` is 0-based and `column` counts
|
||||
* UTF-16 code units inside the line, converted to a CodeMirror position by
|
||||
* {@link positionOf} (CRLF-safe). Out-of-range values are clamped. Without
|
||||
* a `path` it centres the cursor of the active tab, which is what running
|
||||
* it from the palette does. The Find, Go-to and Structure windows and
|
||||
* agents (`uiCommand`) call it.
|
||||
*/
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { nextTick } from "vue";
|
||||
import { t } from "../../i18n";
|
||||
import type { useEditorStore } from "../../stores/editor";
|
||||
import { positionOf } from "./engineText";
|
||||
|
||||
/** Command id of the reveal command. */
|
||||
export const REVEAL_COMMAND = "editor.reveal";
|
||||
|
||||
/** A position to reveal. */
|
||||
export interface RevealTarget {
|
||||
/** File path as `file.open` takes it; null for the active tab. */
|
||||
path: string | null;
|
||||
/** 0-based line; null keeps the cursor. */
|
||||
line: number | null;
|
||||
/** 0-based column in UTF-16 code units. */
|
||||
column: number;
|
||||
}
|
||||
|
||||
/** The editor store as reveal uses it. */
|
||||
type EditorStore = ReturnType<typeof useEditorStore>;
|
||||
|
||||
/**
|
||||
* Reads the params of `editor.reveal`.
|
||||
*
|
||||
* @param params - untrusted params from the engine, the palette or a caller.
|
||||
* @returns the target, or null if a field has the wrong type.
|
||||
*/
|
||||
export function parseReveal(params: unknown): RevealTarget | null {
|
||||
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
|
||||
const number = (value: unknown): number | null | undefined =>
|
||||
value === undefined || value === null ? null : typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
const path = p.path === undefined || p.path === null ? null : typeof p.path === "string" && p.path !== "" ? p.path : undefined;
|
||||
const line = number(p.line);
|
||||
const column = number(p.column);
|
||||
if (path === undefined || line === undefined || column === undefined) {
|
||||
return null;
|
||||
}
|
||||
return { path, line, column: column ?? 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reveals a position.
|
||||
*
|
||||
* @param editor - the editor store.
|
||||
* @param params - the command params, see {@link parseReveal}.
|
||||
* @throws Error with a catalog message when the params are invalid or the
|
||||
* file cannot be opened; the command store shows it as an error toast.
|
||||
*/
|
||||
export async function reveal(editor: EditorStore, params: unknown): Promise<void> {
|
||||
const target = parseReveal(params);
|
||||
if (!target) {
|
||||
throw new Error(t("editor.reveal.invalidParams"));
|
||||
}
|
||||
let id = editor.activeId;
|
||||
if (target.path !== null) {
|
||||
const path = target.path;
|
||||
id = editor.tabs.find((tab) => tab.path === path)?.id ?? (await editor.openFile(path));
|
||||
if (id === null) {
|
||||
throw new Error(editor.lastError?.message ?? t("editor.reveal.openFailed", { path }));
|
||||
}
|
||||
editor.activate(id);
|
||||
await nextTick();
|
||||
}
|
||||
const sync = id === null ? undefined : editor.syncOf(id);
|
||||
if (!sync) {
|
||||
return;
|
||||
}
|
||||
const state = sync.state;
|
||||
const pos = target.line === null ? state.selection.main.head : positionOf(state.doc, target.line, target.column);
|
||||
sync.dispatch({
|
||||
selection: { anchor: pos },
|
||||
effects: EditorView.scrollIntoView(pos, { y: "center" }),
|
||||
userEvent: "select.reveal",
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue