Sublime Forum

open_file + set_syntax_file

#1

Hi, I can’t figure out what is wrong, please help me (OS: Windows, Sublime Text 3 Build 3059)

I wrote simple plugin:

class OpenHostsFileCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view.window().open_file('c:/windows/system32/drivers/etc/hosts')
        view.set_syntax_file('Packages/INI/INI.tmLanguage')

Menu item:

            ...
            {
                "caption": "Open System Hosts File",
                "command": "open_hosts_file"
            }
            ...

In this case file is opening but function set_syntax_file does not do anything.
Opened file still has default syntax (Plain Text).

0 Likes

#2

You need to wait until the view is finished loading. Something along these lines:

    def run(self, edit):
        view = self.view.window().open_file('/private/etc/hosts')
        def set_syntax():
            if view.is_loading():
                sublime.set_timeout_async(set_syntax, 0.1)
            else:
                view.set_syntax_file('Packages/INI/INI.tmLanguage')
        set_syntax()
1 Like

#3

Try first with view.settings().set(‘syntax’, ‘path to syntax file’), before going to the is_loading loop

0 Likes

#4

Thank you!

Set syntax via settings not working,
I think you can call view.settings().get(‘syntax’) but not view.settings().set(‘syntax’, ‘…’).

Now I know that I need to wait until view is loaded.
So I found another solution rather then going to the is_loading loop:

[code]class OpenHostsFileCommand(sublime_plugin.TextCommand, sublime_plugin.EventListener):
__path = None

def __init__(self, view = None):
    self.view = view;

    if sublime.platform() == 'windows':
        self.__path = 'c:\\windows\\system32\\drivers\\etc\\hosts'
    else:
        self.__path = '\\etc\\hosts'


def run(self, edit):
    self.view.window().open_file(self.__path)

def on_load(self, view):
    if view.file_name().lower() == self.__path:
        view.set_syntax_file('Packages/INI/INI.tmLanguage')

[/code]

0 Likes