Python sublime 模块,ENCODED_POSITION 实例源码
我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用sublime.ENCODED_POSITION。
def run(self, edit, **args):
data = run_command(self.view, {"type": "definition", "lineCharPositions": True})
if data is None: return
file = data.get("file", None)
if file is not None:
# Found an actual definition
row, col = self.view.rowcol(self.view.sel()[0].b)
cur_pos = self.view.file_name() + ":" + str(row + 1) + ":" + str(col + 1)
jump_stack.append(cur_pos)
if len(jump_stack) > 50: jump_stack.pop(0)
real_file = (os.path.join(get_pfile(self.view).project.dir, file) +
":" + str(data["start"]["line"] + 1) + ":" + str(data["start"]["ch"] + 1))
sublime.active_window().open_file(real_file, sublime.ENCODED_POSITION)
else:
url = data.get("url", None)
if url is None:
sublime.error_message("Could not find a definition")
else:
webbrowser.open(url)
def run(self, edit):
for region in self.view.sel():
if not region.empty():
self.view.insert(edit, region.begin(), self.view.substr(region))
continue
line_contents = self.view.substr(self.view.line(region))
match = re.search(r'File "(.*?)", line (\d*), in .*', line_contents)
if match:
sublime.active_window().open_file("{}:{}".format(os.path.realpath(match.group(1)),
match.group(2)),
sublime.ENCODED_POSITION)
return
match = re.search(r"', \('(.*?)', (\d+), (\d+), ", line_contents)
if match:
sublime.active_window().open_file("{}:{}:{}".format(os.path.realpath(match.group(1)),
match.group(2),
match.group(3)),
sublime.ENCODED_POSITION)
return
def run_async(self):
result = None
try:
result = CLI(self.view).get_def()
except InvalidContext:
print('Invalid context')
pass
except Exception as e:
display_unknown_error(self.view, e)
return
print(result)
if not result or not result.get('path'):
return
sublime.active_window().open_file(
result['path'] +
':' + str(result['line']) +
':' + str(result['start']),
sublime.ENCODED_POSITION |
sublime.TRANSIENT
)
def run(self, edit, event):
if self.symbol_details:
view_path = self.symbol_details[0]
focus_region = self.symbol_details[1]
# collapse the region to a single point, the region start
focus_region = sublime.Region(focus_region.begin(), focus_region.begin())
# get the view with this path
view = sublime.active_window().find_open_file(view_path)
if view:
self.showSymbol(view, focus_region)
else:
# weird issue, but unless we open the file with 'ENCODED_POSITION' it won't scroll afterwards
# https://github.com/SublimeTextIssues/Core/issues/538
view = sublime.active_window().open_file("%s:%d:%d" % (view_path, 1, 0), sublime.ENCODED_POSITION)
def viewLoadedTimeout():
# we can run methods only on loaded views
if not view.is_loading():
self.showSymbol(view, focus_region)
else:
sublime.set_timeout(viewLoadedTimeout, 100)
# open is asynchronous, wait for a bit and then try to focus
sublime.set_timeout(viewLoadedTimeout, 100)
def run(self, edit):
"""Run goto declaration command.
Navigates to delcaration of entity located by current position
of cursor.
"""
if not Tools.is_valid_view(self.view):
return
config_manager = EasyClangComplete.view_config_manager
if not config_manager:
return
location = config_manager.trigger_get_declaration_location(self.view)
if location:
loc = location.file.name
loc += ":" + str(location.line)
loc += ":" + str(location.column)
log.debug("Navigating to declaration: %s", loc)
sublime.active_window().open_file(loc, sublime.ENCODED_POSITION)
def rename(self, edit: sublime.Edit) -> None:
"""Rename in the buffer
"""
data = self.data
if data['success'] is True:
for filename, data in data['renames'].items():
for line in data:
view = sublime.active_window().open_file(
'{}:{}:0'.format(filename, line['lineno']),
sublime.ENCODED_POSITION
)
while view.is_loading():
time.sleep(0.01)
lines = view.lines(sublime.Region(0, view.size()))
view.replace(edit, lines[line['lineno']], line['line'])
self.data = None
def on_navigate(self, url):
if self.view.is_popup_visible():
self.view.hide_popup()
filepath, line, offsets = url.split(":")
column, length = offsets.split("-")
new_view = self.view.window().open_file(url, sublime.ENCODED_POSITION)
start_offset = int(column) - 1
end_offset = start_offset + int(length)
region = Region(start_offset, end_offset)
# Add a highlight
new_view.add_regions("highlight", [region], "comment")
# Remove highlight after a second
Timer(1.0, lambda: new_view.add_regions("highlight", [], "comment")).start()
def run(self, edit, **args):
if not self._is_kiwilime_view:
return
point = current.point(self.view)
file_name, lineno = get_file_location(self.view, point)
if not file_name:
return None
if os.path.exists(file_name):
file_loc = "{0}:{1}".format(file_name, lineno)
self.view.window().open_file(file_loc, sublime.ENCODED_POSITION)
else:
show_error("File '{0}'' doses not exists.".format(
file_name))
def handle_process(self, returncode, stdout, error):
"""Handle the output from the threaded process."""
if type(error) is bytes:
error = error.decode('utf-8')
if returncode != 0:
logger.logger.error('get_def %s' % error)
return
logger.logger.debug(stdout)
if stdout and stdout['path']:
self.active_window.open_file(
stdout['path'] +
':' + str(stdout['line']) +
':' + str(stdout['start']),
sublime.ENCODED_POSITION |
False
)
else:
self.view.set_status('flow_type', 'Flow: no definition found')
def on_navigate(self, href):
""" open the link in a new tab on web browser """
if '$$$' in href:
try:
arr = href.split('$$$')
file_name = arr[0].strip()
location = arr[1].split(',')
row = int(location[0].strip())
col = int(location[1].strip())
sublime.active_window().open_file("%s:%s:%s" %
(file_name, row, col),
sublime.ENCODED_POSITION)
except Exception as e:
# print(e)
self.logger_msg += str(e) + '\n'
else:
try:
webbrowser.open_new_tab(href)
except Exception as e:
# logging.error('cannot open link on web browser.')
self.logger_msg += str(e) + '\n'
def open_file(self, file_name):
flags = (FORCE_GROUP | ENCODED_POSITION)
self.window.open_file(file_name, group=(self.window.num_groups() - 1), flags=flags)
def run(self, edit, mode=None, character=None, count=1):
def f(view, s):
if mode == modes.VISUAL:
if s.a <= s.b:
if address.b < s.b:
return Region(s.a + 1, address.b)
else:
return Region(s.a, address.b)
else:
return Region(s.a + 1, address.b)
elif mode == modes.NORMAL:
return address
elif mode == modes.INTERNAL_NORMAL:
if s.a < address.a:
return Region(view.full_line(s.b).a, view.line(address.b).b)
return Region(view.full_line(s.b).b, view.line(address.b).a)
return s
state = self.state
address = state.marks.get_as_encoded_address(character)
if address is None:
return
if isinstance(address, str):
if not address.startswith('<command'):
self.view.window().open_file(address, ENCODED_POSITION)
else:
# We get a command in this form: <command _vi_double_quote>
self.view.run_command(address.split(' ')[1][:-1])
return
regions_transformer(self.view, f)
if not self.view.visible_region().intersects(address):
self.view.show_at_center(address)
def run(self, edit, count=1, mode=None, character=None):
def f(view, s):
if mode == modes.VISUAL:
if s.a <= s.b:
if address.b < s.b:
return Region(s.a + 1, address.b)
else:
return Region(s.a, address.b)
else:
return Region(s.a + 1, address.b)
elif mode == modes.NORMAL:
return address
elif mode == modes.INTERNAL_NORMAL:
return Region(s.a, address.b)
return s
state = self.state
address = state.marks.get_as_encoded_address(character, exact=True)
if address is None:
return
if isinstance(address, str):
if not address.startswith('<command'):
self.view.window().open_file(address, ENCODED_POSITION)
return
# This is a motion in a composite command.
regions_transformer(self.view, f)
def run(self, edit, **args):
if len(jump_stack) > 0:
sublime.active_window().open_file(jump_stack.pop(), sublime.ENCODED_POSITION)
def on_done(self, index):
if index == -1:
return None
node = self.nodes[index]
view = self.window.open_file("%s:%i" % (node["file"], node["line"]),
sublime.ENCODED_POSITION)
self.select_text(view, node)
def show_preview(self, index):
node = self.nodes[index]
self.window.open_file("%s:%i" % (node["file"], node["line"]),
sublime.ENCODED_POSITION | sublime.TRANSIENT)
def run(self):
flags = sublime.CLASS_WORD_START | sublime.CLASS_WORD_END
view = self.window.active_view()
position = INFOS.go_to_tag(keyword=utils.get_node_content(view, flags),
folder=view.file_name().split(os.sep)[-2])
if position:
self.window.open_file(position, sublime.ENCODED_POSITION)
def on_done(self, index):
if index == -1:
return None
node = self.nodes[index]
self.window.open_file("%s:%i" % (node["file"], node["line"]),
sublime.ENCODED_POSITION)
def show_type_hint(self, view, point):
project_path = find_project_dir(view)
module_info = get_module_imports(project_path, view.file_name())
module, word = module_word(view, point)
if word == '':
return
if word[0] == '(' and word[-1] == ')':
word = word[1:-1]
# TODO: use module from module_word to improve accuracy
type_info = get_type(
project_path,
module_info['moduleName'],
word,
[m['module'] for m in module_info['imports']]
)
if len(type_info) == 0:
return
first_result = type_info[0]
def on_navigate(string):
view.window().open_file(string, sublime.ENCODED_POSITION)
#file_path:row:col
link_url = first_result['definedAt']['name'] + ':' + \
str(first_result['definedAt']['start'][0]) + ':' + \
str(first_result['definedAt']['start'][1])
view.show_popup('''
<p>From: <a href="%s">%s</a> </p>
<p>Type: %s </p>
''' % ( link_url,
",".join(first_result['exportedFrom']),
first_result['type']),
sublime.HIDE_ON_MOUSE_MOVE_AWAY,
point,
500, # max width
500, # max height
on_navigate)
def select(self, row):
if row >= len(self.error_lines):
return
errorline = self.error_lines[row]
sublime.active_window().open_file("%s:%d" % (errorline.file_name, errorline.line), sublime.ENCODED_POSITION)
def on_selection_modified(self, view):
if view.name() == "GoGuru Output":
if len(view.sel()) != 1:
return
if view.sel()[0].size() == 0:
return
lines = view.lines(view.sel()[0])
if len(lines) != 1:
return
line = view.full_line(lines[0])
text = view.substr(line)
# format = get_setting("guru_format")
# "filename:line:col" pattern for json
m = re.search("\"([^\"]+):([0-9]+):([0-9]+)\"", text)
# >filename:line:col< pattern for xml
if m is None:
m = re.search(">([^<]+):([0-9]+):([0-9]+)<", text)
# filename:line.col-line.col: pattern for plain
if m is None:
m = re.search("^(.+\.go):([0-9]+).([0-9]+)[-: ]", text)
if m:
w = view.window()
new_view = w.open_file(m.group(1) + ':' + m.group(2) + ':' + m.group(3), sublime.ENCODED_POSITION)
group, index = w.get_view_index(new_view)
if group != -1:
w.focus_group(group)
def on_done(self, idx):
"""Pick this error to navigate to a file."""
log.debug("Picked idx: %s", idx)
if idx < 0:
return
picked_entry = self.errors[idx]
file_str = "{file}:{row}:{col}".format(file=picked_entry['file'],
row=picked_entry['row'],
col=picked_entry['col'])
self.view.window().open_file(file_str, sublime.ENCODED_POSITION)
def on_open_declaration(location):
"""Call this callback when link to type is clicked in info popup.
Opens location with type declaration
"""
sublime.active_window().open_file(location, sublime.ENCODED_POSITION)
def handle_response(self, response, position):
window = sublime.active_window()
if response:
location = response if isinstance(response, dict) else response[0]
file_path = uri_to_filename(location.get("uri"))
start = Point.from_lsp(location['range']['start'])
file_location = "{}:{}:{}".format(file_path, start.row + 1, start.col + 1)
debug("opening location", location)
window.open_file(file_location, sublime.ENCODED_POSITION)
# TODO: can add region here.
else:
window.run_command("goto_definition")
def jump(self, transient: bool=False) -> None:
"""Jump to the selection
"""
flags = sublime.ENCODED_POSITION
if transient is True:
flags |= sublime.TRANSIENT
get_jump_history_for_view(self.view).push_selection(self.view)
sublime.active_window().open_file(self.position, flags)
if not transient:
self._toggle_indicator()
def _jump(self, filename: Union[int, str], lineno: int =None,
columno: int =None, transient: bool =False) -> None:
"""Jump to a window
"""
# process jumps from options window
if type(filename) is int:
if filename == -1:
# restore view
view = self.text.view
point = self.point
sublime.active_window().focus_view(view)
view.show(point)
if view.sel()[0] != point:
view.sel().clear()
view.sel().add(point)
return
opts = self.options[filename]
if len(self.options[filename]) == 4:
opts = opts[1:]
filename, lineno, columno = opts
flags = sublime.ENCODED_POSITION
if transient:
flags |= sublime.TRANSIENT
sublime.active_window().open_file(
'{}:{}:{}'.format(filename, lineno or 0, columno or 0),
flags
)
self._toggle_indicator(lineno, columno)
def goToLocation(cmd, src_path, caller, view):
line = caller['line'];
path = src_path + caller['filename']
# Open the file and jump to the line
new_view = view.window().open_file(path + ":%d:0" % line, sublime.ENCODED_POSITION)
if new_view.is_loading():
global g_open_callbacks_on_load
g_open_callbacks_on_load[path] = lambda: finishGoingToLocation(caller, new_view)
return
finishGoingToLocation(caller, new_view)
def on_selection_modified(self, view):
if not self.enable(view):
return
if len(list(view.sel())) == 0:
return
cursor = view.sel()[0].begin()
if "filename" in view.scope_name(cursor):
line = view.substr(view.line(cursor))
parts = [p.strip() for p in line.split(":", maxsplit=5)]
filename = os.path.join(os.path.dirname(view.window().project_file_name()), parts[0])
view.window().open_file(filename + ":" + parts[1] + ":" + parts[2], sublime.ENCODED_POSITION)
def on_navigate(self, href):
href_s = href.split('@')
pos = sublime.Region(0,0)
v = self.view.window().open_file(href_s[1], sublime.ENCODED_POSITION)
############################################################################
# Helper function to retrieve current module name based on cursor position #
def open_file(self, file_name):
flags = (sublime.FORCE_GROUP | sublime.ENCODED_POSITION)
self.window.open_file(file_name, group=(self.window.num_groups() - 1),
flags=flags)
def run(self, count=1, mode=None, globally=False):
def f(view, s):
if mode == modes.NORMAL:
return sublime.Region(location, location)
elif mode == modes.VISUAL:
return sublime.Region(s.a + 1, location)
elif mode == modes.INTERNAL_NORMAL:
return sublime.Region(s.a, location)
return s
current_sel = self.view.sel()[0]
self.view.sel().clear()
self.view.sel().add(current_sel)
location = self.find_symbol(current_sel, globally=globally)
if not location:
return
if globally:
# Global symbol; simply open the file; not a motion.
# TODO: Perhaps must be a motion if the target file happens to be
# the current one?
self.view.window().open_file(
location[0] + ':' + ':'.join([str(x) for x in location[2]]),
sublime.ENCODED_POSITION)
return
# Local symbol; select.
location = self.view.text_point(*location)
regions_transformer(self.view, f)
def run(self, edit, mode=None, character=None, count=1):
def f(view, s):
if mode == modes.VISUAL:
if s.a <= s.b:
if address.b < s.b:
return R(s.a + 1, address.b)
else:
return R(s.a, address.b)
else:
return R(s.a + 1, address.b)
elif mode == modes.NORMAL:
return address
elif mode == modes.INTERNAL_NORMAL:
if s.a < address.a:
return R(view.full_line(s.b).a,
view.line(address.b).b)
return R(view.full_line(s.b).b,
view.line(address.b).a)
return s
state = self.state
address = state.marks.get_as_encoded_address(character)
if address is None:
return
if isinstance(address, str):
if not address.startswith('<command'):
self.view.window().open_file(address, sublime.ENCODED_POSITION)
else:
# We get a command in this form: <command _vi_double_quote>
self.view.run_command(address.split(' ')[1][:-1])
return
regions_transformer(self.view, f)
if not self.view.visible_region().intersects(address):
self.view.show_at_center(address)
def run(self, edit, count=1, mode=None, character=None):
def f(view, s):
if mode == modes.VISUAL:
if s.a <= s.b:
if address.b < s.b:
return R(s.a + 1, address.b)
else:
return R(s.a, address.b)
else:
return R(s.a + 1, address.b)
elif mode == modes.NORMAL:
return address
elif mode == modes.INTERNAL_NORMAL:
return R(s.a, address.b)
return s
state = self.state
address = state.marks.get_as_encoded_address(character, exact=True)
if address is None:
return
if isinstance(address, str):
if not address.startswith('<command'):
self.view.window().open_file(address, sublime.ENCODED_POSITION)
return
# This is a motion in a composite command.
regions_transformer(self.view, f)
def on_found(self, path, line):
self.window.open_file(path + ':' + line, sublime.ENCODED_POSITION)
def update_run_marker(window, lldb=None):
if not lldb:
for view in window.views():
view.erase_regions("run_pointer")
return
with retry():
try:
bt = lldb.get_backtrace_for_selected_thread()
if 'bt' not in bt:
for view in window.views():
view.erase_regions("run_pointer")
return
for frame in bt['bt']:
if 'file' in frame and frame['line'] != 0:
found = False
for view in window.views():
if view.file_name() == frame['file']:
location = view.line(view.text_point(frame['line'] - 1, 0))
view.add_regions("run_pointer", [location], "entity.name.class", "Packages/SublimeAnarchyDebug/images/stop_point.png", sublime.DRAW_NO_FILL)
if not view.visible_region().contains(location):
view.show_at_center(location)
if window.active_group() == 0:
window.focus_view(view)
found = True
if not found:
grp = window.active_group()
window.focus_group(0)
view = window.open_file(frame['file'] + ":" + str(frame['line']), sublime.ENCODED_POSITION)
window.focus_group(grp)
location = view.line(view.text_point(frame['line'] - 1, 0))
view.add_regions("run_pointer", [location], "entity.name.class", "Packages/SublimeAnarchyDebug/images/stop_point.png", sublime.DRAW_NO_FILL)
if not view.visible_region().contains(location):
view.show_at_center(location)
break
except xmlrpc.client.Fault:
for view in window.views():
view.erase_regions("run_pointer")
def setCursorPosition(filePath, row, col):
if (os.path.exists(filePath)):
sublime.active_window().open_file(filePath + ":" + str(row) +
":" + str(col), sublime.ENCODED_POSITION)
else:
sublime.error_message(
"Sourcetrail is trying to jump to a file that does not exist: " + filePath)
def _open_file(self, window, file):
self.log('rui => ' + str(file.to_args()))
path_row_col = '{path}:{row}:{col}'.format(
path=file.local_path(),
row=file.row,
col=file.col)
view = window.open_file(path_row_col, sublime.ENCODED_POSITION)
def make_script(self, project_info_path, script_dir_path, script_name):
with open(project_info_path, "r+", encoding="utf-8-sig") as f:
try:
# Generate script parameters
script_key = str(uuid.uuid4())
script_id = str(uuid.uuid4())
info = json.load(f, object_pairs_hook=OrderedDict)
# TODO: check if dir or script exisits already
# Insert the new script into the project info file
resource_path = "scripts\\%s\\%s.yy" % (script_name, script_name)
new_resource_item = OrderedDict(
[("Key", script_key),
("Value", OrderedDict(
[("id", script_id),
("resourcePath", resource_path),
("resourceType", "GMScript")]
))
])
info['resources'].insert(0, new_resource_item)
info['script_order'].append(script_key)
f.seek(0)
f.write(json.dumps(info, separators=(',', ': '), indent=4))
f.truncate()
os.chdir(script_dir_path)
os.mkdir(script_name)
os.chdir(script_dir_path + "/" + script_name)
# Generate script file and open for edit
with open(script_name + ".gml", "w", encoding="utf-8-sig") as f:
window = self.view.window()
view = window.open_file(script_dir_path + "/" +
script_name + "/" + script_name + ".gml", sublime.ENCODED_POSITION)
window.focus_view(view)
# Generate and fills the script info file
with open(script_name + ".yy", "w", encoding="utf-8-sig") as f:
info = OrderedDict(
[("id", script_key),
("modelName", "GMScript"),
("mvc", "1.0"),
("name", script_name),
("IsCompatibility", False),
("IsDnD", False)
])
json.dump(info, f, separators=(',', ': '), indent=4)
except Exception as e:
print(e)
def update_cursor():
global gdb_cursor
global gdb_cursor_position
global gdb_stack_index
global gdb_stack_frame
if not get_setting("update_while_running", True) and gdb_run_status == "running":
return
res = run_cmd("-stack-info-frame", True)
if get_result(res) == "error":
if gdb_run_status != "running":
print("run_status is %s, but got error: %s" % (gdb_run_status, res))
return
currFrame = parse_result_line(res)["frame"]
gdb_stack_index = int(currFrame["level"])
if "fullname" in currFrame:
gdb_cursor = gdb_source_path.translate_remote_path(currFrame["fullname"])
gdb_cursor_position = int(currFrame["line"])
sublime.active_window().focus_group(get_setting("file_group", 0))
sublime.active_window().open_file("%s:%d" % (gdb_cursor, gdb_cursor_position), sublime.ENCODED_POSITION)
global gdb_global_command_input_focused
if gdb_global_command_input_focused == True:
sublime.active_window().focus_view(gdb_input_view)
gdb_global_command_input_focused = False
else:
gdb_cursor_position = 0
sameFrame = gdb_stack_frame is not None and \
gdb_stack_frame["func"] == currFrame["func"]
if sameFrame and "shlibname" in currFrame and "shlibname" in gdb_stack_frame:
sameFrame = currFrame["shlibname"] == gdb_stack_frame["shlibname"]
if sameFrame and "fullname" in currFrame and "fullname" in gdb_stack_frame:
sameFrame = currFrame["fullname"] == gdb_stack_frame["fullname"]
gdb_stack_frame = currFrame
# Always need to update the callstack since it's possible to
# end up in the current function from many different call stacks
gdb_callstack_view.update_callstack()
gdb_threads_view.update_threads()
update_view_markers()
gdb_variables_view.update_variables(sameFrame)
gdb_register_view.update_values()
gdb_disassembly_view.update_disassembly()
global gdb_first_callstack
if gdb_first_callstack == False and gdb_settings.get("debug_mode") in ["attach", "coredump"]:
gdb_first_callstack = True
gdb_breakpoint_view.sync_breakpoints()
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)