Hayden Chambers
Hayden Chambers

Reputation: 747

open a file in sublime and show that it needs saving

I am making a sublime plugin that makes changes to files which may not be open

f = open(file_name, 'r+')
text = f.read()
lines = text.splitlines()
for i in reversed(range(len(lines))): #iterate backwards
    #modifications to final_text made here
    if not text == final_text:
        #open before change so user can see which files changed and possibly undo
        sublime.active_window().run_command('open_file', {'file': file_name}) 

        #make change
        f.seek(0)
        f.write(final_text)
        f.truncate()

This indeed opens the file and edits the content as desired. But the file doesn't appear to require saving. I can hit undo and the edit is undone as expected. But why doesn't it require saving?

EDIT: if anyone reads this, skuroda's answer below was correct and lead to the following code

newView = sublime.active_window().open_file(file_name);
'''
note: you cant just do this:
newView.run_command('select_all')
newView.run_command('cut')
newView.run_command('insert_text', {'string': final_text})
because the file takes time to open, use a timeout instead...
'''
sublime.set_timeout(lambda: write_to_file(newView, final_text), 10)

and the timeout function like this

def write_to_file(newView, final_text):
    if not newView.is_loading():
        newView.run_command('select_all')
        newView.run_command('cut')
        newView.run_command('insert_text', {'string': final_text})
    else:
        sublime.set_timeout(lambda: write_to_file(newView, final_text), 10)

Upvotes: 0

Views: 561

Answers (1)

skuroda
skuroda

Reputation: 19744

You are writing to the file directly not within the context of ST. Note that in the above posted code, the only ST dependent code you have is opening the file. You are not using view#erase, view#insert, view#replace etc. As further demonstration of this, remove the open file from your plugin. The content of the file will still be updated, even though it's not "open" in the editor.

Upvotes: 1

Related Questions