Sublime Text: Add the ability to get a file’s relative project path to the Command Palette

Often enough when I’m debugging an issue that doesn’t occur the same in the staging or production environment as it does on a development or local environment, like most developers I add debug statements on those environments to catch/view output from various function calls.

Navigating the files in a complex project eats up significant time; since you’ve likely got the file that needs debug statements sitting open locally in Sublime Text, here’s a little Command Palette addition to copy the relative path (to project root) of the current file to your clipboard:

Step #1: Create the Plugin

  1. In Sublime Text, go to ToolsDeveloper > New Plugin…
  2. Replace the default code with the contents as shown below.
  3. Save the plugin with a name like copy_relative_path.py in your Packages/User directory.
import sublime
import sublime_plugin
import os

class CopyRelativeFilePathCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        window = self.view.window()
        file_path = self.view.file_name()
        project_data = window.project_data()

        if not file_path or not project_data:
            sublime.status_message("No file or project data available.")
            return

        folders = window.folders()
        for folder in folders:
            if file_path.startswith(folder):
                relative_path = os.path.relpath(file_path, folder)
                sublime.set_clipboard(relative_path)
                sublime.status_message(f"Copied: {relative_path}")
                return

        sublime.status_message("File not in project folder.")

Step #2: Add Plugin to Command Palette

  1. Open your User package folder In Sublime Text, go to PreferencesBrowse Packages… and open the User folder.
  2. Create a new file named copy_relative_path.sublime-commandswith the contents as shown below.
    • "caption" is what will appear in the Command Palette.
    • "command" must match the name of the command class you defined in your plugin (copy_relative_file_path).
  3. Save the file and restart Sublime Text (or just use the Command Palette).
[
  {
    "caption": "Copy Relative File Path to Project Root",
    "command": "copy_relative_file_path"
  }
]

Leave a Reply

Your email address will not be published. Required fields are marked *