Sublime Forum

Open Multiple Files and Replace Contents

#1

I have a dictionary with a value of an array of dictionaries:

{"changes"{"filename":"/users/johnsmith/test.txt","buffer":"123"},{"filename":"/users/johnsmith/anothertest.txt","buffer":"456"}]}

In my plugin I would like to open the files specified and replace the contents of it with the buffer value.

I have something like this

def _process_rename(self, edit):
        data = self.data
        for item in data'Changes']:
            filename = item'FileName']
            text = item'Buffer']
            view = sublime.active_window().open_file(
                '{}:0:0'.format(filename),
                sublime.ENCODED_POSITION
            )
            while view.is_loading():
                time.sleep(0.01)

            region = sublime.Region(0, view.size())
            view.replace(edit, region, text)
        self.data = None

However this hangs Sublime.

I have looked at using a “sublime.set_timeout” as suggested here but I appear to have a race condition in that the second file gets the contents replaced multiple times. I also tried creating a new command that I could pass the “edit” object to but then I had the possibility that the view object passed to the new command would be empty as the file was still loading.

Could you help achieve opening the files and replacing the contents?

Thanks

0 Likes

#2

I went with this in the end:

[code]def _process_rename(self, edit):
data = self.data
for item in data’Changes’]:
filename = item’FileName’]
text = item’Buffer’]
view = sublime.active_window().open_file(
‘{}:0:0’.format(filename),
sublime.ENCODED_POSITION
)
sublime.active_window().run_command(“replace_file”,{“args”:{‘text’:item’Buffer’],‘filename’:filename}})

    self.data = None

class ReplaceFile(sublime_plugin.TextCommand):

def run(self,edit,args):
    foundview = sublime.active_window().find_open_file(args'filename'])
    if not foundview.is_loading():
        region = sublime.Region(0, foundview.size())
        foundview.replace(edit,region,args'text'])
    else:
        sublime.set_timeout(lambda: self._try_again(args'text'],args'filename']), 10)

def _try_again(self, text, filename):
    sublime.active_window().run_command("omni_sharp_replace_file",{"args":{'text':text,'filename':filename}})[/code]
0 Likes