def _make_style_from_name(self, name): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_cls = get_style_by_name(name) style_overrides = { Token.Prompt: style_cls.styles.get( Token.Keyword, '#009900'), Token.PromptNum: style_cls.styles.get( Token.Literal.Number, '#00ff00 bold') } if name is 'default': style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def render_GET(self, request): try: style = get_style_by_name(self.style_name) except ClassNotFound: style = get_style_by_name('default') self.style_name = 'default' prev_url = None if self.days_back: prev_url = self.url_for(request, self.days_back - 1) next_url = self.url_for(request, (self.days_back or 0) + 1) formatter = LogFormatter(style=style) if self.days_back: log_date = date.today() - timedelta(self.days_back) suffix = log_date.strftime('.%Y_%m_%d').replace('_0', '_') self.logfilename += suffix try: with codecs.open(self.logfilename, 'r', 'utf-8') as logfile: html = self.render_log(logfile.read(), formatter, prev_url, next_url) except IOError: request.setResponseCode(404) return '<html><body>Go away.</body></html>' request.setHeader('Content-Type', 'text/html;charset=utf-8') return html.encode('utf-8')
def _make_style_from_name(self, name): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_cls = get_style_by_name(name) style_overrides = { Token.Prompt: "#009900", Token.PromptNum: "#00ff00 bold", Token.OutPrompt: "#990000", Token.OutPromptNum: "#ff0000 bold", } if name == "default": style_cls = get_style_by_name("default") # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update( { Token.Number: "#007700", Token.Operator: "noinherit", Token.String: "#BB6622", Token.Name.Function: "#2080D0", Token.Name.Class: "bold #2080D0", Token.Name.Namespace: "bold #2080D0", } ) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def render(self, context): if not is_qouted(self.style): self.style = template.Variable(self.style).resolve(context) else: self.style = self.style[1:-1] if self.linenos: formatter = HtmlFormatter(style = get_style_by_name(self.style), linenos = self.linenos) else: formatter = HtmlFormatter(style = get_style_by_name(self.style)) return mark_safe(formatter.get_style_defs('.highlight'))
def _make_style_from_name_or_cls(self, name_or_cls): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_overrides = {} if name_or_cls == 'legacy': legacy = self.colors.lower() if legacy == 'linux': style_cls = get_style_by_name('monokai') style_overrides = _style_overrides_linux elif legacy == 'lightbg': style_overrides = _style_overrides_light_bg style_cls = get_style_by_name('pastie') elif legacy == 'neutral': # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_cls = get_style_by_name('default') style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', }) elif legacy =='nocolor': style_cls=_NoStyle style_overrides = {} else : raise ValueError('Got unknown colors: ', legacy) else : if isinstance(name_or_cls, string_types): style_cls = get_style_by_name(name_or_cls) else: style_cls = name_or_cls style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', } style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def set_style(self, extensions, settings): """ Search the extensions for the style to be used and return it. If it is not explicitly set, go ahead and insert the default style (github). """ style = 'default' if not PYGMENTS_AVAILABLE: # pragma: no cover settings["settings"]["use_pygments_css"] = False global_use_pygments_css = settings["settings"]["use_pygments_css"] use_pygments_css = False # Search for highlight extensions to see what whether pygments css is required. for hilite_ext in ('markdown.extensions.codehilite', 'pymdownx.inlinehilite'): if hilite_ext not in extensions: continue config = extensions[hilite_ext] if config is None: config = {} use_pygments_css = use_pygments_css or ( not config.get('noclasses', False) and config.get('use_pygments', True) and config.get('use_codehilite_settings', True) and PYGMENTS_AVAILABLE and global_use_pygments_css ) if global_use_pygments_css and not use_pygments_css: settings["settings"]["use_pygments_css"] = False else: settings["settings"]["use_pygments_css"] = use_pygments_css if use_pygments_css: # Ensure a working style is set style = settings["settings"]['pygments_style'] try: # Check if the desired style exists internally get_style_by_name(style) except Exception: logger.Log.error("Cannot find style: %s! Falling back to 'default' style." % style) style = "default" settings["settings"]["pygments_style"] = style settings["page"]["pygments_style"] = self.load_highlight( style, settings["settings"]["use_pygments_css"], settings["settings"]['pygments_class'] )
def init_syntax_highlighting(self, pygments_style): self.past_lines = [] if pygments_style: if isstr(pygments_style): self.pygments_style = get_style_by_name(pygments_style) else: self.pygments_style = pygments_style else: self.pygments_style = get_style_by_name('default') self.lexer = PythonLexer() self.formatter = Terminal256Formatter(style=self.pygments_style)
def _make_style_from_name(self, name): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_overrides = {} if name == "legacy": legacy = self.colors.lower() if legacy == "linux": style_cls = get_style_by_name("monokai") style_overrides = _style_overrides_linux elif legacy == "lightbg": style_overrides = _style_overrides_light_bg style_cls = get_style_by_name("pastie") elif legacy == "neutral": # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_cls = get_style_by_name("default") style_overrides.update( { Token.Number: "#007700", Token.Operator: "noinherit", Token.String: "#BB6622", Token.Name.Function: "#2080D0", Token.Name.Class: "bold #2080D0", Token.Name.Namespace: "bold #2080D0", Token.Prompt: "#009900", Token.PromptNum: "#00ff00 bold", Token.OutPrompt: "#990000", Token.OutPromptNum: "#ff0000 bold", } ) elif legacy == "nocolor": style_cls = _NoStyle style_overrides = {} else: raise ValueError("Got unknown colors: ", legacy) else: style_cls = get_style_by_name(name) style_overrides = { Token.Prompt: "#009900", Token.PromptNum: "#00ff00 bold", Token.OutPrompt: "#990000", Token.OutPromptNum: "#ff0000 bold", } style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def style_factory(name, cli_style): try: style = get_style_by_name(name) except ClassNotFound: style = get_style_by_name('native') class VStyle(Style): styles = {} styles.update(style.styles) styles.update(default_style_extensions) custom_styles = dict([(string_to_tokentype(x), y) for x, y in cli_style.items()]) styles.update(custom_styles) return PygmentsStyle(VStyle)
def cli(url): click.echo('Version: %s' % __version__) # Override less options os.environ['LESS'] = '-RXF' url = fix_incomplete_url(url) context = Context(url) # For prompt-toolkit history = InMemoryHistory() lexer = PygmentsLexer(HttpPromptLexer) completer = HttpPromptCompleter(context) style = style_from_pygments(get_style_by_name('monokai')) while True: try: text = prompt('%s> ' % context.url, completer=completer, lexer=lexer, style=style, history=history) except EOFError: break # Control-D pressed else: if text.strip() == 'exit': break else: execute(text, context) click.echo("Goodbye!")
def process_request(self, req): style = req.args['style'] try: style_cls = get_style_by_name(style) except ValueError as e: raise HTTPNotFound(e) parts = style_cls.__module__.split('.') filename = resource_filename('.'.join(parts[:-1]), parts[-1] + '.py') mtime = datetime.fromtimestamp(os.path.getmtime(filename), localtz) last_modified = http_date(mtime) if last_modified == req.get_header('If-Modified-Since'): req.send_response(304) req.end_headers() return formatter = HtmlFormatter(style=style_cls) content = u'\n\n'.join([ formatter.get_style_defs('div.code pre'), formatter.get_style_defs('table.code td') ]).encode('utf-8') req.send_response(200) req.send_header('Content-Type', 'text/css; charset=utf-8') req.send_header('Last-Modified', last_modified) req.send_header('Content-Length', len(content)) req.write(content)
def __init__(self, style='default'): """ The parameter *style* select the Pygments style. Pygments style attributes are: * bgcolor, * bold, * border, * color, * italic, * mono, * roman, * sans, * underline. """ pygments_style = get_style_by_name(style) for token, style_attributes in pygments_style.list_styles(): text_format = QtGui.QTextCharFormat() if style_attributes['bgcolor']: text_format.setBackground(to_brush(style_attributes['bgcolor'])) if style_attributes['color']: text_format.setForeground(to_brush(style_attributes['color'])) if style_attributes['bold']: text_format.setFontWeight(QtGui.QFont.Bold) if style_attributes['italic']: text_format.setFontItalic(True) self[token] = text_format
def format(self, tokensource, outfile): x = y = 0 colors = {} for (ttype, d) in get_style_by_name('default'): if d["color"]: color = "#" + d["color"] elif d["italic"]: color = "#991212" elif d["bold"]: color = "#129912" else: color = "#cccccc" colors[ttype] = ImageColor.getrgb(color) for (ttype, value) in tokensource: for char in value: if not char.isspace() or (ttype in Token.Comment): self.canvas.image.putpixel((x, y), colors[ttype]) if char == '\t': x += TAB_SIZE elif char == '\n': x = 0 y += 1 else: x += 1
def _discover_styles(): import inspect from pygments.styles import get_all_styles, get_style_by_name # maps style 'name' (not the class name) and aliases to (module, classname) tuples default_names = {} names = {} styles = {"names": names} if DEBUG: from collections import defaultdict duplicates = defaultdict(set) for name in get_all_styles(): cls = get_style_by_name(name) mod = inspect.getmodule(cls) val = (mod.__name__, cls.__name__) if DEBUG and name in names and names[name] != val and name not in default_names: duplicates[name].add(val) duplicates[name].add(names[name]) names[name] = val # remove some ambiquity names.update(default_names) # print dumplicate message if DEBUG: _print_duplicate_message(duplicates) return styles
def blog_mod_render_items(self, blog, items): if self.markdown_highlight_style: from pygments.style import Style from pygments.styles import get_style_by_name from pygments.formatters import HtmlFormatter # User-defined custom style takes precedence try: with tmp_sys_path(self.config.get('command_dir', "")): mod = import_module(self.markdown_highlight_style) except ImportError: mdstyle = None else: mdstyle = first_subclass(mod, Style) # Try for built-in style if no custom style if not mdstyle: mdstyle = get_style_by_name(self.markdown_highlight_style) # Generate CSS with selector for markdown codehilite extension css = HtmlFormatter(style=mdstyle).get_style_defs(arg=".codehilite") if not css.endswith(os.linesep): css = "{}{}".format(css, os.linesep) csspath = blog.metadata['highlight_stylesheet_url'] if csspath.startswith('/'): csspath = csspath[1:] items.append((encode(css, blog.metadata['charset']), csspath)) return items
def get_all_code_styles(): """ Return a mapping from style names to their classes. """ result = dict((name, style_from_pygments_cls(get_style_by_name(name))) for name in get_all_styles()) result['win32'] = Style.from_dict(win32_code_style) return result
def create_tags(self): tags={} bold_font = font.Font(self.text, self.text.cget("font")) bold_font.configure(weight=font.BOLD) italic_font = font.Font(self.text, self.text.cget("font")) italic_font.configure(slant=font.ITALIC) bold_italic_font = font.Font(self.text, self.text.cget("font")) bold_italic_font.configure(weight=font.BOLD, slant=font.ITALIC) style = get_style_by_name("default") for ttype, ndef in style: # print(ttype, ndef) tag_font = None if ndef["bold"] and ndef["italic"]: tag_font = bold_italic_font elif ndef["bold"]: tag_font = bold_font elif ndef["italic"]: tag_font = italic_font if ndef["color"]: foreground = "#%s" % ndef["color"] else: foreground = None tags[ttype]=str(ttype) self.text.tag_configure(tags[ttype], foreground=foreground, font=tag_font) # self.text.tag_configure(str(ttype), foreground=foreground, font=tag_font) return tags
def cli(url, http_options): click.echo('Version: %s' % __version__) # Override less options os.environ['LESS'] = '-RXF' url = fix_incomplete_url(url) context = Context(url) load_context(context) # For prompt-toolkit history = InMemoryHistory() lexer = PygmentsLexer(HttpPromptLexer) completer = HttpPromptCompleter(context) style = style_from_pygments(get_style_by_name('monokai')) # Execute default http options. execute(' '.join(http_options), context) save_context(context) while True: try: text = prompt('%s> ' % context.url, completer=completer, lexer=lexer, style=style, history=history) except EOFError: break # Control-D pressed else: execute(text, context) save_context(context) if context.should_exit: break click.echo("Goodbye!")
def set_style(self, style): """ Sets the style to the specified Pygments style. """ if isinstance(style, str): style = styles.get_style_by_name(style) self._style = style self._clear_caches()
def _style(raw_code, language, cssclass): """Returns a string of formatted and styled HTML, where raw_code is a string, language is a string that Pygments has a lexer for, and cssclass is a class style available for Pygments.""" # Note: eventually, cssclass would be obtained from a user's preferences # and would not need to be passed as an argument to style() global _pygment_lexer_names, _sharp raw_code = replace_entity_pattern(raw_code) requested_language = language try: lexer = lexers[language] except: if language in _pygment_lexer_names: language = _pygment_lexer_names[requested_language] lexers[requested_language] = get_lexer_by_name(language) else: lexers[language] = get_lexer_by_name(language) lexer = lexers[requested_language] formatter = PreHtmlFormatter() formatter.cssclass = cssclass formatter.style = get_style_by_name(cssclass) # the removal of "\n" below prevents an extra space to be introduced # with the background color of the selected cssclass styled_code = highlight(raw_code, lexer, formatter).replace("\n</pre>", "</pre>") return recover_entity_pattern(styled_code)
def _bbcodeAsHtml(self): style = get_style_by_name('igor') formatter = HtmlFormatter(style=style) lexer = get_lexer_by_name("bbcode", stripall=True) css = formatter.get_style_defs() txt = highlight(self._bbcode, lexer, HtmlFormatter()) return "<style>%s</style>\n%s" % (css, txt)
def get_all_code_styles(): """ Return a mapping from style names to their classes. """ result = dict((name, get_style_by_name(name).styles) for name in get_all_styles()) result['win32'] = win32_code_style return result
def text_content(self): if self.size <= MAX_TEXTFILE_SIZE and not self.is_image: possible_markdown = self.extension in (MARKDOWN_FILE_EXTENSIONS + TEXTILE_FILE_EXTENSIONS) fake_extension = self.extension if not possible_markdown else u'txt' fake_filename = u'.'.join((self.filename, fake_extension,)) style = styles.get_style_by_name('friendly') formatter = formatters.HtmlFormatter(style=style) style = formatter.get_style_defs() f = urlopen(self.file_obj.cdn_url) data = f.read() f.close() try: data = data.decode('utf-8') lexer = lexers.guess_lexer_for_filename(fake_filename, data) except (ClassNotFound, UnicodeDecodeError): return None if isinstance(lexer, lexers.TextLexer) and possible_markdown: format_string = u'<div class="%s">%s</div>' if self.extension in MARKDOWN_FILE_EXTENSIONS: data = format_string % ('markdown', markdown(data)) if self.extension in TEXTILE_FILE_EXTENSIONS: data = format_string % ('textile', textile(data)) else: data = u'<style>%s</style>\n%s' % (style, highlight(data, lexer, formatter)) return data
def _create_styles(self): from pygments.styles import get_style_by_name global _tokens_name self._style = get_style_by_name(session.config.get('hlstyle')) tkStyles = dict(self._style) for token in sorted(tkStyles): while True: if token == Token: break parent = token.parent if not tkStyles[token]['color']: tkStyles[token]['color'] = tkStyles[parent]['color'] if not tkStyles[token]['bgcolor']: tkStyles[token]['bgcolor'] = tkStyles[parent]['bgcolor'] if tkStyles[token]['color'] and tkStyles[token]['bgcolor']: break token = parent self._styles = {} for token,tStyle in tkStyles.items(): token = _tokens_name.setdefault(token,"DP::SH::%s"%str(token)) self._styles[token] = {} self._styles[token]['foreground'] = "#%s"%tStyle['color'] if tStyle['color'] else "" self._styles[token]['background'] = "#%s"%tStyle['bgcolor'] if tStyle['bgcolor'] else "" self._styles[token]['underline'] = tStyle['underline'] self._styles[token]['font'] = self._fonts[(tStyle['bold'],tStyle['italic'])] self._styles.setdefault("DP::SH::Token.Error", {})['background'] = "red" self._styles.setdefault("DP::SH::Token.Generic.Error", {})['background'] = "red"
def style(request): try: style = get_style_by_name(request.GET['style']) except (KeyError, ValueError): style = 'autumn' formatter = HtmlFormatter(style=style) return HttpResponse(formatter.get_style_defs('.highlight'), mimetype='text/css')
def __set_style(self, style): """ Sets the style to the specified Pygments style. """ if (isinstance(style, str) or isinstance(style, unicode)): style = get_style_by_name(style) self._style = style self._clear_caches()
def setup(builder): global html_formatter style = get_style_by_name(builder.config.root_get("modules.pygments.style")) html_formatter = HtmlFormatter(style=style) directives.register_directive("code-block", CodeBlock) directives.register_directive("sourcecode", CodeBlock) before_file_processed.connect(inject_stylesheet) before_build_finished.connect(write_stylesheet)
def __init__(self): from pygments.styles import get_style_by_name from pygments.formatters import HtmlFormatter # Get ready to use Pygments: self.style = get_style_by_name('default') self.formatter = HtmlFormatter(classprefix='source_', linenos='inline')
def style_factory(self, style_name): """Retrieve the specified pygments style. If the specified style is not found, the vim style is returned. :type style_name: str :param style_name: The pygments style name. :rtype: :class:`pygments.style.StyleMeta` :return: Pygments style info. """ try: style = get_style_by_name(style_name) except ClassNotFound: style = get_style_by_name('vim') class CliStyle(Style): """Provides styles for the autocomplete menu and the toolbar. :type styles: dict :param styles: Contains pygments style info. """ styles = {} styles.update(style.styles) styles.update(default_style_extensions) t = Token styles.update({ t.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000', t.Menu.Completions.Completion: 'bg:#008888 #ffffff', t.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000', t.Menu.Completions.Meta: 'bg:#00aaaa #ffffff', t.Menu.Completions.ProgressButton: 'bg:#003333', t.Menu.Completions.ProgressBar: 'bg:#00aaaa', t.Toolbar: 'bg:#222222 #cccccc', t.Toolbar.Off: 'bg:#222222 #696969', t.Toolbar.On: 'bg:#222222 #ffffff', t.Toolbar.Search: 'noinherit bold', t.Toolbar.Search.Text: 'nobold', t.Toolbar.System: 'noinherit bold', t.Toolbar.Arg: 'noinherit bold', t.Toolbar.Arg.Text: 'nobold' }) return CliStyle
def setup(builder): global html_formatter style = get_style_by_name(builder.config.root_get('modules.pygments.style')) html_formatter = HtmlFormatter(style=style, cssclass='hll') directives.register_directive('code-block', CodeBlock) directives.register_directive('sourcecode', CodeBlock) directives.register_directive('literalinclude', LiteralInclude) before_file_processed.connect(inject_stylesheet) before_build_finished.connect(write_stylesheet)
def _print_list_as_json(requested_items): import json result = {} if 'lexer' in requested_items: info = {} for fullname, names, filenames, mimetypes in get_all_lexers(): info[fullname] = { 'aliases': names, 'filenames': filenames, 'mimetypes': mimetypes } result['lexers'] = info if 'formatter' in requested_items: info = {} for cls in get_all_formatters(): doc = docstring_headline(cls) info[cls.name] = { 'aliases': cls.aliases, 'filenames': cls.filenames, 'doc': doc } result['formatters'] = info if 'filter' in requested_items: info = {} for name in get_all_filters(): cls = find_filter_class(name) info[name] = {'doc': docstring_headline(cls)} result['filters'] = info if 'style' in requested_items: info = {} for name in get_all_styles(): cls = get_style_by_name(name) info[name] = {'doc': docstring_headline(cls)} result['styles'] = info json.dump(result, sys.stdout)
def __init__(self, dest='html', stylename='sphinx', trim_doctest_flags=False): self.dest = dest if stylename is None or stylename == 'sphinx': style = SphinxStyle elif stylename == 'none': style = NoneStyle elif '.' in stylename: module, stylename = stylename.rsplit('.', 1) style = getattr(__import__(module, None, None, ['__name__']), stylename) else: style = get_style_by_name(stylename) self.trim_doctest_flags = trim_doctest_flags self.formatter_args = {'style': style} if dest == 'html': self.formatter = self.html_formatter else: self.formatter = self.latex_formatter self.formatter_args['commandprefix'] = 'PYG'
def draw_window(contents: Image, style: str, padding: int = 20) -> Image: # Figure out the background color # https://github.com/theacodes/witchhazel/issues/2 if style == "witchhazel": background_color = witchhazel.WitchHazelStyle.background_color else: style_cls = get_style_by_name(style) background_color = style_cls.background_color # Create a new blank image to draw the window frame and code onto. min_width = _get_minimum_window_width("Roboto Mono", font_size=32) window_width = max(min_width, contents.width) window_img = Image.new( mode="RGBA", size=(window_width + padding * 2, contents.height + padding * 2)) window_img_draw = ImageDraw.ImageDraw(window_img) # Draw the window frame wallart.gfx.rounded_rectangle( window_img_draw, (0, 0, window_img.width, window_img.height), radius=10, fill=background_color) # Paste in the generated code image. window_img.paste(contents, box=(padding, padding)) # Generate the drop shadow final_image = wallart.gfx.drop_shadow( window_img, padding=120, shadow_color=(0, 0, 0, 180), offset=(5, 20), ) return final_image
def __init__(self, parent, haystack, placeholder_text, default): from pygments import styles, token super(QuickSelectorDialog, self).__init__(parent, Qt.FramelessWindowHint) # The Text token is not always defined, in which case the color # defaults to black, which is ugly. Therefore, retry with the generic # token. style = styles.get_style_by_name(cfg.pyqode_color_scheme) foreground = style.styles.get(token.Text) if not foreground: foreground = style.styles.get(token.Token) self.setWindowTitle(u'Quick Selector') self.setStyleSheet( STYLESHEET.format(background=style.highlight_color, selected_background=style.background_color, foreground=foreground, font_family=cfg.pyqode_font_name, font_size=cfg.pyqode_font_size)) # Already create a lowercase version of the label for performance self._haystack = [(label.lower(), label, data, on_select) for label, data, on_select in haystack] self._default = default self._search_box = SearchBox(self) self._search_box.textEdited.connect(self._search) if placeholder_text: self._search_box.setPlaceholderText(placeholder_text) self._result_box = ResultBox(self) self._result_box.setTextElideMode(Qt.ElideMiddle) self._result_box.itemActivated.connect(self._select) self._result_box.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._result_box.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._layout = QVBoxLayout(self) self._layout.addWidget(self._search_box) self._layout.addWidget(self._result_box) self.setMinimumWidth(cfg.quick_selector_min_width) self._search(u'')
def _syntax_highlighting(self, data): try: from pygments import highlight from pygments.lexers import GasLexer from pygments.formatters import TerminalFormatter, Terminal256Formatter from pygments.styles import get_style_by_name style = get_style_by_name('colorful') import curses curses.setupterm() if curses.tigetnum('colors') >= 256: FORMATTER = Terminal256Formatter(style=style) else: FORMATTER = TerminalFormatter() # When pygments is available, we # can print the disassembled # instructions with syntax # highlighting. data = highlight(data, GasLexer(), FORMATTER) except ImportError: pass finally: data = data.encode() return data
def style_name(self, value): if self._style_name == value: return if value not in STYLES: warn('Could not find style {0!r}, using default'.format(value), RuntimeWarning) value = 'default' builtins.__xonsh_env__['XONSH_COLOR_STYLE'] = value cmap = STYLES[value] if value == 'default': self._smap = XONSH_BASE_STYLE.copy() else: try: self._smap = get_style_by_name(value)().styles.copy() except (ImportError, pygments.util.ClassNotFound): self._smap = XONSH_BASE_STYLE.copy() compound = CompoundColorMap( ChainMap(self.trap, cmap, PTK_STYLE, self._smap)) self.styles = ChainMap(self.trap, cmap, PTK_STYLE, self._smap, compound) self._style_name = value if ON_WINDOWS: self.enhance_colors_for_cmd_exe()
def _on_changed_highlightstyle(self, value): self._lexer_style = get_style_by_name(value) self._tk.configure(background=self._lexer_style.background_color, insertbackground=self._lexer_style.highlight_color, foreground=self._lexer_style.highlight_color) for tag in self._tk.tag_names(): self._tk.tag_delete(tag) for token, value in self._lexer_style.styles.items(): token_value = value.split(' ') foreground = list(filter(lambda x: x.startswith("#"), token_value)) if len(foreground) == 0: continue if str(token) == "Token.Text": self._tk.configure(insertbackground=foreground[0], foreground=foreground[0]) self._tk.tag_configure(str(token), foreground=foreground[0]) self._highlight()
def get_style_by_name(name): """Gets a style class from its name or alias. This mimics the behavior of ``pygments.styles.get_style_by_name()``. """ if CACHE is None: load_or_build() names = CACHE['styles']['names'] if name in names: modname, clsname = names[name] mod = importlib.import_module(modname) style = getattr(mod, clsname) elif name in CUSTOM_STYLES: style = CUSTOM_STYLES[name] else: # couldn't find style in cache, fallback to the hard way import inspect from pygments.styles import get_style_by_name style = get_style_by_name(name) # add this style to the cache for future use mod = inspect.getmodule(style) names[name] = (mod.__name__, style.__name__) write_cache(cache_filename()) return style
def setup_prompt(self): """ This needs to happen after __init__ when the database is fully initialized. """ history = DatabaseHistory() completer = CommandCompleter(self.commands) lexer = PygmentsLexer(CommandLexer.build(self.commands)) style = style_from_pygments_cls(get_style_by_name("monokai")) auto_suggest = AutoSuggestFromHistory() self.prompt = PromptSession( [ ("fg:ansiyellow bold", "(local) "), ("fg:ansimagenta bold", "pwncat"), ("", "$ "), ], completer=completer, lexer=lexer, style=style, auto_suggest=auto_suggest, complete_while_typing=False, history=history, ) self.toolbar = PromptSession( [ ("fg:ansiyellow bold", "(local) "), ("fg:ansimagenta bold", "pwncat"), ("", "$ "), ], completer=completer, lexer=lexer, style=style, auto_suggest=auto_suggest, complete_while_typing=False, prompt_in_toolbar=True, history=history, )
def __init__(self): self.executer = Executer() self.command_start = '/' self._commands = { #|| -> both keys map to same value 'quit || exit': lambda: sys.exit(), 'reset': lambda: self.executer.reset(), 'undo': lambda: self.executer.fileIO.file_empty() or self.executer.fileIO. delete_last_line(), 'abort': lambda: 0, 'help': lambda: self.help_command(), } self._regular_start = '>>>' self._multiline_start = '...' self.indent = ' ' * 4 self.title = 'C REPL' self.style = style_from_pygments_cls(get_style_by_name('C_REPL')) self.set_title()
def __init__(self, comp_env, runtime_env, code_templ, lexer=None, output_dir='/tmp/repl/', output_name='repl', enclosers=[('{', '}')], prolog_char='$'): assert (isinstance(comp_env, CompilationEnvironment)) assert (isinstance(runtime_env, RuntimeEnvironment)) assert (isinstance(code_templ, CodeTemplate)) self.comp_env = comp_env self.runtime_env = runtime_env self.code_templ = code_templ self.lexer = None if lexer is None else PygmentsLexer(lexer) self.output_dir = output_dir self.prolog_lines = [] self.repl_lines = [] self.executions = defaultdict(list) self.output_name = output_name self.output_fname_nonce = 0 self.enclosers = enclosers self.prolog_char = prolog_char self.style = get_style_by_name('native') self.history = InMemoryHistory() if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) os.system(' '.join(['rm -rf', self.output_dir + '*']))
def __init__(self, **kwargs): stylename = kwargs.get('style_name', 'default') style = kwargs['style'] if 'style' in kwargs \ else styles.get_style_by_name(stylename) self.formatter = BBCodeFormatter(style=style) self.lexer = lexers.PythonLexer() self.text_color = '#000000' self._label_cached = Label() self.use_text_color = True super(CodeInput, self).__init__(**kwargs) self._line_options = kw = self._get_line_options() self._label_cached = Label(**kw) # use text_color as foreground color text_color = kwargs.get('foreground_color') if text_color: self.text_color = get_hex_from_color(text_color) # set foreground to white to allow text colors to show # use text_color as the default color in bbcodes self.use_text_color = False self.foreground_color = [1, 1, 1, .999] if not kwargs.get('background_color'): self.background_color = [.9, .92, .92, 1]
def __init__(self, dest='html', stylename='sphinx', trim_doctest_flags=None): # type: (unicode, unicode, bool) -> None self.dest = dest if stylename is None or stylename == 'sphinx': style = SphinxStyle elif stylename == 'none': style = NoneStyle elif '.' in stylename: module, stylename = stylename.rsplit('.', 1) style = getattr(__import__(module, None, None, ['__name__']), stylename) else: style = get_style_by_name(stylename) self.formatter_args = {'style': style} # type: Dict[unicode, Any] if dest == 'html': self.formatter = self.html_formatter else: self.formatter = self.latex_formatter self.formatter_args['commandprefix'] = 'PYG' self.trim_doctest_flags = trim_doctest_flags if trim_doctest_flags is not None: warnings.warn('trim_doctest_flags option for PygmentsBridge is now deprecated.', RemovedInSphinx30Warning, stacklevel=2)
def __init__(self, *args, **kwargs): """EQL Shell.""" super(EqlShell, self).__init__(*args, **kwargs) self.tty = callmethod(self.stdout, "isatty", False) self.multiline = False self.stop = False self.last_results = [] self.columns = [] self.input_file = None self.empty_count = 0 self.prompt_session = False self.config = None self.last_display_fn = None self.display_fn = None self.last_query = None if prompt_toolkit and self.tty: self.tk_lexer = None if EqlLexer: self.tk_lexer = PygmentsLexer(EqlLexer) self.tk_completer = ShellCompleter(self) self.tk_history = FileHistory(self.history_file + ".tk") style_cls = None # switch to something more friendly if get_style_by_name: style = get_style_by_name( "rrt" if sys.platform.startswith("win") else "monokai") if style: style_cls = style_from_pygments_cls(style) self.default_style = style_cls self.prompt_session = PromptSession(style=style_cls, history=self.tk_history, completer=self.tk_completer)
def loop(cursor, reserved=None, history_file=None, raise_=False, *args, **kwargs): lexer = PygmentsLexer(SqlLexer) completer = WordCompleter(reserved, ignore_case=True) style = style_from_pygments_cls(get_style_by_name('manni')) history = FileHistory(history_file) if history_file else None while True: try: query = prompt('sql> ', lexer=lexer, completer=completer, style=style, history=history) except (EOFError, KeyboardInterrupt): break # Control-D pressed. # run query query = query.strip('; ').replace('%', '%%') if query: try: result = cursor.execute(query, *args, **kwargs) except Exception as e: if raise_: raise print(e) continue columns = [t[0] for t in cursor.description or []] print(tabulate(result, headers=columns)) print('See ya!')
def create_radian_prompt_session(options, settings): history_file = ".radian_history" if options.no_history: history = ModalInMemoryHistory() elif not options.global_history and os.path.exists(history_file): history = ModalFileHistory(os.path.abspath(history_file)) else: history = ModalFileHistory( os.path.join(os.path.expanduser("~"), history_file)) if is_windows(): output = None else: output = CustomVt100Output.from_pty( sys.stdout, term=get_term_environment_variable()) def get_inputhook(): terminal_width = [None] def _(context): while True: if context.input_is_ready(): break try: process_events() except Exception: pass output_width = session.app.output.get_size().columns if output_width and terminal_width[0] != output_width: terminal_width[0] = output_width setoption("width", max(terminal_width[0], 20)) time.sleep(1.0 / 30) return _ def vi_mode_prompt(): if session.editing_mode.lower( ) == "vi" and settings.show_vi_mode_prompt: return settings.vi_mode_prompt.format( str(session.app.vi_state.input_mode)[3:6]) return "" def message(): if hasattr(session.current_mode, "get_message"): return ANSI(vi_mode_prompt() + session.current_mode.get_message()) elif hasattr(session.current_mode, "message"): message = session.current_mode.message if callable(message): return ANSI(vi_mode_prompt() + message()) else: return ANSI(vi_mode_prompt() + message) else: return "" session = ModalPromptSession( message=message, color_depth=ColorDepth.default(term=os.environ.get("TERM")), style=style_from_pygments_cls(get_style_by_name( settings.color_scheme)), editing_mode="VI" if settings.editing_mode in ["vim", "vi"] else "EMACS", history=history, enable_history_search=True, history_search_no_duplicates=settings.history_search_no_duplicates, search_ignore_case=settings.history_search_ignore_case, enable_suspend=True, tempfile_suffix=".R", input=CustomVt100Input(sys.stdin) if not is_windows() else None, output=output, inputhook=get_inputhook(), mode_class=RadianMode) apply_settings(session, settings) def browse_activator(session): message = session.prompt_text if BROWSE_PATTERN.match(message): session.browse_level = BROWSE_PATTERN.match(message).group(1) return True else: return False def browse_on_pre_accept(session): if session.default_buffer.text.strip() in [ "n", "s", "f", "c", "cont", "Q", "where", "help" ]: session.add_history = False def shell_process_text(session): text = session.default_buffer.text shell.run_command(text) input_processors = [] if settings.highlight_matching_bracket: input_processors.append(HighlightMatchingBracketProcessor()) session.register_mode( "r", activator=lambda session: session.prompt_text == settings.prompt, insert_new_line=True, history_share_with="browse", get_message=lambda: settings.prompt, multiline=settings.indent_lines, complete_while_typing=settings.complete_while_typing, lexer=PygmentsLexer(SLexer), completer=RCompleter(timeout=settings.completion_timeout), key_bindings=create_key_bindings(), input_processors=input_processors, prompt_key_bindings=create_r_key_bindings(prase_text_complete)) session.register_mode("shell", on_post_accept=shell_process_text, insert_new_line=True, get_message=lambda: settings.shell_prompt, multiline=settings.indent_lines, complete_while_typing=settings.complete_while_typing, lexer=None, completer=SmartPathCompleter(), prompt_key_bindings=create_shell_key_bindings()) session.register_mode( "browse", activator=browse_activator, # on_pre_accept=browse_on_pre_accept, # disable insert_new_line=True, history_share_with="r", get_message=lambda: settings.browse_prompt.format(session.browse_level ), multiline=settings.indent_lines, complete_while_typing=True, lexer=PygmentsLexer(SLexer), completer=RCompleter(timeout=settings.completion_timeout), input_processors=input_processors, prompt_key_bindings=create_r_key_bindings(prase_text_complete), switchable_from=False, switchable_to=False) session.register_mode("unknown", insert_new_line=False, get_message=lambda: session.prompt_text, complete_while_typing=False, lexer=None, completer=None, prompt_key_bindings=None, switchable_from=False, switchable_to=False, input_processors=[]) return session
def __init__(self, project=None, extra_locals=None): """ Launch the Brownie console. Arguments --------- project : `Project`, optional Active Brownie project to include in the console's local namespace. extra_locals: dict, optional Additional variables to add to the console namespace. """ console_settings = CONFIG.settings["console"] locals_dict = dict((i, getattr(brownie, i)) for i in brownie.__all__) locals_dict.update(_dir=dir, dir=self._dir, exit=_Quitter("exit"), quit=_Quitter("quit"), _console=self) if project: project._update_and_register(locals_dict) # only make GUI available if Tkinter is installed try: Gui = importlib.import_module("brownie._gui").Gui locals_dict["Gui"] = Gui except ModuleNotFoundError: pass if extra_locals: locals_dict.update(extra_locals) # create prompt session object history_file = str(_get_data_folder().joinpath(".history").absolute()) kwargs = {} if console_settings["show_colors"]: kwargs.update( lexer=PygmentsLexer(PythonLexer), style=style_from_pygments_cls( get_style_by_name(console_settings["color_style"])), include_default_pygments_style=False, ) if console_settings["auto_suggest"]: kwargs["auto_suggest"] = ConsoleAutoSuggest(self, locals_dict) if console_settings["completions"]: kwargs["completer"] = ConsoleCompleter(self, locals_dict) self.compile_mode = "single" self.prompt_session = PromptSession( history=SanitizedFileHistory(history_file, locals_dict), input=self.prompt_input, key_bindings=KeyBindings(), **kwargs, ) # add custom bindings key_bindings = self.prompt_session.key_bindings key_bindings.add(Keys.BracketedPaste)(self.paste_event) key_bindings.add("c-i")(self.tab_event) key_bindings.get_bindings_for_keys( ("c-i", ))[-1].filter = lambda: not self.tab_filter() # modify default bindings key_bindings = load_key_bindings() key_bindings.get_bindings_for_keys( ("c-i", ))[-1].filter = self.tab_filter if console_settings["auto_suggest"]: # remove the builtin binding for auto-suggest acceptance key_bindings = self.prompt_session.app.key_bindings accept_binding = key_bindings.get_bindings_for_keys(("right", ))[0] key_bindings._bindings2.remove(accept_binding.handler) # this is required because of a pytest conflict when using the debugging console if sys.platform == "win32": import colorama colorama.init() super().__init__(locals_dict)
def _make_style_from_name_or_cls(self, name_or_cls): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_overrides = {} if name_or_cls == 'legacy': legacy = self.colors.lower() if legacy == 'linux': style_cls = get_style_by_name('monokai') style_overrides = _style_overrides_linux elif legacy == 'lightbg': style_overrides = _style_overrides_light_bg style_cls = get_style_by_name('pastie') elif legacy == 'neutral': # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_cls = get_style_by_name('default') style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', }) # Hack: Due to limited color support on the Windows console # the prompt colors will be wrong without this if os.name == 'nt': style_overrides.update({ Token.Prompt: '#ansidarkgreen', Token.PromptNum: '#ansigreen bold', Token.OutPrompt: '#ansidarkred', Token.OutPromptNum: '#ansired bold', }) elif legacy =='nocolor': style_cls=_NoStyle style_overrides = {} else : raise ValueError('Got unknown colors: ', legacy) else : if isinstance(name_or_cls, string_types): style_cls = get_style_by_name(name_or_cls) else: style_cls = name_or_cls style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', } style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def init_prompt_toolkit_cli(self): if self.simple_prompt or ('JUPYTER_CONSOLE_TEST' in os.environ): # Simple restricted interface for tests so we can find prompts with # pexpect. Multi-line input not supported. async def prompt(): prompt = 'In [%d]: ' % self.execution_count raw = await async_input(prompt) return raw self.prompt_for_code = prompt self.print_out_prompt = \ lambda: print('Out[%d]: ' % self.execution_count, end='') return kb = KeyBindings() insert_mode = vi_insert_mode | emacs_insert_mode @kb.add("enter", filter=(has_focus(DEFAULT_BUFFER) & ~has_selection & insert_mode)) def _(event): b = event.current_buffer d = b.document if not (d.on_last_line or d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()): b.newline() return # Pressing enter flushes any pending display. This also ensures # the displayed execution_count is correct. self.handle_iopub() more, indent = self.check_complete(d.text) if (not more) and b.accept_handler: b.validate_and_handle() else: b.insert_text('\n' + indent) @kb.add("c-c", filter=has_focus(DEFAULT_BUFFER)) def _(event): event.current_buffer.reset() @kb.add("c-\\", filter=has_focus(DEFAULT_BUFFER)) def _(event): raise EOFError @kb.add("c-z", filter=Condition(lambda: suspend_to_background_supported())) def _(event): event.cli.suspend_to_background() @kb.add("c-o", filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode)) def _(event): event.current_buffer.insert_text("\n") # Pre-populate history from IPython's history database history = InMemoryHistory() last_cell = u"" for _, _, cell in self.history_manager.get_tail( self.history_load_length, include_latest=True): # Ignore blank lines and consecutive duplicates cell = cell.rstrip() if cell and (cell != last_cell): history.append_string(cell) style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#ff2200', Token.OutPromptNum: '#ff0000 bold', Token.RemotePrompt: '#999900', } if self.highlighting_style: style_cls = get_style_by_name(self.highlighting_style) else: style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = merge_styles([ style_from_pygments_cls(style_cls), style_from_pygments_dict(style_overrides), ]) editing_mode = getattr(EditingMode, self.editing_mode.upper()) langinfo = self.kernel_info.get('language_info', {}) lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text')) # If enabled in the settings, highlight matching brackets # when the DEFAULT_BUFFER has the focus input_processors = [ ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars='[](){}'), filter=has_focus(DEFAULT_BUFFER) & ~is_done & Condition(lambda: self.highlight_matching_brackets)) ] # Tell prompt_toolkit to use the asyncio event loop. # Obsolete in prompt_toolkit.v3 if not PTK3: use_asyncio_event_loop() self.pt_cli = PromptSession( message=(lambda: PygmentsTokens(self.get_prompt_tokens())), multiline=True, complete_style=self.pt_complete_style, editing_mode=editing_mode, lexer=PygmentsLexer(get_pygments_lexer(lexer)), prompt_continuation=( lambda width, lineno, is_soft_wrap: PygmentsTokens( self.get_continuation_tokens(width))), key_bindings=kb, history=history, completer=JupyterPTCompleter(self.Completer), enable_history_search=True, style=style, input_processors=input_processors, color_depth=(ColorDepth.TRUE_COLOR if self.true_color else None), )
def cli(spec, url, http_options): click.echo('Version: %s' % __version__) copied, config_path = config.initialize() if copied: click.echo('Config file not found. Initialized a new one: %s' % config_path) cfg = config.load() # Override pager/less options os.environ['PAGER'] = cfg['pager'] os.environ['LESS'] = '-RXF' if spec: f = urlopen(spec) try: content = f.read().decode('utf-8') try: spec = json.loads(content) except json.JSONDecodeError: click.secho("Warning: Specification file '%s' is not JSON" % spec, err=True, fg='red') spec = None finally: f.close() url = fix_incomplete_url(url) context = Context(url, spec=spec) output_style = cfg.get('output_style') if output_style: context.options['--style'] = output_style # For prompt-toolkit history = InMemoryHistory() lexer = PygmentsLexer(HttpPromptLexer) completer = HttpPromptCompleter(context) try: style_class = get_style_by_name(cfg['command_style']) except ClassNotFound: style_class = Solarized256Style style = style_from_pygments(style_class) listener = ExecutionListener(cfg) # Execute HTTPie options from CLI or load from last context if len(sys.argv) > 1: http_options = [smart_quote(a) for a in http_options] execute(' '.join(http_options), context, listener=listener) else: load_context(context) while True: try: text = prompt('%s> ' % context.url, completer=completer, lexer=lexer, style=style, history=history, auto_suggest=AutoSuggestFromHistory(), on_abort=AbortAction.RETRY, vi_mode=cfg['vi']) except EOFError: break # Control-D pressed else: execute(text, context, listener=listener, style=style_class) if context.should_exit: break click.echo("Goodbye!")
import os import os.path import re from collections import namedtuple from pygments import highlight from pygments.lexers.c_cpp import CLexer from pygments.styles import get_style_by_name from pygments.formatters import Terminal256Formatter from amidev.binfmt import hunk TheFormatter = Terminal256Formatter(style=get_style_by_name('monokai')) Segment = namedtuple('Segment', 'start size') class StabInfoParser(): # https://sourceware.org/gdb/onlinedocs/stabs/ Types = namedtuple('Types', 'decls') Entry = namedtuple('Entry', 'name value') Field = namedtuple('Field', 'name type offset size') StructType = namedtuple('StructType', 'size fields') UnionType = namedtuple('UnionType', 'size fields') EnumType = namedtuple('EnumType', 'values') SizeOf = namedtuple('SizeOf', 'size type') Subrange = namedtuple('Subrange', 'itype lo hi') ArrayType = namedtuple('ArrayType', 'range type') Function = namedtuple('Function', 'name attr type')
def session_initialize(session): if not sys.platform.startswith("win"): def reticulate_hook(*args): rcall(("base", "source"), os.path.join(os.path.dirname(__file__), "data", "patching_reticulate.R"), new_env()) set_hook(package_event("reticulate", "onLoad"), reticulate_hook) if not roption("radian.suppress_reticulate_message", False): def reticulate_message_hook(*args): if not roption("radian.suppress_reticulate_message", False): rcall("packageStartupMessage", RETICULATE_MESSAGE) set_hook(package_event("reticulate", "onLoad"), reticulate_message_hook) if roption("radian.enable_reticulate_prompt", True): def reticulate_prompt(*args): rcall(("base", "source"), os.path.join(os.path.dirname(__file__), "data", "register_reticulate.R"), new_env()) set_hook(package_event("reticulate", "onLoad"), reticulate_prompt) if roption("radian.editing_mode", "emacs") in ["vim", "vi"]: session.app.editing_mode = EditingMode.VI else: session.app.editing_mode = EditingMode.EMACS color_scheme = roption("radian.color_scheme", "native") session.style = style_from_pygments_cls(get_style_by_name(color_scheme)) session.auto_match = roption("radian.auto_match", False) session.auto_indentation = roption("radian.auto_indentation", True) session.tab_size = int(roption("radian.tab_size", 4)) session.complete_while_typing = roption("radian.complete_while_typing", True) session.completion_timeout = roption("radian.completion_timeout", 0.05) session.history_search_no_duplicates = roption( "radian.history_search_no_duplicates", False) session.insert_new_line = roption("radian.insert_new_line", True) session.indent_lines = roption("radian.indent_lines", True) prompt = roption("radian.prompt", None) if not prompt: sys_prompt = roption("prompt") if sys_prompt == "> ": prompt = PROMPT else: prompt = sys_prompt session.default_prompt = prompt setoption("prompt", prompt) shell_prompt = roption("radian.shell_prompt", SHELL_PROMPT) session.shell_prompt = shell_prompt browse_prompt = roption("radian.browse_prompt", BROWSE_PROMPT) session.browse_prompt = browse_prompt set_width_on_resize = roption("setWidthOnResize", True) session.auto_width = roption("radian.auto_width", set_width_on_resize) output_width = session.app.output.get_size().columns if output_width and session.auto_width: setoption("width", output_width) # necessary on windows setoption("menu.graphics", False) # enables completion of installed package names if rcopy(reval("rc.settings('ipck')")) is None: reval("rc.settings(ipck = TRUE)") # backup the updated settings session._backup_settings()
from pyramid.util import DottedNameResolver from pyramid.settings import asbool from pyramid_debugtoolbar.compat import binary_type from pyramid_debugtoolbar.compat import text_type from pyramid_debugtoolbar.compat import string_types from pyramid_debugtoolbar.compat import text_ from pyramid_debugtoolbar import ipaddr try: from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import SqlLexer from pygments.styles import get_style_by_name PYGMENT_STYLE = get_style_by_name('colorful') HAVE_PYGMENTS = True except ImportError: # pragma: no cover HAVE_PYGMENTS = False SETTINGS_PREFIX = 'debugtoolbar.' STATIC_PATH = 'pyramid_debugtoolbar:static/' ROOT_ROUTE_NAME = 'debugtoolbar.root' EXC_ROUTE_NAME = 'debugtoolbar.exception' def format_fname(value, _sys_path=None): if _sys_path is None: _sys_path = sys.path # dependency injection # If the value is not an absolute path, the it is a builtin or # a relative file (thus a project file).
def process_request(self, req): style = req.args['style'] try: style_cls = get_style_by_name(style) except ValueError, e: raise HTTPNotFound(e)
def init_prompt_toolkit_cli(self): if self.simple_prompt or ('JUPYTER_CONSOLE_TEST' in os.environ): # Simple restricted interface for tests so we can find prompts with # pexpect. Multi-line input not supported. def prompt(): return cast_unicode_py2( input('In [%d]: ' % self.execution_count)) self.prompt_for_code = prompt self.print_out_prompt = \ lambda: print('Out[%d]: ' % self.execution_count, end='') return kbmanager = KeyBindingManager.for_prompt() insert_mode = ViInsertMode() | EmacsInsertMode() # Ctrl+J == Enter, seemingly @kbmanager.registry.add_binding(Keys.ControlJ, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode)) def _(event): b = event.current_buffer d = b.document if not (d.on_last_line or d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()): b.newline() return # Pressing enter flushes any pending display. This also ensures # the displayed execution_count is correct. self.handle_iopub() more, indent = self.check_complete(d.text) if (not more) and b.accept_action.is_returnable: b.accept_action.validate_and_handle(event.cli, b) else: b.insert_text('\n' + indent) @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)) def _(event): event.current_buffer.reset() @kbmanager.registry.add_binding(Keys.ControlBackslash, filter=HasFocus(DEFAULT_BUFFER)) def _(event): raise EOFError # Pre-populate history from IPython's history database history = InMemoryHistory() last_cell = u"" for _, _, cell in self.history_manager.get_tail( self.history_load_length, include_latest=True): # Ignore blank lines and consecutive duplicates cell = cast_unicode_py2(cell.rstrip()) if cell and (cell != last_cell): history.append(cell) style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#ff2200', Token.OutPromptNum: '#ff0000 bold', } if self.highlighting_style: style_cls = get_style_by_name(self.highlighting_style) else: style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) editing_mode = getattr(EditingMode, self.editing_mode.upper()) langinfo = self.kernel_info.get('language_info', {}) lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text')) app = create_prompt_application( multiline=True, editing_mode=editing_mode, lexer=PygmentsLexer(get_pygments_lexer(lexer)), get_prompt_tokens=self.get_prompt_tokens, get_continuation_tokens=self.get_continuation_tokens, key_bindings_registry=kbmanager.registry, history=history, completer=JupyterPTCompleter(self.Completer), enable_history_search=True, style=style, ) self._eventloop = create_eventloop() self.pt_cli = CommandLineInterface( app, eventloop=self._eventloop, output=create_output(true_color=self.true_color), )
def cli(spec, env, url, http_options): click.echo('Version: %s' % __version__) copied, config_path = config.initialize() if copied: click.echo('Config file not found. Initialized a new one: %s' % config_path) cfg = config.load() # Override pager/less options os.environ['PAGER'] = cfg['pager'] os.environ['LESS'] = '-RXF' if spec: f = urlopen(spec) try: content = f.read().decode('utf-8') try: spec = json.loads(content) except json.JSONDecodeError: try: spec = yaml.load(content, Loader=yaml.SafeLoader) except yaml.YAMLError: click.secho( "Warning: Specification file '%s' is neither valid JSON nor YAML" % spec, err=True, fg='red') spec = None finally: f.close() else: spec = "https://redfish.dmtf.org/schemas/openapi.yaml" click.echo( "Loading current Redfish OpenAPI schema from '%s' by default; use --spec option on launch if needed to override" % spec) f = urlopen(spec) content = f.read().decode('utf-8') try: spec = yaml.load(content, Loader=yaml.SafeLoader) except yaml.YAMLError: click.secho("Warning: Specification file '%s' is not valid YAML" % spec, err=True, fg='red') spec = None finally: f.close() if url: url = fix_incomplete_url(url) context = Context(url, spec=spec) output_style = cfg.get('output_style') if output_style: context.options['--style'] = output_style # For prompt-toolkit history = FileHistory(os.path.join(get_data_dir(), 'history')) lexer = PygmentsLexer(HttpPromptLexer) completer = HttpPromptCompleter(context) try: style_class = get_style_by_name(cfg['command_style']) except ClassNotFound: style_class = Solarized256Style style = style_from_pygments(style_class) listener = ExecutionListener(cfg) if len(sys.argv) == 1: # load previous context if nothing defined load_context(context) else: if env: load_context(context, env) if url: # Overwrite the env url if not default context.url = url if http_options: # Execute HTTPie options from CLI (can overwrite env file values) http_options = [smart_quote(a) for a in http_options] execute(' '.join(http_options), context, listener=listener) while True: try: text = prompt('%s> ' % context.url, completer=completer, lexer=lexer, style=style, history=history, auto_suggest=AutoSuggestFromHistory(), on_abort=AbortAction.RETRY, vi_mode=cfg['vi']) except EOFError: break # Control-D pressed else: execute(text, context, listener=listener, style=style_class) if context.should_exit: break click.echo("Goodbye!")
def dark_style(stylename): """Guess whether the background of the style with name 'stylename' counts as 'dark'.""" return dark_color(get_style_by_name(stylename).background_color)
def _lookup_style(style): if isinstance(style, string_types): return get_style_by_name(style) return style
from functools import partial from pygments.lexers.html import HtmlLexer from pygments.styles import get_style_by_name from prompt_toolkit.shortcuts import prompt from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.styles.pygments import style_from_pygments_cls from prompt_toolkit import HTML style = style_from_pygments_cls(get_style_by_name('monokai')) text = prompt('Enter HTML: ', lexer=PygmentsLexer(HtmlLexer), style=style, include_default_pygments_style=False) print('You said: %s' % text) prompt([('class:red', 'this will be in red')]) from prompt_toolkit.shortcuts import prompt from prompt_toolkit.styles import Style style = Style.from_dict({ # User input (default text). '': '#ff0066', # Prompt. 'username': '******', 'at': '#00aa00', 'colon': '#0000aa', 'pound': '#00aa00', 'host': '#00ffff bg:#444400', 'path': 'ansicyan underline', })
def init_prompt_toolkit_cli(self): if ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or not sys.stdin.isatty(): # Fall back to plain non-interactive output for tests. # This is very limited, and only accepts a single line. def prompt(): return cast_unicode_py2( input('In [%d]: ' % self.execution_count)) self.prompt_for_code = prompt return kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode) insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT) # Ctrl+J == Enter, seemingly @kbmanager.registry.add_binding(Keys.ControlJ, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode)) def _(event): b = event.current_buffer d = b.document if not (d.on_last_line or d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()): b.newline() return status, indent = self.input_splitter.check_complete(d.text) if (status != 'incomplete') and b.accept_action.is_returnable: b.accept_action.validate_and_handle(event.cli, b) else: b.insert_text('\n' + (' ' * (indent or 0))) @kbmanager.registry.add_binding(Keys.ControlC) def _(event): event.current_buffer.reset() @Condition def cursor_in_leading_ws(cli): before = cli.application.buffer.document.current_line_before_cursor return (not before) or before.isspace() # Ctrl+I == Tab @kbmanager.registry.add_binding(Keys.ControlI, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode & cursor_in_leading_ws)) def _(event): event.current_buffer.insert_text(' ' * 4) # Pre-populate history from IPython's history database history = InMemoryHistory() last_cell = u"" for _, _, cell in self.history_manager.get_tail( self.history_load_length, include_latest=True): # Ignore blank lines and consecutive duplicates cell = cell.rstrip() if cell and (cell != last_cell): history.append(cell) style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', } if self.highlighting_style: style_cls = get_style_by_name(self.highlighting_style) else: style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) app = create_prompt_application( multiline=True, lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer), get_prompt_tokens=self.get_prompt_tokens, get_continuation_tokens=self.get_continuation_tokens, key_bindings_registry=kbmanager.registry, history=history, completer=IPythonPTCompleter(self.Completer), enable_history_search=True, style=style, mouse_support=self.mouse_support, ) self.pt_cli = CommandLineInterface(app, eventloop=create_eventloop( self.inputhook))