Skip to content

Instantly share code, notes, and snippets.

@cskeeters
Created March 23, 2023 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cskeeters/81e8b7f82add423bb2b5b58e2140028e to your computer and use it in GitHub Desktop.
Save cskeeters/81e8b7f82add423bb2b5b58e2140028e to your computer and use it in GitHub Desktop.
# This script allows a users to open files from finder in vim inside of iTerm
#
# If vim is already running in iTerm, this script won't open the file from within
# vim. The script is not that smart.
#
# This script will work in three different scenarios:
# 1. iTerm is not running at all. In this case, when iTerm is launched, a new
# window is created, but only after a second. This window won't have
# anything running in it, so we can start vim in that window without
# creating a new tab first.
# 2. iTerm is running, but there are no open windows. In this case,
# a new window must be created and vim will be started in that window.
# 3. iTerm is running and there is at least one window open. In this case,
# a new tab will be opened in the last active window and vim loaded there.
#
# The app that contains this script can also be run from spotlight/alfred
# directly and it will open vim in a folder of your choosing
on run {input, parameters}
try
set filePath to POSIX path of input
on error
set filePath to "~/working"
end try
set quotedFilePath to quote & filePath & quote
# path to neovim from brew
set vimPath to "/opt/homebrew/bin/nvim"
# This will change directory to the one where the file is located
set cdCmd to "cd \"$(dirname " & quotedFilePath & ")\""
set vimCmd to vimPath & " " & quotedFilePath
# Determine if iTerm is running, only at the start of the script
set isRunning to false
if application "iTerm" is running then
set isRunning to true
end if
tell application "iTerm"
activate
if not isRunning then
# activate will return before the window has had a chance to open.
# Give iTerm time to open the window before we try to manipulate it.
# If this delay is too short, a second window will open.
delay 1
end if
try
# If iTerm was running with no windows open tell current window will error
tell current window
if isRunning then
create tab with default profile
end if
tell current session
write text cdCmd
write text vimCmd
end tell
end tell
on error
# iTerm was running but all of the windows had been closed
create window with default profile
tell current window
tell current session
write text cdCmd
write text vimCmd
end tell
end tell
end try
end tell
end run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment