Пример #1
0
def highlight_python(python_scripts,activity='open',text_style='vim'):
    #['manni', 'igor', 'lovelace', 'xcode', 'vim', 'autumn', 'abap', 'vs', 'rrt', 'native', 'perldoc', 'borland', 'arduino', 'tango', 'emacs', 'friendly', 'monokai', 'paraiso-dark', 'colorful', 'murphy', 'bw', 'pastie', 'rainbow_dash', 'algol_nu', 'paraiso-light', 'trac', 'default', 'algol', 'fruity']
   
    formatter = HtmlFormatter(encoding='utf-8', style = text_style, linenos = True)
    print STYLE_MAP.keys()
    code=''
    if activity=='run':
        #formatter = HtmlFormatter(encoding='utf-8', style = 'manni', linenos = True)
        p = re.compile(r'<img(.{10,100}) />')
        splitlist=p.split(python_scripts)
        findlist =p.findall(python_scripts)
        for str_ in splitlist:
            if str_ not in findlist:
                 code+=highlight(str_,PythonLexer(),formatter)
            else:
                 code+='<img '+str_+" style='border:3px solid #aaaaaa;'"+'/>'
            print 'split:{},{}'.format(str_,len(p.split(python_scripts)))
        for str_ in findlist:
            print 'findall:{},{}'.format(str_,len(p.findall(python_scripts)))
        #code = highlight(python_scripts, PythonLexer(), formatter)
        #code = highlight(python_scripts, PythonLexer(), formatter)
    else: 
        code = highlight(python_scripts, PythonLexer(), formatter)
        #print code
        #print css
    css = formatter.get_style_defs('.highlight') 
    return code,css
Пример #2
0
def fillStyleComboBox (config, comboBox, selectedStyle):
    """
    Заполнить ComboBox имеющимися стилями
    config - конфиг, откда будут читаться настройки (экземпляр класса SourceConfig)
    comboBox - ComboBox, который будет заполняться
    selectedStyle - стиль, который должен быть выбран по умолчанию
    """
    from pygments.styles import STYLE_MAP

    styles = STYLE_MAP.keys()
    styles.sort()

    assert len (styles) > 0

    comboBox.Clear()
    comboBox.AppendItems (styles)

    if selectedStyle not in styles:
        selectedStyle = getDefaultStyle (config)

    if selectedStyle in STYLE_MAP:
        index = styles.index (selectedStyle)
        assert index >= 0

        comboBox.SetSelection (index)
Пример #3
0
 def make_default_style_picker(self) -> W.Dropdown:
     widget = W.Dropdown(
         description="Style",
         options=list(STYLE_MAP.keys()),
         layout=W.Layout(min_height="30px"),
     )
     T.link((self, "formatter_style"), (widget, "value"))
     return widget
Пример #4
0
class QueryColorizer(W.VBox):
    """Takes sparql query and runs it through pygments lexer and html formatter"""

    query = T.Unicode()
    formatter_style = T.Enum(values=list(STYLE_MAP.keys()),
                             default_value="colorful")
    style_picker = T.Instance(W.Dropdown)
    html_output = T.Instance(W.HTML)

    _style_defs = T.Unicode(default_value="")
    formatter: HtmlFormatter = None
    _sqrl_lexer: SparqlLexer = None

    @T.default("style_picker")
    def make_default_style_picker(self) -> W.Dropdown:
        widget = W.Dropdown(
            description="Style",
            options=list(STYLE_MAP.keys()),
            layout=W.Layout(min_height="30px"),
        )
        T.link((self, "formatter_style"), (widget, "value"))
        return widget

    @T.default("html_output")
    def make_default_html_output(self) -> W.HTML:
        widget = W.HTML()
        widget.layout = {"width": "50%"}
        return widget

    @T.validate("children")
    def validate_children(self, proposal):
        """
        Validate method for default children.
        This is necessary because @trt.default does not work on children.
        """
        children = proposal.value
        if not children:
            children = (self.style_picker, self.html_output)
        return children

    @T.observe("formatter_style")
    def _update_style(self, change=None) -> HtmlFormatter:
        """update the css style from the formatter"""
        self.formatter = HtmlFormatter(style=self.formatter_style)
        self._sqrl_lexer = SparqlLexer()
        self._style_defs = f"<style>{self.formatter.get_style_defs()}</style>"

    @T.observe(
        "query",
        "_style_defs",
    )
    def update_formatted_query(self, change):
        """Update the html output widget with the highlighted query"""
        if not self.formatter or not self._sqrl_lexer:
            self._update_style()
        self.html_output.value = self._style_defs + highlight(
            self.query, self._sqrl_lexer, self.formatter)
Пример #5
0
class QueryColorizer(W.VBox):
    """Takes sparql query and runs it through pygments lexer and html formatter"""

    query = T.Unicode()
    formatter_style = T.Enum(values=list(STYLE_MAP.keys()),
                             default_value="colorful")
    style_picker = T.Instance(
        W.Dropdown,
        kw=dict(
            description="Style",
            options=list(STYLE_MAP.keys()),
            layout=W.Layout(min_height="30px"),
        ),
    )
    html_output = T.Instance(W.HTML, kw={})

    _style_defs = T.Unicode(default_value="")
    formatter: HtmlFormatter = None
    _sqrl_lexer: SparqlLexer = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        T.link((self, "formatter_style"), (self.style_picker, "value"))
        self.children = [self.style_picker, self.html_output]

    @T.observe("formatter_style")
    def _update_style(self, change=None) -> HtmlFormatter:
        """update the css style from the formatter"""
        self.formatter = HtmlFormatter(style=self.formatter_style)
        self._sqrl_lexer = SparqlLexer()
        self._style_defs = f"<style>{self.formatter.get_style_defs()}</style>"

    @T.observe(
        "query",
        "_style_defs",
    )
    def update_formatted_query(self, change):
        """Update the html output widget with the highlighted query"""
        if not self.formatter or not self._sqrl_lexer:
            self._update_style()
        self.html_output.value = self._style_defs + highlight(
            self.query, self._sqrl_lexer, self.formatter)
Пример #6
0
def all_styles(code,
               outpath,
               lexer=PanelcodeLexer(),
               prefix='test_',
               suffix='.html'):
    """Given code, outputs an HTML file for each available built-in style.
    A testing class for quickly previewing how a particular approach to
    lexer token naming will look across a variety of pre-existing styles.
    """
    # print(STYLE_MAP.keys())
    for smkey in STYLE_MAP.keys():  # pylint: disable=C0201
        fname = outpath + '/' + prefix + smkey + suffix
        with open(fname, 'w') as htmlfile:
            formatter = HtmlFormatter(style=smkey)
            formatter.full = True
            highlight(code, lexer, formatter, outfile=htmlfile)
Пример #7
0
def test_style_from_pygments():
    styles = sorted(STYLE_MAP.keys())

    def compare_style_lists(style, l1, l2):
        d1 = dict(l1)
        d2 = dict(l2)
        keys = sorted(list(set(*[d1.keys() + d2.keys()])))

        for k in keys:
            assert d1[k] == d2[k], '{} != {} (style: {}, token: {})'.format(
                    d1[k], d2[k], style, k)

    def test(style):
        pygments_style = get_style_by_name(style)
        pygout_style = create_style_from_pygments(style)
        # Check that all token styles are the same - at this point they haven't
        # been via TokenStyleEditor.
        compare_style_lists(style, pygments_style.list_styles(),
                            pygout_style.list_styles())
        new_pygout_style = create_style(None, pygout_style.pygout_styles)
        # Check that a style that's gone via the TokenStyleEditor conversion
        # still is the same style.
        compare_style_lists(style, pygout_style.list_styles(),
                            new_pygout_style.list_styles())
Пример #8
0
# Set to True if you want inline CSS styles instead of classes
INLINESTYLES = True

from pygments.formatters import HtmlFormatter

from pygments.styles import STYLE_MAP

# The default formatter
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)

# Add name -> formatter pairs for every variant you want to use
VARIANTS = {
    'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
}

for style in STYLE_MAP.keys():
    VARIANTS[style] = HtmlFormatter(noclasses=INLINESTYLES, style=style)

from docutils import nodes
from docutils.parsers.rst import directives, Directive

from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer


class Pygments(Directive):
    """ Source code syntax hightlighting.
    """
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True
Пример #9
0
# -*- coding: utf-8 -*-
#   Copyright (C) 2015 Rocky Bernstein
#

from pygments.styles import STYLE_MAP

style_names = sorted(list(STYLE_MAP.keys()))

# Our local modules
from trepan.processor.command import base_subcmd as Mbase_subcmd
from trepan.processor import cmdfns as Mcmdfns
from trepan.lib import complete as Mcomplete


class SetStyle(Mbase_subcmd.DebuggerSubcommand):
    """**set style* *pygments-style*

    Set the pygments style in to use in formatting text for a 256-color terminal.
    Note: if your terminal doesn't support 256 colors, you may be better off
    using `--highlight=plain` or `--highlight=dark` instead. To turn off styles
    use `set style none`.

    To list the available pygments styles inside the debugger, use command
    completion on `set style`. Or Give an invalid name, and a list of the
    available pygments styles also shown.

    Examples:
    ---------
    set style colorful   # Pygments 'colorful' style
    set style fdasfda    # Probably display available styles
    set style none       # Turn off style, still use highlight though
Пример #10
0
import importlib

from pygments.lexer import RegexLexer, bygroups
from pygments.styles import STYLE_MAP
from pygments.token import *


def load_style(full_class_string):
    modulename, styleclass = full_class_string.split('::')
    module = importlib.import_module("pygments.styles." + modulename)
    return getattr(module, styleclass)


repl_styles = {}
for name, import_info in STYLE_MAP.items():
    repl_styles[name] = load_style(import_info)
    repl_styles[name].styles[Whitespace] = ''  # some styles underline ws


class FranzLexer(RegexLexer):
    name = 'Franz Lexer'
    tokens = {
        'root':
        [(r'"', String.Double, 'double-quote'), (r'[0-9]+(\.[0-9]+)?', Number),
         (r'\b(if|else|for|while|in|to|fn|ⲗ|try|rescue|assert|include|yield|return|break|continue)\b',
          Keyword.Reserved),
         (r'\b(int|str|any|float|list|dict|bool)\b', Keyword.Type),
         (r'\b(and|or|not)\b', Operator.Word), (r'#.*?$', Comment.Single),
         (r'([a-zA-Z][a-zA-Z0-9_!?\-%$]*)(\s*)(=)(\s*)(fn)',
          bygroups(Name.Function.Definition, Whitespace, Operator, Whitespace,
                   Keyword.Reserved)),
Пример #11
0
def set(key, value):
    """
  Set the value of a bibmanager config parameter.

  Parameters
  ----------
  key: String
     bibmanager config parameter to set.
  value: String
     Value to set for input parameter.

  Examples
  --------
  >>> import bibmanager.config_manager as cm
  >>> # Update text editor:
  >>> cm.set('text_editor', 'vim')
  text_editor updated to: vim.

  >>> # Invalid bibmanager parameter:
  >>> cm.set('styles', 'arduino')
  ValueError: 'styles' is not a valid bibmanager config parameter.
  The available parameters are:
    ['style', 'text_editor', 'paper', 'ads_token', 'ads_display', 'home']

  >>> # Attempt to set an invalid style:
  >>> cm.set('style', 'fake_style')
  ValueError: 'fake_style' is not a valid style option.  Available options are:
    default, emacs, friendly, colorful, autumn, murphy, manni, monokai, perldoc,
    pastie, borland, trac, native, fruity, bw, vim, vs, tango, rrt, xcode, igor,
    paraiso-light, paraiso-dark, lovelace, algol, algol_nu, arduino,
    rainbow_dash, abap

  >>> # Attempt to set an invalid command for text_editor:
  >>> cm.set('text_editor', 'my_own_editor')
  ValueError: 'my_own_editor' is not a valid text editor.

  >>> # Beware, one can still set a valid command that doesn't edit text:
  >>> cm.set('text_editor', 'less')
  text_editor updated to: less.
  """
    config = configparser.ConfigParser()
    config.read(u.HOME + 'config')

    if not config.has_option('BIBMANAGER', key):
        # Use get on invalid key to raise an error:
        get(key)

    # Check for exceptions:
    if key == 'style' and value not in STYLE_MAP.keys():
        raise ValueError(f"'{value}' is not a valid style option.  "
                         f"Available options are:\n{styles}")

    # The code identifies invalid commands, but cannot assure that a
    # command actually applies to a text file.
    if key == 'text_editor' and value != 'default' and shutil.which(
            value) is None:
        raise ValueError(f"'{value}' is not a valid text editor.")

    if key == 'ads_display' and (not value.isnumeric() or value == '0'):
        raise ValueError(f"The {key} value must be a positive integer.")

    if key == 'home':
        value = os.path.abspath(os.path.expanduser(value)) + '/'
        new_home = pathlib.Path(value)
        if not new_home.parent.is_dir():
            raise ValueError(f"The {key} value must have an existing parent "
                             "folder")
        if new_home.suffix != '':
            raise ValueError(f"The {key} value cannot have a file extension")

        # Make sure folders will exist:
        new_home.mkdir(exist_ok=True)
        with pathlib.Path(f'{value}pdf') as pdf_dir:
            pdf_dir.mkdir(exist_ok=True)

        # Files to move (config has to stay at u.HOME):
        bm_files = [
            u.BM_DATABASE(),
            u.BM_BIBFILE(),
            u.BM_CACHE(),
            u.BM_HISTORY_SEARCH(),
            u.BM_HISTORY_ADS(),
            u.BM_HISTORY_PDF(),
        ]
        pdf_files = [
            f'{u.BM_PDF()}{bib.pdf}' for bib in bm.load()
            if bib.pdf is not None if os.path.isfile(f'{u.BM_PDF()}{bib.pdf}')
        ]

        # Merge if there is already a Bibmanager database in new_home:
        new_database = f'{new_home}/{os.path.basename(u.BM_DATABASE())}'
        if os.path.isfile(new_database):
            pickle_ver = bm.get_version(new_database)
            if version.parse(__version__) < version.parse(pickle_ver):
                print(
                    f"Bibmanager version ({__version__}) is older than saved "
                    f"database.  Please update to a version >= {pickle_ver}.")
                return
            new_biblio = f'{new_home}/{os.path.basename(u.BM_BIBFILE())}'
            bm.merge(new=bm.loadfile(new_biblio), take='new')

        # Move (overwrite) database files:
        bm_files = [bm_file for bm_file in bm_files if os.path.isfile(bm_file)]
        new_files = os.listdir(new_home)
        for bm_file in bm_files:
            if os.path.basename(bm_file) in new_files:
                os.remove(f'{new_home}/{os.path.basename(bm_file)}')
            shutil.move(bm_file, str(new_home))

        # Move (overwrite) PDF files:
        new_pdfs = os.listdir(f'{new_home}/pdf')
        for pdf_file in pdf_files:
            if os.path.basename(pdf_file) in new_pdfs:
                os.remove(f'{new_home}/pdf/{os.path.basename(pdf_file)}')
            shutil.move(pdf_file, f'{new_home}/pdf/')

    # Set value if there were no exceptions raised:
    config.set('BIBMANAGER', key, value)
    with open(u.HOME + 'config', 'w') as configfile:
        config.write(configfile)
    print(f'{key} updated to: {value}.')
Пример #12
0
    def run():
        # Test the presence of Pygments
        isPygments = False
        try:
            from pygments.styles import STYLE_MAP
            isPygments = True
        except BaseException:
            print(
                "Pygments is not installed, code blocks won't be highlighted")

        # Allowed themes and transitions
        themes = ['default', 'beige', 'night']
        transitions = [
            'default', 'cube', 'page', 'concave', 'zoom', 'linear', 'fade',
            'none'
        ]
        options = [
            'input_file', 'output_file', 'theme', 'transition', 'mathjax_path',
            'pygments_style'
        ]
        if isPygments:
            pygments_styles = STYLE_MAP.keys()

        # Define arguments
        argparser = argparse.ArgumentParser(
            formatter_class=argparse.RawTextHelpFormatter)
        argparser.description = "reStructuredText to HTML slide generator using reveal.js."
        argparser.add_argument(
            "input_file",
            help="The name of the reStructuredText file to parse.")
        argparser.add_argument(
            "-o",
            "--output_file",
            type=str,
            help=
            "The name of the HTML file to produce (by default the same basename as the input file with a .html suffix."
        )
        argparser.add_argument(
            "-u",
            "--update_file",
            type=str,
            help=
            "The name of a previously generated HTML file for updating only the headers part."
        )

        argparser.add_argument(
            "-t",
            "--theme",
            type=str,
            help="Set rstslide theme (overrides theme set in input file)")

        mode = argparser.add_mutually_exclusive_group(required=False)
        mode.add_argument("-S",
                          "--slide",
                          action='store_true',
                          help="Normal slide mode (default).")
        mode.add_argument(
            "-P",
            "--pdf",
            action='store_true',
            help="Pdf rendering mode (run and follow instructions).")
        mode.add_argument(
            "-N",
            "--pdf-with-notes",
            action='store_true',
            help="Pdf rendering mode with notes (run and follow instructions)."
        )
        mode.add_argument("-H",
                          "--handout",
                          action='store_true',
                          help="Handout rendering mode.")
        mode.add_argument(
            "-X",
            "--handout-alt",
            action='store_true',
            help=
            "An alternative handout rendering mode that uses the default html5 docutils converter."
        )

        argparser.add_argument("-s",
                               "--serve",
                               action='store_true',
                               help="Start webserver that serves the slides.")
        argparser.add_argument('-v',
                               '--version',
                               action='version',
                               version='rstslide ' + version)
        argparser.add_argument('-d',
                               '--debug',
                               action='store_true',
                               help="Write debug output on stdout")

        resource_mgmt_choices = {
            'central':
            "Use centralized resources from where rstslide is installed",
            'local':
            "Copy needed resources to a directory <outfile>-resources",
            'inline': "Embedd all resources into a single file HTML document"
        }

        argparser.add_argument(
            "-r",
            "--resources",
            type=str,
            choices=resource_mgmt_choices,
            help=
            "How to handle resources that the presentation is dependent on:\n"
            + '\n'.join("{}: {}".format(key, value)
                        for key, value in resource_mgmt_choices.items()))
        args = argparser.parse_args()

        # input file name
        filename = args.input_file
        # output file name
        if args.output_file:
            output_file = args.output_file
        else:
            output_file = filename.split('.')[-2] + '.html'

        mode = 'slide'
        notes = False
        if args.pdf or args.pdf_with_notes:
            mode = 'print'
            notes = True
        elif args.handout_alt:
            mode = 'handout-alt'
        elif args.handout:
            mode = 'handout'

        if (args.pdf or args.serve) and args.resources is None:
            args.resources = 'local'

        if (args.pdf or args.serve) and args.resources == 'central':
            print(
                "Pdf printing or serving does not work with resource option 'central', exiting."
            )
            exit(1)

        # Create the RST parser and create the slides
        if mode != 'handout-alt':
            parser = SlidesParser(input_file=filename,
                                  output_file=output_file,
                                  theme=args.theme,
                                  resources=args.resources,
                                  mode=mode,
                                  notes=notes,
                                  debug=args.debug)
            parser.create_slides()
        else:
            parser = HandoutParser(input_file=filename,
                                   output_file=output_file,
                                   theme=args.theme,
                                   resources=args.resources,
                                   mode=mode,
                                   notes=notes,
                                   debug=args.debug)
            parser.create_handout()

        if args.pdf or args.serve:
            port = 8000
            handler = httpserver.SimpleHTTPRequestHandler
            httpd = socketserver.TCPServer(("", port), handler)
            if args.serve:
                print("The slides are served here:")
                print("  http://127.0.0.1:8000/" + output_file + "?print-pdf")
                print("To end serving the slides, end the program with Ctrl+C")
            else:
                print(
                    "Follow the following steps to export the slides as pdf:")
                print("1. Open the following URL in your web browser:")
                print("  http://127.0.0.1:8000/" + output_file + "?print-pdf")
                print("2. Wait for everything to load and then print to pdf")
                print(
                    "  (this is known to work in Google Chrome and similar browsers.)"
                )
                print("3. End this program with Ctrl+C")
            try:
                httpd.serve_forever()
            except KeyboardInterrupt:
                pass
            finally:
                # Clean-up server (close socket, etc.)
                httpd.server_close()
Пример #13
0
def run(argv=None):
    parser = argparse.ArgumentParser(description="Lanius Markdown Viewer.")
    parser.add_argument('-v', '--version', action='version', version=version)

    default_arg = os.getenv('LANIUS_THEME', 'default')
    parser.add_argument('-t',
                        '--theme',
                        default=default_arg,
                        help="theme to use for markdown display",
                        metavar='KEY',
                        choices=THEME_LIST.keys())

    default_arg = os.getenv('LANIUS_STYLE', 'monokai')
    parser.add_argument('-x',
                        '--style',
                        default=default_arg,
                        help="syntax highlighting style to use",
                        metavar='KEY',
                        choices=STYLE_MAP.keys())

    default_arg = os.getenv('LANIUS_FORMAT', 'color256')
    parser.add_argument('-f',
                        '--format',
                        default=default_arg,
                        help="syntax highlighting format to use",
                        metavar='KEY',
                        choices=['none', 'color', 'color256'])

    default_arg = os.getenv('LANIUS_STRIP', '').strip() != ''
    parser.add_argument('-s',
                        '--strip',
                        default=default_arg,
                        help="strip whitespace at start and end",
                        action='store_true')

    default_arg = os.getenv('LANIUS_JUSTIFY', '').strip() != ''
    parser.add_argument('-j',
                        '--justify',
                        default=default_arg,
                        help="attempt to right-justify the text",
                        action='store_true')

    parser.add_argument('file',
                        nargs='?',
                        default=['-'],
                        help="path to markdown file",
                        metavar='PATH')

    args = parser.parse_args(argv)

    if args.theme not in THEME_LIST.keys():
        raise ValueError("Invalid theme '{0}'".format(args.theme))

    if args.style not in STYLE_MAP.keys():
        raise ValueError("Invalid style '{0}'".format(args.style))

    if args.format not in ['none', 'color', 'color256']:
        raise ValueError("Invalid format '{0}'".format(args.format))

    exts = [
        'markdown.extensions.smart_strong',
        'markdown.extensions.fenced_code',
        'markdown.extensions.sane_lists',
        'markdown.extensions.smarty',
    ]

    f = fileinput.input(files=args.file, mode='rb')
    text = six.u('').join([line.decode('utf-8') for line in f])
    stream = markdown.markdown(text, exts)
    f.close()

    if stream.strip() == '':
        return  # no input

    try:
        markup = lxml.html.fromstring(stream)
    except Exception:
        raise ValueError("Failed to parse input markdown")

    try:
        width = int(subprocess.check_output(['tput', 'cols']))
    except Exception:
        width = 80

    renderer = Renderer(THEME_LIST[args.theme], args.style, args.format,
                        args.strip, args.justify, width - 1)

    output = renderer.render(markup)

    print(output if six.PY3 else output.encode('utf-8'))
Пример #14
0
import os
from pygments.styles import STYLE_MAP

for style in STYLE_MAP.keys():
    os.system('pygmentize -S ' + style + ' -f html > ' + style + '.css')
    from pygments.lexers.compiled import ObjectiveCLexer
    from pygments.lexers.compiled import ObjectiveCppLexer
    from pygments.lexers.compiled import ValaLexer
except ImportError as e:  # too new on some systems
    logger.error("Faile to import pygments lexer, please update your pygments "
                 "installation. %s" % e)

from pygments.styles import get_style_by_name
from pygments.token import Whitespace, Comment
from pygments.util import ClassNotFound


from pygments.styles import STYLE_MAP

#: A sorted list of available pygments styles, for convenience
PYGMENTS_STYLES = sorted(STYLE_MAP.keys())


def get_tokens_unprocessed(self, text, stack=('root',)):
    """ Split ``text`` into (tokentype, text) pairs.

        Monkeypatched to store the final stack on the object itself.
    """
    pos = 0
    tokendefs = self._tokens
    if hasattr(self, '_saved_state_stack'):
        statestack = list(self._saved_state_stack)
    else:
        statestack = list(stack)
    try:
        statetokens = tokendefs[statestack[-1]]
Пример #16
0
    file2file_remap[path] = filename
    return True


# example usage
if __name__ == '__main__':

    def yes_no(var):
        if var: return ""
        else: return "not "
        return  # Not reached

    print(getline(__file__, 1, {'output': 'dark'}))
    print(getline(__file__, 2, {'output': 'light'}))
    from pygments.styles import STYLE_MAP
    opts = {'style': list(STYLE_MAP.keys())[0]}
    print(getline(__file__, 1, opts))
    update_cache('os')

    lines = getlines(__file__)
    print("%s has %s lines" % (__file__, len(lines)))
    lines = getlines(__file__, {'output': 'light'})
    i = 0
    for line in lines:
        i += 1
        print(line.rstrip('\n').rstrip('\n'))
        if i > 20: break
        pass
    line = getline(__file__, 6)
    print("The 6th line is\n%s" % line)
    line = remap_file(__file__, 'another_name')
Пример #17
0
def set(key, value):
  """
  Set the value of a bibmanager config parameter.

  Parameters
  ----------
  key: String
     bibmanager config parameter to set.
  value: String
     Value to set for input parameter.

  Examples
  --------
  >>> import bibmanager.config_manager as cm
  >>> # Update text editor:
  >>> cm.set('text_editor', 'vim')
  text_editor updated to: vim.

  >>> # Invalid bibmanager parameter:
  >>> cm.set('styles', 'arduino')
  ValueError: 'styles' is not a valid bibmanager config parameter. The available
  parameters are:  ['style', 'text_editor', 'paper', 'ads_token', 'ads_display']

  >>> # Attempt to set an invalid style:
  >>> cm.set('style', 'fake_style')
  ValueError: 'fake_style' is not a valid style option.  Available options are:
    default, emacs, friendly, colorful, autumn, murphy, manni, monokai, perldoc,
    pastie, borland, trac, native, fruity, bw, vim, vs, tango, rrt, xcode, igor,
    paraiso-light, paraiso-dark, lovelace, algol, algol_nu, arduino,
    rainbow_dash, abap

  >>> # Attempt to set an invalid command for text_editor:
  >>> cm.set('text_editor', 'my_own_editor')
  ValueError: 'my_own_editor' is not a valid text editor.

  >>> # Beware, one can still set a valid command that doesn't edit text:
  >>> cm.set('text_editor', 'less')
  text_editor updated to: less.
  """
  config = configparser.ConfigParser()
  config.read(u.HOME+'config')
  if not config.has_option('BIBMANAGER', key):
      # Use gt on invalid key to raise an error:
      get(key)

  # Check for exceptions:
  if key == 'style' and value not in STYLE_MAP.keys():
      raise ValueError(f"'{value}' is not a valid style option.  "
                       f"Available options are:\n{styles}")

  # The code identifies invalid commands, but cannot assure that a
  # command actually applies to a text file.
  if key == 'text_editor' and value!='default' and shutil.which(value) is None:
      raise ValueError(f"'{value}' is not a valid text editor.")

  if key == 'ads_display' and (not value.isnumeric() or value=='0'):
      raise ValueError(f"The {key} value must be a positive integer.")

  # Set value if there were no exceptions raised:
  config.set('BIBMANAGER', key, value)
  with open(u.HOME+'config', 'w') as configfile:
      config.write(configfile)
  print(f'{key} updated to: {value}.')
Пример #18
0
def get_pygments_stylemap():
    pygments_stylemap = list(STYLE_MAP.keys())
    pygments_stylemap.remove(get_configs()['highlight_style'])
    pygments_stylemap.insert(0, get_configs()['highlight_style'])
    return pygments_stylemap
Пример #19
0
    return 'break'


def assert_text(old_text, new_text):
    dmp = diff_match_patch()
    patches = dmp.patch_make(old_text, new_text)
    diff = dmp.patch_toText(patches)

    patches = dmp.patch_fromText(diff)
    new_text, _ = dmp.patch_apply(patches, old_text)
    return bool(_)


if __name__ == "__main__":
    c = 0
    items = list(STYLE_MAP.keys())

    def next_stules():
        global c
        if c >= len(items) - 1:
            c = 0
        c += 1
        code_color(text, items[c])
        button.config(text='下一个主题 (现在主题: {})'.format(items[c]),
                      bg=text.cget('bg'),
                      fg=text.cget('fg'))

    root = tk.Tk()
    root.title('TkPy2 Code Color')
    text = tk.Text(root, bd=0)
    code_color(text, items[c])
Пример #20
0
import os
from pygments.styles import STYLE_MAP


def generate(s):
    # command = f'pygmentize -f html -a .highlight -S {s} > {s}.css'
    command = f'pygmentize -f html -a .codehilite -S {s} > {s}.css'
    os.system(command)


for key in STYLE_MAP.keys():
    print(key)
    generate(key)

Пример #21
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Joshua
# @E-Mail: [email protected]
# @Date:   2015-04-09 17:27:58
# @About test.py

from pygments.styles import STYLE_MAP

print(STYLE_MAP.keys())
Пример #22
0
import os
import json
import pygments
from pygments import token
from pygments.util import ClassNotFound
from pygments.lexers import get_lexer_for_mimetype
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.formatters.terminal import TerminalFormatter
from pygments.lexer import RegexLexer, bygroups
from pygments.styles import get_style_by_name, STYLE_MAP
from . import solarized

DEFAULT_STYLE = 'solarized'
AVAILABLE_STYLES = [DEFAULT_STYLE] + STYLE_MAP.keys()
TYPE_JS = 'application/javascript'
FORMATTER = (Terminal256Formatter if '256color' in os.environ.get('TERM', '')
             else TerminalFormatter)


class HTTPLexer(RegexLexer):
    name = 'HTTP'
    aliases = ['http']
    filenames = ['*.http']
    tokens = {
        'root': [(r'\s+', token.Text),
                 (r'(HTTP/[\d.]+\s+)(\d+)(\s+.+)',
                  bygroups(token.Operator, token.Number, token.String)),
                 (r'(.*?:)(.+)', bygroups(token.Name, token.String))]
    }

Пример #23
0
import os
import json

import pygments

from pygments.util import ClassNotFound
from pygments.styles import get_style_by_name, STYLE_MAP
from pygments.lexers import get_lexer_for_mimetype, HttpLexer
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.formatters.terminal import TerminalFormatter

from . import solarized

DEFAULT_STYLE = 'solarized'
AVAILABLE_STYLES = [DEFAULT_STYLE] + list(STYLE_MAP.keys())
FORMATTER = (Terminal256Formatter if '256color' in os.environ.get('TERM', '')
             else TerminalFormatter)


class PrettyHttp(object):
    def __init__(self, style_name):
        if style_name == 'solarized':
            style = solarized.SolarizedStyle
        else:
            style = get_style_by_name(style_name)
        self.formatter = FORMATTER(style=style)

    def headers(self, content):
        return pygments.highlight(content, HttpLexer(), self.formatter)

    def body(self, content, content_type):
Пример #24
0
from pygments.formatters.terminal import TerminalFormatter
from requests.compat import is_windows
from . import solarized

if is_windows:
    import colorama

    colorama.init()
    # 256 looks better on Windows
    FORMATTER = Terminal256Formatter
else:
    FORMATTER = Terminal256Formatter if "256color" in os.environ.get("TERM", "") else TerminalFormatter


DEFAULT_STYLE = "solarized"
AVAILABLE_STYLES = [DEFAULT_STYLE] + list(STYLE_MAP.keys())

application_content_type_re = re.compile(r"application/(.+\+)(json|xml)$")


class PrettyHttp(object):
    def __init__(self, style_name):
        if style_name == "solarized":
            style = solarized.SolarizedStyle
        else:
            style = get_style_by_name(style_name)
        self.formatter = FORMATTER(style=style)

    def headers(self, content):
        return pygments.highlight(content, HttpLexer(), self.formatter)
Пример #25
0
import pygments
from pygments import token, lexer
from pygments.styles import get_style_by_name, STYLE_MAP
from pygments.lexers import get_lexer_for_mimetype, get_lexer_by_name
from pygments.formatters.terminal import TerminalFormatter
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.util import ClassNotFound
from requests.compat import is_windows

from .solarized import Solarized256Style
from .models import HTTPRequest, HTTPResponse, Environment
from .input import (OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_HEAD, OUT_RESP_BODY)

# Colors on Windows via colorama don't look that
# great and fruity seems to give the best result there.
AVAILABLE_STYLES = set(STYLE_MAP.keys())
AVAILABLE_STYLES.add('solarized')
DEFAULT_STYLE = 'solarized' if not is_windows else 'fruity'

BINARY_SUPPRESSED_NOTICE = (b'\n'
                            b'+-----------------------------------------+\n'
                            b'| NOTE: binary data not shown in terminal |\n'
                            b'+-----------------------------------------+')


class BinarySuppressedError(Exception):
    """An error indicating that the body is binary and won't be written,
     e.g., for terminal output)."""

    message = BINARY_SUPPRESSED_NOTICE
Пример #26
0
def main():
    parser = argparse.ArgumentParser(description='Parser of output files metadata for PiCoPiC.')
    parser.add_argument('properties_path', metavar='properties_path', type=str,
                        help='Full path to properties.xml')
    parser.add_argument('--subtree', type=str,
                        help='Config`s subtree', default=None)
    parser.add_argument('--color-style', type=str,
                        help='Style of metadata colorization (works only with "--colorize" option)', default='autumn')
    parser.add_argument('--help-colors', action='store_true',
                        help='Output list of available color style names and exits', default=False)
    parser.add_argument('--colorize', action='store_true',
                        help='Make metadata output colorful',
                        default=False)
    parser.add_argument('--bo', action='store_true',
                        help='Display build options of PiCoPiC package, generated the data. Shortcut for `--subtree=[build_options]`',
                        default=False)
    parser.add_argument('--phys-info', action='store_true',
                        help='Display useful physical info about background plasma and particle beams',
                        default=False)
    parser.add_argument('-c', '--comment', action='store_true',
                        help='Display comment for datafile',
                        default=False)

    args = parser.parse_args()

    ## display physical info and exit
    if args.phys_info:
        phys_info(args.properties_path)
        sys.exit(0)

    ## display help about color schemes and exit
    if args.help_colors:
        print(list(STYLE_MAP.keys()))
        sys.exit(0)

    # set reader
    if os.path.isfile(args.properties_path) or os.path.isfile(os.path.join(args.properties_path, "data.h5")):
        reader = H5Reader(path = args.properties_path, use_cache=False, verbose=False)
    else:
        raise EnvironmentError("There is no corresponding data files in the path " + args.properties_path + ". Can not continue.")

    config = reader.meta.json
    if args.comment:
        args.bo = False
        args.subtree = False
        try:
            config = config['comment']
        except KeyError:
            print("Invalid metadata subtree key >>", args.comment, "<< can not continue")
            sys.exit(1)

    if args.bo: args.subtree = False
    if args.subtree:
        try:
            config = eval('config' + str(args.subtree).replace('[', '["').replace(']', '"]'))
        except KeyError:
            print("Invalid metadata subtree key >>", args.subtree, "<< can not continue")
            sys.exit(1)

    if args.bo:
        try:
            config = config['build_options']
        except KeyError:
            print("ERROR: Build options are absent. Seems, metadata is incomplete (is it configfile?).")
            sys.exit(1)

    json_dumped = json.dumps(config, indent=2, sort_keys=True)
    if args.colorize:
        print(highlight(json_dumped, JsonLexer(), Terminal256Formatter(style=args.color_style)))
    else:
        print(json_dumped)
Пример #27
0
import simplejson as json
from flask import Flask, render_template, request, send_from_directory, g, config
from flask.ext.paginate import Pagination

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments.styles import STYLE_MAP


json_lexer = None
json_formatter = None


app = Flask(__name__)
app.jinja_env.globals['styles'] = STYLE_MAP.keys()

cur_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(cur_dir)

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

def parse_row(row):
    msgs = json.loads(row['stream'])

    # for msg in msgs:
    #     print msg[0]
Пример #28
0
def run(argv=None):
    parser = argparse.ArgumentParser(description="Lanius Markdown Viewer.", version=version)

    default_arg = os.getenv('LANIUS_THEME', 'default')
    parser.add_argument('-t', '--theme', default=default_arg,
                        help="theme to use for markdown display",
                        metavar='KEY', choices=THEME_LIST.keys())

    default_arg = os.getenv('LANIUS_STYLE', 'monokai')
    parser.add_argument('-x', '--style', default=default_arg,
                        help="syntax highlighting style to use",
                        metavar='KEY', choices=STYLE_MAP.keys())

    default_arg = os.getenv('LANIUS_FORMAT', 'color256')
    parser.add_argument('-f', '--format', default=default_arg,
                        help="syntax highlighting format to use",
                        metavar='KEY', choices=['none', 'color', 'color256'])

    default_arg = os.getenv('LANIUS_STRIP', '').strip() != ''
    parser.add_argument('-s', '--strip', default=default_arg,
                        help="strip whitespace at start and end",
                        action='store_true')

    default_arg = os.getenv('LANIUS_JUSTIFY', '').strip() != ''
    parser.add_argument('-j', '--justify', default=default_arg,
                        help="attempt to right-justify the text",
                        action='store_true')

    parser.add_argument('file', nargs='?', default=['-'],
                        help="path to markdown file",
                        metavar='PATH')

    args = parser.parse_args(argv)

    if args.theme not in THEME_LIST.keys():
        raise ValueError("Invalid theme '{0}'".format(args.theme))

    if args.style not in STYLE_MAP.keys():
        raise ValueError("Invalid style '{0}'".format(args.style))

    if args.format not in ['none', 'color', 'color256']:
        raise ValueError("Invalid format '{0}'".format(args.format))

    exts = [
        'markdown.extensions.smart_strong',
        'markdown.extensions.fenced_code',
        'markdown.extensions.sane_lists',
        'markdown.extensions.smarty',
    ]

    f = fileinput.input(files=args.file, mode='rb')
    text = six.u('').join([line.decode('utf-8') for line in f])
    stream = markdown.markdown(text, exts)
    f.close()

    if stream.strip() == '':
        return  # no input

    try:
        markup = lxml.html.fromstring(stream)
    except Exception:
        raise ValueError("Failed to parse input markdown")

    try:
        width = int(subprocess.check_output(['tput', 'cols']))
    except Exception:
        width = 80

    renderer = Renderer(THEME_LIST[args.theme],
                        args.style, args.format,
                        args.strip, args.justify,
                        width - 1)

    output = renderer.render(markup)

    print(output if six.PY3 else output.encode('utf-8'))
Пример #29
0
from pygments.formatters.terminal import TerminalFormatter
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.util import ClassNotFound
from requests.compat import is_windows

from .solarized import Solarized256Style
from .models import HTTPRequest, HTTPResponse, Environment
from .input import (OUT_REQ_BODY, OUT_REQ_HEAD,
                    OUT_RESP_HEAD, OUT_RESP_BODY)


# Colors on Windows via colorama don't look that
# great and fruity seems to give the best result there.
DEFAULT_STYLE = 'solarized' if not is_windows else 'fruity'
#noinspection PySetFunctionToLiteral
AVAILABLE_STYLES = set([DEFAULT_STYLE]) | set(STYLE_MAP.keys())


BINARY_SUPPRESSED_NOTICE = (
    b'\n'
    b'+-----------------------------------------+\n'
    b'| NOTE: binary data not shown in terminal |\n'
    b'+-----------------------------------------+'
)


class BinarySuppressedError(Exception):
    """An error indicating that the body is binary and won't be written,
     e.g., for terminal output)."""

    message = BINARY_SUPPRESSED_NOTICE
Пример #30
0
from pygments.styles import get_style_by_name, STYLE_MAP
from pygments.lexers import get_lexer_for_mimetype, get_lexer_by_name
from pygments.formatters.terminal import TerminalFormatter
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.util import ClassNotFound

from .compat import is_windows
from .solarized import Solarized256Style
from .models import HTTPRequest, HTTPResponse, Environment
from .input import (OUT_REQ_BODY, OUT_REQ_HEAD,
                    OUT_RESP_HEAD, OUT_RESP_BODY)


# Colors on Windows via colorama don't look that
# great and fruity seems to give the best result there.
AVAILABLE_STYLES = set(STYLE_MAP.keys())
AVAILABLE_STYLES.add('solarized')
DEFAULT_STYLE = 'solarized' if not is_windows else 'fruity'


BINARY_SUPPRESSED_NOTICE = (
    b'\n'
    b'+-----------------------------------------+\n'
    b'| NOTE: binary data not shown in terminal |\n'
    b'+-----------------------------------------+'
)


class BinarySuppressedError(Exception):
    """An error indicating that the body is binary and won't be written,
     e.g., for terminal output)."""
Пример #31
0
 def __init__(self):
     self.styles = STYLE_MAP.keys()
     self.formatter = TextNodeFormatter(style="paraiso-dark")
     self.lexer = PythonLexer()
Пример #32
0
import warnings
import os, re, sys

from tempfile import mktemp
from pygments import highlight
from pygments.console import ansiformat
from pygments.lexers import BashLexer, RstLexer
from pygments.filter import Filter
from pygments.formatter import Formatter
from pygments.formatters import TerminalFormatter, Terminal256Formatter
from pygments.token      import Keyword, Name, Comment, String, Error, \
    Number, Operator, Generic, Token, Whitespace
from pygments.util import get_choice_opt

from pygments.styles import STYLE_MAP
style_names = sorted(list(STYLE_MAP.keys()))

warnings.simplefilter("ignore")

#: Map token types to a tuple of color values for light and dark
#: backgrounds.
TERMINAL_COLORS = {
    Token: ('', ''),
    Whitespace: ('lightgray', 'darkgray'),
    Comment: ('brown', 'yellow'),
    Comment.Preproc: ('teal', 'turquoise'),
    Keyword: ('*darkgreen*', 'turquoise'),
    Keyword.Type: ('teal', 'turquoise'),
    Operator.Word: ('purple', 'fuchsia'),
    Name.Builtin: ('teal', 'turquoise'),
    Name.Function: ('darkgreen', 'green'),
Пример #33
0
import os
import json
import pygments
from pygments import token
from pygments.util import ClassNotFound
from pygments.lexers import get_lexer_for_mimetype
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.formatters.terminal import TerminalFormatter
from pygments.lexer import RegexLexer, bygroups
from pygments.styles import get_style_by_name, STYLE_MAP
from . import solarized


DEFAULT_STYLE = 'solarized'
AVAILABLE_STYLES = [DEFAULT_STYLE] + STYLE_MAP.keys()
TYPE_JS = 'application/javascript'
FORMATTER = (Terminal256Formatter
             if '256color' in os.environ.get('TERM', '')
             else TerminalFormatter)


class HTTPLexer(RegexLexer):
    name = 'HTTP'
    aliases = ['http']
    filenames = ['*.http']
    tokens = {
        'root': [
            (r'\s+', token.Text),
            (r'(HTTP/[\d.]+\s+)(\d+)(\s+.+)', bygroups(
             token.Operator, token.Number, token.String)),
            (r'(.*?:)(.+)',  bygroups(token.Name, token.String))
Пример #34
0
#extensions = extension_s.split(";")

if __name__ == '__main__':
	parser = argparse.ArgumentParser(description='Convert code to PDF files')
	parser.add_argument('-e','--ext', metavar='Ext', type=str, dest='extensions', nargs='*',
		help='the letters of the file extensions')
	parser.add_argument('-x','--exclude', metavar='Regex', type=str, dest='exclusions', nargs='*',
		help='each element of exclude is a regex to be excluded')
	parser.add_argument('-o', metavar='File', type=str, dest='outfile', nargs='?',
		help='name of output file')
	parser.add_argument('-u', '--user-name', type=str, dest='username', nargs='?',
		help='set custom user name')
	parser.add_argument('-n', '--project-name', type=str, dest='project_name', nargs='?',
		help='set custom project name')
	parser.add_argument('--style', type=str, dest='style', nargs='?',
		choices=STYLE_MAP.keys(),
		help='set pygments style')
	parser.add_argument('-l', '--line-numbers', dest='linenumbers', action='store_true',
		help='use line numbers')
	parser.add_argument('-i', metavar='File', type=str, dest='files', nargs='*',
		help='file names to be converted')

	args = parser.parse_args()
	outfile = args.outfile
	s = Searcher(args)
	s.search()
	doc = s.documents[0]
	
	if not outfile:
		outfile = "render.pdf"
	
Пример #35
0
from pygments import highlight
from pygments.lexers.c_cpp import CppLexer
from pygments.formatters import RtfFormatter
from pygments.style import Style
from pygments.styles import STYLE_MAP
import sys
import win32clipboard as clippy

# Stylizer settings
styles = list(STYLE_MAP.keys()) # Available styles
style = styles[6]
font = "Monaco"
fontsize = 24


# Get input and style it
input = str(sys.argv[1])

output = highlight(input, CppLexer(), RtfFormatter(style=style, fontface=font, fontsize=fontsize))


# Copy to clipboard
CF_RTF = clippy.RegisterClipboardFormat("Rich Text Format")

output = bytearray(output, "utf8")

clippy.OpenClipboard(0)
clippy.EmptyClipboard()
clippy.SetClipboardData(CF_RTF, output)
clippy.CloseClipboard()