How to Copy/Export Results from an Advanced Query in Logseq

Thank you so much for your help, it worked! You really saved the day.

I don’t have much of a coding background and I never knew that Logseq could be extended in this way. I’m thrilled and I definitely want to continue exploring more. I really appreciate your guidance.

I used GPT to modify the copyquery code to make the results appear as links, which better suits my needs. Here’s the modified code:

const LS = logseq.api;
const Module = logseq.Module;
const Kits = Module.Kits;
const Msg = Module.Msg;

function advancedQuery(content, queryWord) {
    const queryStart = content.indexOf("[", queryWord + 5);
    if (queryStart < 0) return;

    var queryEnd = queryStart + 1;
    var n = 1;
    while (n > 0) {
        const close = content.indexOf("]", queryEnd);
        if (close < 0) return;

        const open = content.indexOf("[", queryEnd);
        if (close < open || open < 0) {
            queryEnd = close + 1;
            n -= 1;
            continue;
        }

        queryEnd = open + 1;
        n += 1;
    }

    return content.slice(queryStart, queryEnd);
}

function simpleQuery(content, queryWord) {
    const queryStart = queryWord + 6;
    const queryEnd = content.indexOf("}}", queryStart);
    return content.slice(queryStart, queryEnd);
}

function getBlocks(content, queryWord) {
    if (queryWord < 0) return;

    if (content[queryWord - 1] === ":") {
        const query = advancedQuery(content, queryWord);
        if (query) {
            const name = query.includes("?current") ? `"${LS.get_current_page().name}"` : null;
            return LS.datascript_query(query, name).flat();
        }
    } else if (content.slice(queryWord - 2, queryWord) === "{{") {
        const query = simpleQuery(content, queryWord);
        if (query) return LS.custom_query(query);
    }
}

logseq.kits.copyquery = Kits.addClickEventToButton.bind(null, async function onCopyParentClicked(e) {
    const child = e.target.closest("div.ls-block");
    const parent = child.parentElement.closest("div.ls-block");
    const blockId = parent.getAttribute("blockid");
    const block = await logseq.api.get_block(blockId);
    const content = block.content.replace(/\n?.*[:][:].*\n?/g, "\n").trim();

    const queryWord = content.indexOf("query");
    const res = getBlocks(content, queryWord);
    if (!res) return Msg.ofStatus("Missing query", "warning");

    const out = [];
    res.forEach((r) => {
        const name = r.name;
        if (name) out.push(`[[${name}]]`);
        else out.push(r.content);
    });
    navigator.clipboard.writeText(out.join("\n"));
    Msg.ofStatus("Copied " + res.length, "success");
});

Thanks again for all your help!

1 Like