def handle_response(self, response, point): if response is not None: self._signatures = response.get("signatures", []) self._active_signature = response.get("activeSignature", -1) if self._signatures: if not 0 <= self._active_signature < len(self._signatures): debug( "activeSignature {} not a valid index for signatures length {}" .format(self._active_signature, len(self._signatures))) self._active_signature = 0 else: if self._active_signature != -1: debug( "activeSignature should be -1 or null when no signatures are returned" ) self._active_signature = -1 if len(self._signatures) > 0: mdpopups.show_popup( self.view, self._build_popup_content(), css=popup_css, md=True, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, wrapper_class=popup_class, max_width=800, on_hide=self._on_hide, on_navigate=lambda href: self._on_hover_navigate(href)) self._visible = True
def run(self): if self.checkword(self.word): json_data = self.acquiredata(self.word) snippet = '!!! panel-success "' + self.args + '"\n' format_data = json_data = self.format(json_data) self.parse_to_clipboard(format_data) snippet += format_data else: snippet = '!!! panel-error "Error"\n' + " 忘记选字了吧?\n" settings = sublime.load_settings("cndict.sublime-settings") if settings.get("format") == "phantom": mdpopups.add_phantom( view=self.view, key="trans", region=self.view.sel()[0], content=snippet, layout=sublime.LAYOUT_BELOW, on_navigate=self.on_close_phantom_and_popup, md=True) elif settings.get("format") == "pannel": print("pannel") board = self.window.create_output_panel("trans") board.run_command('append', {'characters': snippet}) self.window.run_command("show_panel", {"panel": "output.trans"}) else: mdpopups.show_popup( view=self.view, content=snippet, on_navigate=self.on_close_phantom_and_popup, md=True)
def show_popup(self, symbol, symbolDescription): output = symbolDescription if getSetting('debug'): print(output) self.currentSymbol = symbol width, height = self.view.viewport_extent() output = self.formatPopup(output, symbol=symbol) # It seems sublime will core when the output is too long # In some cases the value can set to 76200, but we use a 65535 for safety. output = output[:65535] if output else '' popups, popups_classname = self.getCss() mdpopups.show_popup(self.view, output, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, css=popups, wrapper_class=popups_classname, max_width=min(getSetting('popup_max_width', 0), width), max_height=min(getSetting('popup_max_height', 0), height), on_navigate=self.on_navigate, on_hide=self.on_hide) stop_indicator()
def show_signature(view, point, flags): """Display a documentation signature popup using `gogetdoc`. """ results = util.info_for_symbol(view, point) if results.get('decl', '').startswith('package'): md = IMPORT_SIG.format(path='import "{0}"'.format(results['import'])) elif results.get('decl', '').startswith('var'): path = results['decl'].split(' ')[-1] if '/' in path: # Don't show the full import path. results['decl'] = re.sub('[\w.]+/', '', path) md = VAR_SIG.format(declaration=results['decl']) elif results.get('decl') and results.get('doc'): md = SIGNATURE.format(declaration=results['decl'], documentation=format_doc(results['doc'])) else: # We don't have enough information to show a popup. util.set_status('No information on symbol.') return mdpopups.show_popup( view, content=md, flags=flags, css=sublime.load_resource(util.get_setting('popup_css')), location=point, max_width=util.get_setting('popup_width'), wrapper_class='gide', on_navigate=lambda x: handle_hint_navigation(x, results))
def run(self): if self.checkword(self.word): json_data = self.acquiredata(self.word) snippet = '!!! panel-success "' + self.args + '"\n' format_data = json_data = self.format(json_data) self.parse_to_clipboard(format_data) snippet += format_data else: snippet = '!!! panel-error "Error"\n' + " 忘记选字了吧?\n" settings = sublime.load_settings("cndict.sublime-settings") if settings.get("format") == "phantom": mdpopups.add_phantom(view=self.view, key="trans", region=self.view.sel()[0], content=snippet, layout=sublime.LAYOUT_BELOW, on_navigate=self.on_close_phantom_and_popup, md=True) elif settings.get("format") == "pannel": print("pannel") board = self.window.create_output_panel("trans") board.run_command('append', {'characters': snippet}) self.window.run_command("show_panel", {"panel": "output.trans"}) else: mdpopups.show_popup(view=self.view, content=snippet, on_navigate=self.on_close_phantom_and_popup, md=True)
def show_hover(self, point, contents): formatted = [] if not isinstance(contents, list): contents = [contents] for item in contents: value = "" language = None if isinstance(item, str): value = item else: value = item.get("value") language = item.get("language") if language: formatted.append("```{}\n{}\n```\n".format(language, value)) else: formatted.append(value) mdpopups.show_popup( self.view, "\n".join(formatted), css=popup_css, md=True, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, wrapper_class=popup_class, max_width=800, on_navigate=lambda href: self.on_hover_navigate(href))
def run(self) -> None: view = self.window.active_view() if view: syntax = view.settings().get("syntax") or "" available_config = get_global_client_config( view, client_configs.all) syntax_name = extract_syntax_name(syntax) title = "# Language Server for {}\n".format(syntax_name) if available_config: content = supported_syntax_template.format(syntax_name) else: title = "# No Language Server support" content = unsupported_syntax_template.format(syntax_name) mdpopups.show_popup(view, "\n".join([title, content]), css=''' .lsp_documentation { margin: 1rem 1rem 0.5rem 1rem; font-family: system; } .lsp_documentation h1, .lsp_documentation p { margin: 0 0 0.5rem 0; } ''', md=True, wrapper_class="lsp_documentation", max_width=800, max_height=600, on_navigate=self.on_hover_navigate)
def show_hover(self, point, contents): formatted = [] if not isinstance(contents, list): contents = [contents] for item in contents: value = "" language = None if isinstance(item, str): value = item else: value = item.get("value") language = item.get("language") if language: formatted.append("```{}\n{}\n```".format(language, value)) else: formatted.append(value) mdpopups.show_popup( self.view, preserve_whitespace("\n".join(formatted)), css=".mdpopups .lsp_hover { margin: 4px; } .mdpopups p { margin: 0.1rem; }", md=True, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, wrapper_class="lsp_hover", max_width=800)
def show_unmatched_popup(self, view, point): """Show unmatched popup.""" if HOVER_SUPPORT: self.popup_view = view mdpopups.show_popup( view, textwrap.dedent( """ ### Matching bracket could not be found! {: .error} - There *might* be no match. - Brackets *might* be nested poorly --> `([)(])` - Matching bracket *might* be beyond the search threshold. A match done without the threshold *might* find it. [(Match brackets without threshold)](%d) """ % point ), wrapper_class=WRAPPER_CLASS, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, css=CSS, max_width=800, max_height=800, location=point, on_navigate=self.on_navigate_unmatched )
def _show_tooltip(self, sections): cursor = self.view.sel()[0].begin() line = self.view.line(cursor) line_content = self.view.substr(line) if line_content.startswith('-'): task = None for s in sections: task = s.find_by_line(line_content) if task is not None: break if task: content = '' categories = task.categories() max_len = max([len(c) for c in categories]) data = [] for cat in categories: data.append((cat, task.scheduled_start_date(cat).date(), task.scheduled_end_date(cat).date())) data = sorted(data, key=itemgetter(1)) for d in data: if d[1] == d[2]: content += '{:.>{}}: {}\n\n'.format( d[0], max_len, d[1]) else: content += '{:.>{}}: {} - {}\n\n'.format( d[0], max_len, d[1], d[2]) mdpopups.show_popup(self.view, content)
def run_async(self, pkg, funct, point=-1): if not funct: pkg, funct = self.function_name_at_point(self.view, point) if not pkg: pkg = namespace_manager.find_object_in_packages(funct) funct_call = namespace_manager.get_function_call(pkg, funct) if not funct_call: return with preference_temporary_settings("mdpopups.use_sublime_highlighter", True): with preference_temporary_settings( "mdpopups.sublime_user_lang_map", {"s": [["r"], ["R/R.sublime-syntax"]]}): text = POPUP_TEMPLATE.format( mdpopups.syntax_highlight( self.view, funct_call.strip(), language="r"), pkg, funct) mdpopups.show_popup( self.view, text, css=POPUP_CSS, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE | sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, max_width=800, on_navigate=lambda x: self.on_navigate(x, pkg, funct, point))
def run(self): view = self.window.active_view() syntax = view.settings().get("syntax") available_config = get_global_client_config(view) syntax_name = extract_syntax_name(syntax) title = "# Language Server for {}\n".format(syntax_name) if available_config: content = supported_syntax_template.format(syntax_name) else: title = "# No Language Server support" content = unsupported_syntax_template.format(syntax_name) mdpopups.show_popup( view, "\n".join([title, content]), css=''' .code_intel_documentation { margin: 1rem 1rem 0.5rem 1rem; font-family: system; } .code_intel_documentation h1, .code_intel_documentation p { margin: 0 0 0.5rem 0; } ''', md=True, wrapper_class="code_intel_documentation", max_width=800, max_height=600, on_navigate=self.on_hover_navigate )
def show_popup_between(self, view, point, region, region2, icon): """Show popup between.""" if HOVER_SUPPORT: markup = '' if not self.is_bracket_visible(view, region): markup += self.get_markup(view, point, region, icon) if not self.is_bracket_visible(view, region2): markup += '\n\n' markup += self.get_markup(view, point, region2, icon) if markup: self.popup_view = view mdpopups.show_popup( view, markup, wrapper_class=WRAPPER_CLASS, css=CSS, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, max_width=800, location=point, on_navigate=self.on_navigate, template_vars={'mdpopups_version': mdpopups.version()}, template_env_options=template_options ) else: self.show_unmatched_popup(view, point)
def show_panel(self, pos=None): mdpopups.show_popup(self.view, self._first(), location=pos if pos else -1, max_width=800, max_height=600, allow_code_wrap=True)
def show_color_info(self, update=False): """Show the color under the cursor.""" color = self.get_cursor_color() template_vars = {} if color is not None: html = [] html.append(self.format_info(color, template_vars)) if update: mdpopups.update_popup( self.view, util.FRONTMATTER + sublime.load_resource( 'Packages/ColorHelper/panels/info.html'), wrapper_class="color-helper content", css=util.ADD_CSS, template_vars=template_vars) else: mdpopups.show_popup( self.view, util.FRONTMATTER + sublime.load_resource( 'Packages/ColorHelper/panels/info.html'), wrapper_class="color-helper content", css=util.ADD_CSS, location=-1, max_width=1024, max_height=512, on_navigate=self.on_navigate, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, template_vars=template_vars) elif update: self.view.hide_popup()
def initialize_ProgressBar( self, view ): #▒▒▒ Text ▒▒▒# self.popUp_Label_InProgress = "PROGRESS:" self.popUp_Label_Complete = "COMPLETE!" #▒▒▒ Progress Tracking ▒▒▒# self.maxPercent = 100 self.updateFrequency = 50 # In Milliseconds #▒▒▒ Dimensions ▒▒▒# self.popupWidth = 500 self.popupMaxHeight = 500 self.progressBar_Height = 21 #▒▒▒ Colors ▒▒▒# self.progressBar_Incomplete_Color = "#0B121A" self.progressBar_Complete_Color = "#57BB80" self.progressBar_Progress_Color = "#5A91BC" self.progressBar_BorderColor = "#000000" self.popupCSS = sublime.load_resource( sublime.find_resources( "ProgressBarDemo_ProgressBar.css" )[ 0 ] ) self.progressBar_Width = int( float( self.popupWidth * 0.8 ) ) self.progressPercent = 0 mdpopups.show_popup( view, # view "", # content True, # markdown self.popupCSS, # css 0, # flags -1, # location self.popupWidth, # width self.popupMaxHeight # height )
def show_lsp_popup(view: sublime.View, contents: str, location: int = -1, md: bool = False, flags: int = 0, css: Optional[str] = None, wrapper_class: Optional[str] = None, on_navigate: Optional[Callable] = None, on_hide: Optional[Callable] = None) -> None: css = css if css is not None else lsp_css().popups wrapper_class = wrapper_class if wrapper_class is not None else lsp_css( ).popups_classname contents += LSP_POPUP_SPACER_HTML mdpopups.show_popup( view, contents, css=css, md=md, flags=flags, location=location, wrapper_class=wrapper_class, max_width=int(view.em_width() * float(userprefs().popup_max_characters_width)), max_height=int(view.line_height() * float(userprefs().popup_max_characters_height)), on_navigate=on_navigate)
def display(view, msg): mdpopups.show_popup(view, msg, css="default.css", location=-1, max_width=600, max_height=350, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE)
def show_insert(self, color, dialog_type, palette_name=None, update=False, raw=None): """Show insert panel.""" original = color color = Color(color) sels = self.view.sel() if color is not None and len(sels) == 1: outputs = [] if raw is not None: outputs.append((util.encode_color(raw), util.html_encode(raw))) custom = self.custom_color_class(color) for output in self.output_options: params = output.get("format", {}) value = custom.convert(output["space"]).to_string(**params) outputs.append( (util.encode_color(value), util.html_encode(value))) template_vars = { "dialog_type": dialog_type, "palette_name": palette_name, "current_color": original, "tool_color": util.encode_color(raw if raw else color.to_string( **util.COLOR_FULL_PREC)) } template_vars['outputs'] = outputs if update: mdpopups.update_popup( self.view, util.FRONTMATTER + sublime.load_resource( 'Packages/ColorHelper/panels/insert.html'), wrapper_class="color-helper content", css=util.ADD_CSS, template_vars=template_vars) else: mdpopups.show_popup( self.view, util.FRONTMATTER + sublime.load_resource( 'Packages/ColorHelper/panels/insert.html'), wrapper_class="color-helper content", css=util.ADD_CSS, location=-1, max_width=1024, max_height=512, on_navigate=self.on_navigate, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, template_vars=template_vars)
def show_popup(text): """Show the popup.""" close = '\n[(close)](#)' view = active_view() region = view.visible_region() mdpopups.show_popup(active_view(), text + close, location=region.a, on_navigate=on_close_popup)
def show_colors(self, palette_type, palette_name, delete=False, update=False): """Show colors under the given palette.""" target = None current = False if palette_type == "__special__": if palette_name == "Current Colors": current = True target = { "name": palette_name, "colors": self.view.settings().get('color_helper_file_palette', []) } elif palette_name == "Project Colors": data = self.view.window().project_data() current = True target = { "name": palette_name, "colors": [] if data is None else data.get('color_helper_project_palette', []) } elif palette_name == "Favorites": target = util.get_favs() elif palette_type == "__global__": for palette in util.get_palettes(): if palette_name == palette['name']: target = palette elif palette_type == "__project__": for palette in util.get_project_palettes(self.view.window()): if palette_name == palette['name']: target = palette if target is not None: html = [] if not delete: html.append(BACK_PALETTE_MENU) if not current: html.append(DELETE_COLOR_MENU % (palette_type, target['name'])) else: html.append(BACK_COLORS_MENU % (palette_type, target['name'])) if delete: html.append(DELETE_COLOR) html.append( self.format_colors(target['colors'], target['name'], palette_type, delete) ) if update: mdpopups.update_popup(self.view, ''.join(html), css=ADD_CSS) else: mdpopups.show_popup( self.view, ''.join(html), location=-1, max_width=600, on_navigate=self.on_navigate, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, css=ADD_CSS )
def show(self, view, location=-1, on_navigate=None): """Show this popup.""" mdpopups.show_popup(view, self.as_markdown(), max_width=Popup.MAX_POPUP_WIDTH, max_height=Popup.MAX_POPUP_HEIGHT, wrapper_class=Popup.WRAPPER_CLASS, css=self.CSS, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=location, on_navigate=on_navigate)
def show_hover(self, point, contents): mdpopups.show_popup( self.view, contents, css=popup_css, md=False, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, wrapper_class=popup_class, max_width=800, on_navigate=lambda href: self.on_hover_navigate(href, point))
def show_popup(text): """Show the popup.""" clear_cache() close = '\n[close](#){: .btn .btn-small .btn-info}\n' view = active_view() region = view.visible_region() mdpopups.show_popup( active_view(), text + close, location=region.a, on_navigate=on_close_popup, max_height=650, max_width=600, wrapper_class='mdpopups-test', css='div.mdpopups-test { padding: 0.5rem; }' )
def show_errors(self, view, errs): if not errs: return None _pre = '<div class="invalid"> Haxe Errors </div>' _css = 'div { margin:0.3em; } .flow-error-line { margin-left:1em; margin-right:2em; }' _res = '' for _err in errs: _res += '<div class="flow-error-line">' + _err + '</div>' mdpopups.show_popup(view, _pre + _res, css=_css, max_width=1280)
def _show_popup(self, point: int) -> None: mdpopups.show_popup(self.view, self._build_popup_content(), css=popup_css, md=True, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, wrapper_class=popup_class, max_width=800, on_hide=self._on_hide, on_navigate=self._on_hover_navigate) self._visible = True
def show_popup(self, view, docstring, location=None): if location is None: location = view.sel()[0].begin() mdpopups.show_popup(view=view, content=self._build_html(view, docstring), location=location, max_width=int(view.viewport_extent()[0]), md=True, css=self._get_style(), wrapper_class='jedi', flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY)
def _show_popup(self, data, location): if mdpopups.is_popup_visible(self.view): mdpopups.hide_popup(self.view) mdpopups.show_popup(self.view, TEMPLATE.format(**data), css=CSS, wrapper_class=WRAPPER_CLASS, max_width=400, location=location, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, on_navigate=self.on_popup_navigate)
def show_errors(self, view, errs): if not errs: return None _pre = '<div class="invalid"> Haxe Errors </div>' _css = 'div { margin:0.3em; } .flow-error-line { margin-left:1em; margin-right:2em; }' _res = '' for _err in errs: _res += '<div class="flow-error-line">'+_err+'</div>' mdpopups.show_popup(view, _pre + _res, css=_css, max_width=1280)
def _show_popup(self, content: str, point: int) -> None: mdpopups.show_popup(self.view, content, css=popups.stylesheet, md=True, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, wrapper_class=popups.classname, max_width=800, on_hide=self._on_hide, on_navigate=self._on_hover_navigate) self._visible = True
def show_popup(self, region, content): def on_navigate(href): self.handle_href(href) self.view.hide_popup() mdpopups.show_popup(view=self.view, css=sublime.load_resource(self.mdpopups_css), max_width=480, max_height=320, location=(region.a + region.b) // 2, content=content, on_navigate=on_navigate, md=True)
def show_diagnostics_hover(self, point, diagnostics): formatted = list("{}: {}".format(diagnostic.source, diagnostic.message) for diagnostic in diagnostics) formatted.append("[{}]({})".format('Code Actions', 'code-actions')) mdpopups.show_popup( self.view, "\n".join(formatted), css=".mdpopups .lsp_hover { margin: 4px; }", md=True, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, wrapper_class="lsp_hover", max_width=800, on_navigate=lambda href: self.on_diagnostics_navigate(href, point, diagnostics))
def show_popup(self, view, docstring, location=None): if location is None: location = view.sel()[0].begin() mdpopups.show_popup( view=view, content=self._build_html(view, docstring), location=location, max_width=int(view.viewport_extent()[0]), md=True, css=self._get_style(), wrapper_class='jedi', flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY)
def show_popup(content: Dict[str, Any], view: sublime.View, location: int) -> None: html = minihtml(view, content, allowed_formats=FORMAT_MARKED_STRING | FORMAT_MARKUP_CONTENT) viewport_width = view.viewport_extent()[0] mdpopups.show_popup( view, html, css=css().popups, md=False, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=location, wrapper_class=css().popups_classname, max_width=viewport_width, on_navigate=None)
def show_colors(self, palette_type, palette_name, delete=False, update=False): """Show colors under the given palette.""" target = None current = False if palette_type == "__special__": if palette_name == "Current Colors": current = True target = { "name": palette_name, "colors": self.view.settings().get('color_helper.file_palette', []) } elif palette_name == "Favorites": target = util.get_favs() elif palette_type == "__global__": for palette in util.get_palettes(): if palette_name == palette['name']: target = palette elif palette_type == "__project__": for palette in util.get_project_palettes(self.view.window()): if palette_name == palette['name']: target = palette if target is not None: template_vars = { "delete": delete, 'show_delete_menu': not delete and not current, "back": '__colors__' if delete else '__palettes__', "palette_type": palette_type, "palette_name": target["name"], "colors": self.format_colors(target['colors'], target['name'], palette_type, delete) } if update: mdpopups.update_popup( self.view, util.FRONTMATTER + sublime.load_resource('Packages/ColorHelper/panels/colors.html.j2'), wrapper_class="color-helper content", css=util.ADD_CSS, template_vars=template_vars ) else: mdpopups.show_popup( self.view, util.FRONTMATTER + sublime.load_resource('Packages/ColorHelper/panels/colors.html.j2'), wrapper_class="color-helper content", css=util.ADD_CSS, location=-1, max_width=1024, max_height=512, on_navigate=self.on_navigate, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, template_vars=template_vars )
def show_popup(text): """Show the popup.""" clear_cache() close = '\n[close](#){: .btn .btn-small .btn-info}\n' view = active_view() region = view.visible_region() mdpopups.show_popup(active_view(), text + close, location=region.a, on_navigate=on_close_popup, max_height=650, max_width=600, wrapper_class='mdpopups-test', css='div.mdpopups-test { padding: 0.5rem; }')
def show_tooltip(self, view): """ show tooltip using mdpopups """ if not view.file_name(): return None tooltip = self.get_tooltip(view) if not tooltip: return None mdpopups.show_popup(view=view, content=tooltip, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, max_width=self.settings.get("tooltip_width", 1000), max_height=self.settings.get("height", 400), on_navigate=lambda label_id, view=view: utils.jump_to_label_declaration(view, tooltip))
def show_notification(view: sublime.View, source: str, message_type: int, message: str, titles: List[str], on_navigate: Callable, on_hide: Callable) -> None: stylesheet = sublime.load_resource("Packages/LSP/notification.css") contents = message_content(source, message_type, message, titles) mdpopups.show_popup(view, contents, css=stylesheet, md=False, location=-1, wrapper_class='notification', max_width=800, max_height=800, on_navigate=on_navigate, on_hide=on_hide)
def show_tooltip(self, view): """ show tooltip using mdpopups """ if not view.file_name(): return None tooltip = self.get_tooltip(view) if not tooltip: return None mdpopups.show_popup(view=view, content=tooltip, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, max_width=self.settings.get("tooltip_width", 1000), max_height=self.settings.get("height", 400), on_navigate=lambda label_id, view=view: utils. jump_to_label_declaration(view, tooltip))
def show_popup(self, view, point, region, icon): """Show the popup.""" if HOVER_SUPPORT: if not self.is_bracket_visible(view, region): markup = self.get_markup(view, point, region, icon) self.popup_view = view mdpopups.show_popup(view, markup, wrapper_class=WRAPPER_CLASS, css=CSS, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, max_width=800, location=point, on_navigate=self.on_navigate)
def show_popup(self, view, point, region, icon): """Show the popup.""" if HOVER_SUPPORT: if not self.is_bracket_visible(view, region): markup = self.get_markup(view, point, region, icon) self.popup_view = view mdpopups.show_popup( view, markup, wrapper_class=WRAPPER_CLASS, css=CSS, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, max_width=800, location=point, on_navigate=self.on_navigate )
def show_args(self, view, args): if not args: return [] # print('[flow] args ' + args) _res = [] _list = args.split(', ') for _arg in _list: _parts = _arg.split(':') _res.append('<span class="entity name">' + _parts[0] + '</span>:<span class="storage type">' + _parts[1] + '</span>') args = '<div>'+', '.join(_res)+'</div>' _css = 'p,div { margin:0.3em; }' mdpopups.show_popup(view, args, css=_css, max_width=1280) return None
def show_unmatched_popup(self, view, point): """Show unmatched popup.""" if HOVER_SUPPORT: self.popup_view = view mdpopups.show_popup( view, textwrap.dedent(MATCH_ERR % {"pt": str(point)}), wrapper_class=WRAPPER_CLASS, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, css=CSS, max_width=800, max_height=800, location=point, on_navigate=self.on_navigate_unmatched, template_vars={'mdpopups_version': mdpopups.version()}, template_env_options=template_options )
def show_color_info(self, update=False): """Show the color under the cursor.""" color = None sels = self.view.sel() if (len(sels) == 1 and sels[0].size() == 0): point = sels[0].begin() visible = self.view.visible_region() start = point - 50 end = point + 50 alpha = None if start < visible.begin(): start = visible.begin() if end > visible.end(): end = visible.end() bfr = self.view.substr(sublime.Region(start, end)) ref = point - start for m in util.COLOR_RE.finditer(bfr): if ref >= m.start(0) and ref < m.end(0): color, alpha = util.translate_color(m) break if color is not None: if alpha is not None: color += "%02X" % int('%.0f' % (float(alpha) * 255.0)) html = [] html.append( self.format_info(color.lower(), alpha) ) if update: mdpopups.update_popup(self.view, ''.join(html), css=ADD_CSS) else: mdpopups.show_popup( self.view, ''.join(html), location=-1, max_width=600, on_navigate=self.on_navigate, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, css=ADD_CSS ) elif update: self.view.hide_popup()
def _show_tooltip(self, sections): cursor = self.view.sel()[0].begin() line = self.view.line(cursor) line_content = self.view.substr(line) if line_content.startswith('-'): task = None for s in sections: task = s.find_by_line(line_content) if task is not None: break if task: content = '' categories = task.categories() max_len = max([len(c) for c in categories]) data = [] for cat in categories: data.append(( cat, task.scheduled_start_date(cat).date(), task.scheduled_end_date(cat).date() )) data = sorted(data, key=itemgetter(1)) for d in data: if d[1] == d[2]: content += '{:.>{}}: {}\n\n'.format( d[0], max_len, d[1]) else: content += '{:.>{}}: {} - {}\n\n'.format( d[0], max_len, d[1], d[2]) mdpopups.show_popup(self.view, content)
def get_holidays(self, view, day, month, year, pt): """Get the holidays for the given day.""" bfr = '' target = "%4d-%02d-%02d" % (year, month, day) region = ("", sublime.load_settings("quickcal.sublime-settings").get("region", "")) for d in view.settings().get('calendar_holidays', []): if d['date'] == target: if d["region"] in region: bfr += "* **%s:**{: .keyword} %s %s\n" % ( d["date"], d["description"], "(Region: %s)" % d["region"] if d["region"] != "" else "" ) mdpopups.show_popup( view, '## Holidays {: .header}\n' + bfr, css=CSS, wrapper_class='quick-cal', location=pt, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY ) self.last = time.time()
def on_hover(self, view, point, hover_zone): if view.settings().get('is_widget'): return if not view.settings().get('show_definitions'): return if hover_zone != sublime.HOVER_TEXT: return if not view.score_selector(point, 'source.lsl'): return word = view.substr(view.word(point)) if not word: return if not KWDB: return try: tooltipRows = [] for result in KWDB.findall(".//*[@name='" + word + "']"): if result.tag == 'param': continue if result.tag == 'function' or result.tag == 'constant': tooltipRows.append('### (%s) <a href="https://wiki.secondlife.com/w/index.php?title=Special:Search&go=Go&search=%s">%s</a>' % (result.get('type', 'void'), result.get('name'), result.get('name'))) else: tooltipRows.append('### <a href="https://wiki.secondlife.com/w/index.php?title=Special:Search&go=Go&search=%s">%s</a>' % (result.get('name'), result.get('name'))) if result.tag == 'constant': tooltipRows.append(' ') tooltipRows.append('**Value**: %s' % str(result.get('value'))) if result.get('status', None) is not None and result.get('status', 'normal') != 'normal': tooltipRows.append(' ') tooltipRows.append('<body class="danger">**Status**: %s</body>' % result.get('status', 'normal')) if result.get('delay', None) is not None: tooltipRows.append(' ') tooltipRows.append('**Delay**: %s' % str(result.get('delay'))) if result.get('energy', None) is not None: tooltipRows.append(' ') tooltipRows.append('**Energy**: %s' % str(result.get('energy'))) if result.tag == 'function' or result.tag == 'event': if result.findall('./param') != []: tooltipRows.append(' ') tooltipRows.append('#### Parameters') for param in result.iter('param'): tooltipRows.append('* (%s) **%s**' % (param.get('type'), param.get('name'))) if result.find('description').text is not None: tooltipRows.append(' ') tooltipRows.append('#### Description') tooltipRows.append(' ') tooltipRows.append('%s' % result.find('description').text.strip()) # add version info # add grid info by splitting spaces and re-joining as markdown list # seperate entries by horizontal line if 0 < len(tooltipRows): mdpopups.show_popup(view, '\n'.join(tooltipRows), flags=sublime.COOPERATE_WITH_AUTO_COMPLETE|sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, max_width=1024, on_navigate=self.on_navigate ) return except Exception as e: print(e) mdpopups.hide_popup(view)
def show_diff_popup(view, point, flags=0): if not _MDPOPUPS_INSTALLED: return line = view.rowcol(point)[0] + 1 lines, start, size, meta = ViewCollection.diff_line_change(view, line) if start == -1: return # extract the type of the hunk: removed, modified, (x)or added is_removed = size == 0 is_modified = not is_removed and bool(lines) is_added = not is_removed and not is_modified def navigate(href): if href == "hide": view.hide_popup() elif href == "revert": new_text = "\n".join(lines) # (removed) if there is no text to remove, set the # region to the end of the line, where the hunk starts # and add a new line to the start of the text if is_removed: if start != 0: # set the start and the end to the end of the start line start_point = end_point = view.text_point(start, 0) - 1 # add a leading newline before inserting the text new_text = "\n" + new_text else: # (special handling for deleted at the start of the file) # if we are before the start we need to set the start # to 0 and add the newline behind the text start_point = end_point = 0 new_text = new_text + "\n" # (modified/added) # set the start point to the start of the hunk # and the end point to the end of the hunk else: start_point = view.text_point(start - 1, 0) end_point = view.text_point(start + size - 1, 0) # (modified) if there is text to insert, we # don't want to capture the trailing newline, # because we insert lines without a trailing newline if is_modified and end_point != view.size(): end_point -= 1 replace_param = { "a": start_point, "b": end_point, "text": new_text } view.run_command("git_gutter_replace_text", replace_param) # hide the popup and update the gutter view.hide_popup() view.window().run_command("git_gutter") elif href == "copy": sublime.set_clipboard("\n".join(lines)) copy_message = " ".join(l.strip() for l in lines) sublime.status_message("Copied: " + copy_message) elif href in ["next_change", "prev_change", "first_change"]: next_line = meta.get(href, line) pt = view.text_point(next_line - 1, 0) def show_new_popup(): if view.visible_region().contains(pt): show_diff_popup(view, pt, flags=flags) else: sublime.set_timeout(show_new_popup, 10) view.show_at_center(pt) show_new_popup() # write the symbols/text for each button use_icons = settings.get("diff_popup_use_icon_buttons") # the buttons as a map from the href to the caption/icon button_descriptions = { "hide": chr(0x00D7) if use_icons else "(close)", "copy": chr(0x2398) if use_icons else "(copy)", "revert": chr(0x27F2) if use_icons else "(revert)", "first_change": chr(0x2912) if use_icons else "(first)", "prev_change": chr(0x2191) if use_icons else "(previous)", "next_change": chr(0x2193) if use_icons else "(next)" } def is_button_enabled(k): if k in ["first_change", "next_change", "prev_change"]: return meta.get(k, start) != start return True buttons = {} for k, v in button_descriptions.items(): if is_button_enabled(k): buttons[k] = '[{0}]({1})'.format(v, k) else: buttons[k] = v if not is_added: # (modified/removed) show the button line above the content, # which in git lang = mdpopups.get_language_from_view(view) or "" # strip the indent to the minimal indentation is_tab_indent = any(l.startswith("\t") for l in lines) indent_char = "\t" if is_tab_indent else " " min_indent = min(len(l) - len(l.lstrip(indent_char)) for l in lines) source_content = "\n".join(l[min_indent:] for l in lines) # replace spaces by non-breakable ones to avoid line wrapping source_content = source_content.replace(" ", "\u00A0") button_line = ( '{hide} ' '{first_change} {prev_change} {next_change} ' '{copy} {revert}' .format(**buttons) ) content = ( '{button_line}\n' '``` {lang}\n' '{source_content}\n' '```' .format(**locals()) ) else: # (added) only show the button line without the copy button # (there is nothing to show or copy) button_line = ( '{hide} ' '{first_change} {prev_change} {next_change} ' '{revert}' .format(**buttons) ) content = button_line css = '' if _MD_POPUPS_USE_WRAPPER_CLASS: wrapper_class = "git-gutter" if use_icons: css = 'div.git-gutter a { text-decoration: none; }' else: wrapper_class = "" if use_icons: css = 'a { text-decoration: none; }' location = view.line(point).a window_width = int(view.viewport_extent()[0]) mdpopups.show_popup( view, content, location=location, on_navigate=navigate, wrapper_class=wrapper_class, css=css, flags=flags, max_width=window_width)
def show_popup(self, menu): settings = sublime.load_settings('Preferences.sublime-settings') popup = [] if menu != 'Main': popup = [BACK] if menu == 'Main': popup.append(SECTIONS_LABEL) for k in ['Theme', 'Color Scheme'] + list(OPTIONS.keys()): popup.append(SECTIONS % {"section": k}) elif menu == 'Theme': theme = settings.get('theme', '') mt_themes = [ os.path.basename(bt) for bt in sorted(sublime.find_resources('Material-Theme*.sublime-theme')) if is_mt_res(bt) ] popup.append(THEME_LABEL) for option in mt_themes: option_value = theme == option popup.append( THEME % { "name": option, "status": RADIO_MARKED if option_value else RADIO_UNMARKED, "set": option, "class": '.success' if option_value else '.error', 'section': "Theme" } ) if theme is not None and theme not in mt_themes: popup.append( OTHER_THEME % { "name": theme, "status": RADIO_MARKED, "set": option, "class": '.success' if option_value else '.error', 'section': "Theme" } ) elif menu == 'Color Scheme': scheme = settings.get('color_scheme', '') mt_schemes = [ bs for bs in sorted(sublime.find_resources('Material-Theme*.tmTheme')) if is_mt_res(bs) ] popup.append(SCHEME_LABEL) for option in mt_schemes: option_value = scheme == option scheme_name = option[32:].replace('/', ' ⚠️ ') popup.append( SCHEME % { "name": scheme_name, "status": RADIO_MARKED if option_value else RADIO_UNMARKED, "set": option, "class": '.success' if option_value else '.error', "section": 'Color Scheme' } ) if scheme is not None and scheme not in mt_schemes: popup.append( OTHER_SCHEME % { "name": scheme, "status": RADIO_MARKED, "set": option, "class": '.success', "section": 'Color Scheme' } ) else: popup.append(SECTION_LABEL % menu) for option in OPTIONS[menu]: option_value = bool(settings.get(option, False)) popup.append( GENERAL_SETTING % { "name": option, "status": MARKED if option_value else UNMARKED, "set": str(not option_value), "class": '.success' if option_value else '.error', "section": menu } ) mdpopups.hide_popup(self.view) mdpopups.show_popup( self.view, ''.join(popup), css=STYLE, on_navigate=self.on_navigate, max_width=800, max_height=400 )
def show_palettes(self, delete=False, color=None, update=False): """Show preview of all palettes.""" show_div = False s = sublime.load_settings('color_helper.sublime-settings') show_global_palettes = s.get('enable_global_user_palettes', True) show_project_palettes = s.get('enable_project_user_palettes', True) show_favorite_palette = s.get('enable_favorite_palette', True) show_current_palette = s.get('enable_current_file_palette', True) html = [] if (not self.no_info and not delete) or color: html.append(BACK_INFO_MENU) elif delete: html.append(BACK_PALETTE_MENU) if not delete and not color and (show_global_palettes or show_project_palettes or show_favorite_palette): html.append(DELETE_PALETTE_MENU) if delete: html.append(DELETE_PALETTE) if color: html.append(NEW_PALETTE % {'color': color}) if show_favorite_palette: favs = util.get_favs() if len(favs['colors']) or color: show_div = True html.append( self.format_palettes(favs['colors'], favs['name'], '__special__', delete=delete, color=color) ) if show_current_palette: current_colors = self.view.settings().get('color_helper_file_palette', []) if not delete and not color and len(current_colors): show_div = True html.append( self.format_palettes(current_colors, "Current Colors", '__special__', delete=delete, color=color) ) if show_global_palettes: palettes = util.get_palettes() if len(palettes) and show_div: show_div = False html.append('\n\n---\n\n') for palette in palettes: show_div = True name = palette.get("name") html.append( self.format_palettes( palette.get('colors', []), name, '__global__', palette.get('caption'), delete=delete, color=color ) ) if show_project_palettes: palettes = util.get_project_palettes(self.view.window()) if len(palettes) and show_div: show_div = False html.append(DIVIDER) for palette in palettes: name = palette.get("name") html.append( self.format_palettes( palette.get('colors', []), name, '__project__', palette.get('caption'), delete=delete, color=color ) ) if update: mdpopups.update_popup(self.view, ''.join(html), css=ADD_CSS) else: mdpopups.show_popup( self.view, ''.join(html), location=-1, max_width=600, on_navigate=self.on_navigate, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, css=ADD_CSS )
def run( self, edit, color='#ffffff', allowed_colors=util.ALL, use_hex_argb=None, compress_hex=False, hsl=False, hirespick=None, colornames=False, on_done=None, on_cancel=None ): """Run command.""" self.on_done = on_done self.on_cancel = on_cancel self.use_hex_argb = use_hex_argb self.compress_hex = compress_hex self.allowed_colors = allowed_colors self.hex_map = sublime.load_settings('color_helper.sublime-settings').get('use_hex_color_picker', True) rgba = util.RGBA(color) self.set_sizes() self.hsl = hsl self.color = rgba.get_rgba() self.alpha = util.fmt_float(float(int(self.color[-2:], 16)) / 255.0, 3) try: self.web_color = csscolors.hex2name(rgba.get_rgb()) except Exception: self.web_color = None text = [] if colornames: text.append('[cancel](%s){: .color-helper .small} ' % self.color) text.append('\n\n## CSS Color Names\n\n') self.get_css_color_names(text) elif hirespick: text.append('[cancel](%s){: .color-helper .small} ' % self.color) text.append('\n\n## %s\n\n' % hirespick) self.get_hires_color_channel(text, hirespick) else: text.append('[cancel](cancel){: .color-helper .small} ') text.append('[CSS color names](colornames){: .color-helper .small} ') text.append('[enter new color](edit){: .color-helper .small}\n\n') if self.hex_map: self.get_color_map_hex(text) else: self.get_color_map_square(text) self.get_current_color(text) text.append('\n\n---\n\n') if hsl: self.get_channel(text, 'H', -15, 15, 'hue') self.get_channel(text, 'S', 0.975, 1.025, 'saturation') self.get_channel(text, 'L', 0.975, 1.025, 'luminance') else: self.get_channel(text, 'R', 0.975, 1.025, 'red') self.get_channel(text, 'G', 0.975, 1.025, 'green') self.get_channel(text, 'B', 0.975, 1.025, 'blue') self.get_channel(text, 'A', 0.975, 1.025, 'alpha') text.append( '[switch to %s](%s){: .color-helper .small}\n' % ( 'rgb' if self.hsl else 'hsl', 'rgb' if self.hsl else 'hsl' ) ) text.append('\n\n---\n\n') self.get_color_info(text) md = mdpopups.md2html(self.view, ''.join(text)) mdpopups.show_popup( self.view, '<div class="color-helper content">%s</div>' % md, css=util.ADD_CSS, max_width=600, max_height=(500 if hirespick or colornames else 725), on_navigate=self.handle_href )
def run(self, v): """Run ScopeHunter and display in the approriate way.""" self.view = v self.window = self.view.window() view = self.window.create_output_panel('scopehunter.results', unlisted=True) self.scope_bfr = [] self.scope_bfr_tool = [] self.clips = [] self.status = "" self.popup_template = sublime.load_resource('Packages/ScopeHunter/popup.j2') self.scheme_file = None self.syntax_file = None self.show_statusbar = bool(sh_settings.get("show_statusbar", False)) self.show_panel = bool(sh_settings.get("show_panel", False)) if TOOLTIP_SUPPORT: self.show_popup = bool(sh_settings.get("show_popup", False)) else: self.show_popup = False self.clipboard = bool(sh_settings.get("clipboard", False)) self.multiselect = bool(sh_settings.get("multiselect", False)) self.console_log = bool(sh_settings.get("console_log", False)) self.highlight_extent = bool(sh_settings.get("highlight_extent", False)) self.highlight_scope = sh_settings.get("highlight_scope", 'invalid') self.highlight_style = sh_settings.get("highlight_style", 'outline') self.highlight_max_size = int(sh_settings.get("highlight_max_size", 100)) self.rowcol_info = bool(sh_settings.get("extent_line_char", False)) self.points_info = bool(sh_settings.get("extent_points", False)) self.appearance_info = bool(sh_settings.get("styling", False)) self.show_simulated = bool(sh_settings.get("show_simulated_alpha_colors", False)) self.file_path_info = bool(sh_settings.get("file_paths", False)) self.selector_info = bool(sh_settings.get("selectors", False)) self.scheme_info = self.appearance_info or self.selector_info self.first = True self.extents = [] # Get scope info for each selection wanted self.index = -1 if len(self.view.sel()): if self.multiselect: count = 0 for sel in self.view.sel(): if count > 0 and self.show_popup: self.scope_bfr_tool.append('\n---\n') self.init_template_vars() self.get_info(sel.b) count += 1 else: self.init_template_vars() self.get_info(self.view.sel()[0].b) # Copy scopes to clipboard if self.clipboard: sublime.set_clipboard('\n'.join(self.clips)) # Display in status bar if self.show_statusbar: sublime.status_message(self.status) # Show panel if self.show_panel: ScopeHunterEditCommand.bfr = '\n'.join(self.scope_bfr) ScopeHunterEditCommand.pt = 0 view.run_command('scope_hunter_edit') ScopeHunterEditCommand.clear() self.window.run_command("show_panel", {"panel": "output.scopehunter.results"}) if self.console_log: print('\n'.join(["Scope Hunter"] + self.scope_bfr)) if self.highlight_extent: style = extent_style(self.highlight_style) if style == 'underline': self.extents = underline(self.extents) self.view.add_regions( 'scope_hunter', self.extents, self.highlight_scope, '', style ) if self.show_popup: if self.scheme_info or self.rowcol_info or self.points_info or self.file_path_info: tail = mdpopups.md2html(self.view, COPY_ALL % ('' if GOOD_CSS_SUPPORT else '.scope-hunter ')) else: tail = '' mdpopups.show_popup( self.view, ''.join(self.scope_bfr_tool) + tail, md=False, css=ADD_CSS, wrapper_class=('scope-hunter' if GOOD_CSS_SUPPORT else 'scope-hunter content'), max_width=1000, on_navigate=self.on_navigate, )
def show_popup(self, menu): global BACK global BACK_TO_SUBMENU settings = sublime.load_settings('Preferences.sublime-settings') popup = [] marked = settings.get('theme_config_marked', False) unmarked = settings.get('theme_config_unmarked', False) radio_marked = settings.get('theme_config_radio_marked', False) radio_unmarked = settings.get('theme_config_radio_unmarked', False) if marked is False: marked = MARKED if unmarked is False: unmarked = UNMARKED if radio_marked is False: radio_marked = RADIO_MARKED if radio_unmarked is False: radio_unmarked = RADIO_UNMARKED if menu == 'Home': popup.append(SECTIONS_LABEL) for k in (['UI Theme', 'Color Scheme'] + list(SUB_SECTIONS.keys()) + list(SECTION_OPTIONS.keys())): popup.append(SECTIONS % {'section': k}) elif menu == 'UI Theme': theme = settings.get('theme', '') boxy_themes = [ os.path.basename(bt) for bt in sorted( sublime.find_resources('Boxy*.sublime-theme') ) if is_boxy_res(bt) ] popup.append(THEME_LABEL) for option in boxy_themes: option_value = theme == option popup.append( THEME % { 'name': option, 'status': radio_marked if option_value else radio_unmarked, 'set': option, 'class': '.success' if option_value else '.error', 'section': 'UI Theme' } ) if theme is not None and theme not in boxy_themes: popup.append( OTHER_THEME % { 'name': theme, 'status': radio_marked, 'set': option, 'class': '.success' if option_value else '.error', 'section': 'UI Theme' } ) elif menu == 'Color Scheme': scheme = settings.get('color_scheme', '') boxy_schemes = [ bs for bs in sorted( sublime.find_resources('Boxy*.tmTheme') ) if is_boxy_res(bs) ] popup.append(SCHEME_LABEL) for option in boxy_schemes: option_value = scheme == option popup.append( SCHEME % { 'name': option, 'status': radio_marked if option_value else radio_unmarked, 'set': option, 'class': '.success' if option_value else '.error', 'section': 'Color Scheme' } ) if scheme is not None and scheme not in boxy_schemes: popup.append( OTHER_SCHEME % { 'name': scheme, 'status': radio_marked, 'set': option, 'class': '.success', 'section': 'Color Scheme' } ) elif menu in SUB_SECTIONS.keys(): popup.append(SECTION_LABEL % menu) for k in SUB_SECTIONS[menu]: popup.append(SECTIONS % {'section': k}) BACK = '[← Back](back-Home){: .boxy-control .boxy-control-back }' BACK_TO_SUBMENU = '''[← Back](back-%s){: .boxy-control\ .boxy-control-back }''' % (menu) elif menu in SECTION_OPTIONS.keys(): popup.append(SECTION_LABEL % menu) for option in SECTION_OPTIONS[menu]: option_value = bool(settings.get(option, False)) popup.append( GENERAL_SETTING % { 'name': option, 'status': marked if option_value else unmarked, 'set': str(not option_value), 'class': '.success' if option_value else '.error', 'section': menu } ) BACK = '[← Back](back-Home){: .boxy-control .boxy-control-back }' else: popup.append(SECTION_LABEL % menu) for option in SUB_SECTION_OPTIONS[menu]: option_value = bool(settings.get(option, False)) popup.append( GENERAL_SETTING % { 'name': option, 'status': marked if option_value else unmarked, 'set': str(not option_value), 'class': '.success' if option_value else '.error', 'section': menu } ) BACK = BACK_TO_SUBMENU if menu != 'Home': popup.append(BACK) mdpopups.hide_popup(self.view) mdpopups.show_popup( self.view, ''.join(popup), css=STYLES, wrapper_class='boxy-config', on_navigate=self.on_navigate, max_width=1024, max_height=1024 )
def show_popup(self, menu): settings = sublime.load_settings('Preferences.sublime-settings') popup = [] marked = settings.get('theme_config_marked', False) unmarked = settings.get('theme_config_unmarked', False) radio_marked = settings.get('theme_config_radio_marked', False) radio_unmarked = settings.get('theme_config_radio_unmarked', False) if marked is False: marked = MARKED if unmarked is False: unmarked = UNMARKED if radio_marked is False: radio_marked = RADIO_MARKED if radio_unmarked is False: radio_unmarked = RADIO_UNMARKED if menu != 'Main': popup = [BACK] if menu == 'Main': popup.append(SECTIONS_LABEL) for k in sorted(['Theme', 'Color Scheme'] + list(OPTIONS.keys())): popup.append(SECTIONS % {'section': k}) elif menu == 'Theme': theme = settings.get('theme', '') mt_themes = [ os.path.basename(bt) for bt in sorted(sublime.find_resources('Material-Theme*.sublime-theme')) if is_mt_res(bt) ] popup.append(THEME_LABEL) for option in sorted(mt_themes): option_value = theme == option popup.append( THEME % { 'name': option, 'status': RADIO_MARKED if option_value else RADIO_UNMARKED, 'set': option, 'class': '.success' if option_value else '.error', 'section': 'Theme' } ) if theme is not None and theme not in mt_themes: popup.append( OTHER_THEME % { 'name': theme, 'status': RADIO_MARKED, 'set': option, 'class': '.success' if option_value else '.error', 'section': 'Theme' } ) elif menu == 'Color Scheme': scheme = settings.get('color_scheme', '') mt_schemes = [ bs for bs in sorted(sublime.find_resources('Material-Theme*.tmTheme')) if is_mt_res(bs) ] popup.append(SCHEME_LABEL) for option in sorted(mt_schemes): option_value = scheme == option scheme_name = option[32:].replace('.tmTheme', '') popup.append( SCHEME % { 'name': scheme_name, 'status': RADIO_MARKED if option_value else RADIO_UNMARKED, 'set': option, 'class': '.success' if option_value else '.error', 'section': 'Color Scheme' } ) if scheme is not None and scheme not in mt_schemes: popup.append( OTHER_SCHEME % { 'name': scheme, 'status': RADIO_MARKED, 'set': option, 'class': '.success', 'section': 'Color Scheme' } ) else: popup.append(SECTION_LABEL % menu) for option in sorted(OPTIONS[menu]): option_value = bool(settings.get(option, False)) popup.append( GENERAL_SETTING % { 'name': option, 'status': MARKED if option_value else UNMARKED, 'set': str(not option_value), 'class': '.success' if option_value else '.error', 'section': menu } ) mdpopups.hide_popup(self.view) mdpopups.show_popup( self.view, ''.join(popup), css=STYLE, wrapper_class='mt-config', on_navigate=self.on_navigate, max_width=800, max_height=400 )
def _show_diff_popup_impl(git_gutter, line, highlight_diff, flags, diff_info): """Show and update the diff popup. Arguments: git_gutter (GitGutterCommand): The main command object, which represents GitGutter. line (int): The line number the diff popup is requested for highlight_diff (bool): If True to the diff is displayed instead of the old revision. flags (int): Sublime Text popup flags. diff_info (tuple): All the information required to display the diff popup. """ del_lines, start, size, meta = diff_info if start == -1: return view = git_gutter.view # extract the type of the hunk: removed, modified, (x)or added is_removed = size == 0 is_modified = not is_removed and bool(del_lines) is_added = not is_removed and not is_modified def navigate(href): # allow navigate() to manipulate the outer variables nonlocal highlight_diff if href == 'hide': view.hide_popup() elif href == 'copy': del_text = '\n'.join(del_lines) sublime.set_clipboard(del_text) sublime.status_message( 'Copied: {0} characters'.format(len(del_text))) elif href == 'revert': # hide the popup and update the view view.hide_popup() revert.revert_change_impl(view, diff_info) elif href == 'disable_hl_diff': # show a diff popup with the same diff info (previous revision) highlight_diff = False _show_diff_popup_impl( git_gutter, line, highlight_diff, flags, diff_info) elif href == 'enable_hl_diff': # show a diff popup with the same diff info (highlight diff) highlight_diff = True _show_diff_popup_impl( git_gutter, line, highlight_diff, flags, diff_info) elif href in ('first_change', 'next_change', 'prev_change'): next_line = meta.get(href, line) point = view.text_point(next_line - 1, 0) def show_new_popup(): # wait until scrolling has completed if not view.visible_region().contains(point): return sublime.set_timeout_async(show_new_popup, 20) # show a diff popup with new diff info _show_diff_popup_impl( git_gutter, next_line, highlight_diff, 0, git_gutter.git_handler.diff_line_change(next_line)) view.hide_popup() view.show_at_center(point) show_new_popup() # write the symbols/text for each button buttons = _built_toolbar_buttons(start, meta) location = _visible_text_point(view, line - 1, 0) code_wrap = view.settings().get('word_wrap') if code_wrap == 'auto': code_wrap = view.match_selector(location, 'source') if highlight_diff: # (*) show a highlighted diff of the merged git and editor content new_lines = meta['added_lines'] tab_width = view.settings().get('tab_width', 4) min_indent = _get_min_indent(del_lines + new_lines, tab_width) content = ( '<div class="toolbar">' '{hide} ' '{first_change} {prev_change} {next_change} ' '{disable_hl_diff} {revert}' '</div>' .format(**buttons) ) + differ.highlight_diff( [line.expandtabs(tab_width)[min_indent:] for line in del_lines], [line.expandtabs(tab_width)[min_indent:] for line in new_lines]) elif not is_added: # (modified/removed) show content from git database tab_width = view.settings().get('tab_width', 4) min_indent = _get_min_indent(del_lines, tab_width) source_content = '\n'.join( (line.expandtabs(tab_width)[min_indent:] for line in del_lines)) # common arguments used to highlight the content popup_kwargs = { 'allow_code_wrap': code_wrap, 'language': mdpopups.get_language_from_view(view) or '' } content = ( '<div class="toolbar">' '{hide} ' '{first_change} {prev_change} {next_change} ' '{enable_hl_diff} {copy} {revert}' '</div>' .format(**buttons) ) + mdpopups.syntax_highlight(view, source_content, **popup_kwargs) else: # (added) only show the button line without the copy button # (there is nothing to show or copy) content = ( '<div class="toolbar">' '{hide} ' '{first_change} {prev_change} {next_change} ' '{enable_hl_diff} {revert}' '</div>' .format(**buttons) ) # common arguments used to create or update the popup popup_kwargs = { 'view': view, 'content': content, 'md': False, 'css': _load_popup_css(git_gutter.settings.theme_path), 'wrapper_class': 'git-gutter', 'allow_code_wrap': code_wrap } # update visible popup if view.is_popup_visible(): return mdpopups.update_popup(**popup_kwargs) # calculate optimal popup width to apply desired wrapping popup_width = int(view.viewport_extent()[0]) if code_wrap: line_length = view.settings().get('wrap_width', 0) if line_length > 0: popup_width = (line_length + 5) * view.em_width() # create new popup return mdpopups.show_popup( location=location, max_width=popup_width, flags=flags, on_navigate=navigate, **popup_kwargs)