def blink(times=4, delay=55):
prefs = load_settings('Preferences.sublime-settings')
if prefs.get('vintageous_visualbell') is False:
return
v = active_window().active_view()
settings = v.settings()
# Ensure we leave the setting as we found it.
times = times if (times % 2) == 0 else times + 1
def do_blink():
nonlocal times
if times > 0:
settings.set('highlight_line', not settings.get('highlight_line'))
times -= 1
set_timeout(do_blink, delay)
do_blink()
python类active_window()的实例源码
def run(self):
sublime.run_command('new_window')
new_window = sublime.active_window()
new_window.run_command('set_layout', {
'cols': [0.0, 0.5, 1.0],
'rows': [0.0, 1.0],
'cells': [[0, 0, 1, 1], [1, 0, 2, 1]]
})
new_window.focus_group(0)
edit_view = new_window.new_file()
edit_view_settings = edit_view.settings()
edit_view_settings.set('minihtml_preview_edit_view', True)
edit_view.set_scratch(True)
edit_view.set_syntax_file('Packages/HTML/HTML.sublime-syntax')
# Unfortunately Sublime indents on 'insert'
edit_view.settings().set('auto_indent', False)
edit_view.run_command('insert', {'characters': template})
edit_view.settings().set('auto_indent', True)
new_window.focus_group(1)
output_view = new_window.new_file()
output_view.set_scratch(True)
edit_view_settings.set('minihtml_preview_output_view_id',
output_view.id())
new_window.focus_group(0)
def help_view(window=None):
"""
Find and return the help view for the provided window. If no window is
provided, the currently active window is checked instead.
The return value is the view on success or None if there is currently no
help view in the window.
"""
window = window if window is not None else sublime.active_window()
view = find_view(window, "HyperHelp")
if view is not None:
settings = view.settings()
if settings.has("_hh_package") and settings.has("_hh_file"):
return view
return None
def on_api_ready():
global api_ready
api_ready = True
for m in list(sys.modules.values()):
if "plugin_loaded" in m.__dict__:
try:
m.plugin_loaded()
except:
traceback.print_exc()
# Synthesize an on_activated call
w = sublime.active_window()
if w:
view_id = sublime_api.window_active_view(w.window_id)
if view_id != 0:
try:
on_activated(view_id)
except:
traceback.print_exc()
def wait_for_open(self, dest):
"""Wait for new linter window to open in another thread."""
def open_linter_py():
"""Wait until the new linter window has opened and open linter.py."""
start = datetime.datetime.now()
while True:
time.sleep(0.25)
delta = datetime.datetime.now() - start
# Wait a maximum of 5 seconds
if delta.seconds > 5:
break
window = sublime.active_window()
folders = window.folders()
if folders and folders[0] == dest:
window.open_file(os.path.join(dest, 'linter.py'))
break
sublime.set_timeout_async(open_linter_py, 0)
def plugin_loaded():
"""The ST3 entry point for plugins."""
persist.plugin_is_loaded = True
persist.settings.load()
persist.printf('debug mode:', 'on' if persist.debug_mode() else 'off')
util.create_tempdir()
for linter in persist.linter_classes.values():
linter.initialize()
plugin = SublimeLinter.shared_plugin()
queue.start(plugin.lint)
util.generate_menus()
util.generate_color_scheme(from_reload=False)
persist.settings.on_update_call(SublimeLinter.on_settings_updated)
# This ensures we lint the active view on a fresh install
window = sublime.active_window()
if window:
plugin.on_activated(window.active_view())
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(self, edit):
flags = sublime.CLASS_WORD_START | sublime.CLASS_WORD_END
path = utils.get_node_content(self.view, flags)
imagepath = INFOS.addon.translate_path(path)
if not os.path.exists(imagepath):
return None
if os.path.isdir(imagepath):
self.files = []
for (_dirpath, _dirnames, filenames) in os.walk(imagepath):
self.files.extend(filenames)
break
self.files = [imagepath + s for s in self.files]
else:
self.files = [imagepath]
sublime.active_window().show_quick_panel(items=self.files,
on_select=self.on_done,
selected_index=0,
on_highlight=self.show_preview)
def run(self, edit):
self.label_ids = []
self.labels = []
region = self.view.sel()[0]
if region.begin() == region.end():
logging.critical("Please select the complete label")
return False
word = self.view.substr(region)
for po_file in INFOS.get_po_files():
for entry in po_file:
if entry.msgid.lower() == word.lower() and entry.msgctxt not in self.label_ids:
self.label_ids.append(entry.msgctxt)
self.labels.append(["%s (%s)" % (entry.msgid, entry.msgctxt), entry.comment])
self.labels.append("Create new label")
sublime.active_window().show_quick_panel(items=self.labels,
on_select=lambda s: self.on_done(s, region),
selected_index=0)
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 handle_diagnostics(update: 'Any'):
util.debug('handling diagnostics')
file_path = util.uri_to_filename(update.get('uri'))
window = sublime.active_window()
if not util.is_apex_file(window.active_view()):
util.debug("Skipping diagnostics for file", file_path,
" it is not in the workspace")
return
diagnostics = list(
Diagnostic.from_lsp(item) for item in update.get('diagnostics', []))
view = window.find_open_file(file_path)
# diagnostics = update.get('diagnostics')
update_diagnostics_in_view(view, diagnostics)
# update panel if available
origin = 'dxmate' # TODO: use actual client name to be able to update diagnostics per client
update_file_diagnostics(window, file_path, origin, diagnostics)
def run_command(self):
dx_folder = util.dxProjectFolder()
args = ['sfdx', 'force:visualforce:page:create',
'-n', self.page_name,'-l', self.page_label, '-d', self.class_dir]
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)
p.wait()
out, err = p.communicate()
r = p.returncode
if p.returncode == 0:
printer.write('\nVisaulforce page created')
file = os.path.join(self.class_dir, self.page_name + '.page')
sublime.active_window().open_file(file)
else:
printer.write('\nError creating Visualforce page:')
printer.write('\n' + str(err, 'utf-8'))
def run_command(self):
dx_folder = util.dxProjectFolder()
args = ['sfdx', 'force:lightning:component:create',
'-n', self.cmp_name, '-d', self.class_dir]
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)
p.wait()
out, err = p.communicate()
r = p.returncode
if p.returncode == 0:
printer.write('\nLightning Component created')
file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp')
sublime.active_window().open_file(file)
else:
printer.write('\nError creating Lightning Component:')
printer.write('\n' + str(err, 'utf-8'))
def run_command(self):
dx_folder = util.dxProjectFolder()
args = ['sfdx', 'force:lightning:component:create',
'-n', self.cmp_name, '-d', self.class_dir]
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)
p.wait()
out, err = p.communicate()
r = p.returncode
if p.returncode == 0:
printer.write('\nLightning Component created')
file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp')
sublime.active_window().open_file(file)
else:
printer.write('\nError creating Lightning Component:')
printer.write('\n' + str(err, 'utf-8'))
def run_command(self):
dx_folder = util.dxProjectFolder()
args = ['sfdx', 'force:lightning:test:create',
'-n', self.event_name, '-d', self.class_dir]
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)
p.wait()
out, err = p.communicate()
r = p.returncode
if p.returncode == 0:
printer.write('\nLightning Test created')
file = os.path.join(self.class_dir, self.event_name + '.resource')
sublime.active_window().open_file(file)
else:
printer.write('\nError creating Lightning Test:')
printer.write('\n' + str(err, 'utf-8'))
def run_command(self):
dx_folder = util.dxProjectFolder()
args = ['sfdx', 'force:lightning:interface:create',
'-n', self.event_name, '-d', self.class_dir]
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)
p.wait()
out, err = p.communicate()
r = p.returncode
if p.returncode == 0:
printer.write('\nLightning Interface created')
file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf')
sublime.active_window().open_file(file)
else:
printer.write('\nError creating Lightning Interface:')
printer.write('\n' + str(err, 'utf-8'))
def run_command(self):
dx_folder = util.dxProjectFolder()
args = ['sfdx', 'force:lightning:event:create',
'-n', self.event_name, '-d', self.class_dir]
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)
p.wait()
out, err = p.communicate()
r = p.returncode
if p.returncode == 0:
printer.write('\nLightning Event created')
file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt')
sublime.active_window().open_file(file)
else:
printer.write('\nError creating Lightning Event:')
printer.write('\n' + str(err, 'utf-8'))
def run_command(self):
dx_folder = util.dxProjectFolder()
args = ['sfdx', 'force:lightning:app:create',
'-n', self.app_name, '-d', self.class_dir]
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)
p.wait()
out, err = p.communicate()
r = p.returncode
if p.returncode == 0:
printer.write('\nLightning App created')
file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app')
sublime.active_window().open_file(file)
else:
printer.write('\nError creating Lightning App:')
printer.write('\n' + str(err, 'utf-8'))
def run_command(self):
dx_folder = util.dxProjectFolder()
args = ['sfdx', 'force:apex:class:create',
'-n', self.class_name, '-d', self.class_dir]
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)
p.wait()
out, err = p.communicate()
r = p.returncode
if p.returncode == 0:
printer.write('\nApex class created')
file = os.path.join(self.class_dir, self.class_name + '.cls')
sublime.active_window().open_file(file)
else:
printer.write('\nError creating Apex Class:')
printer.write('\n' + str(err, 'utf-8'))
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 mm_project_directory(window=None):
if window == None:
window = sublime.active_window()
folders = window.folders()
if len(folders) > 0:
return window.folders()[0]
# def get_project_settings(window=None):
# if window == None:
# window = sublime.active_window()
# try:
# return parse_json_from_file(os.path.join(window.folders()[0],"config",".settings"))
# except:
# # raise BaseException("Could not load project settings")
# print("Could not load project settings")
def run(self, edit):
settings = setting.load()
self.settings = settings
projects = settings["projects"]
default_project = settings["default_project"]
dirs = []
dirs_result = []
for project_key in projects.keys():
project_value = projects[project_key]
if default_project == project_key:
tmp = '[?]' + project_key
else:
tmp = '[X]' + project_key
dirs.append(tmp)
dirs_result.append(project_key)
self.results = dirs_result
window = sublime.active_window()
window.show_quick_panel(dirs, self.panel_done,
sublime.MONOSPACE_FONT)
def plugin_loaded():
global currentSettings, language, currentView
currentSettings = sublime.load_settings(setting_file)
language = currentSettings.get('language')
currentView = sublime.active_window().active_view()
docphpPath = getDocphpPath()
if not os.path.isdir(docphpPath + 'language'):
os.makedirs(docphpPath + 'language')
if not callable(sublime_symbol.symbol_at_point) or not callable(sublime_symbol.navigate_to_symbol):
sublime.error_message('Cannot find symbol_at_point from Default.sublime-package\n\nPlease restore the file which usually replaced by outdated localizations')
from package_control import events
if events.install(package_name) or not language:
currentView.run_command('docphp_checkout_language', {"is_init": True, "set_fallback": True})
def run(self, edit):
# get the cursor point
sel = self.view.sel()[0]
# get the current scope by cursor position
current_scope = self.view.scope_name(sel.begin())
# print(current_file_source)
tooltip_files_arr = self.get_tooltip_files(current_scope)
# get user selection
sel = self.get_user_selection(sel)
# do match with user selection and return the result
results = self.match_selection(sel, tooltip_files_arr)
# print("len results: " + str(len(results)))
for result in results:
# get the correct link if there is
link = self.has_link(result)
# edit the result in html for tooltip window
html_tooltip = Utilities.result_format(result['json_result'], self.keyorder, link)
self.results_arr.append(html_tooltip)
names = self.get_file_names(results)
# print("len results_arr: " + str(len(self.results_arr)))
if len(self.results_arr) == 1:
self.show_popup_with_timeout(self.results_arr[0])
elif len(self.results_arr) > 1:
sublime.active_window().show_quick_panel(names, self.on_done, sublime.MONOSPACE_FONT)
def get_project_dir():
view = sublime.active_window().active_view()
if not view:
return None
fn = view.file_name()
if not fn:
return None
fn = normalize(fn)
folders = sublime.active_window().folders()
if not folders:
return None
for folder in folders:
if fn.startswith(folder + os.sep):
return folder
return None
def get_setting(key, default=None, view=None):
return gdb_settings.get(key, default)
try:
if view is None:
view = sublime.active_window().active_view()
s = view.settings()
# Try executable specific settings first
if exec_settings and key in exec_settings:
return exec_settings[key]
# Then try user settings
if s.has("sublimegdb_%s" % key):
return s.get("sublimegdb_%s" % key)
except:
pass
# Default settings
return sublime.load_settings("SublimeGDB.sublime-settings").get(key, default)
def update_view_markers(view=None):
if view is None:
view = sublime.active_window().active_view()
fn = view.file_name()
if fn is not None:
fn = normalize(fn)
pos_scope = get_setting("position_scope", "entity.name.class")
pos_icon = get_setting("position_icon", "bookmark")
cursor = []
if fn == gdb_cursor and gdb_cursor_position != 0:
cursor.append(view.full_line(view.text_point(gdb_cursor_position - 1, 0)))
global gdb_last_cursor_view
if gdb_last_cursor_view is not None:
gdb_last_cursor_view.erase_regions("sublimegdb.position")
gdb_last_cursor_view = view
view.add_regions("sublimegdb.position", cursor, pos_scope, pos_icon, sublime.HIDDEN)
gdb_callstack_view.update_marker(pos_scope, pos_icon)
gdb_threads_view.update_marker(pos_scope, pos_icon)
gdb_breakpoint_view.update_marker(view)
def create_view(self, errors):
if not self.view:
self.view = sublime.active_window().new_file()
self.view.set_name(self.name)
self.view.set_scratch(True)
self.view.set_read_only(True)
# Setting command_mode to false so that vintage
# does not eat the "enter" keybinding
self.view.settings().set('command_mode', False)
self.closed = False
self.view.run_command("error_view_clear")
self.lines = ""
self.end = -1
for e in errors:
self.add_line(e)
self.view.run_command("error_view_add_line", {"line": self.lines, "doScroll": True})
def run(self, index=None, **args):
command = args.get('command')
active_file_path = self.__active_file_path()
active_folders = sublime.active_window().folders()
if command == 'mlist':
self.__beagle = Phoenix(active_file_path + 'beagle_migrations', self.__patterns(), active_folders)
self.window.show_quick_panel(self.__beagle.descriptions(), self.__open_file)
else:
if not active_folders:
active_folders = os.path.split(active_file_path)[0]
sublime.error_message("SideBar is empty!")
if active_file_path:
if self.__patterns():
self.__beagle = Phoenix(active_file_path, self.__patterns(), active_folders)
self.window.show_quick_panel(self.__beagle.descriptions(), self.__open_file)
else:
self.__status_msg("Patterns are not loaded!")
else:
self.__status_msg("No open files")