iTerm2: Open Text File Paths in Sublime Text with Jump to Line Number
I was able to find & modify a wrapper script for iTerm2 for adding support similar to the "Open with default app
" behavior, while opening any text file found in Sublime Text.
This allows you to:
- Open text files in Sublime Text mentioned in a terminal session with format:
/path/to/file:lineno:colno
-
lineno
- Optional line number to Jump to when opening file -
colno
- Optional column number to Jump to when opening file
-
- Open URLs, and other files with the default application for handling those files (Just like default iTerm2 behavior)
To use:
- Save the following source code into a file called
iterm_open_with
somewhere in your shell's$PATH
( I recommend:${HOME}/bin/iterm_open_with
) -
Follow the instructions here to set that script as a "
⌘
+Click
" "Run Command
" underPreferences
( ⌘ + , )
>Profiles
>Advanced
>Semantic History
:/Users/your_username_here/bin/iterm_open_with \5 \1 \2
#!/bin/sh
# iterm_open_with - open a URL, file from CWD, full path, or path with linenumber in default app or Sublime Text if text file
# For usage with iTerm2:
# In iTerm's Preferences > Profiles > Default > Advanced > Semantic History,
# choose "Run command..." and enter "/your/path/to/iterm_open_with \5 \1 \2".
# Usage: iterm_open_with $(pwd) filename [linenumber]
# $(pwd) = current working directory (either use `pwd` or $PWD)
# filename = filename to open
# lineno = line number
pwd=$1
file=$2
regex='https?://([a-z0-9A-Z]+(:[a-zA-Z0-9]+)?@)?[-a-z0-9A-Z\-]+(\.[-a-z0-9A-Z\-]+)*((:[0-9]+)?)(/[a-zA-Z0-9;:/\.\-_+%~?&@=#\(\)]*)?'
perl -e "if ( \"$file\" =~ m|$regex|) { exit 0 } else { exit 1 }"
if [ $? -ne 0 ]; then
# if it's not a url, try splitting by ':'
arr=($(echo $2 | tr ':' "\n"))
file=${arr[0]}
lineno=${arr[1]:-$3}
colno=${arr[2]:-${3##*:}}
[ -e "$file" ] || file=${pwd}/${file}
fi
file "$file" | grep -q "text"
if [ $? -ne 0 ]; then
/usr/bin/open $file
else
/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl ${file}${lineno:+:${lineno}}${colno:+:${colno}}
fi
I've also kept URL detection intact, and added the ability to open any relative file path with Command+Click
(⌘
+ Left mouse button
). Line and column numbers now work too!
Written by James Cuzella
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Osx
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#