Created
March 21, 2023 13:05
-
-
Save pcrockett/dc52c79106eae884399718a4f93b605f to your computer and use it in GitHub Desktop.
Example of a very basic "new file" command you can add to your Sublime config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sublime | |
import sublime_plugin | |
from typing import Optional | |
# Place this file in your Users directory, right next to your user | |
# preferences file. | |
# | |
# To add this command to your command palette, just add the following | |
# to Default.sublime-commands: | |
# | |
# [ | |
# { | |
# "caption": "Phil: New File", | |
# "command": "phil_new_file", | |
# } | |
# ] | |
# | |
# Much credit goes to the AdvancedNewFile plugin, which helped me | |
# figure out how I want **MY** new file command to work. | |
# | |
class PhilNewFileCommand(sublime_plugin.WindowCommand): | |
def __init__(self, window): | |
super().__init__(window) | |
def run(self): | |
self.window.show_input_panel( | |
"Enter new file path:", | |
self._get_initial_path(), | |
self._on_done, | |
self._on_change, | |
self._on_cancel, | |
) | |
def _on_done(self, path: str): | |
if os.path.exists(path): | |
self._open_existing(path) | |
return | |
directory, filename = os.path.split(path) | |
try: | |
if not os.path.exists(directory): | |
os.makedirs(directory) | |
if filename != "": | |
open(path, "a").close() | |
self.window.open_file(path) | |
except OSError as e: | |
self._show_message(str(e)) | |
def _on_change(self, input: str): | |
pass | |
def _on_cancel(self): | |
pass | |
def _show_message(self, message: str): | |
PANEL_NAME = "phil_message" | |
view = self.window.create_output_panel(PANEL_NAME) | |
self.window.run_command( | |
"show_panel", | |
{"panel": f"output.{PANEL_NAME}"} | |
) | |
view.run_command( | |
"append", | |
{ | |
"characters": message, | |
"force": True, | |
"scroll_to_end": True | |
} | |
) | |
def _get_initial_path(self): | |
view = self.window.active_view() | |
if view is not None: | |
path = view.file_name() | |
if path is None: | |
return self._default_path() | |
else: | |
return path | |
folders = self.window.folders() | |
if len(folders) == 0: | |
return self._default_path() | |
else: | |
return folders[0] + "/" | |
def _default_path(self) -> str: | |
home = os.environ.get("HOME") | |
if home is None: | |
return "/" | |
else: | |
return home + "/" | |
def _open_existing(self, path: str) -> Optional[sublime.View]: | |
if os.path.isdir(path): | |
self._show_message( | |
f"{path} already exists, and it's a directory!" | |
) | |
return None | |
else: | |
return self.window.open_file(path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment