Sublime Forum

New File from Sidebar Context Menu

#1

So when I select New Folder from the right click context menu for the side bar in ST3 I get prompted for the name of the folder before the folder is created.

However, if I select new file from the same context menu it just creates the file and I have to save the file to set the file name.

Is it possible to force ST3 to prompt me for the file name just as it does for the folder name when I create from the context menu?

I don’t know about anyone else but I find this super annoying and inconsistent behaviour.

0 Likes

#2

Natively the command that is triggered when you select that command from the side bar menu creates a new file tab and sets an appropriate default directory for it so that when you save the dialog will default to the location you selected.

The source for that command is available in the Default package as Default/side_bar.py but it doesn’t support any option that would cause it to prompt you.

On the other hand this is easily solvable via a plugin, such as by selecting Tools > Developer > New Plugin... from the menu and replacing the stub code displayed with this code, then saving in the default location as a py file:

import sublime
import sublime_plugin

import os
import functools


class EnhancedNewFileAtCommand(sublime_plugin.WindowCommand):
    def run(self, dirs):
        self.window.show_input_panel("File Name:", "", 
            functools.partial(self.on_done, dirs[0]), None, None)

    def on_done(self, dir_name, file_name):
        view = self.window.new_file()
        view.retarget(os.path.join(dir_name, file_name))
        view.run_command("save")


class NewFileEventListener(sublime_plugin.EventListener):
    def on_window_command(self, window, cmd, args):
        if cmd == "new_file_at":
            return ("enhanced_new_file_at", args)

This implements a new enhanced_new_file_at command that takes the same arguments as the standard new_file_at command, but instead of creating a new tab and setting a default folder, it directly assigns the appropriate path to the file and then tells it to save itself, which will create the file directly.

The provided EventListener will redirect all invocations of the new_file_at command to the new command, so anything that uses the old command (including the side bar context menu) will use the new command and prompt you for a file name.

That said, you probably want the FileManager package for this; amongst it’s many features is a new side bar command menu option named New... that allows you to create folders and files alike in a single command, including being able to create all of the needed intermediate folders automatically.

1 Like

#3

This is incredibly helpful, my sincere thanks.

0 Likes