SublimePlugins / fold_region.py

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()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.