julkarham
julkarham

Reputation: 115

How do I get the path to the file of an open window of an application?

I want to write an AppleScript which creates a new file in the same directory as the file I currently have open (in this case, in the application TexShop).

If I can get the path, then I can write a script like:

set thePath to get path to open window / tell TexShop to get path...?

set response to display dialog "Some text:" default answer ""

set toWrite to text returned of response

tell application "Finder" to set newFile to make new file at thePath

set openFile to open for access file (newFile as string) with write permission

write toWrite to openFile starting at eof

I am ultimately just looking for a way to specify where I want the file to go depending on changing circumstances, that is, when I am working on different files in different directories.

Upvotes: 0

Views: 1129

Answers (2)

CJK
CJK

Reputation: 6092

Here's a technique that should cover both scriptable and non-scriptable applications, with a caveat that it obviously can't return information that isn't provided by the developer through accessibility hooks. However, if it's scriptable, or if the developer chooses to expose app data for accessibility, then this will provide that little extra scope beyond the decreasing circle of AppleScriptable software:

tell application id "com.apple.systemevents" to tell (the first process ¬
    where it is frontmost) to tell (a reference to the front window) ¬
    to if it exists then tell its attribute "AXDocument"'s value to ¬
    if it is not in [missing value, "file:///Irrelevent"] then ¬
        return my (POSIXPathOfFolder for it)

false

on POSIXPathOfFolder for (fileURL as text)
    local fileURL

    set fp to "/tmp/rw" as «class furl»
    close access (open for access fp)
    set eof of fp to 0
    write the fileURL to fp
    read fp as «class furl»
    POSIX path of (result & "::" as text)
end POSIXPathOfFolder

I also avoid employing Finder whenever possible, as it's slow, buggy, and temperamental. The handler at the bottom uses standard additions plus built-in features to get the containing folder of the retrieved document path.

If a document path is not made available, the script returns false.

Upvotes: 1

wch1zpink
wch1zpink

Reputation: 3142

This following AppleScript code should help towards the goal of getting the path to the front most document in the front most application and the path to its containing folder.

(* The Delay Command  Gives You Time To Bring The Desired App To The Front
Mainly For Use While Testing This Code In Script Editor.app *)

delay 5 -- Can Be Removed If Not Needed

tell application (path to frontmost application as text) to ¬
    set documentPath to (get path of document 1) as POSIX file as alias

tell application "Finder" to set containingFolder to container ¬
    of documentPath as alias

Upvotes: 1

Related Questions