Skip to content

Commit

Permalink
add debouncing and remove a leakin view.size() call
Browse files Browse the repository at this point in the history
  • Loading branch information
philippotto committed Dec 8, 2014
1 parent 99a248b commit e889c97
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
41 changes: 32 additions & 9 deletions BracketGuard.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import sublime, sublime_plugin
import re
import re, time

from collections import namedtuple

Expand All @@ -10,6 +10,11 @@

class EventListener(sublime_plugin.EventListener):

def __init__(self):

self.latest_keypresses = {}


def on_modified(self, view):

if view.settings().get("is_test", False):
Expand All @@ -20,8 +25,7 @@ def on_modified_async(self, view):

self.clearRegions(view)
if self.doAutoCheck(view):
self.highlightBracketError(view)

self.debounce(view, "modified", self.highlightBracketError)

def on_post_save_async(self, view):

Expand All @@ -34,16 +38,19 @@ def clearRegions(self, view):
view.erase_regions(bracketGuardRegions)


def settings(self):

return sublime.load_settings("BracketGuard.sublime-settings")


def checkOnSave(self):

settings = sublime.load_settings("BracketGuard.sublime-settings")
return settings.get("check_on_save")
return self.settings().get("check_on_save")


def doAutoCheck(self, view):

settings = sublime.load_settings("BracketGuard.sublime-settings")
threshold = settings.get("file_length_threshold")
threshold = self.settings().get("file_length_threshold")
return threshold == -1 or threshold >= view.size()


Expand All @@ -57,6 +64,21 @@ def highlightBracketError(self, view):
view.add_regions(bracketGuardRegions, [openerRegion, closerRegion], "invalid")


def debounce(self, view, event_type, func):

key = (event_type, view.file_name())
this_keypress = time.time()
self.latest_keypresses[key] = this_keypress
debounceTime = self.settings().get("debounce_time", 500)

def callback():
latest_keypress = self.latest_keypresses.get(key, None)
if this_keypress == latest_keypress:
func(view)

sublime.set_timeout_async(callback, debounceTime)


def getFirstBracketError(self, view):

opener = list("({[")
Expand All @@ -68,8 +90,9 @@ def getFirstBracketError(self, view):

for index, char in enumerate(codeStr):

if len(codeStr ) != view.size():
return successResult
# this leaks memory ?
# if len(codeStr) != view.size():
# return successResult

if char not in opener and not char in closer:
continue
Expand Down
4 changes: 3 additions & 1 deletion BracketGuard.sublime-settings
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
// If the current document has more characters automatic checking of brackets
// is disabled.
"file_length_threshold" : 20000,
"check_on_save" : true
"check_on_save" : true,
// debounce time in milli seconds
"debounce_time": 500
}

0 comments on commit e889c97

Please sign in to comment.