diff --git a/client/client.ts b/client/client.ts index a99c6174..a8c8fe98 100644 --- a/client/client.ts +++ b/client/client.ts @@ -1108,7 +1108,8 @@ export class Client { const idx = doc.text.indexOf(cursorMarker); if (idx !== -1) { markerIndex = idx; - doc.text = doc.text.slice(0, idx) + doc.text.slice(idx + cursorMarker.length); + doc.text = doc.text.slice(0, idx) + + doc.text.slice(idx + cursorMarker.length); } } else if (results.length > 1) { console.error( @@ -1200,7 +1201,10 @@ export class Client { // overwritten by default positioning). if (markerIndex !== -1) { try { - const pos = Math.max(0, Math.min(markerIndex, this.editorView.state.doc.length)); + const pos = Math.max( + 0, + Math.min(markerIndex, this.editorView.state.doc.length), + ); this.editorView.dispatch({ selection: { anchor: pos }, effects: [EditorView.scrollIntoView(pos, { y: "center" })], diff --git a/client/codemirror/inline_content.ts b/client/codemirror/inline_content.ts index 4c10b338..5a491877 100644 --- a/client/codemirror/inline_content.ts +++ b/client/codemirror/inline_content.ts @@ -10,9 +10,15 @@ import { import type { Client } from "../client.ts"; import { LuaWidget } from "./lua_widget.ts"; import { + expandMarkdown, inlineContentFromURL, - parseTransclusion, } from "../markdown_renderer/inline.ts"; +import { parseMarkdown } from "../markdown_parser/parser.ts"; +import { renderToText } from "@silverbulletmd/silverbullet/lib/tree"; +import { + nameFromTransclusion, + parseTransclusion, +} from "@silverbulletmd/silverbullet/lib/transclusion"; export function inlineContentPlugin(client: Client) { return decoratorStateField((state: EditorState) => { @@ -38,6 +44,9 @@ export function inlineContentPlugin(client: Client) { const renderingSyntax = client.ui.viewState.uiOptions .markdownSyntaxRendering; const cursorIsInRange = isCursorInRange(state, [from, to]); + if (cursorIsInRange) { + return; + } if (!renderingSyntax && !cursorIsInRange) { widgets.push(invisibleDecoration.range(from, to)); } @@ -50,14 +59,20 @@ export function inlineContentPlugin(client: Client) { text, async () => { const result = await inlineContentFromURL( - client, - transclusion.url, - transclusion.alias, - transclusion.dimension, - transclusion.linktype !== "wikilink", + client.space, + transclusion, ); const content = typeof result === "string" - ? { markdown: result } + ? { + markdown: renderToText( + await expandMarkdown( + client.space, + nameFromTransclusion(transclusion), + parseMarkdown(result), + client.clientSystem.spaceLuaEnv, + ), + ), + } : { html: result }; return { @@ -71,7 +86,7 @@ export function inlineContentPlugin(client: Client) { true, ), block: true, - }).range(to + 1), + }).range(from), ); }, }); diff --git a/client/codemirror/lua_widget.ts b/client/codemirror/lua_widget.ts index fc17ceb8..83738f54 100644 --- a/client/codemirror/lua_widget.ts +++ b/client/codemirror/lua_widget.ts @@ -13,7 +13,7 @@ import { moveCursorIntoText, } from "./widget_util.ts"; import { expandMarkdown } from "../markdown_renderer/inline.ts"; -import { LuaStackFrame, LuaTable } from "../space_lua/runtime.ts"; +import { LuaTable } from "../space_lua/runtime.ts"; import { isBlockMarkdown, jsonToMDTable, @@ -90,9 +90,10 @@ export class LuaWidget extends WidgetType { async renderContent( div: HTMLElement, ) { + const currentName = this.client.currentName(); let widgetContent = await this.callback( this.bodyText, - this.client.currentName(), + currentName, ); activeWidgets.add(this); if (widgetContent === null || widgetContent === undefined) { @@ -146,14 +147,11 @@ export class LuaWidget extends WidgetType { widgetContent.markdown || "", ); - const sf = LuaStackFrame.createWithGlobalEnv( - client.clientSystem.spaceLuaEnv.env, - ); mdTree = await expandMarkdown( - client, + client.space, + currentName, mdTree, - client.clientSystem.spaceLuaEnv.env, - sf, + client.clientSystem.spaceLuaEnv, ); const trimmedMarkdown = renderToText(mdTree).trim(); diff --git a/client/codemirror/table.ts b/client/codemirror/table.ts index 16147778..c676256a 100644 --- a/client/codemirror/table.ts +++ b/client/codemirror/table.ts @@ -19,7 +19,6 @@ import { resolveMarkdownLink, } from "@silverbulletmd/silverbullet/lib/resolve"; import { expandMarkdown } from "../markdown_renderer/inline.ts"; -import { LuaStackFrame } from "../space_lua/runtime.ts"; import { attachWidgetEventHandlers } from "./widget_util.ts"; class TableViewWidget extends WidgetType { @@ -54,14 +53,11 @@ class TableViewWidget extends WidgetType { }); }); - const sf = LuaStackFrame.createWithGlobalEnv( - client.clientSystem.spaceLuaEnv.env, - ); expandMarkdown( - client, + client.space, + client.currentName(), this.t, - client.clientSystem.spaceLuaEnv.env, - sf, + client.clientSystem.spaceLuaEnv, ).then((t) => { dom.innerHTML = renderMarkdownToHtml(t, { // Annotate every element with its position so we can use it to put diff --git a/client/markdown_renderer/inline.ts b/client/markdown_renderer/inline.ts index f608cdbc..828fd778 100644 --- a/client/markdown_renderer/inline.ts +++ b/client/markdown_renderer/inline.ts @@ -1,41 +1,32 @@ import { + addParentPointers, findNodeOfType, type ParseTree, renderToText, replaceNodesMatchingAsync, - traverseTree, } from "@silverbulletmd/silverbullet/lib/tree"; import { - getNameFromPath, getPathExtension, isMarkdownPath, parseToRef, - type Ref, } from "@silverbulletmd/silverbullet/lib/ref"; -import { - isLocalURL, - resolveMarkdownLink, -} from "@silverbulletmd/silverbullet/lib/resolve"; +import { isLocalURL } from "@silverbulletmd/silverbullet/lib/resolve"; import { mime } from "mimetypes"; -import type { Client } from "../client.ts"; -import type { LuaEnv, LuaStackFrame } from "../space_lua/runtime.ts"; +import { LuaStackFrame } from "../space_lua/runtime.ts"; import { parseMarkdown } from "../markdown_parser/parser.ts"; import { renderExpressionResult } from "./result_render.ts"; import { parseExpressionString } from "../space_lua/parse.ts"; import { evalExpression } from "../space_lua/eval.ts"; import type { LuaExpression } from "../space_lua/ast.ts"; -import { mdLinkRegex, wikiLinkRegex } from "../markdown_parser/constants.ts"; import { fsEndpoint } from "../spaces/constants.ts"; - -/** - * Describes the dimensions of a transclusion, if provided through the alias. - * Can be parsed from the alias using {@link parseDimensionFromAlias} - */ -export type ContentDimensions = { - width?: number; - height?: number; -}; +import { + nameFromTransclusion, + parseTransclusion, + type Transclusion, +} from "@silverbulletmd/silverbullet/lib/transclusion"; +import type { Space } from "../space.ts"; +import type { SpaceLuaEnvironment } from "../space_lua.ts"; /** * Expands custom markdown Lua directives and transclusions into plain markdown @@ -43,49 +34,48 @@ export type ContentDimensions = { * @returns modified mdTree */ export async function expandMarkdown( - client: Client, + space: Space, + pageName: string, mdTree: ParseTree, - env: LuaEnv, - sf: LuaStackFrame, - forbiddenPages: Set = new Set(), + sle: SpaceLuaEnvironment, + processedPages: Set = new Set(), ): Promise { + addParentPointers(mdTree); await replaceNodesMatchingAsync(mdTree, async (n) => { if (n.type === "Image") { // Let's scan for ![[embeds]] that are codified as Images, confusingly const text = renderToText(n); const transclusion = parseTransclusion(text); - if (!transclusion || forbiddenPages.has(transclusion.url)) { + if (!transclusion || processedPages.has(transclusion.url)) { return n; } - const result = await inlineContentFromURL( - client, - transclusion.url, - transclusion.alias, - transclusion.dimension, - transclusion.linktype !== "wikilink", - ); + try { + const result = await inlineContentFromURL(space, transclusion); - // We don't transclude anything that's not markdown - if (typeof result !== "string") { - return n; + // We don't transclude anything that's not markdown + if (typeof result !== "string") { + return n; + } + + // We know it's a markdown page and we know we are transcluding it. "Mark" + // it so we won't touch it down the line and cause endless recursion + processedPages.add(transclusion.url); + + const tree = parseMarkdown(result); + + // Recursively process + return expandMarkdown( + space, + nameFromTransclusion(transclusion), + tree, + sle, + processedPages, + ); + } catch (e: any) { + return parseMarkdown(`**Error:** ${e.message}`); } - - // We know it's a markdown page and we know we are transcluding it. "Mark" - // it so we won't touch it down the line and cause endless recursion - forbiddenPages.add(transclusion.url); - - const tree = parseMarkdown(result); - - // Recursively process - return expandMarkdown( - client, - tree, - env, - sf, - forbiddenPages, - ); } else if (n.type === "LuaDirective") { const expr = findNodeOfType(n, "LuaExpressionDirective") as | LuaExpression @@ -96,108 +86,69 @@ export async function expandMarkdown( const exprText = renderToText(expr); try { + const sf = LuaStackFrame.createWithGlobalEnv(sle.env); + let result = await evalExpression( parseExpressionString(exprText), - env, + sle.env, sf, ); if (result?.markdown) { result = result.markdown; } - const markdown = await renderExpressionResult(result); - return parseMarkdown(markdown); + return parseMarkdown(await renderExpressionResult(result)); } catch (e: any) { // Reduce blast radius and give useful error message console.error("Error evaluating Lua directive", exprText, e); return parseMarkdown(`**Error:** ${e.message}`); } + } else if (n.type === "Task") { + // Add a task reference to this based on the current page name if there's not one already + const existingLink = findNodeOfType(n, "WikiLink"); + if (!existingLink) { + n.children!.splice(1, 0, { + "text": " ", + }, { + "type": "WikiLink", + "children": [ + { + "type": "WikiLinkMark", + "children": [{ "text": "[[" }], + }, + { + "type": "WikiLinkPage", + "children": [{ "text": `${pageName}@${n.parent!.from!}` }], + }, + { + "type": "WikiLinkMark", + "children": [{ "text": "]]" }], + }, + ], + }); + } } }); return mdTree; } -/** - * Extracts the transclusion from a markdown tree. Right now this is only - * supported for headers, in which case the Function will extract the header - * plus all text till the next header - * @returns Returns null if the header isn't found - */ -export function extractTransclusion( - markdown: string, - details: Ref["details"], -): string | null { - if (!details) { - return markdown; - } else if (details.type !== "header") { - return null; - } - - const parseTree = parseMarkdown(markdown); - - let from: undefined | number = undefined, to: undefined | number = undefined; - traverseTree(parseTree, (subTree) => { - // We are done, but we can't properly cancel the traversal - if (from !== undefined && to !== undefined) { - return true; - } - - if (!subTree.type || !subTree.type.startsWith("ATXHeading")) { - return false; - } - - // We already found the first header - if (from !== undefined) { - to = subTree.from; - return true; - } - - const mark = findNodeOfType(subTree, "HeaderMark"); - if (!mark || mark.from === undefined || mark.to === undefined) { - return true; - } - - if ( - renderToText(subTree) - .slice(mark.to - mark.from) - .trimStart() === details.header.trim() - ) { - from = subTree.from; - } - - // No need to continue into a header - return true; - }); - - // Go till end of file if we can't find a second header - to ??= parseTree.to; - - if (from === undefined) { - return null; - } - - return markdown.slice(from, to); -} - /** * Function to generate HTML or markdown for a ![[]] type transclusion. - * @param allowExternal In SB currently, wikilinks don't allow external links - * and markdown links do - * @returns a string for a markdown transclusion or html for everything else + * @param space space object to use to retrieve content (readRef) + * @param transclusion transclusion object to process + * @returns a string for a markdown transclusion, or html for everything else */ export function inlineContentFromURL( - client: Client | undefined, - url: string, - alias: string, - dimension: ContentDimensions | undefined, - allowExternal: boolean = true, + space: Space, + transclusion: Transclusion, ): string | HTMLElement | Promise { + const allowExternal = transclusion.linktype !== "wikilink"; if (!client) { return ""; } let mimeType: string | null | undefined; - if (!isLocalURL(url) && allowExternal) { - // TODO + if (!isLocalURL(transclusion.url) && allowExternal) { + // Remote URL // Realistically we should dertermine the mine type by sending a HEAD // request, this poses multiple problems // 1. This makes `async` a hard requirement here @@ -209,43 +160,47 @@ export function inlineContentFromURL( // complete. This could take a noticeable amount of time. // For this reason we will stick to doing it the `dumb` way by just getting // it from the URL extension - const extension = URL.parse(url)?.pathname.split(".").pop(); + const extension = URL.parse(transclusion.url)?.pathname.split(".").pop(); if (extension) { mimeType = mime.getType(extension); } } else { - const ref = parseToRef(url); + const ref = parseToRef(transclusion.url); if (!ref) { - return `Failed to parse url`; + throw Error(`Failed to parse url: ${transclusion.url}`); } mimeType = mime.getType(getPathExtension(ref.path)); } if (!mimeType) { - return `Failed to determine mime type`; + throw Error(`Failed to determine mime type for ${transclusion.url}`); } const style = `max-width: 100%;` + - (dimension?.width ? `width: ${dimension.width}px;` : "") + - (dimension?.height ? `height: ${dimension.height}px;` : ""); + (transclusion.dimension?.width + ? `width: ${transclusion.dimension.width}px;` + : "") + + (transclusion.dimension?.height + ? `height: ${transclusion.dimension.height}px;` + : ""); // If the URL is a local, prefix it with /.fs and encode the : so that it's not interpreted as a protocol - const sanitizedFsUrl = isLocalURL(url) - ? fsEndpoint.slice(1) + "/" + url.replace(":", "%3A") - : url; + const sanitizedFsUrl = isLocalURL(transclusion.url) + ? fsEndpoint.slice(1) + "/" + transclusion.url.replace(":", "%3A") + : transclusion.url; let result: HTMLElement | string | Promise; if (mimeType.startsWith("image/")) { const img = document.createElement("img"); img.src = sanitizedFsUrl; - img.alt = alias; + img.alt = transclusion.alias; img.style = style; result = img; } else if (mimeType.startsWith("video/")) { const video = document.createElement("video"); video.src = sanitizedFsUrl; - video.title = alias; + video.title = transclusion.alias; video.controls = true; video.autoplay = false; video.style = style; @@ -253,7 +208,7 @@ export function inlineContentFromURL( } else if (mimeType.startsWith("audio/")) { const audio = document.createElement("audio"); audio.src = sanitizedFsUrl; - audio.title = alias; + audio.title = transclusion.alias; audio.controls = true; audio.autoplay = false; audio.style = style; @@ -267,126 +222,22 @@ export function inlineContentFromURL( embed.style = style; result = embed; } else if (mimeType === "text/markdown") { - if (!isLocalURL(url) && allowExternal) { - return `Transcluding markdown from external sources is not supported`; + if (!isLocalURL(transclusion.url) && allowExternal) { + throw Error(`Transcluding markdown from external sources is not allowed`); } - const ref = parseToRef(url); - + const ref = parseToRef(transclusion.url); if (!ref || !isMarkdownPath(ref.path)) { // We can be fairly sure this can't happen, but just be sure - return `Couldn't transclude markdown, invalid path`; - } - - // Do a pre-check, because `readPage` is quite heavy - if (!client.clientSystem.allKnownFiles.has(ref.path)) { - return `Couldn't transclude markdown, page doesn't exist`; - } - - result = (async () => { - // Don't try catch, we just checked the existence - const { text: markdown } = await client.space.readPage( - getNameFromPath(ref.path), + throw Error( + `Couldn't transclude markdown, invalid path: ${transclusion.url}`, ); + } - const transclusion = extractTransclusion(markdown, ref.details); - if (!transclusion) { - return `Couldn't extract transclusion from markdown, try removing any headers '\\#' or positions '@' from your link`; - } - - return transclusion; - })(); + result = space.readRef(ref); } else { result = `File has unsupported mimeType: ${mimeType}`; } return result; } - -/** - * Parse an alias, possibly containing dimensions into an object - * @example "alias", "alias|100", "alias|100x200", "100", "100x200" - */ -export function parseDimensionFromAlias( - text: string, -): { alias: string; dimension?: ContentDimensions } { - let alias: string; - let dim: ContentDimensions | undefined; - if (text.includes("|")) { - const [aliasPart, dimPart] = text.split("|"); - alias = aliasPart; - const [width, height] = dimPart.split("x"); - dim = {}; - if (width) { - dim.width = parseInt(width); - } - if (height) { - dim.height = parseInt(height); - } - } else if (/^[x\d]/.test(text)) { - const [width, height] = text.split("x"); - dim = {}; - if (width) { - dim.width = parseInt(width); - } - if (height) { - dim.height = parseInt(height); - } - alias = ""; - } else { - alias = text; - } - - return { alias, dimension: dim }; -} - -/** - * Parses a transclusion of the type `![[]]` or `![]()` - * @param text - */ -export function parseTransclusion( - text: string, -): { - url: string; - alias: string; - dimension?: ContentDimensions; - linktype: "wikilink" | "markdown"; -} | null { - let url, alias = undefined; - let linktype: "wikilink" | "markdown" = "markdown"; - // TODO: Take in the tree and use tree nodes to get url and alias (Applies to all regex uses) - mdLinkRegex.lastIndex = 0; - wikiLinkRegex.lastIndex = 0; - let match: RegExpMatchArray | null = null; - if ((match = mdLinkRegex.exec(text)) && match.groups) { - ({ url, title: alias } = match.groups); - - if (isLocalURL(url)) { - url = resolveMarkdownLink( - client.currentName(), - decodeURI(url), - ); - } - linktype = "markdown"; - } else if ((match = wikiLinkRegex.exec(text)) && match.groups) { - ({ stringRef: url, alias } = match.groups); - linktype = "wikilink"; - } else { - // We found no match - return null; - } - - let dimension: ContentDimensions | undefined; - if (alias) { - ({ alias, dimension: dimension } = parseDimensionFromAlias(alias)); - } else { - alias = ""; - } - - return { - url, - alias, - dimension, - linktype, - }; -} diff --git a/client/markdown_renderer/markdown_render.ts b/client/markdown_renderer/markdown_render.ts index 131de8f6..c3f3bdef 100644 --- a/client/markdown_renderer/markdown_render.ts +++ b/client/markdown_renderer/markdown_render.ts @@ -16,8 +16,9 @@ import { Fragment, renderHtml, type Tag } from "./html_render.ts"; import * as TagConstants from "../../plugs/index/constants.ts"; import { extractHashtag } from "@silverbulletmd/silverbullet/lib/tags"; import { justifiedTableRender } from "./justified_tables.ts"; -import type { PageMeta } from "../../plug-api/types/index.ts"; -import { inlineContentFromURL, parseTransclusion } from "./inline.ts"; +import type { PageMeta } from "@silverbulletmd/silverbullet/type/index"; +import { inlineContentFromURL } from "./inline.ts"; +import { parseTransclusion } from "@silverbulletmd/silverbullet/lib/transclusion"; export type MarkdownRenderOptions = { failOnUnknown?: true; @@ -257,28 +258,35 @@ function render( return text; } - const result = inlineContentFromURL( - globalThis.client, - transclusion.url, - transclusion.alias, - transclusion.dimension, - transclusion.linktype !== "wikilink", - ); - if (!globalThis.HTMLElement || !(result instanceof HTMLElement)) { - return text; - } + try { + const result = inlineContentFromURL(client.space, transclusion); + if (result instanceof Promise) { + // Can't support promises in this content + throw new Error("Unsupported inline"); + } + // Running in non-browser context + if (!globalThis.HTMLElement || !(result instanceof HTMLElement)) { + return text; + } - return { - name: result.tagName, - attrs: Array.from(result.attributes).reduce( - (obj, attr) => { - obj[attr.name] = attr.value; - return obj; - }, - {} as Record, - ), - body: "", - }; + return { + name: result.tagName, + attrs: Array.from(result.attributes).reduce( + (obj, attr) => { + obj[attr.name] = attr.value; + return obj; + }, + {} as Record, + ), + body: "", + }; + } catch (e: any) { + console.error("Error handling image or transclusion", e.message); + return { + name: "span", + body: "Error loading image", + }; + } } // Custom stuff @@ -381,15 +389,6 @@ function render( } } - case "DeadlineDate": - return { - name: "span", - attrs: { - class: "task-deadline", - }, - body: renderToText(t), - }; - // Tables case "Table": return { diff --git a/client/plugos/syscalls/markdown.ts b/client/plugos/syscalls/markdown.ts index 3d5b290d..9995aae4 100644 --- a/client/plugos/syscalls/markdown.ts +++ b/client/plugos/syscalls/markdown.ts @@ -7,7 +7,6 @@ import { import { extendedMarkdownLanguage } from "../../markdown_parser/parser.ts"; import { expandMarkdown } from "../../markdown_renderer/inline.ts"; import type { Client } from "../../client.ts"; -import { LuaEnv, LuaStackFrame } from "../../space_lua/runtime.ts"; import { type MarkdownRenderOptions, renderMarkdownToHtml, @@ -51,14 +50,10 @@ export function markdownSyscalls(client: Client): SysCallMapping { } function expandMarkdownWithClient(client: Client, tree: ParseTree) { - const globalEnv = client.clientSystem.spaceLuaEnv.env; - const tl = new LuaEnv(); - tl.setLocal("_GLOBAL", globalEnv); - const sf = new LuaStackFrame(tl, null); return expandMarkdown( - client, + client.space, + client.currentName(), tree, - globalEnv, - sf, + client.clientSystem.spaceLuaEnv, ); } diff --git a/client/plugos/syscalls/space.ts b/client/plugos/syscalls/space.ts index 61a3f673..16b641a9 100644 --- a/client/plugos/syscalls/space.ts +++ b/client/plugos/syscalls/space.ts @@ -1,3 +1,4 @@ +import { parseToRef, type Ref } from "@silverbulletmd/silverbullet/lib/ref"; import type { Client } from "../../client.ts"; import type { SysCallMapping } from "../system.ts"; @@ -15,11 +16,20 @@ export function spaceReadSyscalls(client: Client): SysCallMapping { "space.readPage": async (_ctx, name: string): Promise => { return (await client.space.readPage(name)).text; }, - "space.readPageWithMeta": async ( + "space.readPageWithMeta": ( _ctx, name: string, ): Promise<{ text: string; meta: PageMeta }> => { - return await client.space.readPage(name); + return client.space.readPage(name); + }, + "space.readRef": (_ctx, ref: string | Ref): Promise => { + if (typeof ref === "string") { + ref = parseToRef(ref)!; + if (!ref) { + throw new Error(`Invalid ref: ${ref}`); + } + } + return client.space.readRef(ref); }, "space.pageExists": (_ctx, name: string): boolean => { return client.clientSystem.allKnownFiles.has(name + ".md"); diff --git a/client/space.ts b/client/space.ts index 02832f8b..f0a5ed99 100644 --- a/client/space.ts +++ b/client/space.ts @@ -8,9 +8,19 @@ import type { } from "@silverbulletmd/silverbullet/type/index"; import type { SpacePrimitives } from "./spaces/space_primitives.ts"; import { + getOffsetFromLineColumn, getPathExtension, type Path, + type Ref, } from "@silverbulletmd/silverbullet/lib/ref"; +import { parseMarkdown } from "./markdown_parser/parser.ts"; +import { + addParentPointers, + findNodeMatching, + nodeAtPos, + renderToText, + traverseTree, +} from "@silverbulletmd/silverbullet/lib/tree"; const pageWatchInterval = 3000; // + jitter @@ -69,6 +79,70 @@ export class Space { }; } + async readRef(ref: Ref): Promise { + if (!ref.path.endsWith(".md")) { + throw new Error("Not supported"); + } + const name = ref.path.slice(0, -3); + const pageText = (await this.readPage(name)).text; + if (!ref.details) { + return pageText; + } + const tree = parseMarkdown(pageText); + addParentPointers(tree); + if (ref.details.type === "linecolumn") { + ref.details = { + type: "position", + pos: getOffsetFromLineColumn( + pageText, + ref.details.line, + ref.details.column, + ), + }; + } + switch (ref.details.type) { + case "header": { + const desiredHeaderText = ref.details.header; + let text = `**Error:** Header not found: ${desiredHeaderText}`; + traverseTree(tree, (n) => { + if (n.type && n.type.startsWith("ATXHeading")) { + const level = +n.type!.substring("ATXHeading".length); + const headerText = renderToText(n).slice(level + 1); + let endPos = pageText.length; + if (headerText === desiredHeaderText) { + // Now we have to scan for the end point + // Let's go up one level and find either another header at this same level + const parent = n.parent!; + const nextHeader = findNodeMatching( + parent, + (h) => h.type === `ATXHeading${level}` && h.from! > n.from!, + ); + if (nextHeader) { + endPos = nextHeader.from!; + } + text = pageText.slice(n.from!, endPos); + return true; + } + } + return false; + }); + return text; + } + case "position": { + const pos = ref.details.pos; + let n = nodeAtPos(tree, pos); + if (!n) { + throw new Error("No node found at position"); + } + if (["ListMark"].includes(n.type!)) { + n = n.parent!; + } + return pageText.slice(n.from!, n.to!); + } + } + return ""; + } + async writePage( name: string, text: string, diff --git a/deno.json b/deno.json index 91f8b6f6..b88830b7 100644 --- a/deno.json +++ b/deno.json @@ -77,6 +77,7 @@ "@silverbulletmd/silverbullet/lib/attribute": "./plug-api/lib/attribute.ts", "@silverbulletmd/silverbullet/lib/limited_map": "./plug-api/lib/limited_map.ts", "@silverbulletmd/silverbullet/lib/ref": "./plug-api/lib/ref.ts", + "@silverbulletmd/silverbullet/lib/transclusion": "./plug-api/lib/transclusion.ts", "@silverbulletmd/silverbullet/lib/async": "./plug-api/lib/async.ts", "@silverbulletmd/silverbullet/lib/crypto": "./plug-api/lib/crypto.ts", "@silverbulletmd/silverbullet/lib/dates": "./plug-api/lib/dates.ts", diff --git a/plug-api/syscalls/space.ts b/plug-api/syscalls/space.ts index 8fc23b4e..cf161890 100644 --- a/plug-api/syscalls/space.ts +++ b/plug-api/syscalls/space.ts @@ -5,6 +5,7 @@ import type { FileMeta, PageMeta, } from "../../plug-api/types/index.ts"; +import type { Ref } from "@silverbulletmd/silverbullet/lib/ref"; /** * Exposes the space with its pages, documents and plugs. @@ -156,6 +157,13 @@ export function readFile(name: string): Promise { return syscall("space.readFile", name); } +/** + * Reads a reference (e.g. page#header or page@20) and returns it as a string + */ +export function readRef(ref: string | Ref): Promise { + return syscall("space.readRef", ref); +} + /** * Read a file from the space returning both its data and meta data * @param name the name of the page to read diff --git a/plugs/editor/editor.ts b/plugs/editor/editor.ts index f5983273..821f2970 100644 --- a/plugs/editor/editor.ts +++ b/plugs/editor/editor.ts @@ -11,17 +11,19 @@ import type { FilterOption } from "@silverbulletmd/silverbullet/type/client"; export async function setEditorMode() { // TODO: Remove at some point: temporary upgrade code const allSyscalls = await system.listSyscalls(); + // console.log("All syscalls", allSyscalls); const readPageWithMetaCall = allSyscalls.find((sc) => sc.name === "space.readPageWithMeta" ); + // console.log(readPageWithMetaCall); + if (!readPageWithMetaCall) { await editor.alert( "Client needs reloading to update the cache, required syscalls are not available in this version. This message may appear a few times. Reloading now.", ); editor.reloadUI(); } - // END if (await clientStore.get("vimMode")) { await editor.setUiOption("vimMode", true);