Sublime Forum

No undo - what is wrong?

#1

Hi,

am new to Sublime plugin development and somewhat new to Python. I just wrote a plugin that scans the current file for function names, inserts and md5 hash underneath each function declaration and then inserts a “table of contents” at the cursor position. Partly just for fun, partly because it can help me out at work. The problem is that when the plugin finishes running, nothing happens at first, but as soon as I press any button, all the edits are displayed. But I cannot undo what’s just been done and I cannot see the cursor - only the highlighted line - when I scroll either with keys or with the mouse. What is the culprit? I tried googling, staring into the code till I memorized it to the last symbol and reading hundreds of times through the API that I found online, to no avail. Here’s the code in question:

import sublime_plugin
import sublime
import hashlib
import re
import datetime


class CreateContentsCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.contents = "# OBSAH (%s):" % datetime.datetime.now().strftime("%Y-%m-%d")]
        regions = self.view.find_all("^\s*?FUNCTION\s*.*?\(.*", sublime.IGNORECASE)
        for r in reversed(regions):
            try:
                found = re.search("^\s*?FUNCTION\s*(.*?)\(.*", self.view.substr(r)).group(1)
                md = self.calculate_md5(found)
                self.contents += "# " + found + " " + md]
                self.insert_md5(r, md)
            except AttributeError:
                pass
        self.insert_contents(self.contents)

    def insert_contents(self, contents):
        edit = self.view.begin_edit()
        try:
            self.view.insert(edit, self.view.sel()-1].end(), "\n".join(self.contents))
        finally:
            self.view.end_edit(edit)

    def insert_md5(self, region, md):
        edit = self.view.begin_edit()
        try:
            self.view.insert(edit, region.end(), "\n# " + md)
        finally:
            self.view.end_edit(edit)

    def calculate_md5(self, st):
        return hashlib.md5(st.encode('utf8')).hexdigest()
0 Likes

#2

I tried your plugin, and it seemed to work for me. No problems with display, and undo works fine. What platform are you on? Maybe there’s something fishy with your system. Maybe try a different computer?

0 Likes

#3

Thanks for your answer, sapphirehamster. I have just come to work, tried firing up Sublime Text and running the plugin - and it worked fine. I guess I should have just restarted ST. :stuck_out_tongue:

0 Likes