Renae Lider
Renae Lider

Reputation: 1024

How to make a buffer have a read-only in Sublime Text 2

This is not about those files that have their read-only flag set at the OS level, but about every file that users don't intend to modify.

I want Sublime Text to ignore any changes and prevent saving anything to such files. One example for this scenario is when the user is reading source code that shouldn't be altered in anyway.

"Just be really careful, and don't press any buttons" is undoubtedly a good advice, but if I were to "accidentally" delete that octothorpe in front of a comment, or add new lines to a file that is sensitive to such things (some config files in Linux) and then accidently hit save....

I found "toggle-readonly" at GitHub, but it is actually toggling the file permissions ("Read Only", "Write"), which is not quite what I wanted.

Upvotes: 14

Views: 3929

Answers (2)

Franklin Yu
Franklin Yu

Reputation: 9958

The plugin "Toggle the View Read-Only" will do it. It basically does what MattDMo said: when you set the view as read-only, the file can still be changed by another program (or another user), and Sublime Text will pick up those changes. It also has the context menu item you asked for. I like the "Readonly" indicator in status bar.

I didn't test it on Sublime Text 2, but in Sublime Text 3 it works great, and it claims to work on Sublime Text 2 as well.

Upvotes: 2

MattDMo
MattDMo

Reputation: 102892

Yes, this is possible, but you'll have to write a plugin (which actually isn't that hard, especially if you know Python). The API call is view.set_read_only(flag) in the sublime module, where Flag is a boolean. Here's a quick example which checks if a newly-opened file has a certain suffix, and if so sets it to read-only.

import sublime
import sublime_plugin


class MakeViewReadOnlyCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        if self.view.file_name().endswith(".cfg"):
            self.view.set_read_only(True)


class ConfigFileListener(sublime_plugin.EventListener):
    def on_load(self, view):
        view.run_command("make_view_read_only")

Open a new file with Python syntax, copy the code into it, alter it as needed, then save it in your Packages/User directory as make_view_read_only.py. Restart Sublime to load it, and you should be all set. To test if a certain view is read-only, open the console and enter

view.is_read_only()

Upvotes: 9

Related Questions