def on_query_completions(self, view, prefix, locations):
"""
ST API method: gets called when autocompletion triggers
"""
completions = []
scope_name = view.scope_name(view.sel()[0].b)
filename = view.file_name()
if not filename or not INFOS.addon:
return []
folder = filename.split(os.sep)[-2]
if folder not in INFOS.addon.includes:
return []
if "text.xml" in scope_name:
for dir_, _, files in os.walk(INFOS.addon.media_path):
for filename in files:
rel_dir = os.path.relpath(dir_, INFOS.addon.media_path)
rel_file = os.path.join(rel_dir, filename).lstrip("./").lstrip("\\")
rel_file = rel_file.replace("\\", "/")
completions.append([rel_file, rel_file])
colors = []
for node in INFOS.get_colors():
if node["name"] not in colors:
colors.append(node["name"])
completions.append(["%s (%s)" % (node["name"], node["content"]), node["name"]])
for node in chain(INFOS.addon.includes[folder], INFOS.addon.fonts[folder]):
completions.append([node["name"], node["name"]])
for node in chain(INFOS.builtins, INFOS.conditions):
completions.append([node[0], node[0]])
for item in INFOS.WINDOW_NAMES:
completions.append([item, item])
for item in completions:
for i, match in enumerate(re.findall(r"\([a-z,\]\[]+\)", item[1])):
item[1] = item[1].replace(match, "($%i)" % (i + 1))
return completions
# return (completions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
python类INHIBIT_EXPLICIT_COMPLETIONS的实例源码
def on_query_completions(self, view, prefix, locations):
active_file_extension = util.file_extension(view)
if active_file_extension != '.cls' and active_file_extension != '.trigger':
return None
if not self.refreshing:
client = lsClient
if not client:
return
completionProvider = client.get_capability('completionProvider')
if not completionProvider:
return
autocomplete_triggers = completionProvider.get('triggerCharacters')
if locations[0] > 0:
self.completions = []
purge_did_change(view.buffer_id())
client.send_request(
Request.complete(
util.get_document_position(view, locations[0])),
self.handle_response)
self.refreshing = False
return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS
| sublime.INHIBIT_EXPLICIT_COMPLETIONS)
def on_query_completions(self, view, prefix, locations):
"""Runs on all views, but is NOOP unless view is response view or history
view. Inside gql query string, only completions returned by this method
are shown.
"""
response_view = view.settings().get('requester.response_view', False)
history_view = view.settings().get('requester.history_view', False)
if not response_view and not history_view:
return None
content = view.substr(sublime.Region(0, view.size()))
m = re.search(r'\bgql\s*=\s*("|\')+', content)
if m is None:
return None
offset, idx = m.end(), view.sel()[0].begin()
try:
request = parse_requests(content, n=1)[0]
if getattr(view, '_env', None) is None:
view._env = RequestCommandMixin.get_env_dict_from_string(
view.settings().get('requester.env_string', None)
)
req = prepare_request(request, view._env, 1)
schema = view.settings().get('requester.gql_schema', None)
if not schema: # let user know schema is being retrieved
set_graphql_schema_on_view(view, req)
raise Exception('Loading GraphQL schema info')
gql = req.skwargs['gql']
completions = get_completions(gql, idx-offset, schema)
return completions
except Exception as e:
print('GraphQL Error:')
traceback.print_exc(file=sys.stdout)
return (
[[str(e), ' '], ['...', ' ']],
sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
)
def on_query_completions(self, view, prefix, points):
selected_completions = set()
for point in points:
if "source.rbxlua" not in view.scope_name(point):
return None
row_col = view.rowcol(point)
line_region = view.line(point)
line_text = view.substr(line_region)
function_match = FUNCTION_CALL_REGEX.search(line_text, 0, row_col[1])
enum_match = ENUM_REGEX.search(line_text, 0, row_col[1])
if function_match is not None and function_match.end(0) >= row_col[1]:
function_name = function_match.group(1)
value = None
if function_name in service_detections:
value = services
elif function_name in creatable_detections:
value = creatables
elif function_name in class_detections:
value = classes
if value is not None:
selected_completions.update([x for x in value if x.startswith(prefix)])
elif enum_match is not None and enum_match.end(0) >= row_col[1]:
if enum_match.group(2) is None or enum_match.group(2) == "":
selected_completions.update(enum_names)
else:
if enum_match.group(2)[0] == ".":
selected_completions.update(set([ e["entry_completion"] for e in completion_items if e["entry_type"] == "EnumItem" and e["enum_parent"] == enum_match.group(1) ]))
else:
selected_completions.add("GetEnumItems()")
if len(selected_completions) > 0:
return ([ [e] for e in selected_completions ], sublime.INHIBIT_EXPLICIT_COMPLETIONS | sublime.INHIBIT_WORD_COMPLETIONS)
def on_query_completions(self, view, prefix, locations):
if settings.get('no_dialogs_autocomplete_mode') != 'default':
return
if currently_open_prompt is None or currently_open_prompt != view:
return
comps = autocomplete_file_name(read_view(view))
flags = 0
flags |= sublime.INHIBIT_WORD_COMPLETIONS if settings.get('no_dialogs_inhibit_word_completions') else 0
flags |= sublime.INHIBIT_EXPLICIT_COMPLETIONS if settings.get('no_dialogs_inhibit_explicit_completions') else 0
return ([[comp, comp] for comp in comps], flags)
def on_query_completions(self, prefix, locations):
if self.view.match_selector(locations[0], NO_COMPLETION_SCOPES):
return (
[],
sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
)
if not self.initialized:
self.initialize()
if self.enabled:
reuse_completion = self.is_same_completion(prefix, locations)
if self.state == CompletionState.IDLE:
if not reuse_completion:
self.last_prefix = prefix
self.last_location = locations[0]
self.do_request(prefix, locations)
self.completions = []
elif self.state in (CompletionState.REQUESTING, CompletionState.CANCELLING):
self.next_request = (prefix, locations)
self.state = CompletionState.CANCELLING
elif self.state == CompletionState.APPLYING:
self.state = CompletionState.IDLE
return (
self.completions,
0 if not settings.only_show_lsp_completions
else sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
)
def test_enabled(self):
self.view.run_command('insert', {"characters": '.'})
self.client.send_request = MagicMock()
handler = CompletionHandler(self.view)
self.assertEquals(handler.state, CompletionState.IDLE)
items, mask = handler.on_query_completions("", [1])
self.assertEquals(len(items), 0)
self.assertEquals(mask, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
self.assertTrue(handler.initialized)
self.assertTrue(handler.enabled)
self.assertEquals(handler.state, CompletionState.REQUESTING)
self.client.send_request.assert_called_once()
# time.sleep(1000)
# self.assertEquals(len(handler.completions), 2)
# self.assertEquals(handler.state, CompletionState.APPLYING)
# running auto_complete command does not work
# sublime does not know about the instance we registered here.
# we do it directly here
# items, mask = handler.on_query_completions("", [1])
# self.assertEquals(len(items), 2)
# self.assertEquals(mask, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
def on_query_completions(self, view: sublime.View, prefix: str, locations: List[Tuple[int]]) -> Tuple[List[Tuple[str]], int]: # noqa
"""Sublime Text autocompletion event handler
"""
if not is_python(view, autocomplete_ignore_repl=True):
return
if completion_is_disabled(view):
return
global JUST_COMPLETED
if self.ready_from_defer is True:
completion_flags = 0
if get_settings(view, 'suppress_word_completions', False):
completion_flags = sublime.INHIBIT_WORD_COMPLETIONS
if get_settings(view, 'suppress_explicit_completions', False):
completion_flags |= sublime.INHIBIT_EXPLICIT_COMPLETIONS
cpl = self.completions
self.completions = []
self.ready_from_defer = False
JUST_COMPLETED = True
return (cpl, completion_flags)
location = view.rowcol(locations[0])
data = prepare_send_data(location, 'autocomplete', 'jedi')
Worker().execute(self._complete, **data)
def on_query_completions(self, view, prefix, locations):
project = get_or_create_project_and_add_view(view)
if project and project.is_initialized():
pos = view.sel()[0].begin()
(line, col) = view.rowcol(pos)
Debug('autocomplete', "on_query_completions(), sublime wants to see the results, cursor currently at %i , %i (enabled: %s, items: %i)" % (line+1, col+1, project.completion.enabled_for['viewid'], len(project.completion.get_list()) ) )
if project.completion.enabled_for['viewid'] == view.id():
project.completion.enabled_for['viewid'] = -1 # receive only once
return (project.completion.get_list(), sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
# ON QUERY CONTEXT (execute commandy only on opened .ts files)
def on_query_completions(self, view, prefix, locations):
self.view = view
file = view.file_name()
if not _is_swift(file):
return None
offset = locations[0]
project_directory = _project_directory(view)
text = _view_text(view)
suggestions = subl_source_kitten.complete_with_haste(offset, file, project_directory, text)
return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
def add_completions_flags(self, a_completions):
return (a_completions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS,)
#@timed
def on_query_completions(self, view, prefix, locations):
# parts of the code inspired by: https://github.com/agibsonsw/AndyPython/blob/master/PythonCompletions.py
global builtin_compl_vars, builtin_compl_funcs, magic_control_pars
if not view.match_selector(locations[0], 'source.ksp -string -comment -constant'):
return []
pt = locations[0] # - len(prefix) - 1
#ch = view.substr(sublime.Region(pt, pt + 1)) # the character before the trigger
line_start_pos = view.line(sublime.Region(pt, pt)).begin()
line = view.substr(sublime.Region(line_start_pos, pt)) # the character before the trigger
if re.match(r' *declare .*', line) and ':=' not in line:
compl = []
elif re.match(r'.*-> ?[a-zA-Z_]*$', line): # if the line ends with something like '->' or '->valu'
compl = magic_control_pars
else:
compl = self._extract_completions(view, prefix, pt)
compl = [(item + "\tdefault", item) for item in compl
if len(item) > 3 and item not in all_builtins]
if '.' not in prefix:
bc = []
bc.extend(builtin_compl_vars)
bc.extend(builtin_compl_funcs)
compl.extend(bc)
compl = self.unique(compl)
return (compl, sublime.INHIBIT_WORD_COMPLETIONS |
sublime.INHIBIT_EXPLICIT_COMPLETIONS)
def on_query_completions_async(self, view, prefix, locations):
self.completions = None
flow_settings = find_flow_settings(view.window().project_data())
autocomplete_flags = sublime.INHIBIT_WORD_COMPLETIONS | \
sublime.INHIBIT_EXPLICIT_COMPLETIONS
if flow_settings.get('show_sublime_autocomplete_suggestions'):
autocomplete_flags = 0
result = None
try:
result = CLI(view).autocomplete()
except InvalidContext:
pass
except Exception as e:
display_unknown_error(self.view, e)
if not result:
return
self.completions = (
[
(
# matching text
match['name'] + '\t' + match['type'],
# inserted text
build_snippet(
match['name'],
match.get('func_details')['params']
)
if (
match.get('func_details') and
not flow_settings.get('omit_function_parameters')
)
else match['name']
)
for match in result['result']
],
autocomplete_flags
)
self.completions_ready = True
sublime.active_window().active_view().run_command(
'hide_auto_complete'
)
self.run_auto_complete()
def get_completions(gql, idx, schema):
"""Creates AST from `gql` query string, finds out exactly where cursor is in
string, and uses `schema` to get appropriate completions. Doesn't protect
against exceptions. They should be handled by calling code.
"""
try: # at module import time this package is not available
from graphql.parser import GraphQLParser
from graphql.lexer import GraphQLLexer
except ImportError:
raise Exception('Install graphql-py with pip for GraphQL autocomplete')
try: # monkey-patch this class, the `t_NULL` method breaks parsing
delattr(GraphQLLexer, 't_NULL')
except AttributeError:
pass
start, end = slurp_word(gql, idx)
gql_parser = GraphQLParser()
ast = gql_parser.parse(gql[:start] + placeholder + gql[end:], lexer=GraphQLLexer())
for query in ast.definitions: # get path if it exists
path = placeholder_path(query, placeholder)
if path is not None:
break
query_type, types = schema
t = resolve_type(path, types, query_type)
fields = types[t]['fields']
completions = []
for f in fields.values():
name = f['name']
args = [a['name'] + ':' for a in f['args']]
args_string = '({})'.format(', '.join(args)) if args else ''
type_name = resolve_field_type(f)
completions.append([
'{}{}\t{}'.format(name, args_string, type_name),
'{}{}'.format(name, args_string),
])
return (
completions,
sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
)
def on_query_completions(self, view, prefix, locations):
# Check if this is a Crystal source file. This check
# relies on the Crystal syntax formatting extension
# being installed - https://github.com/crystal-lang/sublime-crystal
if view.match_selector(locations[0], "source.crystal"):
try:
raw_results = run_cracker(view, locations[0])
except FileNotFoundError:
print("Unable to find cracker executable (check settings)")
return
results = []
regexp = '[\.#](.+)\('
for r in raw_results:
if r.type == "Function":
if r.name.find("#") != -1:
trigger = r.name.split("#")[1]
else:
trigger = r.name.split(".")[1]
contents = trigger.split("(")[0]
if r.name.find("()") == -1:
contents = contents + '('
else:
trigger = r.name
contents = r.name
results.append([trigger, contents])
if len(results) > 0:
# return results
return (results, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
#class CrystalGotoDefinitionCommand(sublime_plugin.TextCommand):
# def run(self, edit):
# # Get the buffer location in correct format for cracker
# row, col = self.view.rowcol(self.view.sel()[0].begin())
# row += 1
#
# results = run_cracker(self.view, ["find-definition", str(row), str(col)])
#
# if len(results) == 1:
# result = results[0]
# path = result.path
# # On Windows the cracker will return the paths without the drive
# # letter and we need the letter for the open_file to work.
# if sublime.platform() == 'windows' and not re.compile('^\w\:').match(path):
# path = 'c:' + path
# encoded_path = "{0}:{1}:{2}".format(path, result.row, result.column)
# self.view.window().open_file(encoded_path, sublime.ENCODED_POSITION)
def on_query_completions(self, view, prefix, locations):
"""Sublime Text autocompletion event handler
"""
if not is_code(view, lang='rust'):
return
if self.ready_from_defer is True:
completion_flags = 0
if ags(view, 'suppress_word_completions', False):
completion_flags = sublime.INHIBIT_WORD_COMPLETIONS
if ags(view, 'suppress_explicit_completions', False):
completion_flags = sublime.INHIBIT_EXPLICIT_COMPLETIONS
cpl = self.completions
self.completions = []
self.ready_from_defer = False
return (cpl, completion_flags)
code = view.substr(sublime.Region(0, view.size()))
row, col = view.rowcol(locations[0])
racer = get_settings(view, 'racer_binary_path', 'racer')
if racer == '':
racer = 'racer'
data = {
'vid': view.id(),
'filename': view.file_name(),
'settings': {
'racer_binary_path': racer,
'rust_src_path': get_settings(view, 'rust_src_path'),
'row': row,
'col': col,
'source': code,
},
'method': 'autocomplete',
'handler': 'racer'
}
Worker().execute(
Callback(
on_success=self._complete,
on_failure=self._on_failure,
on_timeout=self._on_timeout
),
**data
)