Open a new Terminal window for the current Finder folder

New terminal window for current Finder folder.kmmacros (2.2 KB)

osascript -l JavaScript <<JXA_END
(function () {
	var	a = Application("Terminal"),
		b = Application("Finder").finderWindows();
	a.doScript([
		"cd", b.length ? '"' + decodeURI(b[0].target().url()).slice(7)  + '"' :
		"$HOME",
		"; clear"
	].join(" "));
	a.activate();
})();
JXA_END
3 Likes

Nice to see that in JXA.    :smile:

This vanilla AppleScript will cd the the current Terminal session (if not busy) to the front Finder window (or the Desktop if no windows are open) — it will open a new Terminal window IF the currently selected tab is busy.

tell application "Finder" to set _dir to insertion location as alias

tell application "Terminal"
   tell selected tab of front window
      if its busy = false then
         do script "cd " & (quoted form of (POSIX path of _dir)) in it
      else
         do script "cd " & (quoted form of (POSIX path of _dir))
      end if
   end tell
end tell

-Chris

6 Likes

Thanks – that’s useful – I hadn’t seen the insertionLocation property before.

( Let me know if you manage anything analogous with iTerm 2, it’s defeated me for the moment )

iTerm has somewhat peculiar terminology which is very difficult to figure out without examples.

Change DIR to that of front Finder Window (or Desktop):

tell application "Finder" to set _dir to insertion location as alias

tell application "iTerm2"
   if terminals = {} then reopen
   tell terminal 1
      tell current session to write text "cd " & quoted form of (POSIX path of _dir)
   end tell
end tell

I cannot find a method of discovering if a session is busy, so I've filed a ticket on SourceForge. We'll see if I get a meaningful answer.

Open a new window & session:

tell application "iTerm"
  if terminals = {} then
    reopen
  else
    tell (make new terminal)
      launch session "Chris 01" -- name of desired profile.
      tell last session
        # set name to "New Session"
        write text "dl;" -- alias for my downloads folder.
        write text "clear;"
      end tell
    end tell
  end if
end tell

Open a new tab in the current terminal session:

tell application "iTerm"
  tell terminal 1
    launch session "Default Session" -- 'Default Session' is the profile marked as the default.
  end tell
end tell

-Chris

1 Like

Thank you ! That was fast ...

( switching from exec to write text is just what I need )

So an iTerm 2 version (new iTerm window for active folder), might look like:

new iTerm 2 window for current Finder folder.kmmacros (1.9 KB)

osascript -l JavaScript <<JXA_END
(function () {
	var	a = Application("Finder").finderWindows(),
		b = Application("iTerm");
		
	b.Terminal().make().launch({
		session: "Default"
	}).write({
		text: [
			"cd",
			a.length ?
				'"' + decodeURI(a[0].target().url()).slice(7) + '"':
				"$HOME",
			"; clear"
		].join(" ")
	});
})();
JXA_END

(Essentially equivalent to a LaunchBar Instant Send while selecting a file or folder, but with a single KM keystroke)

Added some comments to the iTerm code.

-ccs

Can a similar macro be created to open a Houdahspot window using the current Finder address?

I have to pass on that one : - ) as it happens I'm not a user of Houdahspot ...

Thanks for the prompt - I did download a trial copy to take a look - it seems useful, and I sketched a quick macro, with the help of @ccstone in the thread which he started:

Does not work for me, I get “Terminal is not a valid class for application iTerm (-2700)” and it has probably to do with iTerm 3.0 released on July 4, 2016, so after your macro. https://www.iterm2.com/version3.html states “The bad news is that existing Applescript won’t work any more.”

Hey Gerrit,

Yes, it would seem they've scrambled the scripting dictionary a bit.

Change DIR to that of front Finder Window (or Desktop):

# Tested with iTerm 3.0.10
tell application "Finder" to set theDIR to insertion location as alias
tell application "iTerm"
   tell front window
      tell current session
         write text ("cd " & "\"" & POSIX path of theDIR & "\"")
      end tell
   end tell
end tell

There's a reasonable amount of scripting info on the site:

-Chris

Might need special handling, I think, for the case in which the Finder is looking at something like:

~/.Trash

(At least if the trash has been opened from the toolbar icon)

More specifically, if I have two Finder windows, both looking at the Trash, but each opened in different ways, the AppleScript expressions

tell application ("Finder") to target of front Finder window

and

tell application ("Finder") to insertion location

both return usable references (on this Sierra system) if the Finder window was created by the following bash command line:

open ~/.Trash

But neither returns a useable reference if the Finder window was created by clicking the trash icon on the toolbar.

(All we get is

folder "" of application "Finder" 

– a strange artefact which responds to no further property or method requests …)

Hey Rob,

I leave that as an exercise for the reader.

I have not handled search windows in the Finder either – nor am I doing any error-handling that will work with Keyboard Maestro.

One of the many reasons I use FastScripts to run most of my AppleScripts is that it has its own error-dialog complete with an “Edit-Script” button – any error is automagially displayed without any intervention on my part.

AppleScripts run from Keyboard Maestro should have at the very least have a generic error-handler that will display any error that occurs.

My iTerm script above for example (with error-handler):

--------------------------------------------------------------------------------
try
   # Tested with iTerm 3.0.10
   tell application "Finder" to set theDIR to insertion location as alias
   tell application "iTerm"
      tell front window
         tell current session
            write text ("cd " & "\"" & POSIX path of theDIR & "\"")
         end tell
      end tell
   end tell
   
on error e number n
   set e to e & return & return & "Num: " & n
   if n ≠ -128 then
      try
         tell application (path to frontmost application as text) to set ddButton to button returned of ¬
            (display dialog e with title "ERROR!" buttons {"Copy Error Message", "Cancel", "OK"} ¬
               default button "OK" giving up after 30)
         if ddButton = "Copy Error Message" then set the clipboard to e
      end try
   end if
end try
--------------------------------------------------------------------------------

-Chris

2 Likes

Perfect, thanks! The following works fine for me using “Execute Shell Script” action and opens a new iTerm2 window:

#!/usr/bin/osascript
tell application "Finder" to set theDIR to insertion location as alias
tell application "iTerm2"
   create window with default profile
   tell front window
      tell current session
         write text ("cd " & "\"" & POSIX path of theDIR & "\"")
      end tell
   end tell
end tell

Hey Gerrit,

There is no advantage to running a pure AppleScript from an Execute a Shell Script action – that's what the Execute an AppleScript action is for.

I'm surprised that:

tell application "iTerm2"

Is working for you.

With iTerm 3.0.10 I've had to use:

tell application "iTerm"

In any case I'm glad you have a working solution.

-Chris