def find_executable(executable):
"""
Return the path to the given executable, or None if not found.
create_environment is used to augment PATH before searching
for the executable.
"""
env = create_environment()
for base in env.get('PATH', '').split(os.pathsep):
path = os.path.join(os.path.expanduser(base), executable)
# On Windows, if path does not have an extension, try .exe, .cmd, .bat
if sublime.platform() == 'windows' and not os.path.splitext(path)[1]:
for extension in ('.exe', '.cmd', '.bat'):
path_ext = path + extension
if can_exec(path_ext):
return path_ext
elif can_exec(path):
return path
return None
python类windows()的实例源码
def on_pre_close(self, view):
if view.file_name() is None:
return
window = view.window()
this_project_path = find_project_dir(view)
def perform():
all_views = [view for win in sublime.windows() for view in win.views()]
all_project_paths = [find_project_dir(v) for v in all_views]
all_project_paths = [p for p in all_project_paths if p is not None]
all_project_paths = list(set(all_project_paths))
if this_project_path not in all_project_paths:
stop_server(this_project_path)
window.status_message('Closed server for path:' + this_project_path)
# delay server closing for 0.5s, because we may be "switching" between files
sublime.set_timeout(perform, 500)
def clean_temp_folder():
tmp_files = os.listdir(TMP_DIR)
for win in sublime.windows():
for view in win.views():
file_name = view.file_name()
tmp_name = get_temp_name(file_name)
if tmp_name in tmp_files:
if not view.is_dirty():
tmp_file = os.path.join(TMP_DIR, tmp_name)
# check mtime
mtime1 = os.path.getmtime(file_name)
mtime2 = os.path.getmtime(tmp_file)
if mtime1 != mtime2:
# file was changed outside
view.settings().erase('prevent_detect')
continue
shutil.move(tmp_file, file_name)
tmp_files.remove(tmp_name)
for tmp_name in tmp_files:
tmp_file = os.path.join(TMP_DIR, tmp_name)
os.unlink(tmp_file)
def run(self):
for win in sublime.windows():
self.window = win
for view in self.window.views():
self.view = view
if not self.will_closing_discard(view):
continue
self.last_focused_view = self.window.active_view()
self.window.focus_view(view)
self.show_discard_prompt()
return # wait for input, then start over
sublime.run_command('exit')
#
# Rest of the commands
#
def is_hidden(self, filename, path, goto=''):
if not (path or goto): # special case for ThisPC
return False
tests = self.view.settings().get('outline_hidden_files_patterns', ['.*'])
if isinstance(tests, str):
tests = [tests]
if any(fnmatch.fnmatch(filename, pattern) for pattern in tests):
return True
if sublime.platform() != 'windows':
return False
# check for attribute on windows:
try:
attrs = ctypes.windll.kernel32.GetFileAttributesW(join(path, goto, filename))
assert attrs != -1
result = bool(attrs & 2)
except (AttributeError, AssertionError):
result = False
return result
def run(self, paths = [], application = "", extensions = "", args=[]):
application_dir, application_name = os.path.split(application)
if extensions == '*':
extensions = '.*'
if extensions == '':
items = SideBarSelection(paths).getSelectedItems()
else:
items = SideBarSelection(paths).getSelectedFilesWithExtension(extensions)
import subprocess
try:
for item in items:
if sublime.platform() == 'osx':
subprocess.Popen(['open', '-a', application] + args + [item.name()], cwd=item.dirname())
elif sublime.platform() == 'windows':
subprocess.Popen([application_name] + args + [escapeCMDWindows(item.path())], cwd=expandVars(application_dir), shell=True)
else:
subprocess.Popen([application_name] + args + [escapeCMDWindows(item.name())], cwd=item.dirname())
except:
sublime.error_message('Unable to "Open With..", probably incorrect path to application.')
def plugin_loaded():
""" plugin_loaded """
# from default/user settings
get_severity_list()
# register callback
lhs = get_prefs()
lhs.clear_on_change('lh-prefs')
lhs.add_on_change('lh-prefs', plugin_loaded)
# check all log-highlited views
wins_l = sublime.windows()
global logh_view
for w in wins_l:
view_l = w.views()
for v in view_l:
if check_syntax(v):
logh_view.append([v.id(), 0])
if v.settings().get('logh_lastv') is True:
global logh_lastv
logh_lastv = v.id()
def find_executable(executable):
"""
Return the path to the given executable, or None if not found.
create_environment is used to augment PATH before searching
for the executable.
"""
env = create_environment()
for base in env.get('PATH', '').split(os.pathsep):
path = os.path.join(os.path.expanduser(base), executable)
# On Windows, if path does not have an extension, try .exe, .cmd, .bat
if sublime.platform() == 'windows' and not os.path.splitext(path)[1]:
for extension in ('.exe', '.cmd', '.bat'):
path_ext = path + extension
if can_exec(path_ext):
return path_ext
elif can_exec(path):
return path
return None
def open(self, view):
""" Should be called if a new view is opened, and this view belongs
to the same tsconfig.json file """
if view not in self.views:
Debug('project+', "View %s added to project %s" % (view.file_name(), self.tsconfigfile))
self.views.append(view)
view.settings().set('auto_complete', self.get_setting("auto_complete"))
view.settings().set('extensions', ['ts'])
window = view.window()
if window is None:
Debug('notify', "ArcticTypescript: Window is None, why??")
return
if window not in self.windows:
Debug('project+', "New Window added to project %s" % (self.tsconfigfile, ))
self.windows.append(view.window())
def highlight_all_open_files(self):
""" update hightlights (red underline) in all files, using the errors in project """
self.errors = {}
# iterate through all open views, to remove all remaining outdated underlinings
for window in sublime.windows():
for view in window.views():
if is_ts(view):
error_regions, warning_regions, error_texts = \
self.project.errors.tssjs_to_highlighter(view)
self.errors[fn2k(view.file_name())] = error_texts
# apply regions, even if empty (that will remove every highlight in that file)
view.add_regions('typescript-error' , error_regions , 'invalid' , self.error_icon, self.underline)
view.add_regions('typescript-warnings' , warning_regions , 'invalid' , self.warning_icon, self.underline)
def on_request(self, request):
if len(sublime.windows()) == 0 or self.new_window_on_connect:
sublime.run_command('new_window')
if len(self.window_command_on_connect) > 0:
sublime.active_window().run_command(self.window_command_on_connect)
web_socket_server_thread = WebSocketServerThread(self._settings)
web_socket_server_thread.start()
while not web_socket_server_thread.get_server().get_running():
sleep(0.1)
port = web_socket_server_thread.get_server().get_port()
Utils.show_status('Connection opened')
return Response(json.dumps({"WebSocketPort": port, "ProtocolVersion": 1}),
"200 OK",
{'Content-Type': 'application/json'})
def clear_local_caches():
files = []
roots = set()
for window in sublime.windows():
# All views in a window share the same settings.
view = window.views()[0]
cwd = s_cwd(view)
local_root = File.local_root_for_cwd(cwd)
roots.add(local_root)
for root in roots:
log('Deleting local cache directory [{0}]...'.format(root))
if os.path.exists(root):
shutil.rmtree(root)
for file in files:
log("Refreshing open file [{0}]...".format(file.remote_path()))
download_file(file)
def _cleanup_views():
# Resets cursor and mode. In the case of errors loading the plugin this can
# help prevent the normal functioning of editor becoming unusable e.g. the
# cursor getting stuck in a block shape or the mode getting stuck in normal
# or visual mode.
for window in sublime.windows():
for view in window.views():
settings = view.settings()
settings.set('command_mode', False)
settings.set('inverse_caret_state', False)
# TODO should the "vintage" setting be erased too? i.e. v.settings().erase('vintage')
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()
# Create ViewEventListener instances
if len(view_event_listener_classes) > 0:
for w in sublime.windows():
for v in w.views():
attach_view(v)
def check_all_view_event_listeners():
global check_all_view_event_listeners_scheduled
check_all_view_event_listeners_scheduled = False
for w in sublime.windows():
for v in w.views():
check_view_event_listeners(v)
def run(self, string, current_window_only=True):
"""
Send a string
Args:
string (str): string of characters to send
current_window_only (bool, optional): constrain terminal search to
the current ST window only
"""
if current_window_only:
windows = [self.window]
else:
windows = sublime.windows()
term_view = None
for w in windows:
for v in w.views():
term_view = TerminalViewManager.load_from_id(v.id())
if term_view is not None:
group, index = w.get_view_index(v)
active_view = w.active_view_in_group(group)
if active_view == v:
break
if term_view is None:
utils.ConsoleLogger.log("No terminal found")
return
term_view.send_string_to_shell(string)
def create_tempdir():
"""Create a directory within the system temp directory used to create temp files."""
try:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
os.mkdir(tempdir)
# Make sure the directory can be removed by anyone in case the user
# runs ST later as another user.
os.chmod(tempdir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
except PermissionError:
if sublime.platform() != 'windows':
current_user = pwd.getpwuid(os.geteuid())[0]
temp_uid = os.stat(tempdir).st_uid
temp_user = pwd.getpwuid(temp_uid)[0]
message = (
'The SublimeLinter temp directory:\n\n{0}\n\ncould not be cleared '
'because it is owned by \'{1}\' and you are logged in as \'{2}\'. '
'Please use sudo to remove the temp directory from a terminal.'
).format(tempdir, temp_user, current_user)
else:
message = (
'The SublimeLinter temp directory ({}) could not be reset '
'because it belongs to a different user.'
).format(tempdir)
sublime.error_message(message)
from . import persist
persist.debug('temp directory:', tempdir)
def apply_to_all_views(callback):
"""Apply callback to all views in all windows."""
for window in sublime.windows():
for view in window.views():
callback(view)
# misc utils
def load(self):
Pref.view = False
Pref.elapsed_time = 0.4
Pref.running = False
Pref.wrdRx = re.compile(s.get('word_regexp', "^[^\w]?`*\w+[^\w]*$"), re.U)
Pref.wrdRx = Pref.wrdRx.match
Pref.splitRx = s.get('word_split', None)
if Pref.splitRx:
Pref.splitRx = re.compile(Pref.splitRx, re.U)
Pref.splitRx = Pref.splitRx.findall
Pref.enable_live_count = s.get('enable_live_count', True)
Pref.enable_readtime = s.get('enable_readtime', False)
Pref.enable_line_word_count = s.get('enable_line_word_count', False)
Pref.enable_line_char_count = s.get('enable_line_char_count', False)
Pref.enable_count_lines = s.get('enable_count_lines', False)
Pref.enable_count_chars = s.get('enable_count_chars', False)
Pref.enable_count_pages = s.get('enable_count_pages', True)
Pref.words_per_page = s.get('words_per_page', 300)
Pref.page_count_mode_count_words = s.get('page_count_mode_count_words', True)
Pref.char_ignore_whitespace = s.get('char_ignore_whitespace', True)
Pref.readtime_wpm = s.get('readtime_wpm', 200)
Pref.whitelist = [x.lower() for x in s.get('whitelist_syntaxes', []) or []]
Pref.blacklist = [x.lower() for x in s.get('blacklist_syntaxes', []) or []]
Pref.strip = s.get('strip', [])
for window in sublime.windows():
for view in window.views():
view.erase_status('WordCount');
view.settings().erase('WordCount')
def dxProjectFolder(self):
for window in sublime.windows():
folder = self.get_dx_folder_for_window(window)
if folder != '':
return folder
return ''
def plugin_loaded():
for win in sublime.windows():
for view in win.views():
initial(view)
def setup_views():
clean_temp_folder()
# check existing views
for win in sublime.windows():
for view in win.views():
if not get_setting(view, 'convert_on_load'):
break
view.settings().set('is_init_dirty_state', view.is_dirty())
if view.is_dirty() or view.settings().get('origin_encoding'):
show_encoding_status(view)
continue
file_name = view.file_name()
cnt = get_setting(view, 'max_detect_lines')
threading.Thread(target=lambda: detect(view, file_name, cnt)).start()
def wait_for_ready():
if sublime.windows():
setup_views()
else:
sublime.set_timeout(wait_for_ready, 100)
def retarget_all_views(source, destination):
if source[-1] != os.path.sep:
source += os.path.sep
if destination[-1] != os.path.sep:
destination += os.path.sep
for window in sublime.windows():
for view in window.views():
filename = view.file_name()
if os.path.commonprefix([source, filename]) == source:
view.retarget(
os.path.join(destination, filename[len(source):])
)
def retarget_view(source, destination):
source = os.path.normcase(os.path.abspath(source))
destination = os.path.normcase(os.path.abspath(destination))
for window in sublime.windows():
for view in window.views():
path = os.path.abspath(view.file_name())
if os.path.normcase(path) == source:
view.retarget(destination)
def hijack_window():
'''Execute on loading plugin or on new window open;
allow to open FB automatically in ST3
'''
settings = sublime.load_settings('outline.sublime-settings')
command = settings.get("outline_hijack_new_window")
if command:
if command == "jump_list":
sublime.set_timeout(lambda: sublime.windows()[-1].run_command("outline_jump_list"), 1)
else:
sublime.set_timeout(lambda: sublime.windows()[-1].run_command("outline", {"immediate": True}), 1)
def get_all_project_names():
"Return a list of all open project names"
windows = sublime.windows()
varses = [w.extract_variables() for w in windows]
project_names = [v.get('project_base_name') for v in varses]
return project_names
def window_set_status(key, name =''):
for window in sublime.windows():
for view in window.views():
view.set_status('SideBar-'+key, name)
def _delete_threaded(self, paths):
key = 'delete-'+str(time.time())
window_set_status(key, 'Deleting…')
try:
from .send2trash import send2trash
for item in SideBarSelection(paths).getSelectedItemsWithoutChildItems():
if s.get('close_affected_buffers_when_deleting_even_if_dirty', False):
item.closeViews()
if s.get('disable_send_to_trash', False):
if sublime.platform() == 'windows':
self.remove('\\\\?\\'+item.path());
else:
self.remove(item.path());
else:
send2trash(item.path())
SideBarProject().refresh();
except:
should_confirm = s.get('confirm_before_permanently_deleting', True)
if not should_confirm or sublime.ok_cancel_dialog('There is no trash bin, permanently delete?', 'Yes, Permanent Deletion'):
for item in SideBarSelection(paths).getSelectedItemsWithoutChildItems():
if s.get('close_affected_buffers_when_deleting_even_if_dirty', False):
item.closeViews()
if sublime.platform() == 'windows':
self.remove('\\\\?\\'+item.path());
else:
self.remove(item.path());
SideBarProject().refresh();
window_set_status(key, '')
def on_done(self, old, new):
if s.get('close_affected_buffers_when_deleting_even_if_dirty', False):
item = SideBarItem(new, os.path.isdir(new))
item.closeViews()
if sublime.platform() == 'windows':
self.remove('\\\\?\\'+new);
else:
self.remove(new)
SideBarProject().refresh();