1. ananelson
  2. pygments-main

Commits

ananelson  committed 076e66d

Add CMYK support for LaTeX and a CMYK style which only uses pure CMYK colors.

  • Participants
  • Parent commits 763fc8b
  • Branches default

Comments (0)

Files changed (6)

File pygments/formatters/latex.py

View file
         If set to ``True``, enables LaTeX math mode escape in comments. That
         is, ``'$...$'`` inside a comment will trigger math mode (default:
         ``False``).  *New in Pygments 1.2.*
+
+    `cmyk`
+        If set to ``True``, use CMYK rather than RGB color codes in stylesheets
+        (default: ``False``). *New in Pygments 1.X*
     """
     name = 'LaTeX'
     aliases = ['latex', 'tex']
         self.commandprefix = options.get('commandprefix', 'PY')
         self.texcomments = get_bool_opt(options, 'texcomments', False)
         self.mathescape = get_bool_opt(options, 'mathescape', False)
+        self.cmyk = get_bool_opt(options, 'cmyk', False)
 
         self._create_stylesheet()
 
             else:
                 return '1,1,1'
 
+        def cmykcolor(col):
+            if not col:
+                # Default to black
+                col = "000000"
+
+            rgb = rgbcolor(col).split(",")
+
+            red = float(rgb[0])
+            green = float(rgb[1])
+            blue = float(rgb[2])
+
+            black = min(1.0-red, 1.0-green, 1.0-blue)
+
+            if black == 1.0:
+                cyan = 0.0
+                magenta = 0.0
+                yellow = 0.0
+            else:
+                cyan = (1.0-red-black)/(1.0-black)
+                magenta = (1.0-green-black)/(1.0-black)
+                yellow = (1.0-blue-black)/(1.0-black)
+
+            return ",".join("%s" % c for c in [cyan, magenta, yellow, black])
+
+        def latexcolor(col):
+            if self.cmyk:
+                return cmykcolor(col)
+            else:
+                return rgbcolor(col)
+
+        def colorscheme():
+            if self.cmyk:
+                return "cmyk"
+            else:
+                return "rgb"
+
         for ttype, ndef in self.style:
             name = _get_ttype_name(ttype)
             cmndef = ''
             if ndef['mono']:
                 cmndef += r'\let\$$@ff=\textsf'
             if ndef['color']:
-                cmndef += (r'\def\$$@tc##1{\textcolor[rgb]{%s}{##1}}' %
-                           rgbcolor(ndef['color']))
+                cmndef += (r'\def\$$@tc##1{\textcolor[%s]{%s}{##1}}' %
+                           (colorscheme(), latexcolor(ndef['color'])))
             if ndef['border']:
                 cmndef += (r'\def\$$@bc##1{\setlength{\fboxsep}{0pt}'
-                           r'\fcolorbox[rgb]{%s}{%s}{\strut ##1}}' %
-                           (rgbcolor(ndef['border']),
-                            rgbcolor(ndef['bgcolor'])))
+                           r'\fcolorbox[%s]{%s}{%s}{\strut ##1}}' %
+                           (colorscheme(), latexcolor(ndef['border']),
+                            latexcolor(ndef['bgcolor'])))
             elif ndef['bgcolor']:
                 cmndef += (r'\def\$$@bc##1{\setlength{\fboxsep}{0pt}'
-                           r'\colorbox[rgb]{%s}{\strut ##1}}' %
-                           rgbcolor(ndef['bgcolor']))
+                           r'\colorbox[%s]{%s}{\strut ##1}}' %
+                           (colorscheme(), latexcolor(ndef['bgcolor'])))
             if cmndef == '':
                 continue
             cmndef = cmndef.replace('$$', cp)

File pygments/lexers/_mapping.py

View file
     'JSONLexer': ('pygments.lexers.web', 'JSON', ('json',), ('*.json',), ('application/json',)),
     'JadeLexer': ('pygments.lexers.web', 'Jade', ('jade', 'JADE'), ('*.jade',), ('text/x-jade',)),
     'JavaLexer': ('pygments.lexers.compiled', 'Java', ('java',), ('*.java',), ('text/x-java',)),
+    'JavascriptConsoleLexer': ('pygments.lexers.web', 'Javascript console session', ('jscon',), ('*.jscon',), ()),
     'JavascriptDjangoLexer': ('pygments.lexers.templates', 'JavaScript+Django/Jinja', ('js+django', 'javascript+django', 'js+jinja', 'javascript+jinja'), (), ('application/x-javascript+django', 'application/x-javascript+jinja', 'text/x-javascript+django', 'text/x-javascript+jinja', 'text/javascript+django', 'text/javascript+jinja')),
     'JavascriptErbLexer': ('pygments.lexers.templates', 'JavaScript+Ruby', ('js+erb', 'javascript+erb', 'js+ruby', 'javascript+ruby'), (), ('application/x-javascript+ruby', 'text/x-javascript+ruby', 'text/javascript+ruby')),
     'JavascriptGenshiLexer': ('pygments.lexers.templates', 'JavaScript+Genshi Text', ('js+genshitext', 'js+genshi', 'javascript+genshitext', 'javascript+genshi'), (), ('application/x-javascript+genshi', 'text/x-javascript+genshi', 'text/javascript+genshi')),

File pygments/lexers/web.py

View file
 import re
 import copy
 
-from pygments.lexer import RegexLexer, ExtendedRegexLexer, bygroups, using, \
-     include, this
+from pygments.lexer import Lexer, RegexLexer, ExtendedRegexLexer, bygroups, \
+     using, include, this, do_insertions
 from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
-     Number, Other, Punctuation, Literal
+     Number, Other, Punctuation, Literal, Generic
 from pygments.util import get_bool_opt, get_list_opt, looks_like_xml, \
                           html_doctype_matches
 from pygments.lexers.agile import RubyLexer
 from pygments.lexers.compiled import ScalaLexer
 
 
-__all__ = ['HtmlLexer', 'XmlLexer', 'JavascriptLexer', 'JSONLexer', 'CssLexer',
-           'PhpLexer', 'ActionScriptLexer', 'XsltLexer', 'ActionScript3Lexer',
-           'MxmlLexer', 'HaxeLexer', 'HamlLexer', 'SassLexer', 'ScssLexer',
-           'ObjectiveJLexer', 'CoffeeScriptLexer', 'DuelLexer', 'ScamlLexer',
-           'JadeLexer', 'XQueryLexer', 'DtdLexer']
+__all__ = ['HtmlLexer', 'XmlLexer', 'JavascriptLexer', 'JavascriptConsoleLexer',
+            'JSONLexer', 'CssLexer', 'PhpLexer', 'ActionScriptLexer',
+            'XsltLexer', 'ActionScript3Lexer', 'MxmlLexer', 'HaxeLexer',
+            'HamlLexer', 'SassLexer', 'ScssLexer', 'ObjectiveJLexer',
+            'CoffeeScriptLexer', 'DuelLexer', 'ScamlLexer', 'JadeLexer',
+            'XQueryLexer', 'DtdLexer']
 
+line_re  = re.compile('.*?\n')
 
 class JavascriptLexer(RegexLexer):
     """
         ]
     }
 
+class JavascriptConsoleLexer(Lexer):
+    """
+    For JavaScript console output, e.g. from running rhino or some other REPL.
+    """
+    name = 'Javascript console session'
+    aliases = ['jscon']
+    filenames = ['*.jscon']
+
+    def __init__(self, **options):
+        Lexer.__init__(self, **options)
+
+    def get_tokens_unprocessed(self, text):
+        jslexer = JavascriptLexer(**self.options)
+
+        curcode = ''
+        insertions = []
+
+        for match in line_re.finditer(text):
+            line = match.group()
+            if line.startswith(u'js> ') or line.startswith(u'  > '):
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt, line[:4])]))
+                curcode += line[4:]
+            else:
+                if curcode:
+                    for item in do_insertions(insertions,
+                                    jslexer.get_tokens_unprocessed(curcode)):
+                        yield item
+                    curcode = ''
+                    insertions = []
+                else:
+                    yield match.start(), Generic.Output, line
+        if curcode:
+            for item in do_insertions(insertions,
+                                      jslexer.get_tokens_unprocessed(curcode)):
+                yield item
 
 class JSONLexer(RegexLexer):
     """

File pygments/styles/__init__.py

View file
     'vim':      'vim::VimStyle',
     'vs':       'vs::VisualStudioStyle',
     'tango':    'tango::TangoStyle',
+    'cmyk' :    'cmyk::CmykStyle'
 }
 
 

File pygments/styles/cmyk.py

View file
+# -*- coding: utf-8 -*-
+"""
+    pygments.styles.cmyk
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    A style which uses only pure CMYK colors for better clarity with small
+    type.
+
+    :copyright: Copyright 2006-2011 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.style import Style
+from pygments.token import Keyword, Name, Comment, String, Error, \
+     Number, Operator, Generic, Whitespace
+
+class CmykStyle(Style):
+    """
+    A style which uses only pure CMYK colors.
+    """
+    MAGENTA="#00FFFF"
+    CYAN="#FF00FF"
+    YELLOW="#FFFF00"
+    BLACK="#000000"
+    WHITE="#FFFFFF"
+    BOLD="bold "
+    ITALIC="italic "
+
+    background_color = WHITE
+
+    styles = {
+        Comment:            "italic",
+        Comment.Preproc:    "noitalic",
+
+        Keyword:            BOLD + MAGENTA,
+        Keyword.Pseudo:     "nobold",
+        Keyword.Type:       MAGENTA,
+
+        Operator:           MAGENTA,
+        Operator.Word:      BOLD+MAGENTA,
+
+        Name.Builtin:       MAGENTA,
+        Name.Function:      MAGENTA,
+        Name.Class:         BOLD+MAGENTA,
+        Name.Namespace:     BOLD+MAGENTA,
+        Name.Exception:     BOLD+MAGENTA,
+        Name.Variable:      MAGENTA,
+        Name.Constant:      MAGENTA,
+        Name.Label:         MAGENTA,
+        Name.Entity:        BOLD+MAGENTA,
+        Name.Attribute:     MAGENTA,
+        Name.Tag:           BOLD+MAGENTA,
+        Name.Decorator:     BOLD+MAGENTA,
+
+        String:             CYAN,
+        String.Doc:         ITALIC,
+        String.Interpol:    CYAN,
+        String.Escape:      BOLD+CYAN,
+        String.Regex:       CYAN,
+        String.Symbol:      CYAN,
+        String.Other:       CYAN,
+
+        Number:             BOLD + MAGENTA,
+
+        Error:              "bg:#FFAAAA #AA0000"
+    }

File tests/test_basic_api.py

View file
         if cls.__name__ not in (
             'PythonConsoleLexer', 'RConsoleLexer', 'RubyConsoleLexer',
             'SqliteConsoleLexer', 'MatlabSessionLexer', 'ErlangShellLexer',
-            'BashSessionLexer', 'LiterateHaskellLexer', 'PostgresConsoleLexer'):
+            'BashSessionLexer', 'LiterateHaskellLexer', 'PostgresConsoleLexer',
+            'JavascriptConsoleLexer'):
             inst = cls(ensurenl=False)
             ensure(inst.get_tokens('a\nb'), 'a\nb')
             inst = cls(ensurenl=False, stripall=True)