本文整理汇总了Python中pygments.lexers.get_lexer_by_name函数的典型用法代码示例。如果您正苦于以下问题:Python get_lexer_by_name函数的具体用法?Python get_lexer_by_name怎么用?Python get_lexer_by_name使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_lexer_by_name函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: add_code_style
def add_code_style(self, content):
"""
добавялем подсветку кода
"""
code_start = u"<pre><code>"
code_end = u"</code></pre>"
code_start_len = len(code_start)
is_code = False
_lexer = "text"
code = []
result = []
for line in content.splitlines():
if line.startswith(code_start):
is_code = True
_lexer = line[code_start_len:].strip()
elif line.endswith(code_end):
is_code = False
try:
lexer = get_lexer_by_name(_lexer, stripall=True)
except ValueError:
lexer = get_lexer_by_name("text", stripall=True)
formatter = HtmlFormatter()
result.append(
highlight(u"\n".join(i.replace("<", "<").replace(">", ">") for i in code), lexer, formatter)
)
code = []
elif is_code:
code.append(line)
else:
result.append(line)
return u"\n".join(result)
开发者ID:ilnurgi,项目名称:website,代码行数:34,代码来源:models.py
示例2: colorize
def colorize (self, sheet_content):
""" Colorizes cheatsheet content if so configured """
# only colorize if so configured
if 'CHEATCOLORS' not in os.environ:
return sheet_content
try:
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
# if pygments can't load, just return the uncolorized text
except ImportError:
return sheet_content
first_line = sheet_content.splitlines()[0]
lexer = get_lexer_by_name('bash')
if first_line.startswith('```'):
sheet_content = '\n'.join(sheet_content.split('\n')[1:-2])
try:
lexer = get_lexer_by_name(first_line[3:])
except Exception:
pass
return highlight(sheet_content, lexer, TerminalFormatter())
开发者ID:skywind3000,项目名称:vim,代码行数:26,代码来源:cheat.py
示例3: setup
def setup(app):
app.add_domain(HTTPDomain)
try:
get_lexer_by_name('http')
except ClassNotFound:
app.add_lexer('http', HTTPLexer())
app.add_config_value('http_index_ignore_prefixes', [], None)
开发者ID:capnrefsmmat,项目名称:sphinx-contrib,代码行数:7,代码来源:httpdomain.py
示例4: block_code
def block_code(self, text, lang):
try:
lexer = get_lexer_by_name(lang, stripall=True)
except:
lexer = get_lexer_by_name('text')
formatter = HtmlFormatter(cssclass='highlight {0}'.format(lexer.name.lower()))
return highlight(text, lexer, formatter)
开发者ID:mekto,项目名称:mektosoftware,代码行数:7,代码来源:filters.py
示例5: __init__
def __init__(self, config):
super().__init__(config)
log.debug("Text Backend Init.")
if hasattr(self.bot_config, 'BOT_IDENTITY') and 'username' in self.bot_config.BOT_IDENTITY:
self.bot_identifier = self.build_identifier(self.bot_config.BOT_IDENTITY['username'])
else:
# Just a default identity for the bot if nothing has been specified.
self.bot_identifier = self.build_identifier('@errbot')
log.debug('Bot username set at %s.', self.bot_identifier)
self._inroom = False
self._rooms = []
self._multiline = False
self.demo_mode = self.bot_config.TEXT_DEMO_MODE if hasattr(self.bot_config, 'TEXT_DEMO_MODE') else False
if not self.demo_mode:
self.md_html = xhtml() # for more debug feedback on md
self.md_text = text() # for more debug feedback on md
self.md_borderless_ansi = borderless_ansi()
self.md_im = imtext()
self.md_lexer = get_lexer_by_name("md", stripall=True)
self.md_ansi = ansi()
self.html_lexer = get_lexer_by_name("html", stripall=True)
self.terminal_formatter = Terminal256Formatter(style='paraiso-dark')
self.user = self.build_identifier(self.bot_config.BOT_ADMINS[0])
self._register_identifiers_pickling()
开发者ID:apophys,项目名称:errbot,代码行数:28,代码来源:text.py
示例6: process
def process(self, attributes, content, reason):
lexer_name = attributes.get('syntax', 'text')
try:
lexer = get_lexer_by_name(lexer_name)
except ValueError:
lexer = get_lexer_by_name('text')
return HTMLElement(highlight(content, lexer, get_formatter()))
开发者ID:adityaathalye,项目名称:zine,代码行数:7,代码来源:__init__.py
示例7: test_get_lexers
def test_get_lexers():
# test that the lexers functions work
def verify(func, args):
x = func(opt='val', *args)
assert isinstance(x, lexers.PythonLexer)
assert x.options["opt"] == "val"
for func, args in [(lexers.get_lexer_by_name, ("python",)),
(lexers.get_lexer_for_filename, ("test.py",)),
(lexers.get_lexer_for_mimetype, ("text/x-python",)),
(lexers.guess_lexer, ("#!/usr/bin/python -O\nprint",)),
(lexers.guess_lexer_for_filename, ("a.py", "<%= @foo %>"))
]:
yield verify, func, args
for cls, (_, lname, aliases, _, mimetypes) in lexers.LEXERS.items():
assert cls == lexers.find_lexer_class(lname).__name__
for alias in aliases:
assert cls == lexers.get_lexer_by_name(alias).__class__.__name__
for mimetype in mimetypes:
assert cls == lexers.get_lexer_for_mimetype(mimetype).__class__.__name__
try:
lexers.get_lexer_by_name(None)
except ClassNotFound:
pass
else:
raise Exception
开发者ID:spencerlyon2,项目名称:pygments,代码行数:30,代码来源:test_basic_api.py
示例8: syntax_hl
def syntax_hl(src, lang=None, guess_lang=False, inline=False, code_wrap=False):
"""Highlight."""
css_class = 'highlight'
src = src.strip('\n')
try:
lexer = get_lexer_by_name(lang)
except ValueError:
try:
if guess_lang:
lexer = guess_lexer(src)
else:
lexer = get_lexer_by_name('text')
except ValueError:
lexer = get_lexer_by_name('text')
if inline:
formatter = SublimeInlineHtmlFormatter(
cssclass=css_class
)
elif code_wrap:
formatter = SublimeWrapBlockFormatter(
cssclass=css_class
)
else:
formatter = SublimeBlockFormatter(
cssclass=css_class
)
return highlight(src, lexer, formatter)
开发者ID:Haron-Prime,项目名称:My_config_files,代码行数:30,代码来源:st_pygments_highlight.py
示例9: paste_lexer
def paste_lexer(pastename,lexmode=None):
global data, formatter
memory = Client(memcached)
database = Client(memcachedb)
bottle.response.content_type = "text/html;charset=UTF-8"
if bottle.request.environ['HTTP_X_FORWARDED_SSL'] == 'on':
proto = 'https'
else:
proto = 'http'
paste = msgpack.loads(get_data(memory,database,"paste:"+pastename) or "")
if paste:
if lexmode:
url="%s://%s/p%s/%s"%(proto,domain,pastename,lexmode)
else:
url="%s://%s/p%s"%(proto,domain,pastename)
rurl="%s://%s/rp%s"%(proto,domain,pastename)
if not paste[4]:
lexer_name = (lexmode or paste[2]).lower()
try:
lexer = get_lexer_by_name(lexer_name, stripall=True)
except:
lexer = get_lexer_by_name('text', stripall=True)
hlpaste = memory.get("hlcache:%s:%s" % (pastename, lexer_name))
if hlpaste == None:
hlpaste = highlight(paste[0].decode("utf-8"), lexer, formatter)
memory.set("hlcache:%s:%s" % (pastename, lexer_name),
hlpaste.encode("utf-8"))
else:
hlpaste = hlpaste.decode("utf-8")
return bottle.template('paste', paste=hlpaste, title=paste[1],
url=url, rurl=rurl, passwd=None, lexmode=lexer.name)
else:
if 'p' in bottle.request.params:
if sha256(bottle.request.params['p']).digest() == paste[4]:
lexer_name = (lexmode or paste[2]).lower()
try:
lexer = get_lexer_by_name(lexer_name, stripall=True)
except:
lexer = get_lexer_by_name('text', stripall=True)
hlpaste = memory.get("hlcache:%s:%s" % (pastename,
lexer_name))
if hlpaste == None:
hlpaste = highlight(paste[0].decode("utf-8"), lexer,
formatter)
memory.set("hlcache:%s:%s" % (pastename, lexer_name),
hlpaste.encode("utf-8"))
else:
hlpaste = hlpaste.decode("utf-8")
return bottle.template('paste', paste=hlpaste,
title=paste[1], url=url, rurl=rurl,
passwd=bottle.request.params['p'],
lexmode=lexer.name)
else:
return bottle.template("pasteauth", url=url, rurl=rurl,
passwd=None, incorrect=True)
else:
return bottle.template("pasteauth", url=url, rurl=rurl,
passwd=None, incorrect=False)
else:
raise HTTPError(404, "Paste not in database")
开发者ID:andre-d,项目名称:3d3Paste,代码行数:60,代码来源:3d3paste.py
示例10: generate_pygments_tex_file
def generate_pygments_tex_file( input_file_path, output_file_path ):
if output_file_path is None:
inputf_no_ext = input_file_path.split(".")[0]
output_file_path = inputf_no_ext + ".tex"
print "Reading Notation 3 file: " + input_file_path
with open (input_file_path, "r") as input_file:
code = input_file.read()
# LatexFormatter( full = True ) may be useful to see the packages, color definitions, etc. required by the LaTeX document importing it
# linenos = True to show line numbers
linenos = not inputf_no_ext.endswith("nolinenos")
ext = input_file_path.split(".")[1]
lexer = None
if ext=="n3":
lexer = get_lexer_by_name("n3")
elif ext=="sparql":
lexer = get_lexer_by_name("sparql")
highlighted_code = highlight( code, lexer, LatexFormatter( linenos = linenos ) )
# super-ugly fix to hidde syntax errors.
# It would be better to simply fix the lesser
# I really hate setting the font here, but I wasn't able to do it in the main document :-S
highlighted_code = r"\expandafter\def\csname [email protected]@err\endcsname{}" + "\n{\small\n" + highlighted_code
highlighted_code += "\n}"
print "Generating pygmented file: " + output_file_path
with open (output_file_path, "w") as output_file:
output_file.write( highlighted_code )
开发者ID:gomezgoiri,项目名称:dissertation,代码行数:31,代码来源:format.py
示例11: highlight_code
def highlight_code(self, html):
BeautifulSoup.QUOTE_TAGS['code'] = None
soup = BeautifulSoup(html)
preblocks = soup.findAll('code')
for pre in preblocks:
if pre.has_key('class'):
try:
code = ''.join([unicode(item) for item in pre.contents])
if 'inline' in pre['class']:
lexer = lexers.get_lexer_by_name(pre['class'].split(' ')[0])
formatter = InlineHtmlFormatter()
code_hl = highlight(code, lexer, formatter)
pre.contents = [BeautifulSoup(code_hl)]
pre.name = 'span'
print "here"
print pre
else:
lexer = lexers.get_lexer_by_name(pre['class'])
formatter = formatters.HtmlFormatter(linenos='table')
code_hl = highlight(code, lexer, formatter)
pre.contents = [BeautifulSoup(code_hl)]
pre.name = 'div'
except:
#logging.debug(sys.exc_info())
#logging.debug(pre['class'])
break
return unicode(soup)
开发者ID:joelburget,项目名称:formative,代码行数:27,代码来源:models.py
示例12: run
def run(self):
socket = self.context.socket(zmq.REP)
socket.connect('inproc://backend')
while True:
lang, code = socket.recv_multipart()
lang = lang.decode(encoding="UTF-8")
code = code.decode(encoding="UTF-8")
rv = ""
try:
try:
if lang == "gdb":
lex = GDBLexer(encoding="utf-8")
elif lang == "toml":
lex = TOMLLexer(encoding="utf-8")
else:
lex = get_lexer_by_name(lang, encoding="utf-8")
except ClassNotFound as err:
lex = get_lexer_by_name("text", encoding="utf-8")
rv = highlight(code, lex, self.formatter)
except ValueError as err:
rv = "Pygments Error: {}".format(err)
socket.send(rv)
socket.close()
开发者ID:blaenk,项目名称:pig,代码行数:29,代码来源:pig.py
示例13: view_paste
def view_paste(paste):
r = get_paste(paste)
lang = request.args.get('l') if 'l' in request.args else r.language
paste = r.code
lexer = None
if lang == None:
try:
lexer = guess_lexer(paste)
except ClassNotFound:
pass
if lexer is None:
try:
lexer = get_lexer_by_name(lang)
except:
abort(500, 'Invalid lexer: %s' % lang)
if lexer is None:
try:
lexer = get_lexer_by_name('text')
except:
abort(500, 'Invalid lexer: %s' % lang)
formatter = HtmlFormatter(linenos=True)#, cssclass='syntax')#, style='friendly')
h = pygments.highlight(paste, lexer, formatter)
pasteid = r.private_id if r.private_id else r.paste_id
return render_template('viewpaste.html', data=h, theme=get_theme(),
langs=LANGS, pasteid=pasteid, currlang=lexer.aliases[0])
开发者ID:MerlijnWajer,项目名称:Kirby,代码行数:35,代码来源:kirby.py
示例14: __init__
def __init__(self, document):
self.document = document
self.tokens = []
self.offsets = []
self.end = 0 # up to where we lexed last
if document.location:
filename = document.location
try:
# HACK! overrides should come from settings...
if os.path.splitext(filename)[1] == '.html':
# assume django template
self.lexer = get_lexer_by_name('html+django',
stripnl=False,
encoding='utf8')
elif os.path.splitext(filename)[1] == '.py':
# otherwise we end up with the annoying NumPy lexer..
self.lexer = get_lexer_by_name('python',
stripnl=False,
encoding='utf8')
else:
self.lexer = get_lexer_for_filename(filename,
stripnl=False,
encoding='utf8')
except ClassNotFound:
self.lexer = None
else:
self.lexer = None
开发者ID:lerouxb,项目名称:ni,代码行数:28,代码来源:tokenizer.py
示例15: colorize
def colorize(language, title, text):
"""Colorize the text syntax.
Guess the language of the text and colorize it.
Returns a tuple containing the colorized text and the language name.
"""
formatter = HtmlFormatter(
linenos=True, style=PygmentsStyle, noclasses=True, nobackground=True)
#Try to get the lexer by name
try:
lexer = get_lexer_by_name(language.lower())
return highlight(text, lexer, formatter), lexer.name
except LexerNotFound:
pass
#Try to get the lexer by filename
try:
lexer = get_lexer_for_filename(title.lower())
return highlight(text, lexer, formatter), lexer.name
except LexerNotFound:
pass
#Try to guess the lexer from the text
try:
lexer = guess_lexer(text)
if lexer.analyse_text(text) > .3:
return highlight(text, lexer, formatter), lexer.name
except LexerNotFound:
pass
#Fallback to the plain/text lexer
lexer = get_lexer_by_name('text')
return highlight(text, lexer, formatter), lexer.name
开发者ID:Kozea,项目名称:PastaBin,代码行数:31,代码来源:pastabin.py
示例16: hl
def hl(code,lang,p):
try:
lexer = get_lexer_by_name(lang,encoding='utf8')
except ClassNotFound:
lexer = get_lexer_by_name('text',encoding='utf8')
formatter = HtmlLineFormatter(pasteid=p,linenos=True,encoding='utf8')
return highlight(code,lexer,formatter)
开发者ID:glguy,项目名称:hpaste,代码行数:7,代码来源:highlighter.py
示例17: style_ansi
def style_ansi(raw_code, lang=None):
""" actual code hilite """
lexer = 0
if lang:
try:
lexer = get_lexer_by_name(lang)
except ValueError:
print col(R, 'Lexer for %s not found' % lang)
lexer = None
if not lexer:
try:
if guess_lexer:
lexer = pyg_guess_lexer(raw_code)
except:
pass
if not lexer:
lexer = get_lexer_by_name(def_lexer)
tokens = lex(raw_code, lexer)
cod = []
for t, v in tokens:
if not v:
continue
_col = code_hl_tokens.get(t)
if _col:
cod.append(col(v, _col))
else:
cod.append(v)
return ''.join(cod)
开发者ID:dimitri-koussa,项目名称:terminal_markdown_viewer,代码行数:28,代码来源:mdv.py
示例18: highlight
def highlight(value, arg=None, autoescape=None):
"""
Filter syntax-highlights code.
Optional argument: lexer.
"""
if autoescape:
from django.utils.html import conditional_escape
escaper = conditional_escape
else:
escaper = lambda x: x
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, guess_lexer
try:
lexer = get_lexer_by_name(arg, stripnl=False, encoding=u'UTF-8')
except ValueError:
try:
# Guess a lexer by the contents of the block.
lexer = guess_lexer(value)
except ValueError:
# Just make it plain text.
lexer = get_lexer_by_name(u'text', stripnl=False,
encoding=u'UTF-8')
# TODO: Translation. uggettext?
code = highlight(value, lexer, HtmlFormatter())
return mark_safe(code)
开发者ID:cvan,项目名称:secinv,代码行数:31,代码来源:machine_extras.py
示例19: block_code
def block_code(self,
code,
lang,
code_tag=True,
inlinestyles=False,
linenos=False):
"""Render code block.
:param code_tag: If True html will contain <code>-tag.
:param inlinestyles: If True html contains inline styles.
:param linenos: If True html contains line numbers
:return:
"""
try:
lexer = get_lexer_by_name(lang, stripnl=False)
except pygments.util.ClassNotFound:
lexer = get_lexer_by_name('text', stripnl=False)
if code_tag:
formatter = CodeHtmlFormatter(lang,
noclasses=inlinestyles,
linenos=linenos)
else:
formatter = HtmlFormatter(noclasses=inlinestyles, linenos=linenos)
return highlight(code, lexer=lexer, formatter=formatter)
开发者ID:RaoOfPhysics,项目名称:opendata.cern.ch,代码行数:26,代码来源:ext.py
示例20: __highlight__
def __highlight__(content, dom_element="pre", linenos=True, noclasses=True):
"""
Performs syntax highlighting on text inside of dom_element
Uses BeautifulSoup for processing and pygments for highlighting
@param content The HTML (or XML) content to parse
@param dom_element The dom tag to search and replace with highlighted
@return The content with highlighted code withing dom_element
"""
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
decodedString = unicode(BeautifulStoneSoup(content, convertEntities=BeautifulStoneSoup.HTML_ENTITIES))
# decodedString=html_entity_decode(content.encode('utf-8'))
soup = BeautifulSoup(content)
formatter = HtmlFormatter(linenos=linenos, noclasses=noclasses)
for tag in soup.findAll(dom_element):
language = tag.get("lang") or "text"
try:
lexer = get_lexer_by_name(language, encoding="UTF-8")
except:
lexer = get_lexer_by_name("text", encoding="UTF-8")
tag.replaceWith(highlight(tag.renderContents(), lexer, formatter))
pass
return unicode(str(soup), "utf-8", errors="ignore")
开发者ID:wulliam,项目名称:blogitizor,代码行数:30,代码来源:plugin_highlight.py
注:本文中的pygments.lexers.get_lexer_by_name函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论