##// END OF EJS Templates
Merge pull request #13858 from rhelmot/main...
Merge pull request #13858 from rhelmot/main Add py.typed to setup.cfg

File last commit:

r24360:4347deae
r27963:7757313c merge
Show More
PyColorize.py
331 lines | 10.6 KiB | text/x-python | PythonLexer
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 # -*- coding: utf-8 -*-
"""
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 Class and program to colorize python source code for ANSI terminals.
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 Based on an HTML code highlighter by Jurgen Hermann found at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 Modifications by Fernando Perez (fperez@colorado.edu).
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 Information on the original HTML highlighter follows:
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 MoinMoin - Python Source Parser
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 Title: Colorize Python source using the built-in tokenizer
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 Submitter: Jurgen Hermann
Last Updated:2001/04/06
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 Version no:1.2
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Fernando Perez
Remove svn-style $Id marks from docstrings and Release imports....
r1853 Description:
This code is part of MoinMoin (http://moin.sourceforge.net/) and converts
Python source code to HTML markup, rendering comments, keywords,
operators, numeric and string literals in different colors.
It shows how to use the built-in keyword, token and tokenize modules to
scan Python source code and re-emit it with no changes to its original
formatting (which is the hard part).
"""
Jörgen Stenarson
Quick fix for #1688, traceback-unicode issue...
r8299
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360 __all__ = ['ANSICodeColors', 'Parser']
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
_scheme_default = 'Linux'
Matthias BUSSONNIER
use print function in module with `print >>`
r7817
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 # Imports
fperez
Cosmetic cleanups: put all imports in a single line, and sort them...
r52 import keyword
import os
import sys
import token
import tokenize
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Matthias Bussonnier
Pass parent to child for configuration to propagate
r22943 generate_tokens = tokenize.generate_tokens
Thomas Kluyver
Fixes for UltraTB and PyColorize with Python 3
r4758
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360 from IPython.utils.coloransi import TermColors, InputTermColors,ColorScheme, ColorSchemeTable
Matthias Bussonnier
Introduce some classes necessary fro Pygments refactor.
r22109 from .colorable import Colorable
Srinivas Reddy Thatiparthy
remove PY3 variable
r23110 from io import StringIO
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
#############################################################################
Srinivas Reddy Thatiparthy
Add stacklevel=2 to warn function
r23033 ### Python Source Parser (does Highlighting)
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 #############################################################################
_KEYWORD = token.NT_OFFSET + 1
_TEXT = token.NT_OFFSET + 2
#****************************************************************************
# Builtin color schemes
Colors = TermColors # just a shorthand
# Build a few color schemes
NoColor = ColorScheme(
'NoColor',{
Matthias Bussonnier
Deduplicate code
r21774 'header' : Colors.NoColor,
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 token.NUMBER : Colors.NoColor,
token.OP : Colors.NoColor,
token.STRING : Colors.NoColor,
tokenize.COMMENT : Colors.NoColor,
token.NAME : Colors.NoColor,
token.ERRORTOKEN : Colors.NoColor,
_KEYWORD : Colors.NoColor,
_TEXT : Colors.NoColor,
Matthias Bussonnier
Consolidate color scheme localisations.
r21778 'in_prompt' : InputTermColors.NoColor, # Input prompt
'in_number' : InputTermColors.NoColor, # Input prompt number
'in_prompt2' : InputTermColors.NoColor, # Continuation prompt
Tayfun Sen
Fix color schemes in Linux...
r21828 'in_normal' : InputTermColors.NoColor, # color off (usu. Colors.Normal)
Matthias Bussonnier
Consolidate color scheme localisations.
r21778
Tayfun Sen
Fix color schemes in Linux...
r21828 'out_prompt' : Colors.NoColor, # Output prompt
'out_number' : Colors.NoColor, # Output prompt number
Matthias Bussonnier
Consolidate color scheme localisations.
r21778
Tayfun Sen
Fix color schemes in Linux...
r21828 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 } )
LinuxColors = ColorScheme(
'Linux',{
Matthias Bussonnier
Deduplicate code
r21774 'header' : Colors.LightRed,
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 token.NUMBER : Colors.LightCyan,
token.OP : Colors.Yellow,
token.STRING : Colors.LightBlue,
tokenize.COMMENT : Colors.LightRed,
MinRK
use Colors.Normal for NAMEs in PyColorize...
r4243 token.NAME : Colors.Normal,
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 token.ERRORTOKEN : Colors.Red,
_KEYWORD : Colors.LightGreen,
_TEXT : Colors.Yellow,
Matthias Bussonnier
Consolidate color scheme localisations.
r21778 'in_prompt' : InputTermColors.Green,
'in_number' : InputTermColors.LightGreen,
'in_prompt2' : InputTermColors.Green,
Tayfun Sen
Fix color schemes in Linux...
r21828 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
Matthias Bussonnier
Consolidate color scheme localisations.
r21778
Tayfun Sen
Fix color schemes in Linux...
r21828 'out_prompt' : Colors.Red,
'out_number' : Colors.LightRed,
Matthias Bussonnier
Consolidate color scheme localisations.
r21778
Tayfun Sen
Fix color schemes in Linux...
r21828 'normal' : Colors.Normal # color off (usu. Colors.Normal)
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 } )
Matthias Bussonnier
Make everyone happy with a neutral colortheme by default.
r22609 NeutralColors = ColorScheme(
'Neutral',{
'header' : Colors.Red,
token.NUMBER : Colors.Cyan,
token.OP : Colors.Blue,
token.STRING : Colors.Blue,
tokenize.COMMENT : Colors.Red,
token.NAME : Colors.Normal,
token.ERRORTOKEN : Colors.Red,
_KEYWORD : Colors.Green,
_TEXT : Colors.Blue,
'in_prompt' : InputTermColors.Blue,
'in_number' : InputTermColors.LightBlue,
'in_prompt2' : InputTermColors.Blue,
'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
'out_prompt' : Colors.Red,
'out_number' : Colors.LightRed,
'normal' : Colors.Normal # color off (usu. Colors.Normal)
} )
Thomas Kluyver
Use 'Linux' (dark bg) colours for Windows...
r22760 # Hack: the 'neutral' colours are not very visible on a dark background on
# Windows. Since Windows command prompts have a dark background by default, and
# relatively few users are likely to alter that, we will use the 'Linux' colours,
# designed for a dark background, as the default on Windows. Changing it here
# avoids affecting the prompt colours rendered by prompt_toolkit, where the
# neutral defaults do work OK.
if os.name == 'nt':
NeutralColors = LinuxColors.copy(name='Neutral')
Matthias Bussonnier
Make everyone happy with a neutral colortheme by default.
r22609
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 LightBGColors = ColorScheme(
'LightBG',{
Matthias Bussonnier
Deduplicate code
r21774 'header' : Colors.Red,
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 token.NUMBER : Colors.Cyan,
token.OP : Colors.Blue,
token.STRING : Colors.Blue,
tokenize.COMMENT : Colors.Red,
MinRK
use Colors.Normal for NAMEs in PyColorize...
r4243 token.NAME : Colors.Normal,
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 token.ERRORTOKEN : Colors.Red,
Matthias Bussonnier
Make everyone happy with a neutral colortheme by default.
r22609
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 _KEYWORD : Colors.Green,
_TEXT : Colors.Blue,
Matthias Bussonnier
Consolidate color scheme localisations.
r21778 'in_prompt' : InputTermColors.Blue,
'in_number' : InputTermColors.LightBlue,
'in_prompt2' : InputTermColors.Blue,
Tayfun Sen
Fix color schemes in Linux...
r21828 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
Matthias Bussonnier
Consolidate color scheme localisations.
r21778
Tayfun Sen
Fix color schemes in Linux...
r21828 'out_prompt' : Colors.Red,
'out_number' : Colors.LightRed,
Matthias Bussonnier
Consolidate color scheme localisations.
r21778
Tayfun Sen
Fix color schemes in Linux...
r21828 'normal' : Colors.Normal # color off (usu. Colors.Normal)
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 } )
# Build table of color schemes (needed by the parser)
Matthias Bussonnier
Make everyone happy with a neutral colortheme by default.
r22609 ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 _scheme_default)
Matthias Bussonnier
Start refactoring handling of color....
r22911 Undefined = object()
Matthias Bussonnier
Introduce some classes necessary fro Pygments refactor.
r22109 class Parser(Colorable):
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 """ Format colored Python source.
"""
Matthias Bussonnier
Introduce some classes necessary fro Pygments refactor.
r22109 def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 """ Create a parser with a specified color table and output channel.
Call format() to process code.
"""
Matthias Bussonnier
Introduce some classes necessary fro Pygments refactor.
r22109
super(Parser, self).__init__(parent=parent)
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360 self.color_table = color_table if color_table else ANSICodeColors
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 self.out = out
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360 self.pos = None
self.lines = None
self.raw = None
Matthias Bussonnier
Start refactoring handling of color....
r22911 if not style:
self.style = self.default_style
else:
self.style = style
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Matthias Bussonnier
Start refactoring handling of color....
r22911 def format(self, raw, out=None, scheme=Undefined):
import warnings
if scheme is not Undefined:
warnings.warn('The `scheme` argument of IPython.utils.PyColorize:Parser.format is deprecated since IPython 6.0.'
'It will have no effect. Set the parser `style` directly.',
stacklevel=2)
return self.format2(raw, out)[0]
fperez
- R. Bernstein's patches (minor reworks) to provide full syntax highlight in...
r553
Matthias Bussonnier
Start refactoring handling of color....
r22911 def format2(self, raw, out = None):
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 """ Parse and send the colored source.
If out and scheme are not specified, the defaults (given to
constructor) are used.
out should be a file-type object. Optionally, out can be given as the
string 'str' and the parser will automatically return the output in a
string."""
ernie french
remove code adding an extra newline
r6001
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 string_output = 0
jdh2358
- Fix state handling bug in format(). Closes #146.
r622 if out == 'str' or self.out == 'str' or \
Matthias Bussonnier
Refactor of coloring and traceback mechanism....
r24334 isinstance(self.out, StringIO):
jdh2358
- Fix state handling bug in format(). Closes #146.
r622 # XXX - I don't really like this state handling logic, but at this
# point I don't want to make major changes, so adding the
# isinstance() check is the simplest I can do to ensure correct
# behavior.
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 out_old = self.out
Thomas Kluyver
Use StringIO.StringIO on Python 2....
r13366 self.out = StringIO()
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 string_output = 1
elif out is not None:
self.out = out
Matthias Bussonnier
Refactor of coloring and traceback mechanism....
r24334 else:
raise ValueError('`out` or `self.out` should be file-like or the value `"str"`')
fperez
- Close #131.
r588
# Fast return of the unmodified input for NoColor scheme
Matthias Bussonnier
Start refactoring handling of color....
r22911 if self.style == 'NoColor':
fperez
- Close #131.
r588 error = False
self.out.write(raw)
if string_output:
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360 return raw, error
return None, error
ernie french
remove code adding an extra newline
r6001
fperez
- Close #131.
r588 # local shorthands
Matthias Bussonnier
Start refactoring handling of color....
r22911 colors = self.color_table[self.style].colors
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 self.colors = colors # put in object so __call__ sees it
fperez
- Close #131.
r588
# Remove trailing whitespace and normalize tabs
self.raw = raw.expandtabs().rstrip()
ernie french
remove code adding an extra newline
r6001
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 # store line offsets in self.lines
self.lines = [0, 0]
pos = 0
jdh2358
- Final commits for 0.8.0 tag....
r595 raw_find = self.raw.find
fperez
- Close #131.
r588 lines_append = self.lines.append
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360 while True:
fperez
- Close #131.
r588 pos = raw_find('\n', pos) + 1
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360 if not pos:
break
fperez
- Close #131.
r588 lines_append(pos)
lines_append(len(self.raw))
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
# parse the source and write it
self.pos = 0
Thomas Kluyver
Use StringIO.StringIO on Python 2....
r13366 text = StringIO(self.raw)
fperez
- R. Bernstein's patches (minor reworks) to provide full syntax highlight in...
r553
error = False
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 try:
Thomas Kluyver
Fix bugs in PyColorize
r4768 for atoken in generate_tokens(text.readline):
self(*atoken)
except tokenize.TokenError as ex:
msg = ex.args[0]
line = ex.args[1][0]
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
(colors[token.ERRORTOKEN],
msg, self.raw[self.lines[line]:],
colors.normal)
)
fperez
- R. Bernstein's patches (minor reworks) to provide full syntax highlight in...
r553 error = True
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 self.out.write(colors.normal+'\n')
if string_output:
output = self.out.getvalue()
self.out = out_old
fperez
- R. Bernstein's patches (minor reworks) to provide full syntax highlight in...
r553 return (output, error)
return (None, error)
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360
def _inner_call_(self, toktype, toktext, start_pos):
Matthias Bussonnier
Refactor of coloring and traceback mechanism....
r24334 """like call but write to a temporary buffer"""
buff = StringIO()
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360 srow, scol = start_pos
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 colors = self.colors
Matthias Bussonnier
Refactor of coloring and traceback mechanism....
r24334 owrite = buff.write
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
# line separator, so this works across platforms
linesep = os.linesep
# calculate new positions
oldpos = self.pos
newpos = self.lines[srow] + scol
self.pos = newpos + len(toktext)
# send the original whitespace, if needed
if newpos > oldpos:
fperez
- Close #131.
r588 owrite(self.raw[oldpos:newpos])
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
# skip indenting tokens
if toktype in [token.INDENT, token.DEDENT]:
self.pos = newpos
Matthias Bussonnier
Refactor of coloring and traceback mechanism....
r24334 buff.seek(0)
return buff.read()
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0
# map token type to a color group
Rémy Léone
Simplify comparison
r21780 if token.LPAR <= toktype <= token.OP:
fperez
Reorganized the directory for ipython/ to have its own dir, which is a bit...
r0 toktype = token.OP
elif toktype == token.NAME and keyword.iskeyword(toktext):
toktype = _KEYWORD
color = colors.get(toktype, colors[_TEXT])
# Triple quoted strings must be handled carefully so that backtracking
# in pagers works correctly. We need color terminators on _each_ line.
if linesep in toktext:
toktext = toktext.replace(linesep, '%s%s%s' %
(colors.normal,linesep,color))
# send text
fperez
- Close #131.
r588 owrite('%s%s%s' % (color,toktext,colors.normal))
Matthias Bussonnier
Refactor of coloring and traceback mechanism....
r24334 buff.seek(0)
return buff.read()
def __call__(self, toktype, toktext, start_pos, end_pos, line):
""" Token handler, with syntax highlighting."""
self.out.write(
Matthias Bussonnier
Some cleanup of Pycolorize....
r24360 self._inner_call_(toktype, toktext, start_pos))