Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/extended code blocks: create the initial implementation

Adorian Doranf7e7ce75dbf8
diff --git a/apps/client/src/services/experimental_features.spec.ts b/apps/client/src/services/experimental_features.spec.ts
index 219ba69152..3ad57af7a4 100644
--- a/apps/client/src/services/experimental_features.spec.ts
+++ b/apps/client/src/services/experimental_features.spec.ts
@@ -24,7 +24,8 @@ describe("experimental_features", () => {
it("lists every feature", async () => {
const { mod } = await freshModule([]);
- expect(mod.getAvailableExperimentalFeatures().map((f) => f.id)).toEqual(["llm"]);
+ expect(mod.getAvailableExperimentalFeatures().map((f) => f.id))
+ .toEqual(["llm", "extendedCodeBlocks"]);
});
it("llm enablement is driven by the aiEnabled option", async () => {
@@ -44,6 +45,14 @@ describe("experimental_features", () => {
expect(readded.mod.getEnabledExperimentalFeatureIds()).toEqual(["llm"]);
});
+ it("enables a feature that the persisted set lists", async () => {
+ const enabled = await freshModule(["extendedCodeBlocks"]);
+ expect(enabled.mod.isExperimentalFeatureEnabled("extendedCodeBlocks")).toBe(true);
+
+ const disabled = await freshModule([]);
+ expect(disabled.mod.isExperimentalFeatureEnabled("extendedCodeBlocks")).toBe(false);
+ });
+
it("warns and treats the set as empty when persisted JSON is invalid", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { mod } = await freshModule("not-json");
diff --git a/apps/client/src/services/experimental_features.ts b/apps/client/src/services/experimental_features.ts
index de57a21745..d1e2719bf3 100644
--- a/apps/client/src/services/experimental_features.ts
+++ b/apps/client/src/services/experimental_features.ts
@@ -12,6 +12,11 @@ export const experimentalFeatures = [
id: "llm",
name: t("experimental_features.llm_name"),
description: t("experimental_features.llm_description"),
+ },
+ {
+ id: "extendedCodeBlocks",
+ name: t("experimental_features.extended_code_blocks_name"),
+ description: t("experimental_features.extended_code_blocks_description")
}
] as const satisfies ExperimentalFeature[];
diff --git a/apps/client/src/services/source_embeds.spec.ts b/apps/client/src/services/source_embeds.spec.ts
new file mode 100644
index 0000000000..fb39c3a561
--- /dev/null
+++ b/apps/client/src/services/source_embeds.spec.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from "vitest";
+
+import { InlineCodeEmbed } from "../widgets/type_widgets/code/CodeEmbed";
+import { getInlineEmbedType, getSourceEmbedTypeByLanguage } from "./source_embeds";
+
+describe("getInlineEmbedType", () => {
+ it("is the source embed type of a diagram language, else an extended code block", async () => {
+ expect(getInlineEmbedType("mermaid")).toBe(getSourceEmbedTypeByLanguage("mermaid"));
+
+ const codeBlock = getInlineEmbedType("text-x-python");
+ expect(codeBlock.contentType).toBe("extendedCodeBlock");
+ expect(await codeBlock.load()).toBe(InlineCodeEmbed);
+ });
+});
diff --git a/apps/client/src/services/source_embeds.ts b/apps/client/src/services/source_embeds.ts
index f873f68018..36c83ba300 100644
--- a/apps/client/src/services/source_embeds.ts
+++ b/apps/client/src/services/source_embeds.ts
@@ -9,6 +9,8 @@ export interface SourceEmbedProps {
content: string;
/** Saves the edited source. Without it the content is read-only. */
editor?: ContentEditor;
+ /** The language of a source kept inline, as a CKEditor code block language. */
+ language?: string;
}
/**
@@ -48,6 +50,23 @@ export const SOURCE_EMBED_TYPES: readonly SourceEmbedType[] = [
}
];
+/** What an embed of a source kept inline shows, by {@link getInlineEmbedType}. */
+export type InlineEmbedType = Pick<SourceEmbedType, "contentType" | "load">;
+
+/** An extended code block: code kept inline, shown in the code editor by `InlineCodeEmbed`. */
+const EXTENDED_CODE_BLOCK_TYPE: InlineEmbedType = {
+ contentType: "extendedCodeBlock",
+ load: async () => (await import("../widgets/type_widgets/code/CodeEmbed")).InlineCodeEmbed
+};
+
+/**
+ * The type of an embed of a source kept inline, of `language`: the source embed type of that
+ * language, otherwise an extended code block.
+ */
+export function getInlineEmbedType(language: string): InlineEmbedType {
+ return getSourceEmbedTypeByLanguage(language) ?? EXTENDED_CODE_BLOCK_TYPE;
+}
+
/** The type of the source embeds whose code blocks are of `language`, or `undefined`. */
export function getSourceEmbedTypeByLanguage(language: string) {
return SOURCE_EMBED_TYPES.find((type) => type.language === language);
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 43a3478c15..c6fa28af4b 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -1522,6 +1522,19 @@ pre.code-embed-editor.read-only .cm-activeLine {
}
}
+:root .include-note-content.type-extendedCodeBlock pre.code-embed-editor {
+ border-radius: var(--_include-note-content-top-radius) var(--_include-note-content-top-radius)
+ var(--_include-note-content-bottom-radius)
+ var(--_include-note-content-bottom-radius);
+ overflow: hidden;
+
+ /* `.cm-line` adds 6px before each line. */
+ .cm-content {
+ padding-block: var(--padding-size, 1em);
+ padding-inline-start: calc(var(--padding-size, 1em) - 6px);
+ }
+}
+
/* Takes the wheel and the touch gestures for the page until the content has the focus. */
.include-note-backdrop {
position: absolute;
@@ -1570,6 +1583,7 @@ pre.code-embed-editor.read-only .cm-activeLine {
.include-note-content.type-canvas,
.include-note-content.type-canvasDrawing,
.include-note-content.type-mermaidDiagram,
+.include-note-content.type-extendedCodeBlock,
.include-note-content.type-webView,
.include-note-content.type-book:has(.note-list-widget.full-height),
.include-note-content.type-search:has(.note-list-widget.full-height) {
diff --git a/apps/client/src/stylesheets/theme-next/notes/text.css b/apps/client/src/stylesheets/theme-next/notes/text.css
index b8ea043636..8393d9a793 100644
--- a/apps/client/src/stylesheets/theme-next/notes/text.css
+++ b/apps/client/src/stylesheets/theme-next/notes/text.css
@@ -1087,6 +1087,13 @@ button.ck.ck-button:is(.ck-button-action, .ck-button-save, .ck-button-cancel, .c
margin-top: 2px !important;
}
+.include-note.extended-code-block {
+ --_include-note-top-border-radius: 6px;
+ --_include-note-bottom-border-radius: 6px;
+
+ box-shadow: var(--code-block-box-shadow);
+}
+
.attachment-content-wrapper pre {
border-radius: var(--dropdown-border-radius);
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 267f40deb6..692f00d75c 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1882,7 +1882,9 @@
"title": "Experimental Options",
"disclaimer": "These options are experimental and may cause instability. Use with caution.",
"llm_name": "AI / LLM Chat",
- "llm_description": "Enable the AI chat sidebar and LLM chat notes powered by large language models."
+ "llm_description": "Enable the AI chat sidebar and LLM chat notes powered by large language models.",
+ "extended_code_blocks_name": "Extended code blocks",
+ "extended_code_blocks_description": "A faster code block with a more advanced syntax highlighting engine and code folding."
},
"fonts": {
"theme_defined": "Theme defined",
@@ -4683,7 +4685,9 @@
"image-position": "Image position",
"list": "List",
"list-type": "List type",
- "insert-a-preview-of-a-web-page-or-a-video": "Insert a preview of a web page or a video"
+ "insert-a-preview-of-a-web-page-or-a-video": "Insert a preview of a web page or a video",
+ "extended-code-block": "Extended code block",
+ "insert-a-code-block-that-is-edited-as-a-code-note": "Insert a code block that is edited as a code note."
},
"task-state-dropped-title": "Invalid task states",
"task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
index 883224147f..5beb0dad8c 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
@@ -26,7 +26,7 @@ import { CodeMirrorFindTarget } from "../../find_in_code";
import { NoteSaves } from "../text/attachment_saves";
import { getContentEmbedTools, getEmbedFindTarget } from "../text/content_embed_tools";
import EmbedHistories from "../text/embed_history";
-import CodeEmbed from "./CodeEmbed";
+import CodeEmbed, { InlineCodeEmbed } from "./CodeEmbed";
vi.mock("../../../services/i18n", async (importOriginal) => ({
...(await importOriginal<object>()),
@@ -741,6 +741,102 @@ describe("CodeEmbed", () => {
});
});
+describe("InlineCodeEmbed", () => {
+ function getLabel(figure: HTMLElement) {
+ return figure.querySelector("pre.code-embed-editor")?.getAttribute("data-language");
+ }
+
+ it("shows the code in the language of its embed, named while it can edit", async () => {
+ const setMimeType = vi.spyOn(VanillaCodeMirror.prototype, "setMimeType");
+ const { editable } = buildCodeViewTextEditor();
+ const { figure } = await mountInline("pass", buildEditor(), {
+ language: "text-x-python", container: editable
+ });
+
+ const view = await findView(figure, true);
+ expect([ view.state.doc.toString(), view.state.readOnly ]).toEqual([ "pass", true ]);
+ expect(setMimeType).toHaveBeenLastCalledWith("text/x-python");
+ await vi.waitFor(() => expect(getLabel(figure)).toBe("Python"));
+ const tools = getContentEmbedTools(figure);
+ expect([ tools?.hasEditableFlag, tools?.boxSizeIcon ]).toEqual([ true, moveVerticalIcon ]);
+
+ // Without an editor, as in a read-only text note, in a language that names no MIME type.
+ const { figure: shown } = await mountInline("x", undefined, {
+ language: "text-x-trilium-auto"
+ });
+ await findView(shown, true);
+ await vi.waitFor(() => expect(setMimeType).toHaveBeenLastCalledWith("text/plain"));
+ expect(getLabel(shown)).toBeNull();
+ expectBoxSizeIconAlone(shown);
+ });
+
+ it("edits the code, follows the code the note writes, and sets its language", async () => {
+ options.set("codeNotesMimeTypes", JSON.stringify([ "text/x-python", "text/x-sh" ]));
+ vi.spyOn(contextMenu, "show").mockResolvedValue(undefined);
+ const setMimeType = vi.spyOn(VanillaCodeMirror.prototype, "setMimeType");
+ let unsavedContent: string | undefined;
+ const editor = buildEditor({
+ getUnsavedContent: () => unsavedContent,
+ scheduleSave: vi.fn((getContent: () => string) => {
+ unsavedContent = getContent();
+ })
+ });
+ const { textEditor, editable } = buildCodeViewTextEditor();
+ const { figure, rerender } = await mountInline("a", editor, {
+ language: "text-x-python", isEditable: true, container: editable
+ });
+
+ const view = await findView(figure);
+ act(() => view.dispatch({ changes: { from: 1, insert: "b" } }));
+ expect(unsavedContent).toBe("ab");
+
+ // Once written, the code that the note holds replaces the shown code.
+ unsavedContent = undefined;
+ await rerender("c");
+ expect(view.state.doc.toString()).toBe("c");
+ unsavedContent = "c, edited";
+ await rerender("d");
+ expect(view.state.doc.toString()).toBe("c");
+
+ await selectMenuItem(figure, "codeLanguage", "Shell (bash)");
+ expect(textEditor.execute)
+ .toHaveBeenLastCalledWith("setContentEmbedCodeView", { language: "text/x-sh" });
+ await act(async () => {
+ figure.dataset.language = "text-x-sh";
+ await Promise.resolve();
+ });
+ await vi.waitFor(() => expect(setMimeType).toHaveBeenLastCalledWith("text/x-sh"));
+ expect(getLabel(figure)).toBe("Shell (bash)");
+ });
+});
+
+interface InlineMountOptions extends Pick<MountOptions, "isEditable" | "container"> {
+ language: string;
+}
+
+/** Renders `InlineCodeEmbed` in the markup of an embed, as the host does. */
+async function mountInline(
+ content: string,
+ editor: ContentEditor | undefined,
+ { language, isEditable, container }: InlineMountOptions
+) {
+ const { figure, box } = buildFigure({
+ isEditable, container, embedAttributes: { "data-language": language }
+ });
+ const renderContent = (shown: string) => render(
+ <ParentComponent.Provider value={parent}>
+ <InlineCodeEmbed content={shown} editor={editor} language={language} />
+ </ParentComponent.Provider>,
+ box
+ );
+
+ await act(async () => renderContent(content));
+ return {
+ figure,
+ rerender: (shown: string) => act(async () => renderContent(shown))
+ };
+}
+
interface MountOptions {
content?: string;
mime?: string;
@@ -761,6 +857,29 @@ async function mount(
options: MountOptions = {}
) {
const content = options.content ?? "";
+ const { figure, box } = buildFigure(options);
+
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={parent}>
+ <CodeEmbed
+ entity={entity}
+ editor={editor}
+ content={options.content ?? (await entity.getBlob())?.content ?? content}
+ mime={options.mime ?? entity.mime}
+ codeLanguage={options.codeLanguage}
+ isCodeWrapped={options.isCodeWrapped}
+ hasCodeLineNumbers={options.hasCodeLineNumbers}
+ />
+ </ParentComponent.Provider>,
+ box
+ );
+ });
+ return { figure };
+}
+
+/** The markup of an embed in the page, with the box that its content renders in. */
+function buildFigure(options: MountOptions) {
const figure = document.createElement("figure");
figure.className = "include-note";
if (options.isEditable) {
@@ -782,24 +901,7 @@ async function mount(
figure.append(wrapper);
(options.container ?? document.body).append(figure);
figures.push(figure);
-
- await act(async () => {
- render(
- <ParentComponent.Provider value={parent}>
- <CodeEmbed
- entity={entity}
- editor={editor}
- content={options.content ?? (await entity.getBlob())?.content ?? content}
- mime={options.mime ?? entity.mime}
- codeLanguage={options.codeLanguage}
- isCodeWrapped={options.isCodeWrapped}
- hasCodeLineNumbers={options.hasCodeLineNumbers}
- />
- </ParentComponent.Provider>,
- box
- );
- });
- return { figure };
+ return { figure, box };
}
function buildCodeNote(content: string) {
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
index a80fa0c9ad..496c9bfa4e 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
@@ -1,5 +1,6 @@
import type { ContentEmbedCodeView } from "@triliumnext/ckeditor5";
import type VanillaCodeMirror from "@triliumnext/codemirror";
+import { getMimeTypeFromCKEditorLanguage } from "@triliumnext/commons";
import moveVerticalIcon from "boxicons/svg/regular/bx-move-vertical.svg?raw";
import { createPortal, type RefObject } from "preact";
import { lazy, Suspense, useSyncExternalStore } from "preact/compat";
@@ -11,11 +12,14 @@ import FNote from "../../../entities/fnote";
import type { MenuItem } from "../../../menus/context_menu";
import type { CodePreviewLines } from "../../../services/code_note_preview";
import type { ContentEditor } from "../../../services/content_renderer";
+import { PLAIN_TEXT_MIME } from "../../../services/mime_types";
+import type { SourceEmbedProps } from "../../../services/source_embeds";
import {
type CodeSettings, type CodeText, getLineNumbersMenu, getWordWrapMenu, useCodeLanguageMenu,
useNoteCodeSettings, useTabWidthMenu
} from "../../layout/code_menus";
import { SaveStateBadge } from "../../layout/NoteBadges";
+import { useMimeTypes } from "../../layout/NoteTypeSwitcher";
import {
useNoteBlob, useNoteLabelOptionalBool, useTriliumEvent, useWhenShown
} from "../../react/hooks";
@@ -55,21 +59,94 @@ export default function CodeEmbed({
hasCodeLineNumbers
}: CodeEmbedProps) {
const rootRef = useRef<HTMLDivElement>(null);
- const viewRef = useRef<VanillaCodeMirror>(null);
const note = entity instanceof FNote ? entity : null;
- // The toolbar buttons come from `CodeTools`, with the Editable toggle.
- const { canEdit, isEditing } = useEditableEmbed(rootRef, {
- editor, note, tools: null, focusTarget: ".cm-content"
- });
const noteSettings = useNoteCodeSettings(note);
const fileSettings = useFileCodeSettings(rootRef, initialMime, codeLanguage);
const settings = note ? noteSettings : fileSettings;
- const lines = useEmbedLines(rootRef, note, {
- isWrapped: isCodeWrapped, hasLineNumbers: hasCodeLineNumbers
- });
const [ content, setContent ] = useState(initialContent);
- const mime = settings.mime ?? initialMime;
useSavedContent(entity, editor, setContent, rootRef);
+
+ return (
+ <CodeEmbedContent
+ rootRef={rootRef}
+ note={note}
+ ownerNote={entity instanceof FNote ? entity : entity.getNote()}
+ editor={editor}
+ content={content}
+ onContentChange={setContent}
+ settings={settings}
+ mime={settings.mime ?? initialMime}
+ initialLines={{ isWrapped: isCodeWrapped, hasLineNumbers: hasCodeLineNumbers }}
+ hasSaveStatus
+ />
+ );
+}
+
+/**
+ * An extended code block: code kept inline in a text note, shown in a read-only CodeMirror, which
+ * edits it while the Editable toggle of its embed is on. The language is the `data-language`
+ * attribute of the embed, and the indentation and the lines its `data-code-*` attributes.
+ */
+export function InlineCodeEmbed({ content: savedContent, editor, language }: SourceEmbedProps) {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const settings = useInlineCodeSettings(rootRef, language);
+ const [ content, setContent ] = useState(savedContent);
+
+ // Code written elsewhere, or undone, replaces the shown code unless it has unsaved edits.
+ useEffect(() => {
+ if (editor?.getUnsavedContent() === undefined) {
+ setContent(savedContent);
+ }
+ }, [ savedContent ]);
+
+ return (
+ <CodeEmbedContent
+ rootRef={rootRef}
+ note={null}
+ ownerNote={null}
+ editor={editor}
+ content={content}
+ onContentChange={setContent}
+ settings={settings}
+ mime={settings.mime ?? PLAIN_TEXT_MIME}
+ hasLanguageLabel
+ />
+ );
+}
+
+interface CodeEmbedContentProps {
+ /** The root of the content. The parent reads the settings of the embed through it. */
+ rootRef: RefObject<HTMLDivElement | null>;
+ note: FNote | null;
+ /** The note that holds an attachment, which images upload to and new notes go under. */
+ ownerNote: FNote | null;
+ editor: ContentEditor | undefined;
+ content: string;
+ /** Receives the content when it changes in the embed. */
+ onContentChange: (content: string) => void;
+ settings: CodeSettings;
+ /** The MIME type that highlights the content. */
+ mime: string;
+ /** How the lines show until the content is in the embed. */
+ initialLines?: CodePreviewLines;
+ /** Whether the title row shows the save state while the content is edited. */
+ hasSaveStatus?: boolean;
+ /** Whether the editor shows the name of its language in its corner while it can edit. */
+ hasLanguageLabel?: boolean;
+}
+
+/** CodeMirror over the code of an embed, and the tools of the embed toolbar for it. */
+function CodeEmbedContent({
+ rootRef, note, ownerNote, editor, content, onContentChange, settings, mime, initialLines,
+ hasSaveStatus, hasLanguageLabel
+}: CodeEmbedContentProps) {
+ const viewRef = useRef<VanillaCodeMirror>(null);
+ // The toolbar buttons come from `CodeTools`, with the Editable toggle.
+ const { canEdit, isEditing } = useEditableEmbed(rootRef, {
+ editor, note, tools: null, focusTarget: ".cm-content"
+ });
+ const lines = useEmbedLines(rootRef, note, initialLines);
+ const languageLabel = useMimeTypeTitle(mime);
// The editor while the content is edited, otherwise the content with the unsaved changes of any
// embed of it, which a change saves.
const getCodeText = (): CodeText => (isEditing ? viewRef.current : null) ?? {
@@ -83,7 +160,7 @@ export default function CodeEmbed({
}
view?.setText(text);
editor?.scheduleSave(() => text);
- setContent(text);
+ onContentChange(text);
}
};
@@ -94,7 +171,7 @@ export default function CodeEmbed({
<Suspense fallback={null}>
<CodeEmbedEditor
note={note}
- ownerNote={entity instanceof FNote ? entity : entity.getNote()}
+ ownerNote={ownerNote}
editor={isEditing ? editor : undefined}
history={editor?.history}
content={content}
@@ -103,13 +180,16 @@ export default function CodeEmbed({
useTabs={settings.useTabs}
wrapLines={lines.wrapLines}
hasLineNumbers={lines.hasLineNumbers}
+ languageLabel={hasLanguageLabel && canEdit ? languageLabel : undefined}
viewRef={viewRef}
- onClose={setContent}
+ onClose={onContentChange}
/>
</Suspense>
</CaretNavigationContext.Provider>
</div>
- {editor && <SaveStatus rootRef={rootRef} editor={editor} isShown={isEditing} />}
+ {hasSaveStatus && editor && (
+ <SaveStatus rootRef={rootRef} editor={editor} isShown={isEditing} />
+ )}
<CodeTools
rootRef={rootRef}
settings={settings}
@@ -179,14 +259,42 @@ function useFileCodeSettings(
initialLanguage: string | undefined
): CodeSettings {
const language = useContentEmbedAttribute(rootRef, "data-code-language", initialLanguage ?? null);
- const tabWidth = useContentEmbedAttribute(rootRef, "data-code-tab-width");
- const useTabs = useContentEmbedAttribute(rootRef, "data-code-indent-with-tabs");
return {
+ ...useEmbedIndentation(rootRef),
mime: language ?? fileMime,
setMime: (mime) => {
setCodeView(rootRef.current, { language: mime === fileMime ? null : mime });
- },
+ }
+ };
+}
+
+/**
+ * The code settings of an extended code block: the language, from the `data-language` attribute
+ * of its embed, and the indentation. `initialLanguage` is the language until the content is in the
+ * embed. Both languages are CKEditor code block languages.
+ */
+function useInlineCodeSettings(
+ rootRef: RefObject<HTMLElement | null>,
+ initialLanguage: string | undefined
+): CodeSettings {
+ const language = useContentEmbedAttribute(rootRef, "data-language", initialLanguage ?? null);
+
+ return {
+ ...useEmbedIndentation(rootRef),
+ mime: language ? getMimeTypeFromCKEditorLanguage(language) : undefined,
+ setMime: (mime) => setCodeView(rootRef.current, { language: mime })
+ };
+}
+
+/** The indentation, from the `data-code-*` attributes of the embed around `rootRef`. */
+function useEmbedIndentation(
+ rootRef: RefObject<HTMLElement | null>
+): Pick<CodeSettings, "tabWidth" | "useTabs" | "setIndentation"> {
+ const tabWidth = useContentEmbedAttribute(rootRef, "data-code-tab-width");
+ const useTabs = useContentEmbedAttribute(rootRef, "data-code-indent-with-tabs");
+
+ return {
tabWidth: tabWidth ? parseInt(tabWidth, 10) || undefined : undefined,
useTabs: useTabs === null ? undefined : useTabs === "true",
setIndentation: (indentation) => setCodeView(rootRef.current, {
@@ -196,6 +304,12 @@ function useFileCodeSettings(
};
}
+/** The name of the language of `mime`, such as "Python". */
+function useMimeTypeTitle(mime: string) {
+ const { allMimeTypes } = useMimeTypes();
+ return allMimeTypes.find((mimeType) => mimeType.mime === mime)?.title;
+}
+
/** Sets how the embed around `root` shows its code, through the text editor that holds it. */
function setCodeView(root: HTMLElement | null, codeView: ContentEmbedCodeView) {
const editor = findTextEditorAround(root);
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
index 77fc2d578b..30d105405b 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
@@ -31,6 +31,8 @@ export interface CodeEmbedEditorProps {
wrapLines?: boolean;
/** Whether to show the line numbers, or `undefined` to follow the global option. */
hasLineNumbers?: boolean;
+ /** The name of the language, shown in the corner of the editor as on a code block. */
+ languageLabel?: string;
/** Holds the CodeMirror view while the editor is open, and `null` once it goes away. */
viewRef: RefObject<VanillaCodeMirror | null>;
/** Whether the editor shows. "Search in note" skips a hidden one. Shown by default. */
@@ -49,7 +51,7 @@ export interface CodeEmbedEditorProps {
*/
export default function CodeEmbedEditor({
note, ownerNote, editor, history, content, mime, tabWidth, useTabs, wrapLines, hasLineNumbers,
- viewRef, isShown = true, onClose, onChange, onReady
+ languageLabel, viewRef, isShown = true, onClose, onChange, onReady
}: CodeEmbedEditorProps) {
const isLoadingRef = useRef(false);
const [ vimKeymapEnabled ] = useTriliumOptionBool("vimKeymapEnabled");
@@ -137,6 +139,7 @@ export default function CodeEmbedEditor({
vimKeybindings={vimKeymapEnabled}
readOnly={!editor}
lineNumbers={hasLineNumbers}
+ languageLabel={languageLabel}
onInitialized={() => setView(viewRef.current)}
onContentChanged={() => handleChangeRef.current()}
{...(tabWidth !== undefined && { indentSize: tabWidth })}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx
index bb75ed9626..8887f57df1 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx
@@ -22,9 +22,18 @@ export interface CodeMirrorProps extends Omit<EditorConfig, "parent"> {
bulkActionNote?: boolean;
/** The snippets the completion list offers after a `/`, read each time the list opens. */
getSnippets?: () => CodeSnippet[];
+ /**
+ * The name of the language, which a text editor around the code shows in its corner, as on its
+ * code blocks.
+ */
+ languageLabel?: string;
}
-export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, lineNumbers = true, customRequestHandler, bulkActionNote, allowKeyboardSuggestions, getSnippets, ...extraOpts }: CodeMirrorProps) {
+export default function CodeMirror({
+ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef,
+ onInitialized, lineWrapping, lineNumbers = true, customRequestHandler, bulkActionNote,
+ allowKeyboardSuggestions, getSnippets, languageLabel, ...extraOpts
+}: CodeMirrorProps) {
const parentRef = useSyncedRef(externalContainerRef);
const codeEditorRef = useRef<VanillaCodeMirror | undefined>(undefined);
const getSnippetsRef = useRef(getSnippets);
@@ -93,6 +102,6 @@ export default function CodeMirror({ className, content, mime, editorRef: extern
}, [ extraOpts.indentSize, extraOpts.useTabs ]);
return (
- <pre ref={parentRef} className={className} />
+ <pre ref={parentRef} className={className} data-language={languageLabel} />
)
}
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 97c2ea5a4f..76d90a64cf 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -233,6 +233,7 @@ export default function EditableText({
...options, saves: inlineSourceSaves, histories
});
},
+ flushInline: () => inlineSourceSaves.flush(),
focusAttachment(attachmentId) {
focusedAttachmentIdRef.current = attachmentId;
},
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
index f16835241b..644447c88f 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
@@ -531,7 +531,7 @@ describe("ReadOnlyText Mermaid diagrams", () => {
language: "mermaid", source: "graph TD;", isReadOnly: true, boxSize: "small",
options: { isFocused: false }, isInPage: true,
data: {
- boxSize: "small", displayMode: "source", hideTitle: "true",
+ boxSize: "small", displayMode: "source", hideTitle: "true", language: "mermaid",
triliumBlockId: "b1", codeWrapLines: "true", codeLineNumbers: "false"
},
height: "12em"
@@ -539,7 +539,9 @@ describe("ReadOnlyText Mermaid diagrams", () => {
{
language: "mermaid", source: "graph LR;", isReadOnly: true, boxSize: "medium",
options: { isFocused: false }, isInPage: true,
- data: { boxSize: "medium", hideTitle: "true", triliumBlockId: "b2" },
+ data: {
+ boxSize: "medium", hideTitle: "true", language: "mermaid", triliumBlockId: "b2"
+ },
height: ""
}
]);
@@ -562,6 +564,56 @@ describe("ReadOnlyText Mermaid diagrams", () => {
});
});
+describe("ReadOnlyText extended code blocks", () => {
+ it("shows each extended code block in the embed box of the editor, and no other", async () => {
+ loadInlineEmbed.mockClear();
+ const html = `<pre class="extended-code-block" data-box-size="medium"`
+ + ` data-hide-title="true" data-code-tab-width="2" data-code-indent-with-tabs="false">`
+ + `<code class="language-text-x-python">pass</code></pre>`
+ + `<pre class="extended-code-block"><code data-trilium-block-id="b1">x</code></pre>`
+ + `<pre><code class="language-text-x-python">plain</code></pre>`;
+ const container = document.createElement("div");
+ document.body.append(container);
+ await act(async () => render(<ReadOnlyTextContent html={html} />, container));
+
+ const embeds = loadInlineEmbed.mock.calls.map((call: unknown[]) => {
+ const [ source, $el, boxSize ] = call as [
+ { language: string; getSource(): string }, JQuery<HTMLElement>, string
+ ];
+ const figure = $el[0];
+ return {
+ language: source.language,
+ source: source.getSource(),
+ boxSize,
+ className: figure.className,
+ data: { ...figure.dataset }
+ };
+ });
+ expect(embeds).toEqual([
+ {
+ language: "text-x-python", source: "pass", boxSize: "medium",
+ className: "include-note extended-code-block",
+ data: {
+ boxSize: "medium", hideTitle: "true", language: "text-x-python",
+ codeTabWidth: "2", codeIndentWithTabs: "false"
+ }
+ },
+ {
+ language: "text-plain", source: "x", boxSize: "full",
+ className: "include-note extended-code-block",
+ data: {
+ boxSize: "full", hideTitle: "true", language: "text-plain",
+ triliumBlockId: "b1"
+ }
+ }
+ ]);
+ expect(container.querySelector("pre > code.language-text-x-python")?.textContent)
+ .toBe("plain");
+ await act(async () => render(null, container));
+ container.remove();
+ });
+});
+
describe("ReadOnlyText lists", () => {
it("marks the list items whose first paragraph is aligned", async () => {
const harness = setupHarness({ isVisible: true });
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 256a292599..d929eb7cac 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -13,6 +13,9 @@ import {
} from "@triliumnext/ckeditor5/src/plugins/table_sticky_header_read_only.js";
import { CLASSES as TAB_CLASSES } from "@triliumnext/ckeditor5/src/plugins/tabs/constants.js";
import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";
+import {
+ EXTENDED_CODE_BLOCK_CLASS, EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE
+} from "@triliumnext/commons";
import clsx from "clsx";
import { Ref } from "preact";
import { useEffect, useLayoutEffect, useMemo, useRef as usePreactRef } from "preact/hooks";
@@ -259,17 +262,28 @@ function applyContentEmbeds(container: HTMLDivElement) {
*/
function applySourceEmbeds(container: HTMLDivElement) {
const loaded: Promise<unknown>[] = [];
- for (const code of container.querySelectorAll<HTMLElement>("pre > code[class*='language-']")) {
+ for (const code of container.querySelectorAll<HTMLElement>("pre > code")) {
const pre = code.parentElement;
- const language = [ ...code.classList ]
+ const codeLanguage = [ ...code.classList ]
.find((name) => name.startsWith("language-"))?.slice("language-".length);
- if (!pre || !language || !getSourceEmbedTypeByLanguage(language)) continue;
+ const isDiagram = !!codeLanguage && !!getSourceEmbedTypeByLanguage(codeLanguage);
+ const isCodeBlock = !isDiagram && !!pre?.classList.contains(EXTENDED_CODE_BLOCK_CLASS);
+ if (!pre || (!isDiagram && !isCodeBlock)) continue;
+ const language = codeLanguage ?? EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE;
const figure = document.createElement("figure");
- figure.className = "include-note";
- const { boxSize, displayMode, codeWrapLines, codeLineNumbers } = pre.dataset;
- figure.dataset.boxSize = boxSize === "small" || boxSize === "full" ? boxSize : "medium";
- const views = { displayMode, codeWrapLines, codeLineNumbers };
+ figure.className = clsx("include-note", isCodeBlock && EXTENDED_CODE_BLOCK_CLASS);
+ const {
+ boxSize, displayMode, codeWrapLines, codeLineNumbers, codeTabWidth, codeIndentWithTabs
+ } = pre.dataset;
+ const defaultBoxSize = isCodeBlock ? "full" : "medium";
+ figure.dataset.boxSize = boxSize === "small" || boxSize === "medium" || boxSize === "full"
+ ? boxSize
+ : defaultBoxSize;
+ figure.dataset.language = language;
+ const views = {
+ displayMode, codeWrapLines, codeLineNumbers, codeTabWidth, codeIndentWithTabs
+ };
for (const [ name, value ] of Object.entries(views)) {
if (value) {
figure.dataset[name] = value;
diff --git a/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx
index 71867b970d..5d07980661 100644
--- a/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx
@@ -113,7 +113,7 @@ describe("createInlineSourceEditor", () => {
});
describe("InlineSourceEmbed", () => {
- it("passes the source and its editor to the component, and the source again once it changes", () => {
+ it("passes the source, its language and its editor, and the source once it changes", () => {
const container = document.createElement("div");
const source = createSource("graph TD;");
const shown: SourceEmbedProps[] = [];
@@ -124,6 +124,7 @@ describe("InlineSourceEmbed", () => {
act(() => render(<InlineSourceEmbed source={source} component={Probe} />, container));
expect(shown.at(-1)?.content).toBe("graph TD;");
+ expect(shown.at(-1)?.language).toBe("mermaid");
expect(shown.at(-1)?.editor?.canEdit()).toBe(true);
// As an undo in the text editor changes the source.
diff --git a/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx b/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx
index 68df1f5b9b..b0d8198c83 100644
--- a/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx
@@ -49,7 +49,7 @@ export function InlineSourceEmbed({
() => createInlineSourceEditor(source, saves, histories), [ source, saves, histories ]);
useEffect(() => () => editor.release(), [ editor ]);
- return <Component content={content} editor={editor} />;
+ return <Component content={content} editor={editor} language={source.language} />;
}
/**
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index 0aa0f6c410..8881564b12 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -41,6 +41,11 @@ vi.mock("i18next", () => ({
}
}));
+const experimentalState = vi.hoisted(() => ({ enabled: new Set<string>() }));
+vi.mock("../../../services/experimental_features.js", () => ({
+ isExperimentalFeatureEnabled: (id: string) => experimentalState.enabled.has(id)
+}));
+
vi.mock("../../../services/options.js", () => ({
default: {
get(name: string) {
@@ -154,6 +159,7 @@ async function buildDynamicConfig(overrides: Partial<BuildEditorOptions> = {}) {
beforeEach(() => {
optionsState.map = {};
optionsState.json = {};
+ experimentalState.enabled.clear();
imageState.copySupported = false;
catalogState.bundle = undefined;
catalogState.entries = {};
@@ -465,6 +471,7 @@ describe("CK config - tables", () => {
loadNote: vi.fn(),
loadAttachment: vi.fn(),
loadInline: vi.fn(),
+ flushInline: vi.fn(),
focusAttachment: vi.fn(),
getAttachmentHref: vi.fn(async () => "#root/n1?viewMode=attachments&attachmentId=a1"),
openMenu: vi.fn(),
@@ -485,6 +492,7 @@ describe("CK config - tables", () => {
host?.loadNote?.("n2", wrapper, undefined, undefined, onBlockChange);
host?.loadAttachment?.("a1", wrapper, "medium");
host?.loadInline?.(source, wrapper, "full", { isFocused: true });
+ host?.flushInline?.();
host?.focusAttachment?.("a1");
host?.openMenu?.(embed, wrapper);
@@ -492,6 +500,7 @@ describe("CK config - tables", () => {
expect(second.loadNote).toHaveBeenCalledExactlyOnceWith("n2", wrapper, undefined, undefined, onBlockChange);
expect(first.loadAttachment).toHaveBeenCalledWith("a1", wrapper, "medium");
expect(first.loadInline).toHaveBeenCalledWith(source, wrapper, "full", { isFocused: true });
+ expect(first.flushInline).toHaveBeenCalledOnce();
expect(first.focusAttachment).toHaveBeenCalledWith("a1");
expect(first.openMenu).toHaveBeenCalledWith(embed, wrapper);
expect(await host?.getAttachmentHref?.("a1")).toBe("#root/n1?viewMode=attachments&attachmentId=a1");
@@ -504,6 +513,7 @@ describe("CK config - tables", () => {
expect(host?.getTools?.(embed)).toBeNull();
expect(host?.enter?.(embed, "start")).toBe(false);
expect(() => host?.loadNote?.("n1", wrapper, undefined, undefined, onBlockChange)).not.toThrow();
+ expect(() => host?.flushInline?.()).not.toThrow();
});
it("titles reference links through the link service, in the note open at the time", async () => {
@@ -809,6 +819,16 @@ describe("CK config - inline embeds", () => {
const config = await buildDynamicConfig();
expect(config.contentEmbed.inlineLanguages).toEqual([ "mermaid" ]);
});
+
+ it("offers the slash command of extended code blocks while their feature is on", async () => {
+ const getRemoved = async () =>
+ (await buildConfig(baseOpts())).slashCommand?.removeCommands ?? [];
+
+ expect(await getRemoved()).toContain("extended-code-block");
+ experimentalState.enabled.add("extendedCodeBlocks");
+ expect(await getRemoved()).not.toContain("extended-code-block");
+ expect(await getRemoved()).toEqual([ "bulletedList", "numberedList" ]);
+ });
});
describe("CK config - mention feed", () => {
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 51cedfe0a9..4e8074ceba 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -8,6 +8,7 @@ import { buildReferenceConfig, type ReferenceSource } from "../../../services/bl
import { copyHtmlWithToast, copyTextWithToast } from "../../../services/clipboard_ext.js";
import { getUploadBoxSize } from "../../../services/content_renderer.js";
import { prompt } from "../../../services/dialog.js";
+import { isExperimentalFeatureEnabled } from "../../../services/experimental_features.js";
import { t } from "../../../services/i18n.js";
import imageService from "../../../services/image.js";
import { getNoteImageSourceToLoad } from "../../../services/image_urls.js";
@@ -267,8 +268,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
},
slashCommand: {
// Drop CKEditor's built-in list slash commands, whose Title Case titles the palette
- // re-defines in sentence case.
- removeCommands: ["bulletedList", "numberedList"],
+ // re-defines in sentence case, and those of the experimental features that are off.
+ removeCommands: ["bulletedList", "numberedList", ...getDisabledExperimentalCommands()],
list: createSlashCommandList
},
snippets: {
@@ -410,6 +411,7 @@ function bindContentEmbedHandlers(
loadNote: (...args) => getHandlers()?.loadNote(...args),
loadAttachment: (...args) => getHandlers()?.loadAttachment(...args),
loadInline: (...args) => getHandlers()?.loadInline(...args),
+ flushInline: () => getHandlers()?.flushInline(),
focusAttachment: (attachmentId) => getHandlers()?.focusAttachment(attachmentId),
getAttachmentHref: async (attachmentId) =>
(await getHandlers()?.getAttachmentHref(attachmentId)) ?? null,
@@ -419,6 +421,11 @@ function bindContentEmbedHandlers(
};
}
+/** The slash commands of the experimental features that are off. */
+function getDisabledExperimentalCommands(): string[] {
+ return isExperimentalFeatureEnabled("extendedCodeBlocks") ? [] : [ "extended-code-block" ];
+}
+
/** A callback that triggers `command` on the component that hosts the editor, and waits for it. */
function bindHostCommand(opts: BuildEditorOptions, command: CommandNames) {
return async () => {
diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts b/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts
index 5c5aa4f781..dd71c0d5c4 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts
@@ -11,6 +11,11 @@ vi.mock("../../../services/options.js", () => ({
default: { get: (name: string) => optionsState.values[name] }
}));
+const experimentalState = vi.hoisted(() => ({ enabled: new Set<string>() }));
+vi.mock("../../../services/experimental_features.js", () => ({
+ isExperimentalFeatureEnabled: (id: string) => experimentalState.enabled.has(id)
+}));
+
// The group labels are translated when the toolbar is built (CKEditor renders a nested dropdown's
// `label` verbatim), so echo the key back to make the lookup visible to the assertions below.
vi.mock("../../../services/i18n.js", () => ({ t: (key: string) => key }));
@@ -70,6 +75,38 @@ describe("the Insert group", () => {
});
});
+describe("the extended code block", () => {
+ afterEach(() => experimentalState.enabled.clear());
+
+ function getInsertGroups() {
+ const toolbars = [
+ buildClassicToolbar(false, true).toolbar.items,
+ buildFloatingToolbar(true).blockToolbar,
+ buildMobileToolbar(true).toolbar.items
+ ];
+ return toolbars.map((items) => {
+ const group = items.find((item) => typeof item === "object"
+ && "label" in item && item.label === "text-editor.toolbar-groups.insert");
+ return (group as { items: string[] } | undefined)?.items ?? [];
+ });
+ }
+
+ it("follows the columns in the Insert group of every toolbar, while its feature is on", () => {
+ experimentalState.enabled.add("extendedCodeBlocks");
+ for (const items of getInsertGroups()) {
+ const index = items.indexOf("multicolumnLayout");
+ expect(items.slice(index, index + 2))
+ .toEqual([ "multicolumnLayout", "extendedCodeBlock" ]);
+ }
+
+ experimentalState.enabled.clear();
+ for (const items of getInsertGroups()) {
+ expect(items).toContain("multicolumnLayout");
+ expect(items).not.toContain("extendedCodeBlock");
+ }
+ });
+});
+
describe("the attach menu", () => {
it("replaces the image and file uploads on every toolbar, with the camera only on a phone", () => {
const classic = buildClassicToolbar(false, true);
diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.ts
index ee05d36811..e7a21ed4ce 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts
@@ -1,5 +1,6 @@
import utils from "../../../services/utils.js";
import options from "../../../services/options.js";
+import { isExperimentalFeatureEnabled } from "../../../services/experimental_features.js";
import { t } from "../../../services/i18n.js";
import { IconAlignCenter } from "@ckeditor/ckeditor5-icons";
@@ -70,7 +71,7 @@ export function buildMobileToolbar(aiAssistant: boolean) {
"|",
"codeBlock", "blockQuote", "admonition",
"|",
- "collapsible", "tabs", "multicolumnLayout",
+ "collapsible", "tabs", "multicolumnLayout", ...getExtendedCodeBlockItems(),
"|",
"horizontalLine", "pageBreak", "footnote",
"|",
@@ -176,7 +177,14 @@ export function buildClassicToolbar(multilineToolbar: boolean, aiAssistant: bool
"footnote",
{
...buildInsertGroup(),
- items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "|", "dateTime", "specialCharacters", "emoji", "insertIcon"]
+ items: [
+ "link", "linkEmbed", "bookmark", "internallink", "contentEmbed",
+ "|",
+ "collapsible", "tabs", "multicolumnLayout", ...getExtendedCodeBlockItems(),
+ "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak",
+ "|",
+ "dateTime", "specialCharacters", "emoji", "insertIcon"
+ ]
},
"|",
buildAlignmentToolbar(),
@@ -246,7 +254,12 @@ export function buildFloatingToolbar(aiAssistant: boolean) {
"footnote",
{
...buildInsertGroup(),
- items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "dateTime"]
+ items: [
+ "link", "linkEmbed", "bookmark", "internallink", "contentEmbed",
+ "|",
+ "collapsible", "tabs", "multicolumnLayout", ...getExtendedCodeBlockItems(),
+ "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "dateTime"
+ ]
},
"|",
buildAlignmentToolbar(),
@@ -283,6 +296,11 @@ function buildInsertGroup() {
};
}
+/** The button that inserts an extended code block, while its experimental feature is on. */
+function getExtendedCodeBlockItems(): string[] {
+ return isExperimentalFeatureEnabled("extendedCodeBlocks") ? [ "extendedCodeBlock" ] : [];
+}
+
function buildAlignmentToolbar() {
return {
label: t("text-editor.toolbar-groups.alignment"),
diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.ts
index afd269998c..efdb0afb67 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.ts
@@ -11,7 +11,7 @@ import content_renderer, {
import { getEmbedCaption, getEmbedCodeView } from "../../../services/content_renderer_text";
import froca from "../../../services/froca";
import link, { ViewScope } from "../../../services/link";
-import { getSourceEmbedTypeByLanguage } from "../../../services/source_embeds";
+import { getInlineEmbedType } from "../../../services/source_embeds";
import utils from "../../../services/utils";
import type { InlineSourceSaves } from "./attachment_saves";
import { watchContentEmbedTools } from "./content_embed_tools";
@@ -208,9 +208,7 @@ export async function loadInlineEmbed(
boxSize: string | undefined,
{ isFocused, saves, histories }: InlineEmbedOptions
) {
- const type = getSourceEmbedTypeByLanguage(source.language);
- if (!type) return;
-
+ const type = getInlineEmbedType(source.language);
const el = $el[0];
const [ component, { InlineSourceEmbed } ] = await Promise.all([
type.load(),
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index e30f665783..1985dd279f 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -124,7 +124,7 @@
"_help_EK2ckIZ74tbT": "<p>Content tabs group several titled panels of content into one block that shows a single panel at a time. They suit content that comes in variants (such as installation steps for each operating system or the same snippet in several programming languages).</p><p>A tabs block consists of:</p><ul><li><strong>A single row of tab titles</strong>, above the panel or, when the tabs are aligned at the bottom, below it. The title of the panel that is showing is highlighted.</li><li><strong>The panel of the active tab.</strong> A panel can hold any kind of content (including nested tabs blocks).</li></ul><h2>Inserting a tabs block</h2><ul><li>In the formatting bar, go to <em>Insert</em> → <em>Tabs</em>.</li><li>Alternatively, type <code>/tabs</code> and press <kbd>Enter</kbd>, as described in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</li></ul><p>A new block contains two tabs, named “Tab 1” and “Tab 2”. Any content that was selected prior to inserting the tabs will be moved into the first tab. The title of the first tab is selected, so typing replaces it.</p><h2>Scrolling through the titles</h2><p>When the titles of a block do not fit on their row, a <span class=\"tn-icon bx bx-chevron-left\"></span> button and a <span class=\"tn-icon bx bx-chevron-right\"></span> button appear at its ends:</p><ul><li>To scroll the titles, click one of the buttons. Holding a button down scrolls the titles continuously until it is released.</li><li>On a touch screen, the titles can also be swiped sideways.</li></ul><p>Whenever another tab is shown (for example by clicking its title, by moving the cursor into it or by following a link to it), the row scrolls so that its whole title is visible. This works the same while editing, in read-only notes and on shared pages.</p><h2>Editing tabs</h2><ul><li>To show a tab, click its title or move the cursor into it.</li><li>To move from a title into its panel, press <kbd>Enter</kbd>.</li><li>The label of a tab can be formatted just like normal text, including support for&nbsp;<a class=\"reference-link\" href=\"#root/_help_hD8GawVuazff\">Icons</a>.</li></ul><p>While the cursor is inside a tabs block, a toolbar appears above it with the following buttons:</p><ul><li><span class=\"tn-icon cke cke-plus\"></span>&nbsp;<em>(Add tab)</em> inserts a tab after the current one and selects its title.</li><li><span class=\"tn-icon cke cke-remove\"></span>&nbsp;<em>(Remove tab)</em> removes the current tab. Removing the last tab removes the whole block.</li><li><span class=\"tn-icon cke cke-chevron-right bx-flip-horizontal\"></span>&nbsp;<em>(Move tab left)</em> and&nbsp;<span class=\"tn-icon cke cke-chevron-right\"></span> (<em>Move tab right)</em> change the order of the tabs.</li><li><span class=\"tn-icon cke cke-link\"></span>&nbsp;<em>(Copy link to tab)</em> copies a link to the current tab, as described below.</li><li><span class=\"tn-icon cke cke-trilium-tabs\"></span>&nbsp;<em>(Tab alignment)</em> places the tab titles above the panel (<em>Align tabs at top</em>, the default) or below it (<em>Align tabs at bottom</em>).</li></ul><p>The tab that is showing is not saved with the note: every tabs block opens on its first tab.</p><h3>Adding tabs</h3><p>While the cursor is in a tab, either in its title or in its panel, you can use these key combinations:</p><ul><li><kbd>Ctrl</kbd> + <kbd>Enter</kbd>: Add a tab after the current one.</li><li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd>: Add a tab before the current one.</li></ul><p>The new tab is shown and its title is selected, so typing replaces it.</p><p><kbd>Ctrl</kbd> + <kbd>Enter</kbd> keeps its usual function on a link, in a to-do item and in the title of a collapsible block, and <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd> in a to-do item.</p><h3>Reordering tabs</h3><p>While the cursor is in a tab, either in its title or in its panel, you can use these key combinations:</p><ul><li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Right</kbd>: Move the tab to the right.</li><li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Left</kbd>: Move the tab to the left.</li><li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Home</kbd>: Make it the first tab.</li><li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>End</kbd>: Make it the last tab.</li></ul><h2>Moving content between tabs</h2><p>To move content to another tab, select it in the panel, and then use these key combinations:</p><ul><li><kbd>Ctrl</kbd> + <kbd>Right</kbd>: Move to the tab on the right.</li><li><kbd>Ctrl</kbd> + <kbd>Left</kbd>: Move to the tab on the left.</li><li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>End</kbd>: Move to the last tab.</li><li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Home</kbd>: Move to the first tab.</li></ul><p>The tab that receives the content is shown, with the content still selected, so pressing the key again moves it on to the next tab. Paragraphs, list items, tables and other blocks move whole, even when only part of them is selected. Content moved to a tab on the left goes to the end of that tab, and content moved to a tab on the right goes to its start, so it keeps its place in the reading order.</p><p>Without a selection, or with a selection in a tab title, these keys keep their usual function: moving the cursor by word, or selecting up to the start or end of the tab.</p><p>When a tabs block and a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a> are nested in one another, the key combinations act on the one closest to the cursor.</p><h2>Reading tabs</h2><p>In&nbsp;<a class=\"reference-link\" href=\"#root/_help_CoFPLs3dRlXc\">Read-Only Notes</a>&nbsp;and on&nbsp;<a class=\"reference-link\" href=\"#root/_help_R9pX4DGra2Vt\">Sharing</a>, tabs blocks work as tabs as well:</p><ul><li>To show a tab, click its title, or focus it and press <kbd>Enter</kbd> or <kbd>Space</kbd>.</li><li>To move between the titles of a block, use the arrow keys, <kbd>Home</kbd> and <kbd>End</kbd>.</li></ul><p>A tab without a title shows “Tab title” in place of one.</p><p>In read-only notes, a title too long for its tab fades out where it is cut off. To read the rest of it, swipe it sideways or drag it with the mouse.</p><h2>Linking to a tab</h2><p>A link can point to a single tab, much like a link to a block (see&nbsp;<a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>):</p><ol><li>Place the cursor in the tab, either in its title or in its panel.</li><li>Press <em>Copy link to tab</em> (<span class=\"tn-icon cke cke-link\"></span>) in the toolbar of the tabs block. Alternatively, right-click the text and select <em>Copy</em> → <em>Copy link to this tab</em>. The tab flashes briefly.</li><li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li></ol><p>The link shows the title of the note, followed by the title of the tab. Clicking it opens the note, shows the tab and flashes it. As with any block reference, the link can be turned into an&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>&nbsp;that shows only that tab.</p><p>Links to a tab can be copied only from a note being edited. On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, such a link opens the whole note.</p><h2>Content in hidden tabs</h2><p>Content inside a tab that is not showing is still reachable (both while editing and while reading). The tab that holds it is shown when:</p><ul><li>searching the note with <kbd>Ctrl</kbd>+<kbd>F</kbd> highlights a match inside it;</li><li>a link points to an anchor or a block inside it (see&nbsp;<a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a>&nbsp;and&nbsp;<a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>);</li><li>an entry of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_BFvAtE74rbP6\">Table of contents</a>&nbsp;or the&nbsp;<a class=\"reference-link\" href=\"#root/_help_AxshuNRegLAv\">Highlights list</a>&nbsp;points inside it;</li><li>on a shared page, the address of the page points to a heading or an anchor inside it.</li></ul><p>Tab titles are not headings, so they do not appear in the table of contents; headings inside a panel do.</p><h2>Printing and exporting</h2><ul><li>When printing or <a href=\"#root/_help_NRnIZmSMc5sj\">exporting to PDF</a>, every tab is printed, one after another, each with its title above its panel, whatever the tab alignment.</li><li>Markdown export and import write tabs blocks in the content tabs syntax of Material for MkDocs, described in&nbsp;<a class=\"reference-link\" href=\"#root/_help_rJ9grSgoExl9\">Supported syntax</a>.&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>&nbsp;notes use the same syntax, show the blocks as tabs in their preview and insert them with <code>/tabs</code>. That syntax has no tab alignment, so tabs aligned at the bottom are exported as regular tabs.</li><li>Anywhere the tabs cannot work as tabs (such as an HTML export opened elsewhere), a tabs block reads as a sequence of titled sections.</li></ul>",
"_help_2x0ZAX9ePtzV": "<figure class=\"image image_resized image-style-align-right\" style=\"width:64.63%;\"><img style=\"aspect-ratio:812/585;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Cut%20to%20subnote_cut-to-subnote.gif\" width=\"812\" height=\"585\"></figure><p>When editing a document that becomes too large, you can split it into sub-notes:</p><ol><li>Select the desired text and cut it to the clipboard.</li><li>Create a new sub-note and name it.</li><li>Paste the content from the clipboard into the sub-note.</li></ol><p>Trilium can automate this process. Select some text within the note, and in the selection toolbar, click the scissors icon for the \"cut &amp; pasted selection to sub-note\" action. The heading is automatically detected and the new sub-note is named accordingly. You can also assign a keyboard shortcut for this action. This functionality is available through the block toolbar icon. On a phone, the scissors are at the end of the text formatting row, which shows as you select text.</p>",
"_help_UYuUB1ZekNQU": "<h3>Inline code</h3><p>Inline code formats text using a monospace font to indicate technical content in a sentence such as code, paths, etc.</p><p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Developer-specific%20formatting_image.png\"></p><p>Example of inline code being used to illustrate file system paths as well as shell commands (<code>git</code> in this case).</p><p>To insert an inline code:</p><ul><li>Via the&nbsp;<a href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-code\"></span> button.</li><li>Type `code` where <code>code</code> is the desired text to be automatically formatted as inline code.</li><li>Paste a single line copied from Visual Studio Code. See <a href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a> for pasting several lines.</li></ul><h3>Code blocks</h3><p>Code blocks display a snippet of code as a dedicated block:</p><p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Developer-specific%20formatting_image.jpg\"></p><p>A code block with JavaScript syntax highlight enabled.</p><p>Note that these are not meant for very large portions of code. Use the dedicated&nbsp;<a href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note type instead.</p><p>See the dedicated documentation for more information:&nbsp;<a href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a></p><h3>Keyboard shortcuts</h3><p>This allows marking a portion of text as a shortcut key.</p><p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Developer-specific%20formatting_image.jpg\"></p><p>To apply this style, press the&nbsp;<span class=\"tn-icon cke cke-trilium-kbd\"></span> button in&nbsp;<span class=\"tn-icon bx bx-text\"></span> group from the&nbsp;<a href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. On the floating toolbar, the buttons appear when selecting a text.</p><p>Alternatively, press the <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>K</kbd> combination to apply keyboard shortcut formatting to the current text selection.</p><p>The formatting can be removed by pressing again the button (from the UI or from the keyboard), or by using the&nbsp;<span class=\"tn-icon cke cke-remove-format\"></span> <em>Remove formatting</em> button.</p>",
- "_help_QxEyIjRBizuC": "<p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Developer-specific%20formatting/Code%20blocks_image.jpg\"></p><p>The code blocks feature allows entering pieces of code in text notes.</p><p>Note that this feature is meant for generally small snippets of code. For larger files such as an entire log, see the&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note type instead.</p><h2>Inserting a code block</h2><ul><li>Via the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-code-block\"></span> button.<ul><li>Pressing directly on the icon will insert a code block with the language that was selected most recently. If this is the first time a code block is inserted, the language will be “Auto-detected” by default.</li><li>Pressing the arrow next to the icon, which will show a popup with the available languages.</li></ul></li><li>Type <code>```</code> (as in Markdown).<ul><li>Note that it's not possible to specify the language, as it will default to the last selected language.</li></ul></li><li>Paste several lines of code copied from Visual Studio Code.<ul><li>The code block uses the language of the file in Visual Studio Code.</li><li>If that language is not in the list of languages, the code block uses <em>Auto-detected</em>.</li><li>The colors of the Visual Studio Code theme are removed.</li><li>A single line becomes inline code instead of a code block.</li><li>In Firefox, the code block always uses <em>Auto-detected</em>. Firefox can't read the language from Visual Studio Code.</li></ul></li></ul><h2>Exiting out of the code block</h2><ul><li>To exit out of a code block and enter a normal paragraph, move the cursor at the end of the code block and press Enter twice.</li><li>Similarly, to insert a paragraph above the note block, move the cursor at the beginning of the code block and press Enter twice.</li></ul><aside class=\"admonition note\"><p>If you've pasted a code block with a more complex HTML structure, exiting out of the code block by pressing Enter multiple times might not work. In that case the best approach is to delete the code block entirely and use Ctrl+Shift+V (paste as plain text).</p></aside><h2>Syntax highlighting &amp; color schemes</h2><p>Since TriliumNext v0.90.12, Trilium will try to offer syntax highlighting to the code block. Note that the syntax highlighting mechanism is slightly different than the one in&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;notes as different technologies are involved.</p><p>Interaction:</p><ul><li>When the language is set to <em>Auto-detected</em> (by default), Trilium will try to identify the programming language (or similar) that corresponds to the given snippet of text and highlight it. Only the languages enabled in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em> → <em>Available MIME types in the dropdown</em> are considered. If this is problematic, consider changing the language of the code block manually.</li><li>When the language is set to <em>Plain text</em>, there will be no syntax highlighting.</li></ul><p>Note that when editing a text note, syntax highlighting is automatically disabled if the code block is too big (somewhere around 500 lines). In&nbsp;<a class=\"reference-link\" href=\"#root/_help_CoFPLs3dRlXc\">Read-Only Notes</a>, in print and on a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, a code block of more than 500 lines or 50,000 characters is shown without syntax highlighting. These limits are not configurable.</p><p>In order to configure this new feature, a section has been added in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>Appearance</em> to control the syntax highlighting. There the color scheme can be chosen, from a builtin selection of themes from Highlight.js. <em>VS Code (Light)</em> and <em>VS Code (Dark)</em> use the same colors as the default themes of <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> notes, so a code block and a code note color the same code alike.</p><ul><li>It is possible to disable the syntax highlighting for all the notes by selecting “No syntax highlighting” in the “Color scheme” option.</li><li>Word wrapping is disabled by default, but can be configured from the same section.</li><li>The tab width can also be adjusted from Options.</li></ul><aside class=\"admonition note\"><p><strong>Context regarding syntax highlighting</strong></p><p>In order to achieve the syntax highlight, the Highlight.js library is being used. Do note that support for syntax highlighting in code blocks is not a supported feature of the text editor we are using CKEditor), but rather a hack which makes use of the highlights API (used for highlighting search results for example). Nevertheless, we haven't noticed any major issues during the development of the feature, but feel free to report any issues you might have.</p><p>Most of the work to achieve the syntax highlight itself was already done by <a href=\"https://github.com/antoniotejada\">antoniotejada</a> in <a href=\"https://github.com/antoniotejada/Trilium-SyntaxHighlightWidget\">https://github.com/antoniotejada/Trilium-SyntaxHighlightWidget</a>. On our side we added customization but also additional functionality.</p></aside><h3>Migrating from existing syntax highlight plugins</h3><p>If you are already using a syntax highlighting plugin such as the <a href=\"https://github.com/antoniotejada/Trilium-SyntaxHighlightWidget\">Trilium-SyntaxHighlightWidget</a> we are basing off of, it is important to disable that plugin before upgrading in order for it not to conflict with our implementation.</p><p>Should you encounter any issues after the migration, try running Trilium in safe mode.</p><h2>Changing the language of a code block</h2><p>Simply click anywhere inside the code block and press again the code block button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:<br><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Developer-specific%20formatting/Code%20blocks_image.png\"></p><h2>Adjusting the list of languages</h2><p>The code blocks feature shares the list of languages with the&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note type.</p><p>The supported languages, and the order in which they are listed, can be adjusted by going to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em> → <em>Available MIME types in the dropdown</em>. See <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> for how to add, remove and reorder them.</p><p>Note that the list of languages is not immediately refreshed, you'd have to manually <a href=\"#root/_help_s8alTXmpFR61\">refresh the application</a>.</p><h2>Text replacements and ligatures</h2><p><a class=\"reference-link\" href=\"#root/_help_oI7GoyilXXAr\">Automatic replacements</a>&nbsp;are a feature of text notes which converts some character sequences into another and some of them interfere with programming text, such as the conversion of quotes. While in a code block, the automatic replacements <strong>are not effect</strong>. The only way the automatic replacements can interfere is if the text is typed/pasted before being put in a code block.</p><p>A different feature is <em>programming ligatures</em>, which is simply a display affordance which turns <code>!=</code> into <code>≠</code> or <code>-&gt;</code> as <code>→</code> . These come from the <a href=\"#root/_help_w4rMEhJsALlA\">font</a>. The underlying text is not actually changed, and copying it out gives you back <code>!=</code> and <code>-&gt;</code>.</p><p>Ligatures can be disabled in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a><em>→ Appearance → Fonts → Programming ligatures.</em></p>",
+ "_help_QxEyIjRBizuC": "<p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Developer-specific%20formatting/Code%20blocks_image.jpg\"></p><p>The code blocks feature allows entering pieces of code in text notes.</p><p>Note that this feature is meant for generally small snippets of code. For larger files such as an entire log, see the&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note type instead.</p><h2>Inserting a code block</h2><ul><li>Via the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-code-block\"></span> button.<ul><li>Pressing directly on the icon will insert a code block with the language that was selected most recently. If this is the first time a code block is inserted, the language will be “Auto-detected” by default.</li><li>Pressing the arrow next to the icon, which will show a popup with the available languages.</li></ul></li><li>Type <code>```</code> (as in Markdown).<ul><li>Note that it's not possible to specify the language, as it will default to the last selected language.</li></ul></li><li>Paste several lines of code copied from Visual Studio Code.<ul><li>The code block uses the language of the file in Visual Studio Code.</li><li>If that language is not in the list of languages, the code block uses <em>Auto-detected</em>.</li><li>The colors of the Visual Studio Code theme are removed.</li><li>A single line becomes inline code instead of a code block.</li><li>In Firefox, the code block always uses <em>Auto-detected</em>. Firefox can't read the language from Visual Studio Code.</li></ul></li></ul><h2>Exiting out of the code block</h2><ul><li>To exit out of a code block and enter a normal paragraph, move the cursor at the end of the code block and press Enter twice.</li><li>Similarly, to insert a paragraph above the note block, move the cursor at the beginning of the code block and press Enter twice.</li></ul><aside class=\"admonition note\"><p>If you've pasted a code block with a more complex HTML structure, exiting out of the code block by pressing Enter multiple times might not work. In that case the best approach is to delete the code block entirely and use Ctrl+Shift+V (paste as plain text).</p></aside><h2>Syntax highlighting &amp; color schemes</h2><p>Since TriliumNext v0.90.12, Trilium will try to offer syntax highlighting to the code block. Note that the syntax highlighting mechanism is slightly different than the one in&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;notes as different technologies are involved.</p><p>Interaction:</p><ul><li>When the language is set to <em>Auto-detected</em> (by default), Trilium will try to identify the programming language (or similar) that corresponds to the given snippet of text and highlight it. Only the languages enabled in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em> → <em>Available MIME types in the dropdown</em> are considered. If this is problematic, consider changing the language of the code block manually.</li><li>When the language is set to <em>Plain text</em>, there will be no syntax highlighting.</li></ul><p>Note that when editing a text note, syntax highlighting is automatically disabled if the code block is too big (somewhere around 500 lines). In&nbsp;<a class=\"reference-link\" href=\"#root/_help_CoFPLs3dRlXc\">Read-Only Notes</a>, in print and on a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, a code block of more than 500 lines or 50,000 characters is shown without syntax highlighting. These limits are not configurable.</p><p>In order to configure this new feature, a section has been added in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>Appearance</em> to control the syntax highlighting. There the color scheme can be chosen, from a builtin selection of themes from Highlight.js. <em>VS Code (Light)</em> and <em>VS Code (Dark)</em> use the same colors as the default themes of <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> notes, so a code block and a code note color the same code alike.</p><ul><li>It is possible to disable the syntax highlighting for all the notes by selecting “No syntax highlighting” in the “Color scheme” option.</li><li>Word wrapping is disabled by default, but can be configured from the same section.</li><li>The tab width can also be adjusted from Options.</li></ul><aside class=\"admonition note\"><p><strong>Context regarding syntax highlighting</strong></p><p>In order to achieve the syntax highlight, the Highlight.js library is being used. Do note that support for syntax highlighting in code blocks is not a supported feature of the text editor we are using CKEditor), but rather a hack which makes use of the highlights API (used for highlighting search results for example). Nevertheless, we haven't noticed any major issues during the development of the feature, but feel free to report any issues you might have.</p><p>Most of the work to achieve the syntax highlight itself was already done by <a href=\"https://github.com/antoniotejada\">antoniotejada</a> in <a href=\"https://github.com/antoniotejada/Trilium-SyntaxHighlightWidget\">https://github.com/antoniotejada/Trilium-SyntaxHighlightWidget</a>. On our side we added customization but also additional functionality.</p></aside><h3>Migrating from existing syntax highlight plugins</h3><p>If you are already using a syntax highlighting plugin such as the <a href=\"https://github.com/antoniotejada/Trilium-SyntaxHighlightWidget\">Trilium-SyntaxHighlightWidget</a> we are basing off of, it is important to disable that plugin before upgrading in order for it not to conflict with our implementation.</p><p>Should you encounter any issues after the migration, try running Trilium in safe mode.</p><h2>Changing the language of a code block</h2><p>Simply click anywhere inside the code block and press again the code block button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:<br><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Developer-specific%20formatting/Code%20blocks_image.png\"></p><h2>Adjusting the list of languages</h2><p>The code blocks feature shares the list of languages with the&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note type.</p><p>The supported languages, and the order in which they are listed, can be adjusted by going to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em> → <em>Available MIME types in the dropdown</em>. See <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> for how to add, remove and reorder them.</p><p>Note that the list of languages is not immediately refreshed, you'd have to manually <a href=\"#root/_help_s8alTXmpFR61\">refresh the application</a>.</p><h2>Text replacements and ligatures</h2><p><a class=\"reference-link\" href=\"#root/_help_oI7GoyilXXAr\">Automatic replacements</a>&nbsp;are a feature of text notes which converts some character sequences into another and some of them interfere with programming text, such as the conversion of quotes. While in a code block, the automatic replacements <strong>are not effect</strong>. The only way the automatic replacements can interfere is if the text is typed/pasted before being put in a code block.</p><p>A different feature is <em>programming ligatures</em>, which is simply a display affordance which turns <code>!=</code> into <code>≠</code> or <code>-&gt;</code> as <code>→</code> . These come from the <a href=\"#root/_help_w4rMEhJsALlA\">font</a>. The underlying text is not actually changed, and copying it out gives you back <code>!=</code> and <code>-&gt;</code>.</p><p>Ligatures can be disabled in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a><em>→ Appearance → Fonts → Programming ligatures.</em></p><h2>Extended code blocks</h2><aside class=\"admonition important\"><p>Extended code blocks are experimental, and they change as they mature. To use them, turn on <em>Extended code blocks</em> in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Advanced</em> → <em>Experimental Options</em>.</p></aside><p>An extended code block is a code block that is edited with the code editor of a&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, inside the text. It has the same syntax highlighting and code folding as a code note, and it suits longer pieces of code.</p><ul><li>To insert one, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-code-block\"></span> <em>Extended code block</em>, after <em>Columns</em>. It is also available as <em>Extended code block</em> in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</li><li>A new block is empty and editable, in a <em>Full</em> box, and takes the focus. Its language is the one set last on an extended code block, or <em>Plain text</em>.</li><li>The block shows in a box like the one of an included code note, with the corners and the shadow of a code block. While the block can be edited, its language shows in its top corner, as for a code block.</li><li>Its toolbar has the controls of an embedded code file, described in <em>Editing an include in place</em> in&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>: the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button, the <em>Change language mode</em> and <em>Change tab width</em> menus, and the <span class=\"tn-icon bx bx-move-vertical\"></span> <em>Box size</em> menu, with <em>Small</em>, <em>Medium</em> and <em>Full</em>. Its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu has the <em>Word wrap</em> and <em>Line numbers</em> submenus.</li><li>The changes made in the block are part of the undo history of the text note.</li></ul><p>The code stays in the note as a code block of its language. The Markdown export, <a href=\"#root/_help_R9pX4DGra2Vt\">shared pages</a> and printing show it as a code block, and copying it into another application pastes a code block. Pasted into a text note, it becomes an extended code block again, with its settings.</p><p>Turning <em>Extended code blocks</em> off again removes them from the <em>Insert</em> menu and the slash commands only: the extended code blocks already in notes keep working. A version of Trilium without this feature shows them as code blocks, and saves them back as code blocks, without their box size and other settings.</p>",
"_help_AgjCISero73a": "<figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:199/187;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Footnotes_image.png\" width=\"199\" height=\"187\"></figure><p>Footnotes are a good place to insert references to a paragraph or details that are displayed at the bottom of the note.</p><h2>Interaction</h2><ul><li>To insert a new footnote, press&nbsp;<span class=\"tn-icon cke cke-trilium-insert-footnote\"></span> (or press the right arrow and select <em>New footnote</em>).</li><li>To insert a reference to an existing footnote, press the right arrow and select <em>Insert footnote</em>, followed by the number of the footnote to insert.</li><li>Hovering over a reference (e.g. <code>[1]</code>) will display the content of the footnote in a tooltip for easy reference.</li><li>Clicking on a reference in the text (e.g. <code>[1]</code>) will navigate to the corresponding footnote.</li><li>Similarly, clicking on the <code>^</code> button of a footnote will navigate to the corresponding reference in the text.</li></ul>",
"_help_5wZallV2Qo1t": "<figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:220/76;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Format%20Painter_image.png\" width=\"220\" height=\"76\"></figure><p>The Format Painter is a feature in text notes that allows users to copy the formatting of text (such as <strong>bold</strong>, <em>italic</em>, <del>Strikethrough</del>, etc.) and apply it to other parts of the document. It helps maintain consistent formatting and accelerates the creation of rich content.</p><h2>Usage Instructions</h2><p>Click the text that you want to copy the formatting from and use the <em>Copy formatting</em> toolbar button (<span class=\"tn-icon cke cke-paint-roller\"></span>) to copy the style. Then select the target text with your mouse, or click a word, to apply the formatting.</p><ul><li><strong>To copy the formatting</strong>: Place the cursor inside text with some formatting and click the <em>Copy formatting</em> toolbar button. The mouse cursor changes to indicate the painter is armed.</li><li><strong>To paint with the copied formatting</strong>: Select the target text with your mouse. The formatting is applied when you release the button, and the painter disarms — the cursor returns to normal. Clicking or tapping a word applies it to the whole word.</li><li><strong>To paint a selection made otherwise</strong>, such as with the keyboard or the selection handles of a touch screen: select the target text, then use the toolbar button again, which reads <em>Apply formatting</em> once the selection has moved. On a phone, the formatting row stays open while the painter is armed, so the button stays in reach.</li><li><strong>To cancel without painting</strong>: Click the toolbar button again before selecting other text, or press <kbd>Escape</kbd>.</li></ul><h2>Limitations</h2><ol><li>Painting with block-level formatting (like headings or image styles) is not supported yet. This is because, in&nbsp;<a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>, they are considered a part of the content rather than text formatting.</li><li>A click outside a word, such as between two spaces or at the end of a line, only primes the caret, so text you type there takes the copied formatting.</li><li>The painter is one-shot; each paint requires copying the formatting again.</li></ol>",
"_help_nRhnJkTT8cPs": "<p>Trilium allows two different editing experiences for text notes, based on your preference.</p><p>The type of formatting toolbar can be changed by going to&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;and then looking for the&nbsp;<a class=\"reference-link\" href=\"#root/_hidden/_options/_optionsTextNotes\">Text Notes</a>&nbsp;section. In it, look for the <em>Formatting toolbar</em> category.</p><h2>Floating</h2><p>The floating bar is a more minimalist option, in which the formatting is hidden behind two different popups.</p><h3>Block-level popup</h3><p>The first popup is the block-level popup. This will appear to the left of the current paragraph you are currently editing, as a sequence of dots:<br><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Formatting%20toolbar_image.jpg\"></p><p>Clicking this popup will reveal the formatting options that are specific to the entire paragraph, such as setting a heading, lists, tables, etc.</p><p>The dots are also a drag handle: drag them to move the paragraph, all the selected paragraphs, or a selected element such as an image, a table or an included note to another place in the note. Right-clicking them copies a reference to the paragraph or to the selected paragraphs, see&nbsp;<a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><figure class=\"image\"><img style=\"aspect-ratio:1404/156;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Formatting%20toolbar_image.png\" width=\"1404\" height=\"156\"></figure><h3>Inline popup</h3><p>The inline popup appears automatically when selecting a text:</p><figure class=\"image\"><img style=\"aspect-ratio:1008/154;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Formatting%20toolbar_image.png\" width=\"1008\" height=\"154\"></figure><p>All the options here apply only to the selected portion of text, such as changing the font size, or making the text bold.</p><h2>Fixed</h2><p>The fixed formatting offers a more traditional editing paradigm, usually useful if a lot of formatting is needed.</p><p>All the options are combined into a single toolbar that will appear at the above the note. When using&nbsp;<a class=\"reference-link\" href=\"#root/_help_luNhaphA37EO\">Split View</a>, a single toolbar will be available to save space and it acts on the active note.</p><p>The sequence of dots to the left of the current paragraph is still shown, but only as a drag handle: drag it to move the paragraph, all the selected paragraphs, or a selected element such as an image, a table or an included note to another place in the note. Releasing it above the first paragraph or below the last one moves it to the start or the end of the note. Clicking it does not open a popup, and right-clicking it copies a reference to the block, see&nbsp;<a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. Hovering the drag handle shades the blocks that it moves: inside a table, this is the paragraph in the current cell, and with several cells selected, the whole table. The drag handle is not shown in the mobile layout.</p><figure class=\"image\"><img style=\"aspect-ratio:1440/60;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Formatting%20toolbar_image.png\" width=\"1440\" height=\"60\"></figure><p>By default, if the toolbar does not fit on the screen, the rest of the options will be grouped into a single option at the end. It is possible to display items on multiple lines by checking the corresponding option in the <em>Formatting toolbar</em> section.</p>",
@@ -135,7 +135,7 @@
"_help_VRoP0g1uHHc2": "<figure class=\"image image-style-align-center image_resized\" style=\"width:76.29%;\"><img style=\"aspect-ratio:1479/865;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/In-editor%20AI%20assistant_image.png\" width=\"1479\" height=\"865\"></figure><p>The AI assistant works on the text you are already writing: select a passage and have it rewritten, translated or turned into a table, or ask for new content at the cursor. Unlike the <a href=\"#root/_help_LrKznOtw9cQD\">AI chat</a>, it does not open a conversation window, the result is previewed in place and only enters the note when you accept it.</p><h2>Requirements</h2><p>The assistant is only available once at least one provider is configured in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, with at least one model selected for it. Until then the toolbar entry is not shown at all.</p><h2>Accessing the AI assistant</h2><p>To access the AI assistant:</p><ul><li>Look for the&nbsp;<span class=\"tn-icon cke cke-trilium-ai\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. Press the button itself to enter the <em>Ask AI</em> mode or press the arrow key next to it to access the quick commands and the model selection. On a phone, the button has no arrow: tapping it opens the same menu at the bottom of the screen, with <em>Ask AI…</em> at its top, and a group such as <em>Translate</em> opens as a page of its own.</li><li>Look for <em>AI assistant</em> or any of the <em>AI</em>-prefixed quick commands in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</li><li>Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd>.</li><li>Select a text and choose the <em>AI assistant</em> option in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_jcQVxzYybYgz\">Note contextual menu</a>.</li></ul><h2>What the assistant works on</h2><figure class=\"table\"><table><thead><tr><th>Situation</th><th>What is sent</th></tr></thead><tbody><tr><td>Text is selected</td><td>The selection.</td></tr><tr><td>Nothing is selected, and you pick a quick action</td><td>The paragraph the cursor is in.</td></tr><tr><td>Nothing is selected, and you type your own prompt</td><td>Nothing, the response is new content written at the cursor.</td></tr></tbody></table></figure><p>In all cases the assistant also sends the text before and after the target, so that the model can tell what it is writing into: asked to <em>Continue writing</em> or to summarize, a model that can only see the selected words is guessing at the document around them. This surrounding text is context only, it is never rewritten.</p><aside class=\"admonition important\"><p>That means a single run sends more than the passage you highlighted. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_cRRrdZjgyhNc\">Privacy</a>&nbsp;for exactly what leaves your machine.</p></aside><h2>Quick actions</h2><p>The arrow beside the toolbar button opens a menu of ready-made instructions, grouped by what they do.</p><ul><li>The <em>Reformat</em> actions produce real Trilium content rather than plain text: <em>Diagram</em> inserts a Mermaid diagram, <em>Callout</em> an admonition, and <em>Collapsible</em> a collapsible block.</li><li>The <em>Translate</em> group lists the <a href=\"#root/_help_veGu4faJErEM\">content languages</a> you have enabled, or a predefined list if no content languages are set. It can be filled from within the editor, the last entry of the submenu opens the language configuration directly.</li></ul><p>Actions that need something to work on are greyed out when there is nothing to work on (for example an empty paragraph with no selection).</p><h2>Asking for something specific</h2><p>Choosing <em>Ask AI…</em> (<span class=\"tn-icon bx bx-message-square-dots\"></span>) opens a prompt where you can describe the change in your own words, for example: \"make this less formal\", \"add a row for 2024\", \"write an intro paragraph for this section\". Press <kbd>Enter</kbd> or the <span class=\"tn-icon cke cke-arrow-up\"></span> send button to run it.</p><p>Once a response arrives you can keep going in the same prompt, and the assistant treats it as a conversation rather than as a fresh request: after <em>Translate this to German</em>, asking for <em>make it shorter</em> shortens the German, not the original.</p><h2>Reviewing the result</h2><p>The response streams in as it is generated, and can be interrupted at any point by pressing the <em>Stop</em> (<span class=\"tn-icon cke cke-stop\"></span>) button; whatever arrived before that stays usable.</p><p>Nothing is written into the note until you say so. The review offers:</p><ul><li><em>Result</em>, which displays the response as it will be inserted.</li><li><em>Changes</em>, which displays an inline diff against the original, with insertions and deletions marked. When the model rewrote the passage rather than editing it, the review opens on <em>Result</em> instead: a diff of two texts with little in common is harder to read than the answer itself.</li><li><em>Try again</em> (<span class=\"tn-icon cke cke-refresh\"></span>), to re-run the same instruction.</li><li><em>Replace</em>, which substitutes the original passage</li><li><em>Insert below</em>, which keeps the original and adds the response after it.</li></ul><p>Trilium also reports the model that produced it, the tokens consumed and, for providers that report it, the price.</p><p>If you ask for a correction and there is nothing to correct, the assistant will indicate it instead of showing a blank diff.</p><h2>Choosing the model</h2><p>The bottom of the quick actions menu shows which model the assistant runs on, and lets you pick another from the models you selected in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, grouped by provider.</p><p>The model can also be changed while asking for something specific, or after the assistant has generated its response (i.e. if the response needs a better model).</p><p>This choice is separate from the model used by the chat, and is remembered across notes and devices. Left unset, the assistant follows the first configured provider.</p>",
"_help_mVEYwt20exhO": "<p><em>Quick actions</em> are a feature of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a>&nbsp;for&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes which automatically triggers an LLM suggestion based on a defined prompt. The built-in quick actions come with a predefined prompt, but it is also possible to define your own quick actions.</p><h2>Creating a custom quick action</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right-click the note where you want to place the quick action.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>AI Quick Action</em>. The entry appears only when AI is enabled.</li></ol><p>Afterwards, simply type in the content of the note the desired prompt. The text can be formatted in the same manner as a normal text note and it will be passed to the LLM as Markdown.</p><p>The title of the note will become the title of the quick action.</p><p>Of note:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;notes work too.</li><li>An empty note is ignored.</li><li><a class=\"reference-link\" href=\"#root/_help_MKmLg5x6xkor\">Archived Notes</a>&nbsp;are also excluded.</li></ul><h2>Using a quick action</h2><p>Once a quick action is defined, the action will appear under the <em>Quick Actions</em> dropdown in a group called <em>Custom</em>.</p>",
"_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts &amp; \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>The <em>Include note</em> dialog opens with two rows: <em>Note</em>, where you search for the note to include, and <em>Box size</em> (see <em>Box sizes</em> below), a row of buttons each with a small drawing of the size, with a sentence under it describing the size chosen. Once a note is picked, press <em>Include note</em> or <kbd>Enter</kbd> to include it. Typing the title of a note that does not exist offers to create it.</p><p>An image note, a <a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a> or a <a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a> note picked in the dialog is inserted as an image rather than included, so instead of the size buttons, the <em>Box size</em> row says so. In a text note, the image can be resized once it is in the text, and the dialog reminds you of that, as it reminds you that the size of an include can be changed later.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The <em>Include note</em> dialog selects that size among its <em>Box size</em> buttons once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu. For an included code or Markdown note and an embedded code or Markdown file, the <em>Box size</em> menu is the <span class=\"tn-icon bx bx-move-vertical\"></span> button, whose tooltip names the current size.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.</p><p>In a note being edited, the menu also has the commands of the include's toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>, each checked while it is in effect, and <em>Convert to link</em> at the end. A drawing canvas, a Mermaid diagram, an included text, code or Markdown note and an embedded code or Markdown file also have <em>Editable</em>, above <em>Size</em>. An included code or Markdown note, an embedded code or Markdown file and a Mermaid diagram also have the <em>Word wrap</em> and <em>Line numbers</em> submenus after <em>Editable</em> (see <em>Editing an include in place</em> below). A Mermaid diagram, an included Markdown note and an embedded Markdown file also have <em>Source view</em>, <em>Split view</em> and <em>Preview</em> after these submenus. For an embedded attachment they follow its first group of actions; for an included note they end the menu.</p><p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen, press the <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button at the end of its title. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;(e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a>&nbsp;provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></ul><p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.</p><h2>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. Until then, a code note or file is shown read-only in the code editor, where its code can be selected and copied, and its blocks folded and unfolded with the arrows in its gutter. Included Markdown can be edited too, see <em>Included Markdown</em> below.</p><ul><li>To edit, select the include and turn on the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or check <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. Turn <em>Editable</em> off to stop editing.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>Typing <code>/</code> in the code lists the <a class=\"reference-link\" href=\"#root/_help_IEgsWp5hHH35\">Code Snippets</a> of its language, as in a code note.</li><li>The toolbar of an included code note or an embedded code file also has the language and indentation menus of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>, between <em>Editable</em> and the <span class=\"tn-icon bx bx-move-vertical\"></span> <em>Box size</em> menu: <em>Change language mode</em>, which shows the current language, and <em>Change tab width</em>, which shows the current indentation. <em>Re-indent content to</em> converts the indentation of the code itself and saves it to the included note or file, whether <em>Editable</em> is on or off.<ul><li>For an included note, the menus change the note, as they do in its own tab.</li><li>For an embedded code file, the language and indentation settings change only how this include shows the file, and are saved with the note that includes it. The language replaces the one that the file name gives, and the <em>Use default</em> entries return to the indentation set in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. These settings leave the file itself unchanged, and other includes of it keep their own settings.</li></ul></li><li>The <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu of an included code or Markdown note, an embedded code or Markdown file and a <a href=\"#root/_help_CohkqWQC1iBv\">Mermaid diagram</a> has two more submenus after <em>Editable</em>, each with <em>Auto</em>, <em>On</em> and <em>Off</em>. They change how the code editor shows the source.<ul><li><em>Word wrap</em> wraps long lines instead of scrolling them. <em>Auto</em> follows the setting in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. For an included note, it sets the <code>#wrapLines</code> label of the note, as the <em>Word wrap</em> submenu of its <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> does for a code note. For an embedded file or a Mermaid diagram, it changes only this include.</li><li><em>Line numbers</em> shows or hides the numbers at the start of each line. <em>Auto</em> follows the setting in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. It changes only this include, for an included note as well.</li></ul></li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>The changes made in the code editor of an include are part of the undo history of the note that includes it, together with the changes to its text, in the order they were made. This includes the source of included Markdown and of a <a href=\"#root/_help_CohkqWQC1iBv\">Mermaid diagram</a>, and the changes to a drawing canvas (see below).<ul><li><kbd>Ctrl</kbd>+<kbd>Z</kbd> undoes the last change of the note, and <kbd>Ctrl</kbd>+<kbd>Y</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> redoes it, whether the caret is in the text or in an include, and also while <em>Editable</em> is off. The <span class=\"tn-icon cke cke-undo\"></span> <em>Undo</em> and <span class=\"tn-icon cke cke-redo\"></span> <em>Redo</em> buttons of the formatting toolbar do the same. With the Vim key bindings, <code>u</code> and <kbd>Ctrl</kbd>+<kbd>R</kbd> in an include do the same too.</li><li>The focus moves to the change that was undone or redone: into the code editor or the drawing canvas of the include, or back to the text.</li><li>Undoing a change of an included note saves the included note again. Once the included note has been changed elsewhere, for example in another tab, its earlier changes can no longer be undone from here, and undo skips them.</li><li>An included text note keeps an undo history of its own.</li></ul></li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a> finds the text of included text and code notes among the results of the note around them, and replaces it while <em>Editable</em> is on.</li></ul><h2>Included Markdown</h2><p>An included&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>&nbsp;note and an embedded Markdown file, such as a <code>.md</code> attachment, are shown with the same three views as a Markdown note in its own tab (see&nbsp;<a class=\"reference-link\" href=\"#root/_help_SL5f1Auq7sVN\">Note types with split view</a>): <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em>, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em>.</p><ul><li>To switch the view, press one of the three buttons in the title row of the include. In a note being edited, the toolbar of the include has the same buttons after <em>Editable</em>, and its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu has them as <em>Source view</em>, <em>Split view</em> and <em>Preview</em>.</li><li>Until a view is chosen, the include shows the <em>Preview</em>, and the <em>Split view</em> while <em>Editable</em> is on.</li><li>To edit the Markdown, turn on <em>Editable</em> (see <em>Editing an include in place</em> above). The source is edited in the code editor of a Markdown note, and the preview follows the changes as you type. While <em>Editable</em> is off, the source can be read and copied but not changed.</li><li>The source has the slash commands and the <code>@</code> and <code>[[</code> note links of a <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> note. A note created from the <code>@</code> or <code>[[</code> list goes under the included note, or for an embedded file under the note that includes it, and <code>/image</code> uploads the image to that same note.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of the <em>More actions</em> menu change how the source shows, as for code (see <em>Editing an include in place</em> above).</li><li>As in a Markdown note, the preview scrolls along with the source and highlights the block where the cursor is, and <kbd>Ctrl</kbd>+<kbd>B</kbd>, <kbd>Ctrl</kbd>+<kbd>I</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> format the selection.</li><li>In a note being edited, the view is saved with the include, so two includes of the same note can show different views. In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the view can be changed too, until the note is opened again.</li><li>While the source shows, the include has the height of its box size, or the height it was resized to. A <em>Full</em> include fits its content instead.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a>&nbsp;searches the source while it shows, and the preview otherwise.</li></ul><h2>Drawing canvases</h2><p>A drawing canvas is an Excalidraw canvas, like the one of a <a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with <em>Attach and embed file</em>, under the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button, becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>The changes to the drawing are part of the undo history of the text note (see <em>Editing an include in place</em> above). <kbd>Ctrl</kbd>+<kbd>Z</kbd>, <kbd>Ctrl</kbd>+<kbd>Y</kbd> and the <span class=\"tn-icon bx bx-undo\"></span> <em>Undo</em> and <span class=\"tn-icon bx bx-redo\"></span> <em>Redo</em> buttons of the canvas toolbar undo and redo the last change of the note, in the drawing or in the text.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",
- "_help_CohkqWQC1iBv": "<p>Press the&nbsp;<span class=\"tn-icon cke cke-plus\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;to reveal special inserable items and blocks such as symbols, Math expressions and separators.</p><h2>Bookmarks</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a>&nbsp;section.</p><h2>Emoji</h2><figure class=\"image image-style-align-right image_resized\" style=\"width:42.4%;\"><img style=\"aspect-ratio:366/410;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_plus.png\" width=\"366\" height=\"410\"></figure><p>This feature allows inserting Unicode emoji characters. Simply select a category and a desired emoji to insert it.</p><p>Emojis can also be searched by their English name and the skin tone can be selected via a combo box to the right.</p><p>There is also the possibility of inserting emojis directly by typing <code>:</code> followed by a name of an emoji, triggering the display of a list of emojis. Simply use the arrow keys to select one and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to insert it.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_plus.png\" width=\"272\" height=\"187\"><h2>Symbols</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:346/322;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_image.png\" width=\"346\" height=\"322\"></figure><p>Pressing the&nbsp;<span class=\"tn-icon cke cke-special-characters\"></span> button will reveal a popup window displaying a list of characters that are generally more difficult to insert directly from the keyboard, such as a subset of emojis, quotation characters, etc.</p><p>Interaction:</p><ul><li>Click on a character to insert it at the current cursor position.</li><li>The window can be dragged around by the top bar where the title is, to avoid it getting in the way of the text.</li><li>Click on the <em>Category</em> selector to filter the characters.</li></ul><h2>Multicolumn layout</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a>&nbsp;page.</p><h2>Math equations</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a>&nbsp;page.</p><h2>Drawing canvas</h2><p>Choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em> to draw on an Excalidraw canvas inside the text. See <em>Drawing canvases</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><h2>Mermaid diagram</h2><p>Press the&nbsp;<span class=\"tn-icon cke cke-trilium-mermaid-insert\"></span> button to create an inline Mermaid diagram. The arrow next to it lists a template for each kind of diagram. The diagram is also available as <em>Mermaid diagram</em> in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</p><p>This feature is quite similar to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>&nbsp;note types and is meant as an alternative to it for simple diagrams. For more complex diagrams, use the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>&nbsp;feature for a dedicated Mermaid note.</p><figure class=\"image\"><img style=\"aspect-ratio:1174/358;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Insert%20buttons_image.png\" width=\"1174\" height=\"358\"></figure><p>A diagram shows in a box like the one of an included note, so it can be resized, given another box size (<em>Small</em>, <em>Medium</em> or <em>Full</em>) from its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu or shown in fullscreen, as described in&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><ul><li>The <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of the diagram's toolbar decides whether its source can be changed. While it is off, the source still shows, but read-only.</li><li>The buttons next to it choose what the diagram shows, as for a Mermaid note: <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em> for the Mermaid source alone, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> for the source with the diagram next to it, and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em> for the diagram alone. Its <em>More actions</em> menu offers the same choice.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of its <em>More actions</em> menu change how the source shows, each with <em>Auto</em>, <em>On</em> and <em>Off</em>, as for an included code note (see <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>).</li><li>A new diagram starts editable, in <em>Split view</em>. The diagram updates a moment after you stop typing. If the source has an error, the error shows over the last diagram that worked, which stays dimmed, as in a Mermaid note. On desktop, drag the divider between the source and the diagram to resize them.</li><li>A diagram without a chosen view shows the source next to the diagram while it is editable, and the diagram alone otherwise. In a read-only note, the source can never be changed. A read-only note and the AI chat show a diagram in the same box, in the view it was saved with, and with the zoom buttons over the diagram instead of in a toolbar. A <em>Medium</em> or <em>Full</em> diagram also has a <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button there, or over the source in the <em>Source</em> view.</li><li>To zoom, use the <span class=\"tn-icon bx bx-zoom-out\"></span> and <span class=\"tn-icon bx bx-zoom-in\"></span> buttons of the diagram's toolbar; the zoom level between them resets the zoom. In fullscreen, where the toolbar is hidden, the same buttons show over the diagram. Drag the diagram to move around it, and double-click it to reset the view. The mouse wheel scrolls the note until you click the diagram, and then zooms it.</li><li>While the source shows, the <span class=\"tn-icon bx bx-help-circle\"></span> <em>Mermaid syntax help</em> button at the end of the toolbar opens the help on&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>, which links to the Mermaid syntax.</li><li>The changes made to the source of a diagram are part of the undo history of the text note, in the order they were made. <kbd>Ctrl</kbd>+<kbd>Z</kbd> and <kbd>Ctrl</kbd>+<kbd>Y</kbd> undo and redo them from the source as well as from the text, as described in <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</li></ul><p>The source of the diagram stays in the note as a Mermaid code block, so the diagram is exported to Markdown as a <code>mermaid</code> code block that other applications can show.</p><p>Diagrams created in earlier versions keep the view they were saved with, and open editable.</p><h2>Horizontal ruler</h2><p>This feature will display a horizontal line, generally useful to separate different sections of the text. To do so, press the&nbsp;<span class=\"tn-icon cke cke-horizontal-line\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_image.png\" width=\"502\" height=\"95\"><p>Alternatively, it's possible to insert a horizontal ruler by typing <code>---</code>.</p><h2>Page break</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:371/79;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Insert%20buttons_image.png\" width=\"371\" height=\"79\"></figure><p>Page breaks provide a way to force the next paragraph or block (table, image, etc.) to be displayed onto the next page when printing (either to a real printer to <a href=\"#root/_help_NRnIZmSMc5sj\">when exporting to PDF</a>).</p><p>Page breaks are marked in the editor with the words <em>Page break</em>, but they will not actually be shown when printed.</p><ul><li>To insert a page break, press the&nbsp;<span class=\"tn-icon cke cke-page-break\"></span> in the formatting toolbar.</li><li>To insert many page breaks at once, insert a page break first, click on it and press <kbd>Ctrl</kbd>+<kbd>C</kbd>. Then use <kbd>Ctrl</kbd>+<kbd>V</kbd>, to paste as many times as needed.</li></ul><h2>Date and time</h2><p>The <span class=\"tn-icon cke cke-trilium-date-time\"></span> button inserts the current date and time at the cursor, replacing the selected text if there is any. The inserted text takes the formatting of the text around it, so a date inserted inside bold text is bold too.</p><ul><li>To insert the date in the default format, press the button itself or press <kbd>Alt</kbd>+<kbd>T</kbd>.</li><li>To insert it in another format, press the arrow next to the button and pick a format from the list. Each entry shows the current date and time in that format: the default one, the date or the time alone, the date written out, and ISO 8601.</li><li>The same formats are offered by the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>: type <code>/date</code>, <code>/time</code>, <code>/now</code> or <code>/today</code>. The <em>Insert date/time</em> entry uses the default format, and shows what it inserts underneath; the other entries show their output in the title.</li></ul><p>The default format can be changed in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em>, using <a href=\"https://day.js.org/docs/en/display/format\">Day.js format tokens</a> (for example <code>DD.MM.YYYY HH:mm</code>).</p><h2>Icons</h2><p>Icons just like the ones for the <a href=\"#root/_help_p9kXRFAkwN4o\">note icon</a> can be inserted in text. For more information see&nbsp;<a class=\"reference-link\" href=\"#root/_help_hD8GawVuazff\">Icons</a>.</p>",
+ "_help_CohkqWQC1iBv": "<p>Press the&nbsp;<span class=\"tn-icon cke cke-plus\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;to reveal special inserable items and blocks such as symbols, Math expressions and separators.</p><h2>Bookmarks</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a>&nbsp;section.</p><h2>Emoji</h2><figure class=\"image image-style-align-right image_resized\" style=\"width:42.4%;\"><img style=\"aspect-ratio:366/410;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_plus.png\" width=\"366\" height=\"410\"></figure><p>This feature allows inserting Unicode emoji characters. Simply select a category and a desired emoji to insert it.</p><p>Emojis can also be searched by their English name and the skin tone can be selected via a combo box to the right.</p><p>There is also the possibility of inserting emojis directly by typing <code>:</code> followed by a name of an emoji, triggering the display of a list of emojis. Simply use the arrow keys to select one and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to insert it.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_plus.png\" width=\"272\" height=\"187\"><h2>Symbols</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:346/322;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_image.png\" width=\"346\" height=\"322\"></figure><p>Pressing the&nbsp;<span class=\"tn-icon cke cke-special-characters\"></span> button will reveal a popup window displaying a list of characters that are generally more difficult to insert directly from the keyboard, such as a subset of emojis, quotation characters, etc.</p><p>Interaction:</p><ul><li>Click on a character to insert it at the current cursor position.</li><li>The window can be dragged around by the top bar where the title is, to avoid it getting in the way of the text.</li><li>Click on the <em>Category</em> selector to filter the characters.</li></ul><h2>Multicolumn layout</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a>&nbsp;page.</p><h2>Extended code block</h2><p>Choose <span class=\"tn-icon bx bx-code-block\"></span> <em>Extended code block</em> to insert a code block that is edited as a code note. This entry is experimental and is shown only once it is turned on. See <em>Extended code blocks</em> in&nbsp;<a class=\"reference-link\" href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a>.</p><h2>Math equations</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a>&nbsp;page.</p><h2>Drawing canvas</h2><p>Choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em> to draw on an Excalidraw canvas inside the text. See <em>Drawing canvases</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><h2>Mermaid diagram</h2><p>Press the&nbsp;<span class=\"tn-icon cke cke-trilium-mermaid-insert\"></span> button to create an inline Mermaid diagram. The arrow next to it lists a template for each kind of diagram. The diagram is also available as <em>Mermaid diagram</em> in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</p><p>This feature is quite similar to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>&nbsp;note types and is meant as an alternative to it for simple diagrams. For more complex diagrams, use the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>&nbsp;feature for a dedicated Mermaid note.</p><figure class=\"image\"><img style=\"aspect-ratio:1174/358;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Insert%20buttons_image.png\" width=\"1174\" height=\"358\"></figure><p>A diagram shows in a box like the one of an included note, so it can be resized, given another box size (<em>Small</em>, <em>Medium</em> or <em>Full</em>) from its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu or shown in fullscreen, as described in&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><ul><li>The <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of the diagram's toolbar decides whether its source can be changed. While it is off, the source still shows, but read-only.</li><li>The buttons next to it choose what the diagram shows, as for a Mermaid note: <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em> for the Mermaid source alone, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> for the source with the diagram next to it, and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em> for the diagram alone. Its <em>More actions</em> menu offers the same choice.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of its <em>More actions</em> menu change how the source shows, each with <em>Auto</em>, <em>On</em> and <em>Off</em>, as for an included code note (see <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>).</li><li>A new diagram starts editable, in <em>Split view</em>. The diagram updates a moment after you stop typing. If the source has an error, the error shows over the last diagram that worked, which stays dimmed, as in a Mermaid note. On desktop, drag the divider between the source and the diagram to resize them.</li><li>A diagram without a chosen view shows the source next to the diagram while it is editable, and the diagram alone otherwise. In a read-only note, the source can never be changed. A read-only note and the AI chat show a diagram in the same box, in the view it was saved with, and with the zoom buttons over the diagram instead of in a toolbar. A <em>Medium</em> or <em>Full</em> diagram also has a <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button there, or over the source in the <em>Source</em> view.</li><li>To zoom, use the <span class=\"tn-icon bx bx-zoom-out\"></span> and <span class=\"tn-icon bx bx-zoom-in\"></span> buttons of the diagram's toolbar; the zoom level between them resets the zoom. In fullscreen, where the toolbar is hidden, the same buttons show over the diagram. Drag the diagram to move around it, and double-click it to reset the view. The mouse wheel scrolls the note until you click the diagram, and then zooms it.</li><li>While the source shows, the <span class=\"tn-icon bx bx-help-circle\"></span> <em>Mermaid syntax help</em> button at the end of the toolbar opens the help on&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>, which links to the Mermaid syntax.</li><li>The changes made to the source of a diagram are part of the undo history of the text note, in the order they were made. <kbd>Ctrl</kbd>+<kbd>Z</kbd> and <kbd>Ctrl</kbd>+<kbd>Y</kbd> undo and redo them from the source as well as from the text, as described in <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</li></ul><p>The source of the diagram stays in the note as a Mermaid code block, so the diagram is exported to Markdown as a <code>mermaid</code> code block that other applications can show.</p><p>Diagrams created in earlier versions keep the view they were saved with, and open editable.</p><h2>Horizontal ruler</h2><p>This feature will display a horizontal line, generally useful to separate different sections of the text. To do so, press the&nbsp;<span class=\"tn-icon cke cke-horizontal-line\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_image.png\" width=\"502\" height=\"95\"><p>Alternatively, it's possible to insert a horizontal ruler by typing <code>---</code>.</p><h2>Page break</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:371/79;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Insert%20buttons_image.png\" width=\"371\" height=\"79\"></figure><p>Page breaks provide a way to force the next paragraph or block (table, image, etc.) to be displayed onto the next page when printing (either to a real printer to <a href=\"#root/_help_NRnIZmSMc5sj\">when exporting to PDF</a>).</p><p>Page breaks are marked in the editor with the words <em>Page break</em>, but they will not actually be shown when printed.</p><ul><li>To insert a page break, press the&nbsp;<span class=\"tn-icon cke cke-page-break\"></span> in the formatting toolbar.</li><li>To insert many page breaks at once, insert a page break first, click on it and press <kbd>Ctrl</kbd>+<kbd>C</kbd>. Then use <kbd>Ctrl</kbd>+<kbd>V</kbd>, to paste as many times as needed.</li></ul><h2>Date and time</h2><p>The <span class=\"tn-icon cke cke-trilium-date-time\"></span> button inserts the current date and time at the cursor, replacing the selected text if there is any. The inserted text takes the formatting of the text around it, so a date inserted inside bold text is bold too.</p><ul><li>To insert the date in the default format, press the button itself or press <kbd>Alt</kbd>+<kbd>T</kbd>.</li><li>To insert it in another format, press the arrow next to the button and pick a format from the list. Each entry shows the current date and time in that format: the default one, the date or the time alone, the date written out, and ISO 8601.</li><li>The same formats are offered by the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>: type <code>/date</code>, <code>/time</code>, <code>/now</code> or <code>/today</code>. The <em>Insert date/time</em> entry uses the default format, and shows what it inserts underneath; the other entries show their output in the title.</li></ul><p>The default format can be changed in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em>, using <a href=\"https://day.js.org/docs/en/display/format\">Day.js format tokens</a> (for example <code>DD.MM.YYYY HH:mm</code>).</p><h2>Icons</h2><p>Icons just like the ones for the <a href=\"#root/_help_p9kXRFAkwN4o\">note icon</a> can be inserted in text. For more information see&nbsp;<a class=\"reference-link\" href=\"#root/_help_hD8GawVuazff\">Icons</a>.</p>",
"_help_hD8GawVuazff": "<p>Icons just like the <a href=\"#root/_help_hD8GawVuazff\">note icons</a> can be inserted in the content of a note, including from any other <a href=\"#root/_help_gOKqSJgXLcIj\">custom icon packs</a>.</p><h2>Features</h2><ul><li>The icon can be formatted through the<a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a>&nbsp;tools of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:<ul><li>Foreground/icon color</li><li>Background color/highlight</li><li>Font size</li></ul></li><li>Custom&nbsp;<a class=\"reference-link\" href=\"#root/_help_gOKqSJgXLcIj\">Icon Packs</a>&nbsp;are also supported.<ul><li>For emojis, prefer the Emoji functionality from&nbsp;<a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</li></ul></li><li>When an icon is clicked a floating toolbar appears with the following functions:<ul><li><span class=\"tn-icon bx bx-sticker\"></span>&nbsp;which changes the icon.</li><li><span class=\"tn-icon bx bx-reflect-horizontal\"></span>&nbsp;which applies transforms: rotate (90 / 180 / 270) and flip horizontal/vertical. Only one transform can be used per icon.</li></ul></li></ul><h2>Usage</h2><ul><li>The in-app help/user guide makes use of these icons in order to illustrate buttons in the UI.</li><li>The&nbsp;<a class=\"reference-link\" href=\"#root/_help_GnhlmrATVqcH\">Microsoft OneNote</a>&nbsp;importer also makes use of them for the&nbsp;<a class=\"reference-link\" href=\"#root/_help_LpvyEIBIAAj7\">Tags</a>.</li></ul><h2>Inserting an icon</h2><p>There are two ways to insert an icon:</p><ul><li>Via the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;look for the&nbsp;<span class=\"tn-icon bx bx-plus\"></span> icon and then the&nbsp;<span class=\"tn-icon bx bx-sticker\"></span> icon.</li><li>Via&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>, type <code>/icon</code>.</li></ul><p>An icon picker will appear, search for an icon and click it to insert it in the document.</p><h2>Finding notes by their icons</h2><p>An icon can be <a href=\"#root/_help_eIg8jdvaoNNd\">searched</a>. A note containing a&nbsp;<span class=\"tn-icon bx bx-star\"></span> icon can be found by searching for <code>star</code>, or its <code>iconClass</code> (<code>bx-star</code>).</p><p>To find the name of the icon, hover the mouse over an icon while in the icon picker.</p><h2>Markdown rendering</h2><p>When exporting to&nbsp;<a class=\"reference-link\" href=\"#root/_help_Oau6X9rCuegd\">Markdown</a>, the item will render as raw HTML representation of the icon as is used by Trilium:</p><pre><code class=\"language-text-html\">&lt;span class=\"tn-icon bx bx-star\"&gt;&lt;/span&gt;</code></pre>",
"_help_oiVPnW8QfnvS": "<h2>Trilium-specific shortcuts</h2><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Bring up inline formatting toolbar (arrow keys ←,→ to navigate, Enter to apply)</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Bring up block formatting toolbar</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">external link</a></td><td>Ctrl+K</td><td>⌘+K</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">internal (note) link</a></td><td>Ctrl+L</td><td>⌘+L</td></tr><tr><td>Inserts current date and time at caret position</td><td>Alt+T</td><td>⌥+T</td></tr><tr><td>Increase paragraph indentation</td><td>Tab</td><td>⇥</td></tr><tr><td>Decrease paragraph indentation</td><td>Shift + Tab</td><td>⇧ + ⇥</td></tr><tr><td>Mark selected text as <a href=\"#root/_help_UYuUB1ZekNQU\">keyboard shortcut</a></td><td>Ctrl + Alt + K</td><td>⌘+ ⌥+ K</td></tr><tr><td>Insert&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a></td><td>Ctrl + M</td><td>⌘+ M</td></tr><tr><td>Move blocks (lists, paragraphs, etc.) up, or in a <a href=\"#root/_help_NdowYOC1GFKS\">table</a> the rows</td><td>Alt+↑</td><td>⌥+↑</td></tr><tr><td>Move blocks (lists, paragraphs, etc.) down, or in a <a href=\"#root/_help_NdowYOC1GFKS\">table</a> the rows</td><td>Alt+↓</td><td>⌥+↓</td></tr><tr><td>Move the selected content to another column of a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current column of a multicolumn layout</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a column after or before the current one in a multicolumn layout</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr><tr><td>Move the selected content to another tab in <a class=\"reference-link\" href=\"#root/_help_EK2ckIZ74tbT\">Content tabs</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current tab of a tabs block</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a tab after or before the current one in a tabs block</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr></tbody></table></figure><h2>Common shortcuts</h2><aside class=\"admonition tip\"><p>This section of keyboard shortcuts presents a subset of the keyboard shortcuts as supported by the editor technology we are using,&nbsp;<a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>. The shortcuts were taken from the <a href=\"https://ckeditor.com/docs/ckeditor5/latest/features/accessibility.html#keyboard-shortcuts\">official documentation</a>. Note that not all the shortcuts in the original documentation are applicable (due to using a different configuration).</p></aside><h3>Content editing</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a hard break (a new paragraph)</td><td>Enter</td><td></td></tr><tr><td>Insert a soft break (a <code>&lt;br&gt;</code> element)</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Copy selected content</td><td>Ctrl+C</td><td>⌘C</td></tr><tr><td>Paste content</td><td>Ctrl+V</td><td>⌘V</td></tr><tr><td>Paste content as plain text</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Undo</td><td>Ctrl+Z</td><td>⌘Z</td></tr><tr><td>Redo</td><td>Ctrl+Y, Ctrl+Shift+Z</td><td>⌘Y, ⌘⇧Z</td></tr><tr><td>Bold text</td><td>Ctrl+B</td><td>⌘B</td></tr><tr><td>Change text case</td><td>Shift+F3</td><td>⇧F3 (may require Fn)</td></tr><tr><td>Create link</td><td>Ctrl+K</td><td>⌘K</td></tr><tr><td>Move out of a link</td><td>←←, →→</td><td></td></tr><tr><td>Move out of an inline code style</td><td>←←, →→</td><td></td></tr><tr><td>Select all</td><td>Ctrl+A</td><td>⌘A</td></tr><tr><td>Find in the document</td><td>Ctrl+F</td><td>⌘F</td></tr><tr><td>Copy text formatting</td><td>Ctrl+Shift+C</td><td>⌘⇧C</td></tr><tr><td>Paste text formatting</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Italic text</td><td>Ctrl+I</td><td>⌘I</td></tr><tr><td>Strikethrough text</td><td>Ctrl+Shift+X</td><td>⌘⇧X</td></tr><tr><td>Underline text</td><td>Ctrl+U</td><td>⌘U</td></tr><tr><td>Revert autoformatting action</td><td>Backspace</td><td></td></tr></tbody></table></figure><h3>Interacting with blocks</h3><p>Blocks are images, tables, blockquotes, annotations.</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a new paragraph directly after a widget</td><td>Enter</td><td></td></tr><tr><td>Insert a new paragraph directly before a widget</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Move the caret to allow typing directly before a widget</td><td>↑, ←</td><td></td></tr><tr><td>Move the caret to allow typing directly after a widget</td><td>↓, →</td><td></td></tr><tr><td>After entering a nested editable, move the selection to the closest ancestor widget. For example: move from an image caption to the whole image widget.</td><td>Tab then Esc</td><td></td></tr></tbody></table></figure><p>Specifically for lists:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Increase list item indent</td><td>⇥</td><td></td></tr><tr><td>Decrease list item indent</td><td>Shift+⇥</td><td>⇧⇥</td></tr></tbody></table></figure><p>In tables:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Move the selection to the next cell</td><td>⇥</td><td></td></tr><tr><td>Move the selection to the previous cell</td><td>Shift+⇥</td><td>⇧⇥</td></tr><tr><td>Insert a new table row (when in the last cell of a table)</td><td>⇥</td><td></td></tr><tr><td>Navigate through the table</td><td>↑, →, ↓, ←</td><td></td></tr></tbody></table></figure><h3>General UI shortcuts</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Close contextual balloons, dropdowns, and dialogs</td><td>Esc</td><td></td></tr><tr><td>Open the accessibility help dialog</td><td>Alt+0</td><td>⌥0</td></tr><tr><td>Move focus between form fields (inputs, buttons, etc.)</td><td>⇥, Shift+⇥</td><td>⇥, ⇧⇥</td></tr><tr><td>Move focus to the toolbar, navigate between toolbars</td><td>Alt+F10</td><td>⌥F10 (may require Fn)</td></tr><tr><td>Navigate through the toolbar or menu bar</td><td>↑, →, ↓, ←</td><td></td></tr><tr><td>Navigate to the next focusable field or an element outside the editor</td><td>Tab, Shift+Tab</td><td></td></tr><tr><td>Execute the currently focused button. Executing buttons that interact with the editor content moves the focus back to the content.</td><td>Enter, Space</td><td></td></tr><tr><td>Move focus in and out of an active dialog window</td><td>Ctrl+F6</td><td>⌘F6 (may require Fn)</td></tr></tbody></table></figure>",
"_help_UmgZAfcltxkS": "<p>Link previews turn a pasted URL into a rich, metadata-aware widget that can be displayed in three visual modes:</p><h2>Display modes</h2><p>A link preview can be displayed in one of three modes:</p><ul><li><strong>Inline</strong> — a link showing the site's favicon and page title (quite similar to&nbsp;<a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a>). Use this when you want the link to flow with the surrounding paragraph.</li><li><strong>Card</strong> — a block-level preview with thumbnail, title, description, and site name. Use this when the link is the focus of a paragraph.</li><li><strong>Embed</strong> — a block-level interactive embed.<ul><li>Currently supported for YouTube videos, which render interactively (via an <code>iframe</code>).</li><li>To prevent unwanted remote requests, the video is shown only after clicking on it first.</li></ul></li></ul><div class=\"trilium-multicolumn-layout\" data-trilium-column-ratios=\"1-1-1\"><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:251/42;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Link%20Previews_image.png\" width=\"251\" height=\"42\"><figcaption><em>Inline</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:1217/196;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Link%20Previews_image.png\" width=\"1217\" height=\"196\"><figcaption><em>Card</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:994/563;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Link%20Previews_image.png\" width=\"994\" height=\"563\"><figcaption><em>Embed</em> link preview</figcaption></figure></div></div><h2>Inserting a link preview</h2><p>There are three ways to create one:</p><h3>1. By pasting a URL</h3><p>A link preview is automatically created:</p><ul><li>By pasting the URL and pressing <kbd>Space</kbd>. This will create an <em>inline</em> link preview.</li><li>When at the start of a new paragraph, pressing <kbd>Enter</kbd> will create a <em>card</em> or an <em>embed</em> for YouTube URLs.</li></ul><p>To undo an automatic link preview, press <kbd>Ctrl</kbd>+<kbd>Z</kbd> immediately afterwards which keeps it as a plain link instead. Alternatively, once a link preview was created, click on the link and select <em>Plain link</em> from the link preview toolbar.</p><p>This automatic conversion can be disabled by going to&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>Text Notes</em> and unchecking <em>Autogenerate link previews</em> from the <em>Features</em> section.</p><p>If the link is not accessible to the Trilium server (or the network request fails for any other reason), it will not be converted to a link preview.</p><aside class=\"admonition note\"><p>A URL is only auto-converted when the pasted text <em>is</em> the URL. Links with a display name (e.g. <a href=\"https://triliumnotes.org\">Trilium Notes website</a>) are left as plain links.</p></aside><h3>2. By using the \"Link preview\" toolbar button or slash command</h3><p>Click <em>Link preview</em> (<span class=\"tn-icon cke cke-trilium-link-preview\"></span>) in the formatting toolbar to open the <em>Link preview</em> popup. Paste the URL and choose the type of preview.</p><p>Alternatively, use <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a> and look for <em>link preview</em> (it is also found by <em>embed</em>, <em>url</em> or <em>video</em>), which opens the same popup at the cursor.</p><h3>3. By saving browser tabs from the Web Clipper</h3><p>When the&nbsp;<a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a>&nbsp;saves the tabs of a window, each tab becomes an <em>inline</em> link preview showing the title and favicon the browser displays for it. Because this data comes from the browser, pages behind a login keep their real title, and the Trilium server does not contact the saved pages.</p><p>When <em>Autogenerate link previews</em> is turned off, the tabs are saved as a list of plain links instead.</p><h2>Altering an existing link preview</h2><p>Click on an inserted link preview to select it, and a small toolbar will appear with the following options:</p><ul><li>The normal link operations (opening in a new tab, copying the link, unlinking).</li><li>A button to edit the title of the link preview. This is especially useful if the title is hidden behind a login screen.</li><li>A way to switch between the link preview modes (Inline, Card or Embed) as well as to convert it to a normal link instead.<ul><li>The Embed option is only enabled when the URL points to a supported service (YouTube today).</li></ul></li></ul><h2>Where the preview data comes from</h2><p>When you insert a link preview, Trilium fetches metadata once and stores it inside the note's HTML:</p><ul><li><strong>YouTube URLs</strong> — title, channel name, and thumbnail are fetched via YouTube's public oEmbed endpoint.</li><li><strong>All other URLs</strong> — Trilium fetches the page and reads OpenGraph tags (<code>og:title</code>, <code>og:description</code>, <code>og:image</code>, <code>og:site_name</code>), falling back to the page's <code>&lt;title&gt;</code> and <code>&lt;meta name=\"description\"&gt;</code>. The site's favicon is downloaded and inlined.</li></ul><p>Because the data is stored in the note itself, link previews continue to render correctly when you reopen the note, share/publish it, or export to HTML — without any further network requests.</p><p>The metadata is captured <strong>at insertion time</strong> and is not automatically refreshed. If the linked page later changes its title or thumbnail, you'll need to re-insert the link to pick up the new values. To refresh a link, simply create it again.</p><p>When accessing a&nbsp;<a class=\"reference-link\" href=\"#root/_help_WOcw2SLH6tbX\">Server Installation</a>, the data is fetched from the remote URL by the server and not the client.</p><h2>Known limitations</h2><ul><li>The Embed display mode currently only supports YouTube. Other video and media platforms fall back to a Card preview.</li><li>Pages that block automated fetches may produce a minimal preview (hostname only).</li><li>Link previews require the Trilium server to reach the target URL, so they won't generate previews for pages on networks the server can't see.</li></ul>",
diff --git a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md
index 9ac2f435ac..5ee8795643 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md
@@ -76,4 +76,21 @@ Note that the list of languages is not immediately refreshed, you'd have to manu
A different feature is _programming ligatures_, which is simply a display affordance which turns `!=` into `≠` or `->` as `→` . These come from the [font](../../../Basic%20Concepts%20and%20Features/Themes/Personalizing%20the%20font.md). The underlying text is not actually changed, and copying it out gives you back `!=` and `->`.
-Ligatures can be disabled in <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a>_→ Appearance → Fonts → Programming ligatures._
\ No newline at end of file
+Ligatures can be disabled in <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a>_→ Appearance → Fonts → Programming ligatures._
+
+## Extended code blocks
+
+> [!IMPORTANT]
+> Extended code blocks are experimental, and they change as they mature. To use them, turn on _Extended code blocks_ in <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Advanced_ → _Experimental Options_.
+
+An extended code block is a code block that is edited with the code editor of a <a class="reference-link" href="../../Code.md">Code</a> note, inside the text. It has the same syntax highlighting and code folding as a code note, and it suits longer pieces of code.
+
+* To insert one, open the <span class="tn-icon cke cke-plus"></span> _Insert_ menu of the <a class="reference-link" href="../Formatting%20toolbar.md">Formatting toolbar</a> and choose <span class="tn-icon bx bx-code-block"></span> _Extended code block_, after _Columns_. It is also available as _Extended code block_ in the <a class="reference-link" href="../Slash%20Commands.md">Slash Commands</a>.
+* A new block is empty and editable, in a _Full_ box, and takes the focus. Its language is the one set last on an extended code block, or _Plain text_.
+* The block shows in a box like the one of an included code note, with the corners and the shadow of a code block. While the block can be edited, its language shows in its top corner, as for a code block.
+* Its toolbar has the controls of an embedded code file, described in _Editing an include in place_ in <a class="reference-link" href="../Include%20Note.md">Include Note</a>: the <span class="tn-icon bx bx-edit-alt"></span> _Editable_ button, the _Change language mode_ and _Change tab width_ menus, and the <span class="tn-icon bx bx-move-vertical"></span> _Box size_ menu, with _Small_, _Medium_ and _Full_. Its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu has the _Word wrap_ and _Line numbers_ submenus.
+* The changes made in the block are part of the undo history of the text note.
+
+The code stays in the note as a code block of its language. The Markdown export, [shared pages](../../../Advanced%20Usage/Sharing.md) and printing show it as a code block, and copying it into another application pastes a code block. Pasted into a text note, it becomes an extended code block again, with its settings.
+
+Turning _Extended code blocks_ off again removes them from the _Insert_ menu and the slash commands only: the extended code blocks already in notes keep working. A version of Trilium without this feature shows them as code blocks, and saves them back as code blocks, without their box size and other settings.
\ No newline at end of file
diff --git a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md
index 23d5568f42..4b70161e2e 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md
@@ -33,6 +33,10 @@ Interaction:
See the dedicated <a class="reference-link" href="Multicolumn%20layout.md">Multicolumn layout</a> page.
+## Extended code block
+
+Choose <span class="tn-icon bx bx-code-block"></span> _Extended code block_ to insert a code block that is edited as a code note. This entry is experimental and is shown only once it is turned on. See _Extended code blocks_ in <a class="reference-link" href="Developer-specific%20formatting/Code%20blocks.md">Code blocks</a>.
+
## Math equations
See the dedicated <a class="reference-link" href="Math%20Equations.md">Math Equations</a> page.
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index 38eadaf16b..a1093e9ffa 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -64,6 +64,7 @@ import ContentEmbedBoxSizeDropdown
from "./plugins/content_embed/content_embed_box_size_dropdown.js";
import ContentEmbedToolbar from "./plugins/content_embed/content_embed_toolbar.js";
import ContentEmbedCaret from "./plugins/content_embed/content_embed_caret.js";
+import ExtendedCodeBlock from "./plugins/content_embed/extended_code_block.js";
import LinkEmbedToolbar from "./plugins/link_embed/link_embed_toolbar.js";
import TodoListMultistate from "./plugins/todo_list_multistate/todo_list_multistate.js";
import TodoListUncheckOnEnter from "./plugins/todo_list_uncheck_on_enter.js";
@@ -121,6 +122,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
ContentEmbedBoxSizeDropdown,
ContentEmbedToolbar,
ContentEmbedCaret,
+ ExtendedCodeBlock,
LinkEmbedToolbar,
TodoListMultistate,
CollapsibleListItems,
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
index dc34955928..0924551c89 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
@@ -29,13 +29,17 @@ import showIcon from 'boxicons/svg/regular/bx-show.svg?raw';
import dockLeftIcon from 'boxicons/svg/solid/bxs-dock-left.svg?raw';
import windowIcon from 'boxicons/svg/regular/bx-window-alt.svg?raw';
import noteIcon from '../../icons/note.svg?raw';
-import { encodeBlockParameter, parseBlockRange } from '@triliumnext/commons';
+import {
+ encodeBlockParameter, EXTENDED_CODE_BLOCK_CLASS, normalizeMimeTypeForCKEditor, parseBlockRange
+} from '@triliumnext/commons';
import { getAttachmentId, getNoteId } from '../referencelink.js';
import ResizableWidgets, { SIZE_ATTRIBUTES } from '../resizable_widgets/resizable_widgets.js';
import { restoreRendererFocusOnInput } from '../widget_utils.js';
import type { EmbedEdge } from './content_embed_caret.js';
import EmbedHistory from './embed_history.js';
-import ContentEmbedInlineSource, { type InlineEmbedSource, isInlineSourceEmbed } from './inline_source.js';
+import ContentEmbedInlineSource, {
+ type InlineEmbedSource, isExtendedCodeBlock, isInlineSourceEmbed
+} from './inline_source.js';
import './nested_editor_events.js';
export const COMMAND_NAME = 'insertContentEmbed';
@@ -112,6 +116,7 @@ const CODE_VIEW_ATTRIBUTES = [
/** The settings of `SetContentEmbedCodeViewCommand`. `null` removes a setting. */
export interface ContentEmbedCodeView {
+ /** The language, as a MIME type. An extended code block saves it as its `language-…` class. */
language?: string | null;
tabWidth?: number | null;
indentWithTabs?: boolean | null;
@@ -612,8 +617,11 @@ class ContentEmbedEditing extends Plugin {
const boxSize = modelElement.getAttribute( 'boxSize' ) as string | undefined;
+ const extendedClass = isExtendedCodeBlock( editor, modelElement )
+ ? ' ' + EXTENDED_CODE_BLOCK_CLASS
+ : '';
const figure = viewWriter.createContainerElement( 'figure', {
- class: 'include-note box-size-' + boxSize,
+ class: 'include-note box-size-' + boxSize + extendedClass,
...getEmbeddedEntityAttributes( modelElement ),
'data-box-size': boxSize,
...getFlagAttributes( modelElement ),
@@ -677,9 +685,11 @@ class ContentEmbedEditing extends Plugin {
// Marks the view of the embed without drawing the content again. Content with an
// editable mode reads `data-editable` from the embed, content with display modes
- // `data-display-mode`, and a code file the `data-code-*` attributes.
+ // `data-display-mode`, a code file the `data-code-*` attributes, and an extended code
+ // block `data-language`.
const markedAttributes = [
- ...FLAG_ATTRIBUTES, DISPLAY_MODE_ATTRIBUTE, ...CODE_VIEW_ATTRIBUTES
+ ...FLAG_ATTRIBUTES, DISPLAY_MODE_ATTRIBUTE, ...CODE_VIEW_ATTRIBUTES,
+ [ 'language', 'data-language' ] as const
];
for ( const [ attribute, dataAttribute ] of markedAttributes ) {
dispatcher.on( `attribute:${ attribute }:contentEmbed`, ( _evt, data, api ) => {
@@ -971,7 +981,7 @@ export class SetContentEmbedCodeViewCommand extends Command {
const values = embed.getAttribute( 'noteId' ) ? {
codeLineNumbers: lineNumbers
} : {
- codeLanguage: language,
+ ...getLanguageAttribute( this.editor, embed, language ),
codeTabWidth: tabWidth,
codeIndentWithTabs: indentWithTabs,
codeWrapLines: wrapLines,
@@ -1020,6 +1030,20 @@ export class ContentEmbedDisplayModeCommand extends Command {
}
}
+/**
+ * The model attribute to set for `language`, a MIME type: `language` for an extended code block,
+ * which always has one, otherwise `codeLanguage`, the language that a code file shows in.
+ */
+function getLanguageAttribute(
+ editor: Editor, embed: ModelElement, language: string | null | undefined
+): Record<string, string | null | undefined> {
+ if ( !isExtendedCodeBlock( editor, embed ) ) {
+ return { codeLanguage: language };
+ }
+
+ return language ? { language: normalizeMimeTypeForCKEditor( language ) } : {};
+}
+
/** Sets the flag of the selected embed when it is off, and removes it when it is on. */
function toggleSelectedEmbedFlag( editor: Editor, flag: EmbedFlag ) {
const embed = getSelectedContentEmbed( editor );
@@ -1691,6 +1715,8 @@ export interface ContentEmbedHost {
): void;
/** Fills `wrapper` with the attachment. */
loadAttachment( attachmentId: string, wrapper: HTMLElement, boxSize: string | undefined ): void;
+ /** Writes into the note the changes to the sources of inline embeds that are not yet in it. */
+ flushInline(): void;
/** Fills `wrapper` with the source of an inline embed, focused if `isFocused`. */
loadInline(
source: InlineEmbedSource,
diff --git a/packages/ckeditor5/src/plugins/content_embed/extended_code_block.spec.ts b/packages/ckeditor5/src/plugins/content_embed/extended_code_block.spec.ts
new file mode 100644
index 0000000000..ae9857f1a4
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/content_embed/extended_code_block.spec.ts
@@ -0,0 +1,61 @@
+import {
+ _setModelData as setModelData, ButtonView, ClassicEditor, Essentials, Paragraph, Widget
+} from "ckeditor5";
+import { describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { CODE_VIEW_COMMAND_NAME } from "./content_embed.js";
+import ExtendedCodeBlock, {
+ EXTENDED_CODE_BLOCK_BUTTON, INSERT_EXTENDED_CODE_BLOCK_COMMAND, insertExtendedCodeBlock
+} from "./extended_code_block.js";
+
+describe("ExtendedCodeBlock", () => {
+ function createEditor() {
+ return createTestEditor([ Essentials, Paragraph, Widget, ExtendedCodeBlock ], {
+ contentEmbed: { inlineLanguages: [ "mermaid" ], loadInline: vi.fn() }
+ });
+ }
+
+ function createButton(editor: ClassicEditor) {
+ const button = editor.ui.componentFactory.create(EXTENDED_CODE_BLOCK_BUTTON);
+ if (!(button instanceof ButtonView)) throw new Error("Expected a button.");
+ return button;
+ }
+
+ it("inserts an empty block of the box size Full from its button, and focuses", async () => {
+ const editor = await createEditor();
+ setModelData(editor.model, "<paragraph>a[]</paragraph>");
+ const button = createButton(editor);
+ const focus = vi.spyOn(editor.editing.view, "focus");
+
+ expect([ button.label, button.isEnabled ]).toEqual([ "Extended code block", true ]);
+ expect(button.icon).toContain("<svg");
+ button.fire("execute");
+
+ expect(editor.getData()).toBe(`<p>a</p><pre class="extended-code-block"`
+ + ` data-box-size="full" data-hide-title="true" data-editable="true">`
+ + `<code class="language-text-plain"></code></pre>`);
+ expect(focus).toHaveBeenCalled();
+
+ editor.enableReadOnlyMode("spec");
+ expect(button.isEnabled).toBe(false);
+ expect(editor.commands.get(INSERT_EXTENDED_CODE_BLOCK_COMMAND)?.isEnabled).toBe(false);
+ });
+
+ it("gives a new block the language that was set last", async () => {
+ const editor = await createEditor();
+ editor.setData(`<pre class="extended-code-block">`
+ + `<code class="language-text-plain">x</code></pre>`);
+ const embed = editor.model.document.getRoot()?.getChild(0);
+ if (!embed?.is("element")) throw new Error("Expected an embed.");
+ editor.model.change((writer) => writer.setSelection(embed, "on"));
+ editor.execute(CODE_VIEW_COMMAND_NAME, { language: "text/x-python" });
+ // A language removed from an embed leaves the last one.
+ editor.model.change((writer) => writer.removeAttribute("language", embed));
+
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ insertExtendedCodeBlock(editor);
+
+ expect(editor.getData()).toContain(`<code class="language-text-x-python"></code>`);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/content_embed/extended_code_block.ts b/packages/ckeditor5/src/plugins/content_embed/extended_code_block.ts
new file mode 100644
index 0000000000..db7c386bfa
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/content_embed/extended_code_block.ts
@@ -0,0 +1,82 @@
+import { EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE } from "@triliumnext/commons";
+import bxCodeBlock from "boxicons/svg/regular/bx-code-block.svg?raw";
+import { ButtonView, Command, type DowncastAttributeEvent, type Editor, Plugin } from "ckeditor5";
+
+import ContentEmbed from "./content_embed.js";
+import { INSERT_INLINE_EMBED_COMMAND } from "./inline_source.js";
+
+export const INSERT_EXTENDED_CODE_BLOCK_COMMAND = "insertExtendedCodeBlock";
+
+/** The toolbar button that inserts an extended code block. */
+export const EXTENDED_CODE_BLOCK_BUTTON = "extendedCodeBlock";
+
+/**
+ * Extended code blocks: code blocks that the host shows and edits in its code editor, inside an
+ * embed. `ContentEmbedInlineSource` saves each one as a `<pre><code class="language-…">` code block
+ * of the note. This plugin adds the command and the button that insert one.
+ */
+export default class ExtendedCodeBlock extends Plugin {
+ static get requires() {
+ return [ ContentEmbed ] as const;
+ }
+
+ static get pluginName() {
+ return "ExtendedCodeBlock" as const;
+ }
+
+ init() {
+ const editor = this.editor;
+ const t = editor.t;
+ const command = new InsertExtendedCodeBlockCommand(editor);
+ editor.commands.add(INSERT_EXTENDED_CODE_BLOCK_COMMAND, command);
+
+ // A new block takes the language that was set last.
+ editor.editing.downcastDispatcher.on<DowncastAttributeEvent>(
+ "attribute:language:contentEmbed",
+ (_evt, data) => {
+ if (typeof data.attributeNewValue === "string") {
+ command.language = data.attributeNewValue;
+ }
+ }
+ );
+
+ editor.ui.componentFactory.add(EXTENDED_CODE_BLOCK_BUTTON, (locale) => {
+ const button = new ButtonView(locale);
+ button.set({ label: t("Extended code block"), icon: bxCodeBlock, tooltip: true });
+ button.bind("isEnabled").to(command);
+ this.listenTo(button, "execute", () => insertExtendedCodeBlock(editor));
+ return button;
+ });
+ }
+}
+
+/** Inserts an empty extended code block, of the box size Full, which takes the focus. */
+class InsertExtendedCodeBlockCommand extends Command {
+ /** The language of the next block, as a CKEditor code block language. */
+ language = EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE;
+
+ override refresh() {
+ this.isEnabled = !!this.editor.commands.get(INSERT_INLINE_EMBED_COMMAND)?.isEnabled;
+ }
+
+ override execute() {
+ this.editor.execute(INSERT_INLINE_EMBED_COMMAND, {
+ language: this.language,
+ source: "",
+ boxSize: "full"
+ });
+ }
+}
+
+/** Inserts an extended code block as its button does, and scrolls to it. */
+export function insertExtendedCodeBlock(editor: Editor) {
+ editor.execute(INSERT_EXTENDED_CODE_BLOCK_COMMAND);
+ editor.editing.view.scrollToTheSelection();
+ editor.editing.view.focus();
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [ExtendedCodeBlock.pluginName]: ExtendedCodeBlock;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts
index 98cedc63cd..81cf618178 100644
--- a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts
@@ -3,6 +3,7 @@ import {
_setModelData as setModelData,
ButtonView,
ClassicEditor,
+ CodeBlock,
DropdownView,
Essentials,
type ListItemView,
@@ -14,6 +15,7 @@ import {
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
+import BlockReferenceEditing from "../block_reference/block_reference_editing.js";
import { SIZE_ATTRIBUTES } from "../resizable_widgets/resizable_widgets.js";
import ContentEmbedBoxSizeDropdown, {
CONTENT_EMBED_BOX_SIZE_DROPDOWN
@@ -27,7 +29,9 @@ import ContentEmbed, {
TOGGLE_CAPTION_COMMAND_NAME,
TOGGLE_TITLE_COMMAND_NAME
} from "./content_embed.js";
-import { INSERT_INLINE_EMBED_COMMAND, type InlineEmbedSource } from "./inline_source.js";
+import {
+ INSERT_INLINE_EMBED_COMMAND, type InlineEmbedSource, isExtendedCodeBlock
+} from "./inline_source.js";
describe("ContentEmbedInlineSource", () => {
let editor: ClassicEditor;
@@ -123,10 +127,11 @@ describe("ContentEmbedInlineSource", () => {
+ ` data-code-line-numbers="true"><code class="language-mermaid">x</code></pre>`);
});
- it("leaves a code block of another language alone", () => {
+ it("leaves a code block of another language alone, and inline code", () => {
editor.setData(
`<pre><code class="language-javascript">let a;</code></pre>`
+ `<pre><code class="language-mermaid">graph TD;</code></pre>`
+ + `<p><code class="language-mermaid">graph LR;</code></p>`
);
const model = getModelData(editor.model, { withoutSelection: true });
@@ -292,4 +297,130 @@ describe("ContentEmbedInlineSource", () => {
expect(editor.commands.get(TOGGLE_CAPTION_COMMAND_NAME)?.isEnabled).toBe(false);
expect(editor.commands.get(CONVERT_EMBED_TO_LINK_COMMAND)?.isEnabled).toBe(false);
});
+
+ describe("extended code blocks", () => {
+ it("loads a marked code block of any language as an embed, and saves it back", () => {
+ editor.setData(`<pre class="extended-code-block">`
+ + `<code class="language-text-x-python">def a():\n pass</code></pre>`);
+
+ const embed = getEmbed();
+ expect(isExtendedCodeBlock(editor, embed)).toBe(true);
+ expect(embed.getAttribute("language")).toBe("text-x-python");
+ expect(embed.getAttribute("source")).toBe("def a():\n pass");
+ // A code block that has no settings of an embed opens as a code block shows.
+ expect([ "boxSize", "hideTitle", "editable", "displayMode" ]
+ .map((name) => embed.getAttribute(name)))
+ .toEqual([ "full", true, true, undefined ]);
+ expect(editor.getData()).toBe(`<pre class="extended-code-block" data-box-size="full"`
+ + ` data-hide-title="true" data-editable="true">`
+ + `<code class="language-text-x-python">def a():\n pass</code></pre>`);
+
+ editor.setData(`<pre class="extended-code-block"><code class="hljs">a</code></pre>`);
+ expect(getEmbed().getAttribute("language")).toBe("text-plain");
+
+ editor.setData(`<pre><code class="language-mermaid">a</code></pre>`);
+ expect(isExtendedCodeBlock(editor, getEmbed())).toBe(false);
+ });
+
+ it("keeps the box size, the flags and the code view that it saved", () => {
+ const html = `<pre class="extended-code-block" data-box-size="medium"`
+ + ` data-hide-title="true" data-code-tab-width="2">`
+ + `<code class="language-text-x-python">x</code></pre>`;
+ editor.setData(html);
+
+ expect([ "boxSize", "editable", "codeTabWidth" ]
+ .map((name) => getEmbed().getAttribute(name)))
+ .toEqual([ "medium", undefined, "2" ]);
+ expect(editor.getData()).toBe(html);
+ });
+
+ it("marks the box of the editing view, and none of a diagram", () => {
+ editor.setData(`<pre class="extended-code-block">`
+ + `<code class="language-text-x-python">x</code></pre>`
+ + `<pre><code class="language-mermaid">a</code></pre>`);
+
+ const figures = editor.editing.view.getDomRoot()?.querySelectorAll("figure") ?? [];
+ expect([ ...figures ].map((figure) => figure.classList.contains("extended-code-block")))
+ .toEqual([ true, false ]);
+ expect(figures[0]?.dataset.language).toBe("text-x-python");
+ });
+
+ it("changes the language through the code view command", () => {
+ editor.setData(`<pre class="extended-code-block">`
+ + `<code class="language-text-plain">x</code></pre>`);
+ editor.model.change((writer) => writer.setSelection(getEmbed(), "on"));
+
+ editor.execute(CODE_VIEW_COMMAND_NAME, { language: "text/x-c++src" });
+ expect(getEmbed().getAttribute("language")).toBe("text-x-c-src");
+ expect(getEmbed().getAttribute("codeLanguage")).toBeUndefined();
+ expect(getLoadedSource().language).toBe("text-x-c-src");
+ const figure = editor.editing.view.getDomRoot()?.querySelector("figure");
+ expect(figure?.dataset.language).toBe("text-x-c-src");
+ expect(editor.getData()).toContain(`<code class="language-text-x-c-src">x</code>`);
+
+ // An extended code block always has a language.
+ editor.execute(CODE_VIEW_COMMAND_NAME, { language: null });
+ expect(getEmbed().getAttribute("language")).toBe("text-x-c-src");
+ });
+
+ it("inserts an embed of the box size given", () => {
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ editor.execute(INSERT_INLINE_EMBED_COMMAND, {
+ language: "text-x-python", source: "", boxSize: "full"
+ });
+
+ const embed = editor.model.document.selection.getSelectedElement();
+ expect(embed?.getAttribute("boxSize")).toBe("full");
+ expect(editor.getData()).toBe(`<pre class="extended-code-block" data-box-size="full"`
+ + ` data-hide-title="true" data-editable="true">`
+ + `<code class="language-text-x-python"></code></pre>`);
+ });
+
+ it("leaves an unmarked code block to the code blocks, and keeps the block ID", async () => {
+ const withCodeBlocks = await createTestEditor([
+ Essentials, Paragraph, Widget, CodeBlock, ContentEmbed, BlockReferenceEditing
+ ], {
+ contentEmbed: { inlineLanguages: [ "mermaid" ], loadInline: loadInlineEmbed }
+ });
+ withCodeBlocks.setData(`<pre><code class="language-plaintext">a</code></pre>`
+ + `<pre class="extended-code-block"><code class="language-text-x-python"`
+ + ` data-trilium-block-id="b1">x</code></pre>`);
+
+ const model = getModelData(withCodeBlocks.model, { withoutSelection: true });
+ expect(model).toMatch(/^<codeBlock [^>]*>a<\/codeBlock><contentEmbed /);
+ // A code block keeps its block ID on the <code>, an embed on the <pre>.
+ expect(withCodeBlocks.getData()).toContain(
+ ` data-trilium-block-id="b1"><code class="language-text-x-python">x</code></pre>`);
+ });
+
+ it("writes the source that the host holds back before a copy", async () => {
+ let source: InlineEmbedSource | undefined;
+ const plugins = [ Essentials, Paragraph, Widget, ContentEmbed ];
+ const copying = await createTestEditor(plugins, {
+ contentEmbed: {
+ inlineLanguages: [],
+ loadInline: (loaded) => {
+ source = loaded;
+ },
+ flushInline: () => source?.setSource("y")
+ }
+ });
+ copying.setData(`<pre class="extended-code-block">`
+ + `<code class="language-text-plain">x</code></pre>`);
+ const embed = copying.model.document.getRoot()?.getChild(0);
+ if (!embed) throw new Error("Expected an embed.");
+ copying.model.change((writer) => writer.setSelection(embed, "on"));
+
+ const copied = new Map<string, string>();
+ copying.editing.view.document.fire("copy", {
+ dataTransfer: { setData: (type: string, data: string) => copied.set(type, data) },
+ preventDefault: () => {},
+ method: "copy"
+ });
+
+ expect(copied.get("text/html")).toContain(`<code class="language-text-plain">y</code>`);
+ expect(copied.get("text/plain")).toBe("y");
+ });
+ });
});
diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.ts
index 2856051f2e..1497bd045c 100644
--- a/packages/ckeditor5/src/plugins/content_embed/inline_source.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.ts
@@ -1,10 +1,12 @@
+import {
+ EXTENDED_CODE_BLOCK_CLASS, EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE
+} from '@triliumnext/commons';
import {
Command,
type DowncastConversionApi,
type DowncastInsertEvent,
type Editor,
findOptimalInsertionRange,
- type Model,
type ModelElement,
Plugin,
type UpcastConversionApi,
@@ -43,8 +45,11 @@ export interface InlineEmbedSource {
export interface InsertInlineEmbedOptions {
language: string;
source: string;
+ /** Medium by default. */
+ boxSize?: BoxSizeValue;
}
+
/** The flags of an embed and the `data-*` attributes they are saved as on the `<pre>`. */
const FLAG_ATTRIBUTES = [
[ 'hideTitle', 'data-hide-title' ],
@@ -58,8 +63,9 @@ const SIZE_PROPERTIES = [
] as const;
/**
- * Embeds whose content lives in the note, as `<pre><code class="language-…">` code blocks of the
- * languages in `contentEmbed.inlineLanguages`. The embed keeps the language and the source as
+ * Embeds whose content lives in the note, as `<pre><code class="language-…">` code blocks: the
+ * diagrams of the languages in `contentEmbed.inlineLanguages`, and the extended code blocks, whose
+ * `<pre>` has the `EXTENDED_CODE_BLOCK_CLASS` class. The embed keeps the language and the source as
* attributes, and is saved as the code block, with its box size, flags and size on the `<pre>`,
* so that anything reading the note sees a plain code block.
*
@@ -86,13 +92,20 @@ export default class ContentEmbedInlineSource extends Plugin {
editor.data.upcastDispatcher.on<UpcastElementEvent>(
'element:code', ( _evt, data, api ) => this.upcast( data, api ), { priority: 'high' } );
editor.data.downcastDispatcher.on<DowncastInsertEvent<ModelElement>>(
- 'insert:contentEmbed', ( _evt, data, api ) => downcastData( editor.model, data.item, api ),
+ 'insert:contentEmbed', ( _evt, data, api ) => downcastData( editor, data.item, api ),
{ priority: 'high' } );
editor.editing.downcastDispatcher.on( 'attribute:source:contentEmbed', ( _evt, data ) => {
for ( const listener of this.listeners.get( data.item as ModelElement ) ?? [] ) {
listener();
}
} );
+
+ // The host writes edited sources after a delay: write them before the clipboard reads them.
+ for ( const event of [ 'copy', 'cut', 'dragstart' ] as const ) {
+ this.listenTo( editor.editing.view.document, event, () => {
+ editor.config.get( 'contentEmbed' )?.flushInline?.();
+ }, { priority: 'highest' } );
+ }
}
afterInit() {
@@ -125,7 +138,9 @@ export default class ContentEmbedInlineSource extends Plugin {
const listeners = this.listeners;
return {
- language: embed.getAttribute( 'language' ) as string,
+ get language() {
+ return embed.getAttribute( 'language' ) as string;
+ },
getSource: () => embed.getAttribute( 'source' ) as string | undefined ?? '',
setSource: source => {
const root = embed.root;
@@ -152,22 +167,31 @@ export default class ContentEmbedInlineSource extends Plugin {
};
}
- /** Turns a `<pre><code>` of an inline language into an embed of its source. */
+ /**
+ * Turns a `<pre><code>` of an inline language, or of an extended code block, into an embed of
+ * its source.
+ */
private upcast( data: UpcastElementEvent[ 'args' ][ 0 ], api: UpcastConversionApi ) {
const code = data.viewItem;
const pre = code.parent;
- const language = getInlineLanguage( this.editor, code );
- if ( !language || !pre?.is( 'element', 'pre' ) || !api.consumable.test( code, { name: true } ) ) {
+ if ( !pre?.is( 'element', 'pre' ) || !api.consumable.test( code, { name: true } ) ) {
+ return;
+ }
+
+ const codeLanguage = getCodeLanguage( code );
+ const isDiagram = !!codeLanguage && getInlineLanguages( this.editor ).includes( codeLanguage );
+ const isCodeBlock = !isDiagram && pre.hasClass( EXTENDED_CODE_BLOCK_CLASS );
+ if ( !isDiagram && !isCodeBlock ) {
return;
}
const source = getViewText( code );
const embed = api.writer.createElement( 'contentEmbed', {
- language,
+ language: codeLanguage ?? EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE,
source,
- boxSize: getBoxSizeOfView( pre ),
+ boxSize: getBoxSizeOfView( pre, isCodeBlock ? 'full' : 'medium' ),
hideTitle: true,
- ...getModeOfSavedView( pre, code ),
+ ...( isCodeBlock ? getCodeBlockModeOfView( pre ) : getModeOfSavedView( pre, code ) ),
...getFlagsOfView( pre ),
...getSizesOfView( pre ),
...getCodeViewOfView( pre )
@@ -190,7 +214,7 @@ class InsertInlineEmbedCommand extends Command {
this.isEnabled = !!position && model.schema.findAllowedParent( position, 'contentEmbed' ) !== null;
}
- override execute( { language, source }: InsertInlineEmbedOptions ) {
+ override execute( { language, source, boxSize = 'medium' }: InsertInlineEmbedOptions ) {
const editor = this.editor;
const model = editor.model;
@@ -198,7 +222,7 @@ class InsertInlineEmbedCommand extends Command {
const embed = writer.createElement( 'contentEmbed', {
language,
source,
- boxSize: 'medium',
+ boxSize,
hideTitle: true,
editable: true
} );
@@ -215,14 +239,21 @@ export function isInlineSourceEmbed( embed: ModelElement ) {
return !!embed.getAttribute( 'language' );
}
+/** Whether `embed` is an extended code block: an inline embed of a language that is no diagram. */
+export function isExtendedCodeBlock( editor: Editor, embed: ModelElement ) {
+ const language = embed.getAttribute( 'language' );
+ return typeof language === 'string' && !getInlineLanguages( editor ).includes( language );
+}
+
/** Saves an embed of a source as `<pre><code class="language-…">`. */
-function downcastData( model: Model, embed: ModelElement, api: DowncastConversionApi ) {
+function downcastData( editor: Editor, embed: ModelElement, api: DowncastConversionApi ) {
if ( !isInlineSourceEmbed( embed ) || !api.consumable.consume( embed, 'insert' ) ) {
return;
}
const { writer, mapper } = api;
const preAttributes: Record<string, string> = {
+ ...( isExtendedCodeBlock( editor, embed ) ? { class: EXTENDED_CODE_BLOCK_CLASS } : {} ),
'data-box-size': embed.getAttribute( 'boxSize' ) as string,
...getDisplayModeAttributes( embed )
};
@@ -242,7 +273,7 @@ function downcastData( model: Model, embed: ModelElement, api: DowncastConversio
writer.insert( writer.createPositionAt( code, 0 ),
writer.createText( embed.getAttribute( 'source' ) as string | undefined ?? '' ) );
writer.insert( writer.createPositionAt( pre, 0 ), code );
- writer.insert( mapper.toViewPosition( model.createPositionBefore( embed ) ), pre );
+ writer.insert( mapper.toViewPosition( editor.model.createPositionBefore( embed ) ), pre );
// `ResizableWidgets` writes the size attributes on the `<pre>` through this mapping.
mapper.bindElements( embed, pre );
}
@@ -262,13 +293,16 @@ function getViewText( element: ViewElement ): string {
.join( '' );
}
-/** The inline language of `code`, when it is one in `contentEmbed.inlineLanguages`. */
-function getInlineLanguage( editor: Editor, code: ViewElement ) {
- const languages = editor.config.get( 'contentEmbed.inlineLanguages' ) ?? [];
+/** The languages of the diagrams that the host renders, from `contentEmbed.inlineLanguages`. */
+function getInlineLanguages( editor: Editor ): string[] {
+ return editor.config.get( 'contentEmbed.inlineLanguages' ) ?? [];
+}
+
+/** The language that the `language-…` class of `code` names, or `null`. */
+function getCodeLanguage( code: ViewElement ) {
for ( const className of code.getClassNames() ) {
- const language = className.startsWith( 'language-' ) && className.slice( 'language-'.length );
- if ( language && languages.includes( language ) ) {
- return language;
+ if ( className.startsWith( 'language-' ) ) {
+ return className.slice( 'language-'.length );
}
}
return null;
@@ -288,10 +322,18 @@ function getModeOfSavedView( pre: ViewElement, code: ViewElement ) {
return { displayMode: mode ?? 'split', editable: true };
}
-/** The box size of a saved embed, Medium when it has none or one that needs a title. */
-function getBoxSizeOfView( pre: ViewElement ): BoxSizeValue {
+/**
+ * The display mode and Editable flag of an extended code block. A code block saved without the
+ * settings of an embed opens editable, as a code block of the text note is.
+ */
+function getCodeBlockModeOfView( pre: ViewElement ) {
+ return pre.hasAttribute( 'data-box-size' ) ? getDisplayModeOfView( pre ) : { editable: true };
+}
+
+/** The box size of a saved embed, `fallback` when it has none or one that needs a title. */
+function getBoxSizeOfView( pre: ViewElement, fallback: BoxSizeValue ): BoxSizeValue {
const boxSize = INLINE_BOX_SIZES.find( size => size === pre.getAttribute( 'data-box-size' ) );
- return boxSize ?? 'medium';
+ return boxSize ?? fallback;
}
function getFlagsOfView( pre: ViewElement ) {
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
index e3e20387d1..128e136a8e 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
@@ -26,6 +26,9 @@ import { LINK_EMBED_COMMAND } from "../link_embed/link_embed_commands.js";
import LinkEmbedUI from "../link_embed/link_embed_ui.js";
import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";
import MathUI from "../math/math_ui.js";
+import {
+ INSERT_EXTENDED_CODE_BLOCK_COMMAND
+} from "../content_embed/extended_code_block.js";
import { INSERT_INLINE_EMBED_COMMAND } from "../content_embed/inline_source.js";
import { BUTTON_ICON_SIZE, createLayoutFigure } from "../multicolumn/multicolumn_ui.js";
import TriliumSnippets from "../snippets/snippets.js";
@@ -598,7 +601,8 @@ describe("buildTriliumSlashCommands", () => {
[ "bulletedList", "Bulleted list", "bulletedList" ],
[ "numberedList", "Numbered list", "numberedList" ],
[ "todoList", "To-do list", "todoList" ],
- [ "mermaid", "Mermaid diagram", INSERT_INLINE_EMBED_COMMAND ]
+ [ "mermaid", "Mermaid diagram", INSERT_INLINE_EMBED_COMMAND ],
+ [ "extended-code-block", "Extended code block", INSERT_EXTENDED_CODE_BLOCK_COMMAND ]
])("defines %s, running its command with an icon and a description", (id, title, commandName) => {
const entry = definition(id);
@@ -656,6 +660,16 @@ describe("buildTriliumSlashCommands", () => {
expect(focus).toHaveBeenCalled();
});
+ it("inserts an extended code block as its button does, and returns the focus", () => {
+ const execute = vi.spyOn(editor, "execute").mockReturnValue(undefined);
+ const focus = vi.spyOn(editor.editing.view, "focus");
+
+ definition("extended-code-block").execute?.(editor);
+
+ expect(execute).toHaveBeenCalledExactlyOnceWith(INSERT_EXTENDED_CODE_BLOCK_COMMAND);
+ expect(focus).toHaveBeenCalled();
+ });
+
it.each([ "attach-and-embed-file", "drawing-canvas" ])(
"offers %s only where both a file and an embed can go",
(id) => {
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
index 9097c23d2f..326a47e7d0 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@ -25,6 +25,7 @@ import {
} from "@ckeditor/ckeditor5-icons";
import bxBookmark from "boxicons/svg/regular/bx-bookmark.svg?raw";
import bxBulb from "boxicons/svg/regular/bx-bulb.svg?raw";
+import bxCodeBlock from "boxicons/svg/regular/bx-code-block.svg?raw";
import bxCommentError from "boxicons/svg/regular/bx-comment-error.svg?raw";
import bxError from "boxicons/svg/regular/bx-error.svg?raw";
import bxErrorCircle from "boxicons/svg/regular/bx-error-circle.svg?raw";
@@ -47,6 +48,9 @@ import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "../admonition/admoni
import { getAdmonitionTitle } from "../admonition/admonition_ui.js";
import aiIcon from "../ai_assistant/theme/icons/ai.svg?raw";
import { COMMAND_NAME as CONTENT_EMBED_COMMAND } from "../content_embed/content_embed.js";
+import {
+ INSERT_EXTENDED_CODE_BLOCK_COMMAND, insertExtendedCodeBlock
+} from "../content_embed/extended_code_block.js";
import { insertDrawingCanvas } from "../file_upload/file_upload_ui.js";
import { INSERT_ICON_COMMAND } from "../inline_icon/inline_icon_editing.js";
import InlineIconUI from "../inline_icon/inline_icon_ui.js";
@@ -349,6 +353,15 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitio
execute: insertDrawingCanvas
},
...buildMermaidSlashCommands(editor),
+ {
+ id: "extended-code-block",
+ title: t("Extended code block"),
+ description: t("Insert a code block that is edited as a code note."),
+ aliases: [ "code", "codemirror", "pre" ],
+ icon: bxCodeBlock,
+ commandName: INSERT_EXTENDED_CODE_BLOCK_COMMAND,
+ execute: insertExtendedCodeBlock
+ },
{
id: "ai-assistant",
title: t("AI assistant"),
diff --git a/packages/commons/src/lib/content_embeds.ts b/packages/commons/src/lib/content_embeds.ts
index 543d97ff50..29c19f5c4c 100644
--- a/packages/commons/src/lib/content_embeds.ts
+++ b/packages/commons/src/lib/content_embeds.ts
@@ -27,6 +27,15 @@ export interface NestedEmbedOptions {
embedsAsReferenceLinks?: true;
}
+/**
+ * The class of the `<pre>` of an extended code block: a code block of the text note shown in an
+ * embed with the code editor, saved as `<pre><code class="language-…">`.
+ */
+export const EXTENDED_CODE_BLOCK_CLASS = "extended-code-block";
+
+/** The language of an extended code block that names none, as a CKEditor code block language. */
+export const EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE = "text-plain";
+
const ENTITY_ID = /^[a-zA-Z0-9_]+$/;
/** The key of an embed in `seenNoteIds`. A note can embed blocks of itself. */
diff --git a/packages/commons/src/lib/mime_type.spec.ts b/packages/commons/src/lib/mime_type.spec.ts
index 2380fa1cb4..1095a86dff 100644
--- a/packages/commons/src/lib/mime_type.spec.ts
+++ b/packages/commons/src/lib/mime_type.spec.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
import {
- getMarkdownNameFromCKEditorLanguage, getMimeTypeFromFileName, getMimeTypeFromMarkdownName,
- MIME_TYPE_AUTO, MIME_TYPES_DICT,
+ getMarkdownNameFromCKEditorLanguage, getMimeTypeFromCKEditorLanguage, getMimeTypeFromFileName,
+ getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, MIME_TYPES_DICT,
normalizeMimeTypeForCKEditor, resolveEnabledMimeTypes, shouldSyntaxHighlight
} from "./mime_type.js";
@@ -98,6 +98,22 @@ describe("getMimeTypeFromMarkdownName", () => {
});
});
+describe("getMimeTypeFromCKEditorLanguage", () => {
+ it("returns the MIME type of a code block language, for every MIME type", () => {
+ expect(getMimeTypeFromCKEditorLanguage("text-x-python")).toBe("text/x-python");
+ expect(getMimeTypeFromCKEditorLanguage("text-x-c-src")).toBe("text/x-c++src");
+ expect(getMimeTypeFromCKEditorLanguage("text-plain")).toBe("text/plain");
+ for (const { mime } of MIME_TYPES_DICT) {
+ expect(getMimeTypeFromCKEditorLanguage(normalizeMimeTypeForCKEditor(mime))).toBe(mime);
+ }
+ });
+
+ it("returns undefined for an unknown language and for auto-detection", () => {
+ expect(getMimeTypeFromCKEditorLanguage("text-x-not-a-language")).toBeUndefined();
+ expect(getMimeTypeFromCKEditorLanguage(MIME_TYPE_AUTO)).toBeUndefined();
+ });
+});
+
describe("getMarkdownNameFromCKEditorLanguage", () => {
it("keeps the last segment of the language when it resolves back", () => {
expect(getMarkdownNameFromCKEditorLanguage("text-x-toml")).toBe("toml");
diff --git a/packages/commons/src/lib/mime_type.ts b/packages/commons/src/lib/mime_type.ts
index 77ab23a634..6f9fdb49a5 100644
--- a/packages/commons/src/lib/mime_type.ts
+++ b/packages/commons/src/lib/mime_type.ts
@@ -272,6 +272,7 @@ export function shouldSyntaxHighlight(code: string) {
let byMarkdownNameMappings: Record<string, MimeTypeDefinition> | null = null;
let byCKEditorLanguageMappings: Record<string, string> | null = null;
+let mimeTypesByCKEditorLanguage: Map<string, string> | null = null;
export type MermaidMimeType = "text/vnd.mermaid" | "text/mermaid";
export type SupportedMimeTypes = typeof MIME_TYPES_DICT_RAW[number]["mime"] | MermaidMimeType;
@@ -330,6 +331,19 @@ export function getMarkdownNameFromCKEditorLanguage(ckEditorLanguage: string) {
return byCKEditorLanguageMappings[ckEditorLanguage];
}
+/**
+ * The MIME type of a CKEditor code block language, such as `text/x-python` for `text-x-python`.
+ *
+ * @param ckEditorLanguage a MIME type normalized with {@link normalizeMimeTypeForCKEditor}.
+ * @returns the MIME type, or `undefined` for an unknown language and for {@link MIME_TYPE_AUTO}.
+ */
+export function getMimeTypeFromCKEditorLanguage(ckEditorLanguage: string) {
+ mimeTypesByCKEditorLanguage ??= new Map(MIME_TYPES_DICT.map(({ mime }) => [
+ normalizeMimeTypeForCKEditor(mime), mime
+ ]));
+ return mimeTypesByCKEditorLanguage.get(ckEditorLanguage);
+}
+
/**
* The code MIME type of a file, from its extension, such as `text/x-python` for `script.py`, or
* `undefined` for a file without a known language.