Sublime Forum

Make file "view" only

#1

When you open key bindings; it opens two files, one you can edit and the other you can’t edit. You can just browse around. Is there any way to make that functionality for a regular file. So you could toggle “edit” and “browse” modes when you want.

0 Likes

#2

Just run view.set_read_only(True) in the console. Or create a simple plugin for it so you can have a keybinding.

2 Likes

#3

Thanks, this is working. But how to create a plug-in for it?

0 Likes

#4

https://www.sublimetext.com/docs/api_reference.html

But I am pretty sure @OdatNurd’s video on YouTube is more suitable for newbies. Though I am not sure which video exactly since I didn’t watch it.

You basically have to create a sublime_plugin.TextCommand and add a keybinding to the command (toggle_read_only).

from typing import Any, Dict, Optional
import sublime
import sublime_plugin

STATUS_KEY = __file__


def update_status_bar(view: sublime.View) -> None:
    if view.is_read_only():
        view.set_status(STATUS_KEY, "🔒")
    else:
        view.erase_status(STATUS_KEY)


class ToggleReadOnlyCommand(sublime_plugin.TextCommand):
    def run(self, edit: sublime.Edit, *, value: Any = None) -> None:
        if value is None:
            self.view.set_read_only(not self.view.is_read_only())
        else:
            self.view.set_read_only(bool(value))


class ReadOnlyStatusListener(sublime_plugin.ViewEventListener):
    def on_activated(self) -> None:
        update_status_bar(self.view)

    def on_post_text_command(self, command_name: str, args: Optional[Dict[str, Any]]) -> None:
        # why "revert" command makes the view read-only for a moment?
        if command_name not in {"revert"}:
            update_status_bar(self.view)

I am not sure why the revert command makes the view readonly for a moment though.

1 Like

#5

Thanks xD
I found the package “Toggle the View Read-Only”. I didn’t type “view” when I was searching for this kind of package.

0 Likes

#6

Just FYI, this package doesn’t use view settings but rather modifies file permissions

0 Likes

#7

It does what I asked xD

0 Likes