import sublime, sublime_plugin
import re

py_compl = [			# standard Python functions
	("abs()\tabs fn", "abs(${1:number})$0"),
	("all()\tall fn", "all(${1:iterable})$0"),
	("any()\tany fn", "any(${1:iterable})$0"),
	("bin()\tbin fn", "bin(${1:integer})$0"),
	("bool()\tbool fn", "bool(${1:[value]})$0"),
	("bytearray()\tbytearray fn", 
		"bytearray(${1:${2:source}${3:[, encoding]}${4:[, errors]}})$0"),
	("callable()\tcallable fn", "callable(${1:object})$0"),
	("chr()\tchr fn", "chr(${1:integer})$0"),
	("classmethod()\tclassmethod fn", "classmethod(${1:function})$0"),
	("cmp()\tcmp fn", "cmp(${1:x}, ${2:y})$0"),
	("compile()\tcompile fn", 
		"compile(${1:source}, ${2:filename}, ${3:mode}${4:[, flags]}${5:[, dont_inherit]})$0"),
	("complex()\tcomplex fn", "complex(${1:real}${2:[, imag]})$0"),
	("delattr()\tdelattr fn", "delattr(${1:object}, ${2:name})$0"),
	("dict()\tdict fn", "dict(${1:arg})$0"),
	("dir()\tdir fn", "dir(${1:[object]})$0"),
	("divmod()\tdivmod fn", "divmod(${1:a}, ${2:b})$0"),
	("enumerate()\tenumerate fn", "enumerate(${1:sequence}${2:[, start]})$0"),
	("eval()\teval fn", "eval(${1:expression}${2:[, globals]}${3:[, locals]})$0"),
	("execfile()\texecfile fn", "execfile(${1:filename}${2:[, globals]}${3:[, locals]})$0"),
	("file()\tfile fn", "file(${1:filename}${2:[, mode]}${3:[, bufsize]})$0"),
	("filter()\tfilter fn", "filter(${1:function}, ${2:iterable})$0"),
	("float()\tfloat fn", "float(${1:[x]})$0"),
	("format()\tformat fn", "format(${1:value}${2:[, format_spec]})$0"),
	("frozenset()\tfrozenset fn", "frozenset(${1:[iterable]})$0"),
	("getattr()\tgetattr fn", "getattr(${1:object}, ${2:name}${3:[, default]})$0"),
	("globals()\tglobals fn", "globals()$0"),
	("hasattr()\thasattr fn", "hasattr(${1:object}, ${2:name})$0"),
	("hash()\thash fn", "hash(${1:object})$0"),
	("help()\thelp fn", "help(${1:[object]})$0"),
	("hex()\thex fn", "hex(${1:x})$0"),
	("id()\tid fn", "id(${1:object})$0"),
	("input()\tinput fn", "input(${1:[prompt]})$0"),
	("int()\tint fn", "int(${1:x}${2:[, base]})$0"),
	("isinstance()\tisinstance fn", "isinstance(${1:object}, ${2:classinfo})$0"),
	("issubclass()\tissubclass fn", "issubclass(${1:class}, ${2:classinfo})$0"),
	("iter()\titer fn", "iter(${1:o}${2:[, sentinel]})$0"),
	("len()\tlen fn", "len(${1:object})$0"),
	("list()\tlist fn", "list(${1:[iterable]})$0"),
	("locals()\tlocals fn", "locals()$0"),
	("long()\tlong fn", "long(${1:x}${2:[, base]})$0"),
	("map()\tmap fn", "map(${1:function}${2:[, iterables]})$0"),
	("max()\tmax fn", "max(${1:iterable}${2:[, args]}${3:[, key]})$0"),
	("memoryview()\tmemoryview fn", "memoryview(${1:object})$0"),
	("min()\tmin fn", "min(${1:iterable}${2:[, args]}${3:[, key]})$0"),
	("next()\tnext fn", "next(${1:iterator}${2:[, default]})$0"),
	("object()\tobject fn", "object()$0"),
	("oct()\toct fn", "oct(${1:integer})$0"),
	("open()\topen fn", "open(${1:filename}${2:[, mode]}${3:[, bufsize]})$0"),
	("ord()\tord fn", "ord(${1:char})$0"),
	("pow()\tpow fn", "pow(${1:x}, ${2:y}${3:[, modulo]})$0"),
	("print()\tprint fn", 
		"print(${1:[object, ...][, sep=' '][, end='\\n'][, file=sys.stdout]})$0"),
	("property()\tproperty fn", "property(${1:[fget[, fset[, fdel[, doc]]]]})$0"),
	("range()\trange fn", "range(${1:[start, ]}${2:stop}${3:[, step]})$0"),
	("raw_input()\traw_input fn", "raw_input(${1:[prompt]})$0"),
	("reduce()\treduce fn", "reduce(${1:function}, ${2:iterable}${3:[, initializer]})$0"),
	("reload()\treload fn", "reload(${1:module})$0"),
	("repr()\trepr fn", "repr(${1:object})$0"),
	("reversed()\treversed fn", "reversed(${1:seq})$0"),
	("round()\tround fn", "round(${1:float}${2:[, digits]})$0"),
	("set()\tset fn", "set(${1:[iterable]})$0"),
	("setattr()\tsetattr fn", "setattr(${1:object}, ${2:name}, ${3:value})$0"),
	("slice()\tslice fn", "slice(${1:[start, ]}${2:stop}${3:[, step]})$0"),
	("sorted()\tsorted fn", 
		"sorted(${1:iterable}${2:${3:[, cmp]}${4:[, key]}${5:[, reverse]}})$0"),
	("staticmethod()\tstaticmethod fn", "staticmethod(${1:function})$0"),
	("str()\tString fn", "str(${1:object})$0"),
	("sum()\tsum fn", "sum(${1:iterable}${2:[, start]})$0"),
	("super()\tsuper fn", "super(${1:type}${2:[, object/type]})$0"),
	("tuple()\ttuple fn", "tuple(${1:[iterable]})$0"),
	("type()\ttype fn", "type(${1:object})$0"),
	("type()\ttype ctor", "type(${1:name}, ${2:bases}, ${3:dict})$0"),
	("__import__()\t__import__ fn", 
		"__import__(${1:name}${2:[, globals, locals, fromlist, level]})$0"),
	("unichr()\tunichr fn", "unichr(${1:[integer]})$0"),
	("unicode()\tunicode fn", "unicode(${1:[object, ]}${2:encoding}${3:[, errors]})$0"),
	("vars()\tvars fn", "vars(${1:[object]})$0"),
	("xrange()\txrange fn", "xrange(${1:[start, ]}${2:stop}${3:[, step]})$0"),
	("zip()\tzip fn", "zip(${1:iterable})$0")
]

subl_compl = [					# Sublime .methods
	("active_group()\tST Window", "active_group()$0"),
	("active_view()\tST Window", "active_view()$0"),
	("active_view_in_group()\tST Window", "active_view_in_group(${1:group})$0"),
	("active_window()\tsublime", "active_window()$0"),
	("add()\tST RegionSet", "add(${1:region})$0"),
	("add_all()\tST RegionSet", "add_all(${1:region_set})$0"),
	("add_on_change()\tST Settings", "add_on_change(${1:key}, ${2:on_change})$0"),
	("add_regions()\tST View",
		"add_regions(${1:key}${2:[, regions]}, ${3:scope}${4:[, icon]}${5:[, flags]})$0"),
	("arch()\tsublime", "arch()$0"),
	("begin()\tST Region", "begin()$0"),
	("begin_edit()\tST View", "begin_edit(${1:[command]}${2:[, args]})$0"),
	("buffer_id()\tST View", "buffer_id()$0"),
	("clear_on_change()\tST Settings", "clear_on_change(${1:key})$0"),
	("command_history()\tST View", "command_history(${1:[index]}${2:[, modifying_only]})$0"),
	("contains()\tST Region/Set", "contains(${1:region/pt})$0"),
	("cover()\tST Region", "cover(${1:region})$0"),
	("em_width()\tST View", "em_width()$0"),
	("empty()\tST Region", "empty()$0"),
	("encoding()\tST View", "encoding()$0"),
	("end()\tST Region", "end()$0"),
	("end_edit()\tST View", "end_edit(${1:edit})$0"),
	("erase()\tST Settings", "erase(${1:name})$0"),
	("erase()\tST View", "erase(${1:edit}, ${2:region})$0"),
	("erase_regions()\tST View", "erase_regions(${1:key})$0"),
	("erase_status()\tST View", "erase_status(${1:key})$0"),
	("error_message()\tsublime", "error_message(${1:string})$0"),
	("extract_scope()\tST View", "extract_scope(${1:point})$0"),
	("file_name()\tST View", "file_name()$0"),
	("find()\tST View", "find(${1:pattern}, ${2:fromPosition}${3:[, flags]})$0"),
	("find_all()\tST View",
		"find_all(${1:pattern}${2:[, flags]}${3:[, format]}${4:[, extractions]})$0"),
	("focus_group()\tST Window", "focus_group(${1:group})$0"),
	("focus_view()\tST Window", "focus_view(${1:view})$0"),
	("fold()\tST View", "fold(${1:region(s)})$0"),
	("folders()\tST Window", "folders()$0"),
	("full_line()\tST View", "full_line(${1:region/pt})$0"),
	("find_by_selector()\tST View", "find_by_selector(${1:selector})$0"),
	("get()\tST Settings", "get(${1:name}${2:[, default]})$0"),
	("get_clipboard()\tsublime", "get_clipboard()$0"),
	("get_output_panel()\tST Window", "get_output_panel(${1:name})$0"),
	("get_regions()\tST View", "get_regions(${1:key})$0"),
	("get_status()\tST View", "get_status(${1:key})$0"),
	("get_view_index()\tST Window", "get_view_index(${1:view})$0"),
	("has()\tST Settings", "has(${1:name})$0"),
	("id()\tST View/Window", "id()$0"),
	("insert()\tST View", "insert(${1:edit}, ${2:point}, ${3:string})$0"),
	("installed_packages_path()\tsublime", "installed_packages_path()$0"),
	("intersection()\tST Region", "intersection(${1:region})$0"),
	("intersects()\tST Region", "intersects(${1:region})$0"),
	("is_dirty()\tST View", "is_dirty()$0"),
	("is_loading()\tST View", "is_loading()$0"),
	("is_read_only()\tST View", "is_read_only()$0"),
	("is_scratch()\tST View", "is_scratch()$0"),
	("layout_extent()\tST View", "layout_extent()$0"),
	("layout_to_text()\tST View", "layout_to_text(${1:vector})$0"),
	("line()\tST View", "line(${1:region/pt})$0"),
	("line_endings()\tST View", "line_endings()$0"),
	("line_height()\tST View", "line_height()$0"),
	("lines()\tST View", "lines(${1:region})$0"),
	("load_settings()\tsublime", "load_settings(${1:base_name})$0"),
	("log_commands()\tsublime", "log_commands(${1:flag})$0"),
	("log_input()\tsublime", "log_input(${1:flag})$0"),
	("message_dialog()\tsublime", "message_dialog(${1:string})$0"),
	("name()\tST View", "name()$0"),
	("new_file()\tST Window", "new_file()$0"),
	("num_groups()\tST Window", "num_groups()$0"),
	("ok_cancel_dialog()\tsublime", "ok_cancel_dialog(${1:string}${2:[, ok_button]})$0"),
	("open_file()\tST Window", "open_file(${1:file_name}${2:[, flags]})$0"),
	("packages_path()\tsublime", "packages_path()$0"),
	("platform()\tsublime", "platform()$0"),
	("Region()\tsublime", "Region(${1:a}, ${2:b})$0"),
	("replace()\tST View", "replace(${1:edit}, ${2:region}, ${3:string})$0"),
	("rowcol()\tST View", "rowcol(${1:point})$0"),
	("run_command()\tsublime/View/Window", "run_command(${1:string}${2:[, args]})$0"),
	("save_settings()\tsublime", "save_settings(${1:base_name})$0"),
	("scope_name()\tST View", "scope_name(${1:point})$0"),
	("score_selector()\tST View/Window", "score_selector(${1:scope/pt}, ${2:selector})$0"),
	("sel()\tST View", "sel()$0"),
	("set()\tST Settings", "set(${1:name}, ${2:value})$0"),
	("set_clipboard()\tsublime", "set_clipboard(${1:string})$0"),
	("set_encoding()\tST View", "set_encoding(${1:encoding})$0"),
	("set_line_endings()\tST View", "set_line_endings(${1:line_endings})$0"),
	("set_name()\tST View", "set_name(${1:name})$0"),
	("set_read_only()\tST View", "set_read_only(${1:value})$0"),
	("set_scratch()\tST View", "set_scratch(${1:value})$0"),
	("set_status()\tST View", "set_status(${1:key}, ${2:value})$0"),
	("set_syntax_file()\tST View", "set_syntax_file(${1:syntax_file})$0"),
	("set_timeout()\tsublime", "set_timeout(${1:callback}, ${2:delay})$0"),
	("set_view_index()\tST Window", "set_view_index(${1:view}, ${2:group}, ${3:index})$0"),
	("settings()\tST View", "settings()$0"),
	("set_viewport_position()\tST View", "set_viewport_position(${1:vector}${2:[, animate]})$0"),
	("show()\tST View", "show(${1:region/pt}${2:[, show_surrounds]})$0"),
	("show_at_center()\tST View", "show_at_center(${1:region/pt})$0"),
	("show_input_panel()\tST Window",
	"show_input_panel(${1:caption}, ${2:initial_text}, ${3:on_done}, ${4:on_change}, ${5:on_cancel})$0"),
	("show_quick_panel()\tST Window",
		"show_quick_panel(${1:items}, ${2:on_done}${3:[, flags]})$0"),
	("size()\tST Region/View", "size()$0"),
	("split_by_newlines()\tST View", "split_by_newlines(${1:region})$0"),
	("status_message()\tsublime", "status_message(${1:string})$0"),
	("substr()\tST View", "substr(${1:region/pt})$0"),
	("subtract()\tST RegionSet", "subtract(${1:region})$0"),
	("text_point()\tST View", "text_point(${1:row}, ${2:col})$0"),
	("text_to_layout()\tST View", "text_to_layout(${1:point})$0"),
	("unfold()\tST View", "unfold(${1:region(s)})$0"),
	("version()\tsublime", "version()$0"),
	("viewport_extent()\tST View", "viewport_extent()$0"),
	("viewport_position()\tST View", "viewport_position()$0"),
	("views()\tST Window", "views()$0"),
	("views_in_group()\tST Window", "views_in_group(${1:group})$0"),
	("visible_region()\tST View", "visible_region()$0"),
	("window()\tST View", "window()$0"),
	("windows()\tsublime", "windows()$0"),
	("word()\tST View", "word(${1:region/pt})$0")
]

def match1(rex, str):
	m = rex.match(str)
	if m:
		return m.group(0)
	else:
		return None

class PythonCompletions(sublime_plugin.EventListener):
	def on_query_completions(self, view, prefix, locations):
		global py_compl, subl_compl

		if not view.match_selector(locations[0], 'source.python -string -comment -constant'):
			return []
		pt = locations[0] - len(prefix) - 1
		ch = view.substr(sublime.Region(pt, pt + 1))
		is_dot = (ch == '.')
		if not is_dot:
			completions = py_compl				# a reference to py_compl (functions)
		elif view.find("(?:from|import)\s+sublime", 0) is not None:
			completions = subl_compl			# Sublime (.methods)
		else:
			return []
		return (completions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
		# return completions