Applescript if no file is added - vim

I have the following automator apple script that I'm using so that when I drag a file into a dock icon, it opens that file in vim:
on run {input, parameters}
set filename to POSIX path of input
set cmd to "clear && 'vim' '" & filename & "' && exit"
tell application "iTerm"
set newWindow to (create window with default profile)
tell current session of newWindow
write text cmd
end tell
end tell
end run
However, I would also like to allow clicking the icon itself to open vim without any file, i.e., running $ vim. How would I change the above script so that:
If a filename is passed, I open vim with that file, vim filename
If no filename is passed (the icon is just double-clicked), it just opens vim, with vim ?

The following example AppleScript code will do as you've asked; however, keep in mind that input is a list and as presently coded it is expecting a single item list, meaning you've only dragged and dropped one file onto the app's Dock Tile:
on run {input, parameters}
if not input is equal to {} then
set filename to POSIX path of first item of input
set cmd to "clear && 'vim' '" & filename & "' && exit"
else
set cmd to "clear && 'vim' '" & "' && exit"
end if
tell application "iTerm"
set newWindow to (create window with default profile)
tell current session of newWindow
write text cmd
end tell
end tell
end run
Note: The example AppleScript code is just that and does not contain any 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. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

Related

Change desktop app icons on mac, programatically. 2019

Is there a way to change icons on desktop apps for macbooks, that replicates the same action that happens when you copy / paste icons in the finder window? Either through the terminal, node.js or anything ? I have so far tried:
1) Through the terminal, deleting and replacing the icons themselves, I don't like this because it removes the original icon completely and does not work on every app.
2) Through node.js and terminal, creating an icon? file, however this did not work on every program either, and I had trouble with permission access. If anyone have a solution for this I'd like to hear it.
3) With applescript, this worked but looping through multiple icons at once was too much for it.
I've been searching about this for days, but the information is either very limited or outdated. I would appreciate any help!
To change the icon of an application, I use shell script with applescript.
The goal is to change "Icon file" in the application info.plist and copy the icon (file) in the resources of the application. "application".app/Contents/Resources/ " .
All done in a droplet, on which I drag the desired icon, after opens a window to choose the application whose icon must be changed.
With plutil I convert the file info.plist to xml1 (which I save under ".app/ Contents/infoo.plist" to avoid any problem and find the original). To change the value "Icon file", I use "/usr/libexec/PlistBuddy " with " -c Set: "
to see the change, you have to launch the application (whose icon has been changed), in the dock you have to see the new icon (if the dock option is active)
Below the droplet script
global testdir
on open draggedItems
repeat with currentItem in draggedItems
set icon_image_file_string to POSIX path of (draggedItems)
set {name:Nm, name extension:Ex} to info for POSIX file icon_image_file_string
set Nm to do shell script "echo " & Nm & " | sed 's#." & Ex & "##'"
set testdir to POSIX path of (choose file of type {"APPL"} with prompt "Choisissez l'Application pour changer son icone :")
set {name:Nmm, name extension:Ex} to info for POSIX file testdir
do shell script "plutil -convert xml1 " & quoted form of (testdir & "Contents/Info.plist ") & " | cat " & quoted form of (testdir & "Contents/Info.plist") & " >" & quoted form of (testdir & "Contents/Infoo.plist")
try
do shell script "cp -f " & quoted form of icon_image_file_string & " " & quoted form of (testdir & "Contents/Resources/")
end try
try
set icon_image_file to do shell script "/usr/libexec/PlistBuddy " & quoted form of (testdir & "Contents/Info.plist") & " -c \"Set:CFBundleIconFile " & Nm & "\""
end try
end repeat
end open

Searching in Finder from Selection

Usually I get an excel spreadsheet with dozens of filenames, for which I then need to go and search individually.
Spreadhseet
Is there a way that I could simply:
Select All filenames in e.g. row A of Excel,
then Search for all these files on "This Mac"
then Copy all found files into the New Folder on the Desktop
So far I've tried the first part of searching and this is what i get :a)
Automator with Variable. But the problem is, it only searches for 1 file from selection
b)
Automator with Shell Script (Copy to Clipboard > Open Finder > CMD+F (to highlight Search dialog) > CMD+V). It opens a new Finder window, but it doesn't paste the clipboard into search dialog
c) /usr/bin/pbcopy
on run {input, parameters}
tell application "System Events"
keystroke "f" using {command down}
keystroke "v" using {command down}
end tell
return input
end run`
End result, is same as option b). I was planning to run this in Automator as a 'Service', which I could later assign to Keyboard Shortcut.
I am pretty sure there should be a simple shell option for this - any advice would be much appreciated.
I made a bash script that does what you want. You would basically select a bunch of filenames in Excel, or any other app, and copy them to the clipboard with ⌘C. After that you need to run the script and it will take items from the clipboard and search for TIFF or JPEG images that match that name and copy them to a directory on your Desktop called Selected Files:
#!/bin/bash
# Get contents of clipboard into bash array
files=( $(pbpaste) )
# Create output directory - no checks for already existing or already containing files
OUTDIR="$HOME/Desktop/Selected Files"
mkdir -p "$OUTDIR"
# Iterate through fetching files
for ((i=0;i<${#files[#]};i++)) ; do
name=${files[i]}
result=$( mdfind "kMDItemDisplayName == \"${name}.*\" && (kMDItemKind==\"TIFF image\" || kMDItemKind==\"JPEG image\")" )
if [ -f "$result" ]; then
echo $name: $result
cp "$result" "$OUTDIR"
else
echo ERROR: Searched for: $name, found $result
fi
done
I am not sure of your level of familiarity with bash, so you may be able to ignore the following...
Make a new directory for your own scripts:
mkdir -p $HOME/scripts
Save the above script in that directory with filename:
$HOME/scripts/gather
Make the script executable by typing this into Terminal:
chmod +x $HOME/scripts/gather
Edit your login profile ($HOME/.profile) and add your $HOME/scripts directory to your PATH:
export PATH="$PATH":$HOME/scripts
Then start a new Terminal and you can use any script that you have saved in $HOME/scripts without needing to specify the full path to it, e.g.:
gather
Following information kindly contributed by #user3439894 in comments section, as I am out of my depth on this aspect...
To use a keyboard shortcut, you'd have to create an Automator "Service workflow" with a "Run Shell Script" action, which you can assign a keyboard shortcut to under: System Preferences > Keyboard > Shortcuts > Services

Using VBA to run WinSCP script

I am able to download files from SFTP in CMD window, by using following code:
WinSCP.com
# Connect to the host and login using password
open user:pw#address
# get all the files in the remote directory and download them to a specific local directory
lcd C:\Users\xx\Desktop
get *.xlsx
# Close and terminate the session
exit
I searched online and found out that I can put these codes in a bat file and use
Call Shell("cmd.exe /c C:\Users\xx\Desktop\WinSCPGet.bat", 1)
However, only the first line of the bat file WinSCP.com is being executed. It will pop up the cmd window, showing this, without doing anything else.
How to execute all the lines at one time?
Thanks
The code you have is not a Windows batch file. It's one Windows command followed by WinSCP commands. The first command runs winscp.com application, which then sits and waits for input. If you eventually close it, Windows command interpreter (cmd.exe) will carry on executing the remaining commands, failing most, as they are not Windows commands. See also WinSCP script not executing in batch file and WinSCP FAQ Why are some WinSCP scripting commands specified in a batch file not executed/failing?
So you either have to save the commands (open to exit) to a WinSCP script file (say script.txt) and execute the script using the /script switch:
Call Shell("C:\path\winscp.com /ini=nul /script=c:\path\script.txt")
Alternatively, specify all commands on WinSCP command line, using the /command switch:
Call Shell("C:\path\winscp.com /ini=nul /command ""open user:pw#address"" ""lcd C:\Users\xx\Desktop"" ""get *.xlsx"" ""exit""")
Regarding the quotes: With the /command switch, you have to enclose each command to double-quotes. In VBA string, to use a double-quote, you have to escape it by doubling it.
Also note that you generally should use the /ini=nul switch to isolate the WinSCP script run from your WinSCP configuration. This way you can also make sure that the script will run on other machines. Your script won't, as it lacks the -hostkey switch to verify the SSH host key fingerprint. Using the /ini=nul will help you realize that.
You can have WinSCP GUI generate complete command-line (including the -hostkey) for you.
See also Automating file transfers to SFTP server with WinSCP.
I like this small and compact procedure, and use it in my own projects. No temp-files required. Fast and reliable.
Parse a string src (an absolute filepath) to uploadImageByFTP. Etc. C:\Users\user\Desktop\image.jpg, and the file will be uploaded.
Replace:
<username> with FTP-User
<password> with FTP-Password
<hostname> with FTP-hostname (etc. example.com)
<WinSCP.com path> with path on your WinSCP-client (etc. C:\Program Files (x86)\WinSCP\WinSCP.com. Caution: WinSCP.com and not WinSCP.exe)
<FTP-path> with path on your FTP-client (etc. /httpdocs/wp-content/uploads)
Sub uploadImageByFTP(src As String)
Dim script As Object: Set script = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
'Not empty
If (src <> vbNullString) Then
'Execute script
script.Run _
"""<WinSCP.com path>"" " + _
"/ini=nul " + _
"/command " + _
"""open ftp://<username>:<password>#<hostname>/"" " + _
"""cd <FTP-path>"" " + _
"""put " & """""" & src & """""" & """ " + _
"""close"" " + _
"""exit""", windowStyle, waitOnReturn
End If
End Sub
WScript.Shell is more powerful than the default Shell(), as you can append a waitOnReturn-command; this tells VBA, that further execution isn't allowed before the file(s) have been uploaded to the FTP-server.
Change windowStyle to 0, if you don't like the command prompt to open on each execution.

Sublime Text Build For Executing Indesign .jsx Scripts on Windows

I'm trying to write a sublime text build to execute an indesign jsx script strait from sublime text on Windows. For the Mac there's a build by Basil https://github.com/basiljs/basil.js/tree/master/extras/Sublime%20Text that consists of a build and an osascript.
The build is:
// copy this file to ~/Library/Application Support/Sublime Text 2/Packages/User
{
"cmd": ["osascript", "$packages/Basiljs/run_idscript_6.0.scpt", "$file"]
}
The osascript is:
--usage:
--osascript run.scpt myscript.jsx
on run argv
set aScriptPath to "#include \"" & item 1 of argv & "\""
tell application "Adobe InDesign CS6"
do script aScriptPath language javascript
end tell
end run
I would like to do this with For Windows for my build I have done
{
"cmd": ["wscript", "$packages/creative-scripts/run_indesign.vbs", "$file"]
}
and for my wscript I have done
myScript = Wscript.Arguments.Item(0)
Set myInDesign = CreateObject("InDesign.Application")
MsgBox myScript ' just to check the path
Set myFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set myFile = myFileSystemObject.GetFile(myScript)
myInDesign.DoScript myFile, 1246973031
I was getting the following error message
Error: Object required: 'idScriptLanguage'
Code: 800A01A8
I have now edited the script putting in the change as per Vlad's answer and it work very well now.
Trevor
Replacing the idScriptLanguage.idJavascript with it's actual value (1246973031) will solve the problem.
I have come up with a solution with this sublime build :-)
{
// for script to run must have #target "InDesign-7.0" "InDesign" Ietc. in it :-( otherwise the script will just open in the estk
"cmd": ["C:\\Program Files (x86)\\Adobe\\Adobe ExtendScript Toolkit CC\\ExtendScript Toolkit.exe", "-run", "$file"]
}
Above is for a 64 bit system just remove the " (x86)" for a 32 bit one
Take note of the need for the #target
It will come up with a standard warning "Do you about to run .... Do you wish to run the script?"
So one needs to press y space or enter. Not too big a deal, but to suppress this one can put the script into the "Adobe Scripts" folder in Document then the warning won't come up.
See https://forums.adobe.com/message/4689581 and http://jfli04.blogspot.co.il/2011/08/how-to-run-js-in-estk-with-command-line.htm

How do I write to a text file using AppleScript?

So, that's it. How can I write to a text file using AppleScript?
I've tried googling around, but answers seem to be years old and I'm not really sure what should be the preferred idiom this days.
on write_to_file(this_data, target_file, append_data) -- (string, file path as string, boolean)
try
set the target_file to the target_file as text
set the open_target_file to ¬
open for access file target_file with write permission
if append_data is false then ¬
set eof of the open_target_file to 0
write this_data to the open_target_file starting at eof
close access the open_target_file
return true
on error
try
close access file target_file
end try
return false
end try
end write_to_file
Interfacing with it can be cleaned up with the following...
my WriteLog("Once upon a time in Silicon Valley...")
on WriteLog(the_text)
set this_story to the_text
set this_file to (((path to desktop folder) as text) & "MY STORY")
my write_to_file(this_story, this_file, true)
end WriteLog
A short version in pure AppleScript:
set myFile to open for access (choose file name) with write permission
write "hello world" to myFile
close access myFile
It seems there is no native one command solution. Instead you have to open and later close the file.
#JuanANavarro.
When using the shell you should use quoted form of for the TEXT and the file path.
This will help stop errors with spaces in file names and characters like apostrophes in the text for example.
set someText to "I've also learned that a quick hack, if one only wants to spit a bit of text to a file, is to use the shell."
set textFile to "/Users/USERNAME/Desktop/foo.txt"
do shell script "echo " & quoted form of someText & " > " & quoted form of textFile
The above script works fine.
If I did not have & quoted form of someText
but instead I had & someText I would get the following error.
error "sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file" number 2
The apostrophes in "I've" is seen as part of the command.
If I had
set textFile to "/Users/USERNAME/Desktop/some foo.txt" as my file path ( note the space.) And did not have & quoted form of textFile but instead I had & textFile
Then when the file was written out it would write to a file named "some" and not "some foo.txt"
I've also learned that a quick hack, if one only wants to spit a bit of text to a file, is to use the shell.
do shell script "echo TEXT > some_file.txt"
For me running do shell script was too slow on a PowerBook G4 when executed in a loop 300000 times ;), but of course that's quicker to write which sometimes makes sense. You would also want to escape shell characters like this:
do shell script "echo " & quoted form of foobar & " >> some_file.txt"
and for aesthetic reasons I would use
tell me to do shell script "#..."
but I haven't verified yet (what I believe) that if "do shell script" is in a block of "tell Finder" for example it is Finder process that creates a subshell. With "tell me to do shell script" at least Script Editor log looks better for me. ;)

Resources