Skip to content

Instantly share code, notes, and snippets.

@awforsythe
Created June 3, 2015 01:10
Show Gist options
  • Save awforsythe/8da842bdc2f56c058ccd to your computer and use it in GitHub Desktop.
Save awforsythe/8da842bdc2f56c058ccd to your computer and use it in GitHub Desktop.
"""
switch_file_from_project.py
Place in any folder under %APPDATA%\Sublime Text 3\Packages, then add a
line to User Keybindings like so:
{ "keys": ["alt+o"], "command": "switch_file_from_project" }
A quick-and-dirty command for Sublime Text 3. Based on the built-in command
switch_project, but rather than looking for a file in the current file's
directory, this version searches recursively through all folders in the
project. Only supports switching between .h and .cpp, unlike
switch_project which supports multiple extensions.
"""
import sublime, sublime_plugin
import os
import platform
def compare_file_names(x, y):
if platform.system() == 'Windows' or platform.system() == 'Darwin':
return x.lower() == y.lower()
else:
return x == y
class SwitchFileFromProjectCommand(sublime_plugin.WindowCommand):
def run(self, extensions=[]):
if not self.window.active_view():
return
current_filepath = self.window.active_view().file_name()
if not current_filepath:
return
current_filename = os.path.basename(current_filepath)
search_filename = None
if current_filepath.lower().endswith('.h'):
search_filename = current_filename[:-2] + '.cpp'
elif current_filepath.lower().endswith('.cpp'):
search_filename = current_filename[:-4] + '.h'
if not search_filename:
return
if not self.window.project_data() or 'folders' not in self.window.project_data():
return
for search_directory in [folder['path'] for folder in self.window.project_data()['folders']]:
for root, dirs, files in os.walk(search_directory):
for candidate_filename in files:
if compare_file_names(search_filename, candidate_filename):
self.window.open_file(os.path.join(root, candidate_filename))
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment