JXA: Reading/Using Data from the Clipboard

  • Looks like a useful reading exercise – thanks
  • with trivial scriplets (very shallow nesting) there is an argument for simply letting them choke on occasionally invalid input – the error message is informative and free – can be better use of scripter time :slight_smile:
  • If you do want a type check, I might write something like (strClip && (typeof strClip === 'string')) to screen out empty strings as well as images
function run() {
    // writeFile :: FilePath -> String -> IO ()
    function writeFile(strPath, strText) {
        $.NSString.alloc.initWithUTF8String(strText)
            .writeToFileAtomicallyEncodingError(
                strPath, true,
                $.NSUTF8StringEncoding, null
            );
    }

    var a = Application.currentApplication(),
        sa = (a.includeStandardAdditions = true, a),
        strClip = sa.theClipboard();

    if (strClip && (typeof strClip === 'string')) {
        var lines = strClip.split(/[\n\r]/),
            strHead = lines.length > 1 ? lines[0] : undefined,
            strTail = strHead ? lines.slice(1)
            .join('\n') : undefined;

        return strTail ? (
            writeFile(
                (sa.activate,
                    sa.chooseFileName({
                        withPrompt: 'Save As',
                        defaultName: strHead + '.txt'
                    })
                ).toString(),
                strTail
            ),
            strTail
        ) : undefined;
    }
}