Source

SublimePlugins / fold_region.py

Full commit
import sublime, sublime_plugin

start_region = '#region'
end_region = '#endregion'

class FoldRegionCommand(sublime_plugin.TextCommand):
	def fallback(self):
		self.view.run_command("fold")

	def run(self, edit):
		rstart, rend, size = 0, 0, self.view.size()
		text = self.view.substr(sublime.Region(0, size))		
		for region in self.view.sel():
			if region.empty:
				#searching for start_region
				a = region.a
				start, end = text.rfind(start_region, 0, a), text.rfind(end_region, 0, a)
				if start > -1 and end == -1 or start >= end:
					rstart = start
					#searching for end_region
					start, end = text.find(start_region, a, size), text.find(end_region, a, size)
					if end > -1 and start == -1 or end <= start:
						#found, folding the region
						rend = end
						rstart = text.find("\n", rstart)
						region_to_fold = sublime.Region(rstart+1, rend-1)
						self.view.fold(region_to_fold)
					else:
						self.fallback()
				else:
					self.fallback()
			else:			
				self.fallback()