Script to add / remove underscores?

Here, in the meanwhile, is a first draft of a toggling script, which aims to flip ⇄ between the two states on each run.

Expand disclosure triangle to view JS Source
(() => {
    "use strict";

    // TaskPaper front document toggled between two states
    // 1. Projects with hash-prefixed underscored children
    // 2. Plain lines with plain children.

    // Rob Trew @2020
    // Ver 0.01

    // eslint-disable-next-line max-lines-per-function
    const TaskPaperContext = editor => {
        const
            outline = editor.outline,
            topRows = outline.root.children,
            hashRows = outline.evaluateItemPath(
                // eslint-disable-next-line quotes
                '/*/(not @text="")'
            ),
            inHashState = hashRows.some(
                item => item.bodyContentString.startsWith(
                    "#"
                )
            );

        const fromHashState = () => (
            topRows.forEach(
                item => item.setAttribute(
                    "data-type", "note"
                )
            ),
            hashRows.forEach(item => {
                item.bodyContentString = (
                    item.bodyContentString
                    .replace(/^#/u, "")
                    .replace(/_/gu, " ")
                );
            })
        );

        const toHashState = () => (
            topRows.forEach(
                item => item.setAttribute(
                    "data-type", "project"
                )
            ),
            hashRows.forEach(item => {
                const s = item.bodyContentString;

                item.bodyContentString = (
                        s.startsWith("#") ? (
                            s
                        ) : `#${s}`
                    )
                    .replace(/ /gu, "_");
            })
        );

        outline.groupUndoAndChanges(() => {
            if (inHashState) {
                fromHashState();
            } else {
                toHashState();
            }
        });

        return inHashState ? (
            "CLEARED hashes, underscores, colons."
        ) : "ADDED hashes, underscores, colons.";

    };

    const main = () => {
        const
            taskpaper = Application("TaskPaper"),
            frontDoc = taskpaper.documents.at(0);

        return frontDoc.exists() ? (
            frontDoc.evaluate({
                script: `${TaskPaperContext}`
            })
        ) : "No documents open in TaskPaper";
    };

    // MAIN ---
    return main();
})();

I personally tend to attach this kind of thing to a keystroke with Keyboard Maestro, but more generally, see:


PS make sure, of course, that you copy the whole of the script, scrolling all the way down to the bottom, which looks like:

    // MAIN ---
    return main();
})();
2 Likes