MacOS Terminal: Is it possible to create a "drag-and-drop" action via script? - terminal

There are many posts that explain how to drag-and-drop things into an open Terminal window. But what I would like to do is to tell Terminal to drag-and-drop a previously selected directory onto another application like VSCode or Renamer. I have not found any documentation for that. Is it at all possible? And if so, would somebody please point me to a documentation?
UPDATE:
I'd like to clarify my question with what I intend to do:
Pre requisites:
a "work folder" contains folders and files that shall be renamed
the renaming is done by an application called "A better finder renamer" (which allows presets)
An "Automator" (MacOS app) action shall imitate these steps:
the "work folder" is right clicked
the folder is drag-and-dropped onto the ABFR, which initiates the currently active preset
other actions via bash (like 'mv .//.* ./') ...
It is the "drag-and-drop" part of the Automator action that presents a riddle for me.

The "drag-and-drop" operation is manual operation. In AppleScript, instead the command to open the file or folder is given to the destination application itself.
Second thing to keep in mind. Getting Terminal's current working directory is easy with its do script "pwd" command. But the result of the do script Terminal command returned to the script is always the window tab, not the result of the pwd shell command. One solution is to redirect (remember) the result of pwd in a temporary text file.
set tempFolder to (path to temporary items folder from user domain)
set temp to POSIX path of tempFolder & "workingDirectory.txt"
tell application "Terminal" to do script ("pwd > " & temp) in selected tab of window 1
set curDirPosixPath to paragraph 1 of (read file ((tempFolder as text) & "workingDirectory.txt"))
set curDirHFSPath to curDirPosixPath as POSIX file as Unicode text
tell application "Visual Studio Code" to open curDirHFSPath
.
NOTE: other possible solution (I don't like) is parsing the text contents of Terminal window after pwd command execution. You can get contents using property contents (of selected tab of front window).

Open Automator, choose create New Document.
Choose create new Quick Action (service).
Set workflow receives current folders in any application.
From library Add Run AppleScript action. Edit it contents:
on run {input, parameters}
set curDirHFSPath to (item 1 of input) as text
tell application "Visual Studio Code" to open curDirHFSPath
end run
Save this Quick Action as service. Now when right-clicking the folder, opens the context menu, where you can choose and run this service.

Related

How do I make NeoVim my default text/code editor?

Is there a way to make NeoVim as default text/code editor (without any bad side effects) ?Trust me, I looked to lots of StackOverflow question/answers and tried a few things but nothing worked for me.
Note: I'm on macOS Big Sur (version 11.2.1). What I want is when I click on files to open in NeoVim.
--> For example, in ~/.zshrc (and added to ~/.bash_profile also just in case) I have:
Note: zsh is my default shell
alias nvim=$HOME/nvim-osx64/bin/nvim
export EDITOR="nvim"
export VISUAL="nvim"
When I do set in Terminal it shows:
EDITOR=nvim
VISUAL=nvim
And yes, I quit and started the terminal (I'm using iTerm2). I even reboot.
--> I will place my $PATH here just in case it has anything to do it that. When I do echo $PATH it shows:
--> And, just in case someone suggests:
I can't Select a File > Open With... and select NeoVim as default text editor, since that option doesn't show and I can't do Choose Other since I can't select NeoVim in that way.
If anyone needs more information, please say and I will edit the question with that info. Thanks!
Setting variables in the terminal will not affect the GUI file associations. To do that you have to change the OS's file associations.
Though it appears to be a small project and unsupported, I've had a good experience using duti. It's a wrapper around the Apple file extension API. The configuration did take me a minute to figure out. I'll post it if I can find it.
After a while I found the answer to my own question, here it is how you can set NeoVim in Mac as the default text editor. Now, you will be able click on files and opening them in NeoVim:
Some people recommended me to have a look at the follow links:
https://gist.github.com/Huluk/5117702
https://superuser.com/questions/139352/mac-os-x-how-to-open-vim-in-terminal-when-double-click-on-a-file
That didn't work for me but it served as a reference to look up related topics (automator + neovim).
After a while, I discover this blog:
https://blog.schembri.me/post/neovim-everywhere-on-macos/
Go and have a look at the blog, but here it is how you do it:
Launch Automator (Finder -> Applications -> Automator)
New Document -> Choose a type for your document: Application
In Actions search for Run AppleScript and drag that to where it says something like "Drag actions here..."
Delete the default example of AppleScript
Copy and Paste the code in the blog (where it says NeoVim.app) to where it previous had the default code
Save the new Automator app (save as aplicattion format). Save it in the Applications folder
Right-Click a file type you wish to open every time you click on them (e.g. .php file). Select Get Info or do cmd + i, it will open informations about that file. Scroll to wher it says Open With and select Other. Then just go to Aplicattions folder and select your new NeoVim "app".
Do the same to other file types if you wish.
You can now double click on your PHP files (or others if you did the same) and open them in NeoVim. Enjoy!
Note: You really need to do Right-Click, Get Info and look for Open With to change in all files with that extension. If you skip Get Info and just Right-Click + Open With, it will only work for that specific file...
This is the code from the blog:
on run {input, parameters}
set cmd to "nvim"
if input is not {} then
set filePath to POSIX path of input
set cmd to "nvim \"" & filePath & "\""
end if
tell application "iTerm"
create window with default profile
tell the current window
tell the current session to write text cmd
end tell
end tell
end run
This would open a new window even if you already had one open.
I change it so that it would open in a tab:
on run {input, parameters}
set cmd to "nvim"
if input is not {} then
set filePath to POSIX path of input
set cmd to "nvim \"" & filePath & "\""
end if
tell application "iTerm"
tell the current window
create tab with default profile
tell the current session to write text cmd
end tell
end tell
end run
Note: I'm using iTerm2. If you are using another Terminal Emulator, change where it says iTerm to the name of your terminal...
For anyone using Kitty on MacOS, I found a pretty simple way to accomplish this using the remote control feature.
First you need the following set in your kitty.conf:
allow_remote_control yes
listen_on unix:/tmp/mykitty
Using Automator like in #DGF's answer, I created an Application with the "Run Shell Script" action, and this is the script:
if [ -z "$(pgrep kitty)" ]
then
open /Applications/kitty.app
sleep 3 # allow ample time to startup and start listening
fi
/usr/local/bin/kitty # --to=unix:/tmp/mykitty-$(pgrep kitty) launch --type=os-window nvim "$#"
Save that as an application somewhere, and select it from "Open with"!
Note: to be honest, the logic to handle starting up kitty if it's not already running is a little flaky. But it seems to work great when kitty is already running, which of course it is most of the time for me. Also, it doesn't work at all if kitty is running but has no windows. :\
Choose nvim as the default application by means of a txt file sub-menu like here with Preview for PDFs:

How to start a .command script from a mac automator app

I'm trying to create a mac "app" using automator that basically calls a .command file to do all the work. The command file will be in the same dir as the .app but i'm falling at the first which is - get the current directory of the .app file thats been clicked to determine the file location of the .command file.
i've tried
SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
echo "-- $SCRIPTPATH"
This just returns my users director - basically ~
The app itself is in a dir on the Desktop example: ~/Desktop/foo/my.app
I've also tried
here="`dirname \"$0\"`"
echo "cd-ing to $here"
cd "$here" || exit 1
neither work.
ultimately i need to call my.command to run the command but need to know its actual position - or even relative to the app so that it'll fire. currently i get the error that it can't find the my.command as its not located in the root of my user account (since i wont have control over where it can be placed on the end users machine).
Any pointers on what i can do to solve this much appreciated.
Note: To answer - why am i using an app which has a terminal script to call a .command which is essentially a script - basically because if you do it this way a terminal doesn't actually pop up.. which for this demo is what i need to happen.
As you did not include explicit details of your Automator workflow, saved as an application, I'm presenting the following as an example of how to have and Automator app, e.g. my.app, execute the e.g. my.command script file, that which is located in the same folder as e.g. my.app is.
For the purpose of the example, I created a folder named foo on my Desktop, in which my.app was saved along with the my.command script file.
The Automator application workflow uses a Run AppleScript action to accomplish the goal.
Replace the default code with the following example AppleScript code:
set myCommandFilename to "my.command"
set myAppPathAlias to path to me
tell application "System Events"
set myDirName to POSIX path of container of myAppPathAlias
set myCommandFilePathname to myDirName & "/" & myCommandFilename
set myCommandFilenameExists to exists file myCommandFilePathname
end tell
if myCommandFilenameExists then
try
do shell script myCommandFilePathname's quoted form
on error eStr number eNum
display dialog eStr & " number " & eNum ¬
buttons {"OK"} default button 1 ¬
with title "File I/O Error..." with icon stop
end try
else
display dialog "A necessary file, ' " & myCommandFilePathname & ¬
"', is missing!" buttons {"OK"} default button 1 ¬
with title "Missing File..." with icon stop
end if
Note: Change my.command to the actual filename. The rest of the example AppleScript code should not need to be modified.
If my.app is launched and the my.command script file is not in the same folder as my.app, then an error message will be displayed, e.g.:
If my.app is launched and the my.command script file doesn't have its executable bit set, then this error message will be displayed, e.g.:
Also, if the my.command script file does not exit cleanly, it too will display an error message, e.g.:
The content of the error message will vary based on the content of the e.g. my.command script file, how it's coded and how it fails. This example is worst case scenario in that it lets you know something failed, but not what failed.
Note: The example AppleScript code is just that and does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors.

How to debug droplets using AppleScript

Just 3 lines of script to be able to test a droplet application without leaving applescript editor
set fich to POSIX file "/Appli/conv2spct.app" as string
tell application "Finder" to open POSIX file "/Users/yourusername/Desktop/somefile" using application file fich
If there are errors in your droplet a display dialog will be opened by the script editor applescript
The same script with choose file for the 2 elements
set fileappli to POSIX path choose file of type {"APPL"} with prompt "Choose a Droplet application to debug"--the droplet for debug
set fileargument to POSIX path choose file --the file argument to pass at droplet
tell application "Finder" to open fileargument using application file fileappli
If there are errors in your droplet a display dialog will be opened by the script editor applescript
Here's a pragmatic alternative using do shell script, which potentially allows you to specify multiple file arguments:
do shell script "open -a /Appli/conv2spct.app ~/Desktop/somefile1 ~/Desktop/somefile2"
The above paths happen not to need quoting (escaping) for the shell, but when using variables to specify the file paths, it's best to use quoted form of (to pass multiple arguments, apply quoted form of to each):
do shell script "open -a " & quoted form of fileappli & " " & quoted form of fileargument
Looks like this has become simpler since the question was first asked. According to this documentation you can write:
open {choose file}
on open theDroppedItems
...
end open
Run this from within the AppleScript editor and the file you choose will be opened as if it had been dropped onto the compiled script.

Script that launches commands on two Terminals

I need to do a .command file script/batch. Launching it (double-click) it has to to those things:
Open a terminal window (A)
Launching a command that open the folder where the file is (maybe this cd "dirname "$0"")
Launch a command
Open a terminal window (B)
Launching same command at point 2
Launch a command
Given that you explicitly want to create terminal windows, consider creating an application using AppleScript:
Open Script Editor (up to 10.9, AppleScript Editor)
Paste the code below.
Save as an application (via the pop-up list in the Save As dialog) to the desired folder.
# Determine the folder in which this app is located.
set thisFolder to do shell script "dirname " & quoted form of POSIX path of (path to me)
# Sample commands to execute in the new windows.
set cmds to {"date", "echo $$"}
tell application "Terminal"
# Create 2 new windows, change to the
# this app's folder, and execute the respective command.
repeat with i from 1 to 2
do script "cd " & quoted form of thisFolder & "; " & item i of cmds
end repeat
# Activate Terminal.app
activate
end tell
The reason that I recommend using an application over a *.command file is that the latter would itself open in a Terminal window first, before creating the desired windows, which is visually disruptive (and, depending on your Terminal.app preferences, may leave the extra window open).
Alternatively, you could turn that into a virtue and use the *.command file's own window as your 1st terminal window, and only create one additional one.

Is there a way to trigger Finder's "quick look" window with Applescript?

I am using Applescript to automate some tasks in the OSX Finder. The script opens up a folder and selects the first image in that folder. I would like it to also bring up the "quick look" window (exactly as if the user had pressed the space bar).
I did find a way to fire up quick look from the command line using qlmanage, but that brings up a static quick look window, which is no longer tied to the finder selection.
Code so far:
property folderPath : "/Volumes/Media/Images"
on run {}
tell application "Finder"
activate
set imageFolder to folder (folderPath as POSIX file)
set imageFile to first item of imageFolder
select imageFile
-- show quick look?
end tell
end run
If you don't want to do it by scripting the Finder you can run the following shell command
qlmanage -p thefile
In an Applescript you might do this like
do shell script "qlmanage -p " & "thepath/thefile"
Depending upon what you are doing this might be much easier. Especially if you primarily just have a set of paths.
If you have an existing Applescript path you can send it like this
set p to POSIX path of mypath
do shell script "qlmanage -pr " & quoted form of p
Updated (with thanks to Kevin Ballard):
tell application "System Events" to keystroke "y" using command down
Note: this requires that "enable access for assistive devices" is selected in the "Universal Access" control panel.

Resources