When writing e.g. shell scripts, I want to change their permissions (primarily the executable permission) from within Sublime Text 2.
How can I accomplish that?
The following is a general purpose permissions editing command for the file currently being edited. For a more detailed explanation on plugins and editing the Sublime Text 2 menu, see this post.
It will add a Change Mode command in the Edit menu. When selected, the user is asked to enter a valid argument string to chmod (e.g. u+rwx
or 755
; default is the currently set 4 digit octal permissions string like 0644
), that is then applied to the file being edited.
Select Tools » New Plugin, insert the following content and save as chmod.py
in ~/Application Support/Sublime Text 2/Packages/User/
:
import sublime, sublime_plugin, subprocess
def chmod(v, e, permissions):
subprocess.call( [ "chmod", permissions, v.file_name() ] )
def stat(filename):
proc = subprocess.Popen( [ "stat", "-f", '%Mp%Lp', filename ], stdout=subprocess.PIPE )
return str(proc.communicate()[0]).strip()
class ChangeModeCommand(sublime_plugin.TextCommand):
def run(self, edit):
if sublime.platform() != 'osx':
return
fname = self.view.file_name()
if fname == None:
sublime.message_dialog("You need to save this buffer first!")
return
perms = stat(fname)
def done(permissions):
chmod(self.view, edit, permissions)
sublime.active_window().show_input_panel(
"permissions to apply to the file " + fname + ": ", perms, done, None, None)
To insert a menu item for this command, add the following to ~/Application Support/Sublime Text 2/Packages/User/Main.sublime-menu
, merging with existing file contents if the file already exists:
[
{
"id": "edit",
"children":
[
{"id": "wrap"},
{ "command": "change_mode" }
]
}
]
if sublime.platform() == 'windows':
will probably work as well.
It basically works under Linux too, but the stat
command works differently and shows numerous information that is not needed.
stat -c %a filename
will do instead and returns something like '644'.