The provided script is a good starting point for running Laravel Pint on save in Sublime Text 4. However, there are a few improvements and clarifications that can be made to ensure it works correctly.
Firstly, the script uses AppleScript to send commands to iTerm, which is macOS-specific. This means it won't work on other operating systems. Additionally, the script hardcodes the project directory, which is not ideal if you work with multiple Laravel projects.
Here's an improved version of the script that uses the built-in terminal and dynamically determines the project root directory by looking for the artisan file, which is unique to Laravel projects:
import sublime
import sublime_plugin
import subprocess
import os
class LaravelPintOnSaveCommand(sublime_plugin.EventListener):
def on_post_save(self, view):
file_name = view.file_name()
# Check if it's a PHP file
if file_name.endswith('.php'):
# Find the Laravel project root by looking for the artisan file
directory = self.find_project_root(file_name)
if directory:
# Run Pint from the project root
command = f'cd "{directory}" && ./vendor/bin/pint "{file_name}"'
subprocess.run(command, shell=True, check=True)
def find_project_root(self, file_path):
# Start with the directory of the current file
current_dir = os.path.dirname(file_path)
# Traverse up the directory tree to find the Laravel project root
while current_dir != os.path.dirname(current_dir): # Stop at the root directory
if os.path.isfile(os.path.join(current_dir, 'artisan')):
# Found the Laravel project root
return current_dir
else:
# Move up one directory
current_dir = os.path.dirname(current_dir)
# Laravel project root not found
return None
To use this script:
-
Save the script as
pint.pyin your Sublime Text packages directory. You can find this directory by going toSublime Text > Preferences > Browse Packages...in the menu. -
Ensure that Laravel Pint is installed in your Laravel project by running
composer require laravel/pint --devif you haven't already. -
Now, every time you save a
.phpfile, the script will attempt to find the Laravel project root by looking for theartisanfile. If it finds the project root, it will run Pint on the saved file.
Remember that this script assumes you have PHP and Laravel Pint installed and available in your system's PATH. If you have a different setup, you may need to adjust the command accordingly.