Shortcut to open the currently opened file's folder left panel - sublimetext2

I know the "File > Open folder..." dialog box in Sublime.
The problem is that:
it first opens a "file picker" dialog box
after choosing the right folder, it opens the folder in a new Sublime Text window, instead of the current window
How to open the current file's folder in the left "Folder view" of the current Sublime window, without any popup? (I would like to bind a keyboard shortcut for this). Note: I still use Sublime 2.

The menu item Project > Add Folder to project... will prompt you for the name of a folder and then add it to the current window rather than create a new one. Contrary to the name, this will always work even if you're not explicitly using sublime-project files directly.
For doing this without any sort of prompt, a plugin would be needed to adjust the list of folders that are open in the window currently.
In Sublime Text 3 and above, there is API support for directly modifying the list of folders that are open in the window, while Sublime Text 2 only has an API for querying the list of folders.
All versions of Sublime have a command line helper that can be used to interact with the running copy of Sublime (generally referred to as subl), and one of the things it can do is augment the list of folders in the window by adding an additional one. In Sublime Text 2, the subl helper is just the main Sublime Text executable itself.
The following is a plugin that can be used in Sublime Text 2 and above that will perform the appropriate action to get the path of the current file to open in the side bar. If you're unsure of how to use plugins, see this video on how to install them.
import sublime
import sublime_plugin
import os
# This needs to point to the "sublime_text" executable for your platform; if
# you have the location for this in your PATH, this can just be the name of the
# executable; otherwise it needs to be a fully qualified path to the
# executable.
_subl_path = "/home/tmartin/local/sublime_text_2_2221/sublime_text"
def run_subl(path):
"""
Run the configured Sublime Text executable, asking it to add the path that
is provided to the side bar of the current window.
This is only needed for Sublime Text 2; newer versions of Sublime Text have
an enhanced API that can adjust the project contents directly.
"""
import subprocess
# Hide the console window on Windows; otherwise it will flash a window
# while the task runs.
startupinfo = None
if os.name == "nt":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.Popen([_subl_path, "-a", path], startupinfo=startupinfo)
class AddFileFolderToSideBarCommand(sublime_plugin.WindowCommand):
"""
This command will add the path of the currently focused file in the window
to the side bar; the command will disable itself if the current file does
not have a name on disk, or if it's path is already open in the side bar.
"""
def run(self):
# Get the path to the current file and add it to the window
self.add_path(self.get_current_path())
def is_enabled(self):
"""
The command should only be enabled if the current file has a filename
on disk, and the path to that file isn't already in the list of folders
that are open in this window.
"""
path = self.get_current_path()
return path is not None and path not in self.window.folders()
def get_current_path(self):
"""
Gather the path of the file that is currently focused in the window;
will return None if the current file doesn't have a name on disk yet.
"""
if self.window.active_view().file_name() is not None:
return os.path.dirname(self.window.active_view().file_name())
return None
def add_path(self, path):
"""
Add the provided path to the side bar of this window; if this is a
version of Sublime Text 3 or beyond, this will directly adjust the
contents of the project data to include the path. On Sublime Text 2 it
is required to execute the Sublime executable to ask it to adjust the
window's folder list.
"""
if int(sublime.version()) >= 3000:
# Get the project data out of the window, and then the list of
# folders out of the project data; either could be missing if this
# is the first project data/folders in this window.
project_data = self.window.project_data() or {}
folders = project_data.get("folders", [])
# Add in a folder entry for the current file path and update the
# project information in the window; this will also update the
# project file on disk, if there is one.
folders.append({"path": path})
project_data["folders"] = folders
self.window.set_project_data(project_data)
else:
# Run the Sublime executable and ask it to add this file.
run_subl(path)
This will define a command named add_file_folder_to_side_bar which will add the path of the current file to the side bar; the command disables itself if the current file doesn't have a name on disk, or if that path is already open in the side bar.
If you're using Sublime Text 2, note that you need to adjust the variable at the top to point to where your copy of Sublime is installed (including the name of the program itself, as seen in the example code), since the plugin will need to be able to invoke it to adjust the side bar.
In order to trigger the command, you can use a key binding such as:
{ "keys": ["ctrl+alt+a"], "command": "add_file_folder_to_side_bar"},
You can also create a file named Context.sublime-menu in your User package (the same place where you put the plugin) with the following contents to have a context menu item for this as well:
[
{ "caption": "-", "id": "file" },
{ "command": "add_file_folder_to_side_bar", "caption": "Add Folder to Side Bar",}
]

Solved for ST2 with #OdatNurd's idea:
class OpenthisfolderCommand(sublime_plugin.TextCommand):
def run(self, edit):
current_dir = os.path.dirname(self.view.file_name())
subprocess.Popen('"%s" -a "%s"' % ("c:\path\to\sublime_text.exe", current_dir))
Add the key binding with for example:
{ "keys": ["ctrl+shift+o"], "command": "openthisfolder"}

Related

Is there a shortcut for Sublime Text to find an open file (Eclipse Ctrl + E)?

Ctrl+P of Sublime Text lets me find a file from all project files.
However, there are too many duplicated names. I’m looking for a shortcut key like Ctrl+E in Eclipse, so that I just need to find the file in my opened file. That would save a lot of key striking. Probably called “sidebar filter”?
Does not matter if it’s 2 or 3.
Sounds easy to implement just select Tools >> Developer >> New Plugin... and add the content:
import sublime_plugin
import os
def _show_name(name):
return ([os.path.basename(name), name] if name
else ["untitled", "untitled"])
class ShowBuffersCommand(sublime_plugin.WindowCommand):
def run(self):
window = self.window
views = list(window.views())
show_entries = [_show_name(v.file_name()) for v in views]
def on_done(index):
if index == -1:
return
window.focus_view(views[index])
window.show_quick_panel(show_entries, on_done)
Afterwards save it into your Package/User folder and add this (or an other keybinding) to your keymap:
{
"keys": ["ctrl+e"],
"command": "show_buffers"
},
(Tested on ST3)
Option One, Go to the "View" menu and choose "Side Bar", then "Show Open Files"
Option Two, There is a small plugin here https://github.com/rrg/ListOpenFiles
There is in Sublime Text a useful function called Goto Anything. You can access this by pressing Ctrl + P in Windows, and then you can search through any file located in a current project (to open a project, enable the sidebar, and drag and drop a folder from the explorer to the sidebar).

How to negate 'remove all folders' mistake in Sublime Text project

In Sublime Text (2 & 3) I find I accidentally remove all folders from the project when I don't want to (this option is poorly placed in the menu, with no obvious undo or warning and is arguably similar to a 'clear' button on a form).
I often have many folders open in a project each one a leaf in the folder tree structure, which is my workflow, so naturally this is a nasty break in my work if it's accidentally triggered!
I would like to know if I can either disable this option or undo it if I accidentally trigger it?
Aside from a backup, a version control system, or a versioning feature on your file system, there is unfortunately no way of undoing the "Remove all Folders from Project" command, because as soon as the command is fired the folders are removed from the .sublime-project file, and the file is saved. However, there is a way to disable the command. The methods vary between Sublime Text 2 and 3, so I'll go over 2 first.
In Sublime Text 2, click on Preferences -> Browse Packages... to open the Packages folder, whose location varies by operating system. Go into the Default folder, and open Main.sublime-menu in Sublime (it's a JSON file). Search for "close_folder_list" and find the line that looks like this (it's line 737 in version 2.0.2):
{ "command": "close_folder_list", "caption": "Remove all Folders from Project", "mnemonic": "m" },
Now, you can either simply delete the entire line, or comment it out by putting // as the first characters on the line. Save the file, then click on the Project menu to see that the option is gone.
If you're using Sublime Text 3, you'll need a workaround to access the Packages/Default folder and its contents, as in this version most of the packages that you would normally have seen in the Packages directory in ST2 are zipped into .sublime-package files and stored elsewhere. However, there's a plugin for that! Make sure you have Package Control installed, then open the Command Palette, type pci to bring up Package Control: Install Package, and search for PackageResourceViewer. Install it, open the Command Palette again, type prv, and select PackageResourceViewer: Edit Package Resource. Scroll down to Default, click on it or hit Enter, then scroll down to Main.sublime-menu and select it to open it for editing. You can now follow the instructions above to find the line containing "close_folder_list" (it should be line 795) and either delete it or comment it out.
If you'd like to keep the menu item, but move it to a different spot, you can do that as well. For example, if you'd like it at the very bottom of the menu, separated by a divider, delete the original line, put the cursor below the "refresh_folder_list" line, and paste in the following:
{ "caption": "-" },
{ "command": "close_folder_list", "caption": "Remove all Folders from Project", "mnemonic": "m" },
so it looks like this:

Sublime Text Prompt to Save File

I often will have a scratch pad in ST that I then close via Ctrl-F4. It always prompts me to save it, which I find to be a pain.
Is there a setting in ST where I can either change to default of this dialog to "Close without saving", or do not even prompt me at all if it is a new file (i.e. has no name).
You can set a tab to be a scratch buffer (doesn't prompt to save when closed). With the desired tab opened, open the console with Ctrl` and type:
view.set_scratch(True)
then hit Enter, and close the console with Esc. You can now close the tab whenever you want without being prompted. Of course, you can manually save the contents if you wish.
If you would like to have all new buffers set to scratch by default, you'll need a plugin. Create a new Python file in Sublime with the following contents:
import sublime
import sublime_plugin
class SetNewScratchBuffer(sublime_plugin.EventListener):
def on_new(self, view):
view.set_scratch(True)
def on_save(self, view):
view.set_scratch(False)
Save the file as Packages/User/set_new_scratch_buffer.py where Packages is the folder opened when selecting Preferences -> Browse Packages... (~/.config/sublime-text-2/Packages on Linux with ST2). Once saved, it should automatically become active, although you can restart Sublime to make sure. Now, all new buffers created with CtrlN or File -> New File will automatically have the scratch attribute set. This will be disabled when the file is saved, so you don't accidentally destroy changes to an opened file.

Sublime Text Default Save Options

Why when I save a file in Sublime Text 3 is the default save location the Sublime install directory and why is the default file type nothing?
I want to set the default save location to the Desktop and the default file type to .txt, how can I do this?
Here are my settings:
{
"font_size": 9,
"hot_exit": false,
"ignored_packages": ["Vintage"],
"remember_open_files": false
}
Without no line of code:
Preferences -> Settings -> paste this "default_dir": "your/favorite/path"
And you are done.
More here: https://sublime-text-unofficial-documentation.readthedocs.io/en/latest/reference/settings.html#file-and-directory-settings
Doesn't (currently) address the default extension issue, but you can also try AdvancedNewFile. Rather than creating an unnamed buffer, this plugin creates a named file. The default location is configurable, though there is no default extension.
Disclaimer: I'm the maintainer of the AdvancedNewFile plugin.
Edit
I've updated AdvancedNewFile to support default file extensions.
You can install the Default File Type plugin manually. It's a very simple plugin, and while the Package Control page says that it's for Sublime Text 2 only, I just installed it under OSX and it works fine. To install, navigate to %APPDATA%\Sublime Text 3\Packages and run
git clone https://github.com/spadgos/sublime-DefaultFileType.git DefaultFileType
Then, copy Packages\DefaultFileType\default_file_type.sublime-settings to Packages\User and change its contents to the following:
{
"default_new_file_syntax": "Packages/Text/Plain text.tmLanguage",
"use_current_file_syntax": false
}
Save the file, and now whenever you hit CtrlN to create a new file, it will be set to plain text. The plugin only works with the key combo, not via the File -> New File menu option.
As far as the save location goes, I have a theory, but I haven't been able to find documentation to back it up. At least on Win7 (for me), it seems like the default save location is the directory which contains the file that was open when you hit CtrlN or File -> New File to create the new file. For example, I had my Packages\User\Preferences.sublime-settings file open when I created a new file, and hitting CtrlS opened the Save dialog in Packages\User. I saved the file to the Desktop, hit CtrlN for a new file, entered something, then hit CtrlS and the Save dialog opened in the Desktop.
So, while there isn't a preferences setting for default save location, at least on Windows you can tweak it by always keeping a Desktop file open, then creating new files while that Desktop file is focused.
This should be a built-in option, honestly, but it seems fairly simple to automate yourself. Hit Tools -> New Plugin
Then paste this over the file that's created, hit save and call it "DefaultLanguage.py" or something:
import sublime, sublime_plugin
class EverythingIsPowerShell(sublime_plugin.EventListener):
def on_new(self, view):
view.set_syntax_file('Packages/PowerShell/Support/PowershellSyntax.tmLanguage')
Of course, you can change the language from PowerShell to ... whatever you prefer. You just need the relative path to the tmLanguage. You can get that by opening a file in your favorite language and then open the console (View->Show Console) and type:
view.settings().get('syntax')

start opened file from sublimetext in associated program

i usually edit files in sublime text 2 that can also be edited and compiled with another program. As i have them already opened in sublimetext i do the following:
right click and choose "copy file path" (to clipboard)
Win+R to open windows run dialog
CTRL+V to paste the file path
hit enter to open the file with the associated program
i wonder some shortcut can be configured so it automatically starts the opened file with its associate program
thanks in advance
This can be done. I was in a very similar situation using Sublime as my editor of choice over the default SAS program editor. I was able to use the win32com.client.dynamic.Dispatch module to connect to SAS via OLE and pass text from Sublime directly to SAS using Sublime's build system to call my plugin. Making the connection was the easy part, it was the other processing that I had to do which was the time consuming part, but since you want to pass just a file name or the entire contents of your file, this should be a fairly straightforward plugin. Since I do not know what program you wish to open, here is the code that makes my implementation work. Maybe you caan glean something out of this.
def send_to_sas_via_ole(selected_code):
from win32com.client.dynamic import Dispatch
sasinstance = Dispatch("SAS.Application")
# submit the lines to sas
for selection in selected_code:
# for some reason cannot send as one big line to SAS, so split into
# multipe lines and send line by line
for line in selection.splitlines():
sasinstance.Submit(line)
and then the call in the run method of my plugin class:
class RunSasMakoCommand(sublime_plugin.TextCommand):
def run(self, edit):
try:
send_to_sas_via_ole(selected_code)
except Exception as e:
print "\n".join(selected_code)
print "Couldn't connect to SAS OLE"
print e
Good luck!
Open 'regedit.exe';
Navigate to
HKEY_CLASSES_ROOT\Applications\sublime_text.exe\shell\open\command
correct the path. Exit 'regedit.exe'
(optional) restart 'explorer.exe' or reboot your PC.
enjoy :p;
Right click on the file, press "Properties". You will see Opens with SomeProgram and then a change button. Click on the change button, and then look through the list for Sublime Text, if you can't find it, you can choose an application using the file explorer, from there you can navigate to C:\Program Files\Sublime Text 2 and choose sublime_text.exe