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?

wonea
  • 1,877
Daniel Beck
  • 111,893

2 Answers2

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" }
        ]
    }
]
Daniel Beck
  • 111,893
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'.