4

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?

2 Answers 2

7

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.

Screenshot of input panel

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" }
        ]
    }
]
2
  • Is it necessary to restrict to OSX, or could that condition be loosened up to include linux, or even changed to "not windows" ? Aug 20, 2012 at 19:09
  • @DarthAndroid I don't have a GUI Linux at the moment to test it with, so I went most restrictive in both code and question tags. Other than that, I see no reason to exclude Linux. if sublime.platform() == 'windows': will probably work as well.
    – Daniel Beck
    Aug 20, 2012 at 19:12
3

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'.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .