import sublime, sublime_plugin

py_funcs = [
	("__import__()\t__import__ fn", 
		"__import__(${1:name}${2:[, globals, locals, fromlist, level]})$0"),
	("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/ctor", "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/ctor", "float(${1:[x]})$0"),
	("format()\tformat fn", "format(${1:value}${2:[, format_spec]})$0"),
	("frozenset()\tfrozenset fn/ctor", "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/ctor", "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/ctor", "list(${1:[iterable]})$0"),
	("locals()\tlocals fn", "locals()$0"),
	("long()\tlong fn/ctor", "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/ctor", "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/ctor", "tuple(${1:[iterable]})$0"),
	("type()\ttype fn", "type(${1:object})$0"),
	("type()\ttype ctor", "type(${1:name}, ${2:bases}, ${3:dict})$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")
]

py_members = [ 				# methods and attributes
	("add()\tset", "add(${1:elem})$0"),
	("append()\tMutable", "append(${1:x})$0"),
	("as_integer_ratio()\tfloat", "as_integer_ratio()$0"),
	("bit_length() 3.1\tint/long", "bit_length()$0"),
	("capitalize()\tstring", "capitalize()$0"),
	("center()\tstring", "center(${1:width}${2:[, fillchar]})$0"),
	("clear()\tset/dict", "clear()$0"),
	("close()\tfile", "close()$0"),
	("closed\tfile", "closed$0"),
	("conjugate()\tcomplex", "conjugate()$0"),
	("copy()\tSet/dict", "copy()$0"),
	("count()\tSequence", "count(${1:value})$0"),
	("count()\tstring", "count(${1:substr}${2:[, start]}${3:[, end]})$0"),
	("decode()\tstring", "decode(${1:[encoding]}${2:[, errors]})$0"),
	("difference()\tSet", "difference(${1:other,..})$0"),
	("difference_update()\tset", "difference_update(${1:other,..})$0"),
	("discard()\tset", "discard(${1:elem})$0"),
	("encode()\tstring", "encode(${1:[encoding]}${2:[, errors]})$0"),
	("encoding\tfile", "encoding$0"),
	("endswith()\tstring", "endswith(${1:suffix}${2:[, start]}${3:[, end]})$0"),
	("errors\tfile", "errors$0"),
	("expandtabs()\tstring", "expandtabs(${1:[tabsize]})$0"),
	("extend()\tMutable", "extend(${1:x})$0"),
	("fileno()\tfile", "fileno()$0"),
	("find()\tstring", "find(${1:substr}${2:[, start]}${3:[, end]})$0"),
	("flush()\tfile", "flush()$0"),
	("format()\tstring", "format(${1:*args}, ${2:**kwargs})$0"),
	("format\tmemoryview", "format$0"),
	("fromhex()\tfloat", "fromhex(${1:string})$0"),
	("fromkeys()\tDict", "fromkeys(${1:seq}${2:[, value]})$0"),
	("get()\tdict", "get(${1:key}${2:[, default]})$0"),
	("has_key()\tdict", "has_key(${1:key})$0"),
	("hex()\tfloat", "hex()$0"),
	("index()\tSequence", "index(${1:value}${2:[, start]}${3:[, end]})$0"),
	("insert()\tMutable", "insert(${1:i}, ${2:x})$0"),
	("intersection()\tSet", "intersection(${1:other,..})$0"),
	("intersection_update()\tset", "intersection_update(${1:other,..})$0"),
	("is_integer()\tfloat", "is_integer()$0"),
	("isalnum()\tstring", "isalnum()$0"),
	("isalpha()\tstring", "isalpha()$0"),
	("isatty()\tfile", "isatty()$0"),
	("isdecimal()\tunicode", "isdecimal()$0"),
	("isdigit()\tstring", "isdigit()$0"),
	("isdisjoint()\tSet", "isdisjoint(${1:other})$0"),
	("islower()\tstring", "islower()$0"),
	("isnumeric()\tunicode", "isnumeric()$0"),
	("isspace()\tstring", "isspace()$0"),
	("issubset()\tSet", "issubset(${1:other})$0"),
	("issuperset()\tSet", "issuperset(${1:other})$0"),
	("istitle()\tstring", "istitle()$0"),
	("isupper()\tstring", "isupper()$0"),
	("items()\tdict", "items()$0"),
	("itemsize\tmemoryview", "itemsize$0"),
	("iteritems()\tdict", "iteritems()$0"),
	("iterkeys()\tdict", "iterkeys()$0"),
	("itervalues()\tdict", "itervalues()$0"),
	("join()\tstring", "join(${1:iterable})$0"),
	("keys()\tdict", "keys()$0"),
	("ljust()\tstring", "ljust(${1:width}${2:[, fillchar]})$0"),
	("lower()\tstring", "lower()$0"),
	("lstrip()\tstring", "lstrip(${1:[chars]})$0"),
	("mode\tfile", "mode$0"),
	("name\tfile", "name$0"),
	("ndim\tmemoryview", "ndim$0"),
	("newlines\tfile", "newlines$0"),
	("next()\tfile", "next()$0"),
	("partition()\tstring", "partition(${1:sep})$0"),
	("pop()\tdict", "pop(${:key}${2:[, default]})$0"),
	("pop()\tMutable", "pop(${1:[i]})$0"),
	("pop()\tset", "pop()$0"),
	("popitem()\tdict", "popitem()$0"),
	("read()\tfile", "read(${1:[size]})$0"),
	("readline()\tfile", "readline(${1:[size]})$0"),
	("readlines()\tfile", "readlines(${1:[sizehint]})$0"),
	("readonly\tmemoryview", "readonly$0"),
	("remove()\tMutable", "remove(${1:x})$0"),
	("remove()\tset", "remove(${1:elem})$0"),
	("replace()\tstring", "replace(${1:old}, ${2:new}${3:[, count]})$0"),
	("reverse()\tMutable", "reverse()$0"),
	("rfind()\tstring", "rfind(${1:substr}${2:[, start]}${3:[, end]})$0"),
	("rindex()\tstring", "rindex(${1:substr}${2:[, start]}${3:[, end]})$0"),
	("rjust()\tstring", "rjust(${1:width}${2:[, fillchar]})$0"),
	("rpartition()\tstring", "rpartition(${1:sep})$0"),
	("rsplit()\tstring", "rsplit(${1:[sep]}${2:[, maxsplit]})$0"),
	("rstrip()\tstring", "rstrip(${1:[chars]})$0"),
	("seek()\tfile", "seek(${1:offset}${2:[, whence]})$0"),
	("setdefault()\tdict", "setdefault(${:key}${2:[, default]})$0"),
	("shape\tmemoryview", "shape$0"),
	("softspace\tfile", "softspace$0"),
	("sort()\tMutable", "sort(${1:[cmp]}${2:[, key]}${3:[, reverse]})$0"),
	("split()\tstring", "split(${1:[sep]}${2:[, maxsplit]})$0"),
	("splitlines()\tstring", "splitlines(${1:[keepends]})$0"),
	("startswith()\tstring", "startswith(${1:prefix}${2:[, start]}${3:[, end]})$0"),
	("strides\tmemoryview", "strides$0"),
	("strip()\tstring", "strip(${1:[chars]})$0"),
	("swapcase()\tstring", "swapcase()$0"),
	("symmetric_difference()\tSet", "symmetric_difference(${1:other})$0"),
	("symmetric_difference_update()\tset", "symmetric_difference_update(${1:other})$0"),
	("tell()\tfile", "tell()$0"),
	("title()\tstring", "title()$0"),
	("tobytes()\tmemoryview", "tobytes()$0"),
	("tolist()\tmemoryview", "tolist()$0"),
	("translate()\tstring", "translate(${1:table}${2:[, deletechars]})$0"),
	("truncate()\tfile", "truncate(${1:[size]})$0"),
	("union()\tSet", "union(${1:other,..})$0"),
	("update()\tdict/set", "update(${1:other,..})$0"),
	("upper()\tstring", "upper()$0"),
	("values()\tdict", "values()$0"),
	("viewitems()\tdict", "viewitems()$0"),
	("viewkeys()\tdict", "viewkeys()$0"),
	("viewvalues()\tdict", "viewvalues()$0"),
	("write()\tfile", "write(${1:str})$0"),
	("writelines()\tfile", "writelines(${1:sequence})$0"),
	("zfill()\tstring", "zfill(${1:width})$0")
]

subl_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_completions()\tST View", "extract_completions(${1:prefix})$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"),
	("match_selector()\tST View", "match_selector(${1:pt}, ${2:scope_string})$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")
]

sublime_methods_all = list(py_members)
sublime_methods_all.extend(subl_methods)

class PythonCompletions(sublime_plugin.EventListener):
	def on_query_completions(self, view, prefix, locations):
		global py_funcs, py_members, subl_methods, subl_methods_all
		if not view.match_selector(locations[0], 'source.python -string -comment -constant'):
			return []
		completions = []
		pt = locations[0] - len(prefix) - 1
		ch = view.substr(sublime.Region(pt, pt + 1)) 	# the character before the trigger
		is_dot = (ch == '.')
		if is_dot: completions = py_members
		if not is_dot: completions = py_funcs
		if view.find("(?:from|import)\s+sublime", 0) is not None and is_dot:
			completions = sublime_methods_all		# include Python methods/attributes
		compl_default = [view.extract_completions(prefix)]
		compl_default = [(item + "\tDefault", item) for sublist in compl_default 
			for item in sublist if len(item) > 3] 		# flatten
		compl_default = list(set(compl_default))		# make unique
		compl_full = list(completions)
		compl_full.extend(compl_default)
		compl_full.sort()
		return (compl_full, sublime.INHIBIT_WORD_COMPLETIONS |
			sublime.INHIBIT_EXPLICIT_COMPLETIONS)