Jump to content
lululau

A bash script to get path of document open by the frontmost window

Recommended Posts

filename=$(echo 'tell application "System Events"
  set theprocess to the first process whose frontmost is true
  set thetitle to the value of the attribute "AXTitle" of theprocess
  set thewindow to the value of attribute "AXFocusedWindow" of theprocess  
  set thefile to the value of attribute "AXDocument" of thewindow as string
  if thetitle is "Finder" then
      tell application "Finder"
         set thefile to (POSIX path of (target of the first window as alias))
      end tell
  end if
  set thefile to thefile
end tell' | osascript -ss | php -r 'echo urldecode(fgets(STDIN));')
filename=${filename%\"}
filename=${filename#\"}
filename=${filename#file://localhost}
dirname=$(dirname "$filename")
basename=$(basename "$filename")

 

hope this is useful for you

Share this post


Link to post

Nice script. Just want to point out that you need "Enable access for assistive devices" checked in the Accessibility preference pane for this to work.

 

Generally, it'll work with apps that display a little document icon in the menu bar. It should work fine in text editors like Sublime Text or TextMate, but I've had trouble getting the proper AXDocument in Xcode -- not sure if there's a way around that in AppleScript.

 

It might also be useful to get the selection in Finder rather than the open folder, but you'd have to figure out a way to deal with multiple selected files.

 

Edit: Oh, and if you wanted to turn this into a workflow, you could just add something like `tell app "Alfred 2" to search "$filename"` to view the file in Alfred.

Edited by Clinton Strong

Share this post


Link to post

That's really a good idea!

I've quickly made a workflow with your code in order to get and browse the document of the frontmost window in Alfred. If no document can be found, a notification is done.

 

The workflow is here

 

Thanks for your code!

Share this post


Link to post

Excellent workflow which I've been looking for for a while. Thanks.

 

Can someone suggest how I might extend this script to take the document straight to email?

Share this post


Link to post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...