Applescript to open specific Terminal Style Windows - macos

Ok, so the thing is. I want to have different style terminal windows for each job. Each one will have a different job, i.e. , one will connect through ssh to a site, other window to other place, etc.
So I guess this could be done with some Applescripting?
The thing would be to have some applescripts that opens a different terminal window. And then add each applescript to a shortcut.
Any ideas?
Thanks :)

How about setting up a Window group in terminal ?
Open all Terminal windows you want --> Shell --> Show Inspector. Under Settings you can change the theme of each terminal window.
Window --> Save Windows as Group
In preferences set the startup option to display the group.
http://img18.imageshack.us/img18/9681/screenshot20111018at110.png
http://img542.imageshack.us/img542/9681/screenshot20111018at110.png
If you want to use Applescript to set a window's theme you first need to get the id's of all the themes you have using this applescript :
set a to {}
tell application "Terminal"
repeat with i from 1 to count settings set
set temp to {settings set i's name, settings set i's id}
set end of a to temp
end repeat
a
end tell
This will output an array of id # and the theme's name. Next to create a new window use the following :
tell application "Terminal"
set a to do script "" -- creates new window
set a's current settings to (settings set id <one of the id #>)
end tell

tell application "System Events" to tell process "Terminal" to click menu bar 1's menu bar item "Shell"'s menu 1's menu item "New Window"'s menu 1's menu item "Grass"
tell application "Terminal"
set win to do script
set win's current settings to settings set "Basic"
end tell

Related

Trigger an apple script / automator when an application comes to focus in mac

I want to automate the keyboard layout based on the application. I am using an Windows VM over remote I wan't to create a script which can:
Change the Keyboard layout when the application switches to Windows VM
Change it back to normal layout with all other apps.
I have hard time finding a trigger event on application focus change. Is it possible to do it over automator?
Or else kindly suggest another solution to resolve the issue.
Assuming that you only have two keyboard layouts, you can use the following script application.
First, you'll need to open System Preferences and look at Keyboard➔Shortcuts➔Input Sources; see what the what the keyboard shortcut for 'selecting previous input source' is, make sure it's clicked on, and copy it into the script at the marked places. I have mine set to comd-ctrl-space (^⌘ ), but yours is likely different. You should also check that "Windows VM" is the correct name for the app: find the application in the Finder, select it and type ⌘I to open a Get Info window, and look in the Name & Extension text box.
Now do the following
Copy the following script in the Script Editor
Save it as a stay-open application
select 'Application' from the 'Format' menu at the bottom left
click the 'Stay open after run handler' checkbox
Open System Preferences and do the following
add the app to the Accessibility section in Security & Privacy➔Privacy (so it can send keyboard shortcuts)
add the app to the Login Items section for your account in Users & Groups (so it starts automatically at login)
You can then run it and test it out. The app waits in the background to receive notifications that an app has activated or deactivated, then it checks the app name and triggers the keyboard shortcut for the switching the input source when the Window VM app comes or goes.
use AppleScript version "2.4"
use framework "AppKit"
use scripting additions
property NSWorkspace : class "NSWorkspace"
on run
set workSp to NSWorkspace's sharedWorkspace()
set notifCent to workSp's notificationCenter()
tell notifCent to addObserver:me selector:"appHasActivated:" |name|:"NSWorkspaceDidActivateApplicationNotification" object:(missing value)
tell notifCent to addObserver:me selector:"appHasDeactivated:" |name|:"NSWorkspaceDidDeactivateApplicationNotification" object:(missing value)
end run
on idle
-- we don't use the idle loop, so tell the system to check in once an hour
return 3600
end idle
on appHasActivated:notif
set targetApp to (notif's userInfo's valueForKey:"NSWorkspaceApplicationKey")
set targetAppName to (targetApp's localizedName) as text
if targetAppName is "Windows VM" then
tell application "System Events"
tell process "Windows VM"
-- change this line to match your 'Select previous input source' keyboard shortcut
keystroke space using {command down, control down}
end tell
end tell
end if
end appHasActivated:
on appHasDeactivated:notif
set targetApp to (notif's userInfo's valueForKey:"NSWorkspaceApplicationKey")
set targetAppName to (targetApp's localizedName) as text
if targetAppName is "Windows VM" then
tell application "System Events"
tell process targetAppName
-- change this line to match your 'Select previous input source' keyboard shortcut
keystroke space using {command down, control down}
end tell
end tell
end if
end appHasDeactivated:
Once you are satisfied it works, you can run the following command in terminal:
defaults write '/path/to/$name.app/Contents/Info.plist' LSUIElement -bool yes
This will turn the app into a background agent, which never takes the foreground and is invisible in the dock. That way you can just forget about it.

Show/hide Finder, and create new window if none exist via AppleScript

I'd like to create an AppleScript to trigger via key command in Keyboard Maestro that allows me to toggle showing or hiding the Finder window(s) directly. And if when toggling to show the Finder, if there are no existing windows, create one and open it up to my home directory.
The following AppleScript works. However, there seems to be a race condition between activating the finder and detecting if there are any open windows with if not (window 1 exists), hence the delay 0.5.
The problem (which I think is a race condition in detecting the presence of an existing Finder window) results in this script frequently creating new Finder windows when one already existed. The if not (window 1 exists) doesn't always get it right.
Any thoughts, tweaks, or affirmations that this is just the way it is would be appreciated!
tell application "System Events"
set activeApp to name of application processes whose frontmost is true
if ((activeApp as string) is equal to "Finder") then
set visible of process "Finder" to false
else
tell application "Finder"
activate
delay 0.5
if not (window 1 exists) then
make new Finder window
set thePath to POSIX file "/Users/jon"
set the target of the front Finder window to folder thePath
end if
end tell
end if
end tell
Please try this simpler syntax, it uses only Finder terminology
tell application "Finder"
if frontmost then
set visible of process "Finder" to false
else
if (count windows) is 0 then reveal home
activate
end if
end tell
Edit:
To run a Keyboard Maestro macro, open Keyboard Maestro Editor, select the macro and then select Copy as > Copy UUID from the Edit menu.
Then in AppleScript write
tell application "Keyboard Maestro Engine" to do script "<Script-UUID>"
replacing <Script-UUID> with the copied real UUID
Ultimately I needed to activate Finder before running the count windows command or I'd get inconsistent window counts. Sometimes it'd be 0 even when there was a window open already. This code is working well for me so far.
tell application "Finder"
if frontmost then
set visible of process "Finder" to false
else
activate
if (count windows) is 0 then
open home
tell application "Keyboard Maestro Engine" to do script "<Script-UUID>"
end if
end if
end tell

How to create a Custom Keyboard Shortcut for Rename [x] items… in macOS Finder?

The problem in using the standard procedure (via System Preferences… > Keyboard) is that it needs the exact command name…
Many thanks in advance for any answer.
--
kenNash
I am not aware of any wildcard which could be used there, probably there is none.
But there is a silly workaround:
EDIT:
Also, this can be easily done in the Automator.
Create new Automator document like this:
Here is the code:
on run {input, parameters}
tell application "System Events" to tell process "Finder"
tell menu 1 of menu bar item 3 of menu bar 1
click (menu item 1 where name starts with "Rename")
end tell
end tell
return input
end run
It has to be saved to the ~/Library/Services/ directory.
Then set your keyboard shortcut for service:
You will also need to give accessibility permissions to finder:

Error getting the number of tabs in "Terminal" window via Applescript on OSX El Capitan

Basically, I want to change the theme of bash when I open new windows, not new tabs, and then have tabs of a window share the same theme; while themes of separate windows are determined randomly.
After some digging, I found out an applescript which sets the theme of the current tab of Terminal window. I created a
/usr/local/terminal-color.scpt as:
on run argv
tell application "Terminal" to set current settings of selected tab of front window to some settings set
end run
And I have added the following statement to my bash profile:
osascript /usr/local/terminal-color.scpt
Now this script, of course, runs with every new instance of the bash. I cannot do anything about that from bash_profile. However, I should be able to differentiate a new window or a new tab from the applescript itself. Therefore, I am looking for an if statement, which would let the script run only when new windows are created. Something like:
on run argv
if index of selected tab is 0
tell application "Terminal" ....
end if
end run
But I cannot figure out how to achieve this looking at the applescript documentation and scripting dictionary of the terminal application. Help please
Update
I try editing the script as follows:
set tabNum to number of tabs of front window
if tabNum = 1 then
tell app ...
this won't work either giving an error tabs of window 1 doesn’t understand the “count” message
My approach was correct but I had a simple mistake of trying to get tab or window data before choosing an application scope. To put in simple words, first tell the application, then ask about its properties. Here's the code that worked:
on run argv
tell application "Terminal"
if number of tabs of front window = 1 then
set current settings of selected tab of front window to some settings set
end if
end tell
end run
Even Better
Improving the previous script; this one not randomly chooses a theme, it iterates through your available terminal themes according to the windows you have already open. You can also set your default theme that will be set on your first launch of the terminal. In my case, it was the 5th one in the settings set. Here goes the code:
tell application "Terminal"
if number of tabs in front window = 1 then
set defaultThemeOffset to 5
set allThemes to number of settings set
set allWindows to number of windows
set themeIndex to (defaultThemeOffset + allWindows) mod allThemes
set current settings of selected tab of front window to settings set themeIndex
end if
end tell

How do I set Mac OS X 10.6 Terminal tab title programmatically?

I'm trying to learn Applescript as I'd like to, eventually, programmatically set the title of the tab in Terminal to whatever context I'm currently working in. Should be a simple task and I've gotten it almost right I think. This is my experimental code so far...
tell application "Terminal"
activate
set frontIndex to index of the first window whose frontmost is true
tell window frontIndex
set title displays custom title of selected tab to true
set custom title of selected tab to "Bazzy"
end tell
end tell
The problem is that when I set the tab's title, the title of all other tabs also get set. However, if I right-click and inspect a tab and then set the title manually on that tab, its title is not affected when I run my code and the title I manually typed in remains. It's as though the title displays custom title property is not being read or perhaps this property does not do what I think it does.
How can I set the title of exactly one tab to a custom value?
I you're executing the script from the Terminal itself you can use a simple echo, e.g.:
echo -n -e "\033]0;Tech-Recipes rules\007"
It event works if you put it inside $PS1 so that it changes each time the prompt is rendered.
source: How do I set Mac OS X 10.6 Terminal tab title programmatically?
I just tried this and it worked fine:
tell application "Terminal"
set custom title of tab 2 of window 1 to "beta"
set custom title of tab 1 of window 1 to "alpha"
end tell
I admit I wasn't using 10.6 so maybe Apple changed it.
This property does not do what you think it does. Setting the custom title to one tab applies to all tabs in all windows, per this code:
tell application "Terminal"
tell window 1
set title displays custom title of tab 1 to true
set custom title of selected tab to "foo"
end tell
tell window 2
set title displays custom title of tab 2 to true
set custom title of selected tab to "bar"
end tell
end tell
--> RESULT: All tabs in all windows show "bar"
I wonder if it has to do with the title relating to the environment—i.e., bash, csh, zsh, ksh—and not to individual tabs. Even if I quit Terminal and come back in, "bar" still shows everywhere. I'll freely admit that I don't know enough about how the CL interface works to know for sure.
At the same time, if you are learning Applescript, I would suggest learning it on something a little less wonky, like the Finder or something. There are loads more useful things that can be done there than in Terminal with Applescript.
There's some weird behaviour around these commands when grabbing the correct window/tab, but this ended up working for me in 10.5.8 (Terminal v2.0.2)
tell application "Terminal"
do script
set currWin to index of first window
tell window currWin
set custom title of first tab to "A Custom Title"
end tell
set current settings of window currWin to settings set "Grass"
end tell
The key here is that do script opens a new terminal window, thereby forcing it to be 'first' (do script also returns the created tab index, but I couldn't make any use of it).
The custom title then applies only to that window. Also threw in a line to set the profile for the terminal tab.
(Referenced: AppleScript to open named terminal window)
Additional
Example of weird behaviour: removing the do script line results in the custom title being applied to all windows, but only one window receives the settings set change!
As of Mac OS X Lion 10.7, Terminal only sets the custom title property of the target tab/window instead of changing the settings profile (which affects all terminals with that profile). Prior to 10.7, most—but not all—of the terminal properties applied only to the target terminal; however, a few of them applied to the settings profile used by the terminal. Those have been changed in 10.7 to only affect the target terminal.
I was looking for this for a while and as #tponthieux mentioned in his comment, all these scripts change the terminal window title not tab title. Unfortunately, it seems there is no option to change the tab title with a ready apple script, so I did it with using keys and it works without a problem on OSX El Capitan.
tell application "Terminal"
activate
tell application "System Events"
keystroke "i" using {shift down,command down}
keystroke Tab
keystroke "yourtitlehere"
key code 53
end tell
The titles for OSX Terminal come from a few different sources.
1) Preferences > Window: Select Terminal > Preferences > Window (tab). Here you will find all kinds of configuration for titling the window.
2) Preferences > Tab: Select Terminal > Preferences > Tab (tab). Here you will find all kinds of configuration for titling the tab.
3) Console codes: The VT100 commands you can use (more info by searching for OSC here)
echo -n -e "\033]0;Set icon name (tab) and window title to this.\007"
echo -n -e "\033]1;Set the icon name (tab) to this\007"
echo -n -e "\033]2;Set window title to this\007"
NOTE: as Elia Schito said, you can place these console codes inside $PS1 so it updates each command you enter.
This is what I needed to do:
tell application "Terminal"
do script "DISABLE_AUTO_TITLE=true" in selected tab of the front window
do script "echo -n -e \"\\033]0;" & title & "\\007\";" in selected tab of the front window
end tell
The first line is needed for ZSH.
However, it still doesn't work well for long-running processes, since their names continue to dominate the tab title.

Resources