Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/METADATAAdded+57
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/WHEELAdded+4
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/entry_points.txtAdded+2
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/licenses/AUTHORSAdded+292
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/licenses/LICENSEAdded+25
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/__init__.pyAdded+82
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/__main__.pyAdded+17
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/cmdline.pyAdded+668
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/filter.pyAdded+70
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/formatter.pyAdded+129
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexer.pyAdded+963
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/wren.pyAdded+98
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/x10.pyAdded+66
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/xorg.pyAdded+38
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/yang.pyAdded+103
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/yara.pyAdded+69
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/zig.pyAdded+125
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/modeline.pyAdded+43
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/plugin.pyAdded+74
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/regexopt.pyAdded+102
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/scanner.pyAdded+104
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/sphinxext.pyAdded+247
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/style.pyAdded+203
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/__init__.pyAdded+61
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/_mapping.pyAdded+54
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/abap.pyAdded+32
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/algol.pyAdded+65
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/algol_nu.pyAdded+65
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/arduino.pyAdded+100
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/autumn.pyAdded+67
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/borland.pyAdded+53
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/bw.pyAdded+52
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/coffee.pyAdded+80
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/colorful.pyAdded+83
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/default.pyAdded+76
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/dracula.pyAdded+90
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/emacs.pyAdded+75
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/friendly.pyAdded+76
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/friendly_grayscale.pyAdded+80
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/fruity.pyAdded+47
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/gh_dark.pyAdded+113
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/gruvbox.pyAdded+118
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/igor.pyAdded+32
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/inkpot.pyAdded+72
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/lightbulb.pyAdded+110
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/lilypond.pyAdded+62
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/lovelace.pyAdded+100
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/manni.pyAdded+79
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/material.pyAdded+124
- .cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/monokai.pyAdded+112
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657Metadata-Version: 2.4Name: PygmentsVersion: 2.20.0Summary: Pygments is a syntax highlighting package written in Python.Project-URL: Homepage, https://pygments.orgProject-URL: Documentation, https://pygments.org/docsProject-URL: Source, https://github.com/pygments/pygmentsProject-URL: Bug Tracker, https://github.com/pygments/pygments/issuesProject-URL: Changelog, https://github.com/pygments/pygments/blob/master/CHANGESAuthor-email: Georg Brandl <georg@python.org>Maintainer: Matthäus G. ChajdasMaintainer-email: Georg Brandl <georg@python.org>, Jean Abou Samra <jean@abou-samra.fr>License-Expression: BSD-2-ClauseLicense-File: AUTHORSLicense-File: LICENSEKeywords: syntax highlightingClassifier: Development Status :: 6 - MatureClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: End Users/DesktopClassifier: Intended Audience :: System AdministratorsClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Topic :: Text Processing :: FiltersClassifier: Topic :: UtilitiesRequires-Python: >=3.9Provides-Extra: pluginsProvides-Extra: windows-terminalRequires-Dist: colorama>=0.4.6; extra == 'windows-terminal'Description-Content-Type: text/x-rst
Pygments~~~~~~~~
Pygments is a syntax highlighting package written in Python.
It is a generic syntax highlighter suitable for use in code hosting, forums,wikis or other applications that need to prettify source code. Highlightsare:
* a wide range of over 500 languages and other text formats is supported* special attention is paid to details, increasing quality by a fair amount* support for new languages and formats are added easily* a number of output formats, presently HTML, LaTeX, RTF, SVG, all image formats that PIL supports and ANSI sequences* it is usable as a command-line tool and as a library
Copyright 2006-present by the Pygments team, see ``AUTHORS``.Licensed under the BSD, see ``LICENSE`` for details.1234Wheel-Version: 1.0Generator: hatchling 1.29.0Root-Is-Purelib: trueTag: py3-none-any12[console_scripts]pygmentize = pygments.cmdline:main123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292Pygments is written and maintained by Georg Brandl <georg@python.org>.
Major developers are Tim Hatch <tim@timhatch.com> and Armin Ronacher<armin.ronacher@active-4.com>.
Other contributors, listed alphabetically, are:
* Sam Aaron -- Ioke lexer* Jean Abou Samra -- LilyPond lexer* João Abecasis -- JSLT lexer* Ali Afshar -- image formatter* Thomas Aglassinger -- Easytrieve, JCL, Rexx, Transact-SQL and VBScript lexers* Maxence Ahlouche -- PostgreSQL Explain lexer* Muthiah Annamalai -- Ezhil lexer* Nikolay Antipov -- OpenSCAD lexer* Kumar Appaiah -- Debian control lexer* Andreas Amann -- AppleScript lexer* Timothy Armstrong -- Dart lexer fixes* Jeffrey Arnold -- R/S, Rd, BUGS, Jags, and Stan lexers* Eiríkr Åsheim -- Uxntal lexer* Jeremy Ashkenas -- CoffeeScript lexer* José Joaquín Atria -- Praat lexer* Stefan Matthias Aust -- Smalltalk lexer* Lucas Bajolet -- Nit lexer* Ben Bangert -- Mako lexers* Max Battcher -- Darcs patch lexer* Thomas Baruchel -- APL lexer* Tim Baumann -- (Literate) Agda lexer* Paul Baumgart, 280 North, Inc. -- Objective-J lexer* Michael Bayer -- Myghty lexers* Thomas Beale -- Archetype lexers* John Benediktsson -- Factor lexer* David Benjamin, Google LLC -- TLS lexer* Trevor Bergeron -- mIRC formatter* Vincent Bernat -- LessCSS lexer* Christopher Bertels -- Fancy lexer* Sébastien Bigaret -- QVT Operational lexer* Jarrett Billingsley -- MiniD lexer* Adam Blinkinsop -- Haskell, Redcode lexers* Stéphane Blondon -- Procfile, SGF and Sieve lexers* Frits van Bommel -- assembler lexers* Pierre Bourdon -- bugfixes* Martijn Braam -- Kernel log lexer, BARE lexer* JD Browne, Google LLC -- GoogleSQL lexer* Matthias Bussonnier -- ANSI style handling for terminal-256 formatter* chebee7i -- Python traceback lexer improvements* Hiram Chirino -- Scaml and Jade lexers* Mauricio Caceres -- SAS and Stata lexers.* Michael Camilleri, John Gabriele, sogaiu -- Janet lexer* Daren Chandisingh -- Gleam lexer* Ian Cooper -- VGL lexer* David Corbett -- Inform, Jasmin, JSGF, Snowball, and TADS 3 lexers* Leaf Corcoran -- MoonScript lexer* Fraser Cormack -- TableGen lexer* Gabriel Corona -- ASN.1 lexer* Christopher Creutzig -- MuPAD lexer* Daniël W. Crompton -- Pike lexer* Pete Curry -- bugfixes* Bryan Davis -- EBNF lexer* Bruno Deferrari -- Shen lexer* Walter Dörwald -- UL4 lexer* Luke Drummond -- Meson lexer* Giedrius Dubinskas -- HTML formatter improvements* Owen Durni -- Haxe lexer* Alexander Dutton, Oxford University Computing Services -- SPARQL lexer* James Edwards -- Terraform lexer* Nick Efford -- Python 3 lexer* Sven Efftinge -- Xtend lexer* Artem Egorkine -- terminal256 formatter* Matthew Fernandez -- CAmkES lexer* Paweł Fertyk -- GDScript lexer, HTML formatter improvements* Michael Ficarra -- CPSA lexer* James H. Fisher -- PostScript lexer* Amanda Fitch, Google LLC -- GoogleSQL lexer* William S. Fulton -- SWIG lexer* Carlos Galdino -- Elixir and Elixir Console lexers* Michael Galloy -- IDL lexer* Naveen Garg -- Autohotkey lexer* Simon Garnotel -- FreeFem++ lexer* Laurent Gautier -- R/S lexer* Alex Gaynor -- PyPy log lexer* Richard Gerkin -- Igor Pro lexer* Alain Gilbert -- TypeScript lexer* Alex Gilding -- BlitzBasic lexer* GitHub, Inc -- DASM16, Augeas, TOML, and Slash lexers* Bertrand Goetzmann -- Groovy lexer* Krzysiek Goj -- Scala lexer* Rostyslav Golda -- FloScript lexer* Andrey Golovizin -- BibTeX lexers* Matt Good -- Genshi, Cheetah lexers* Michał Górny -- vim modeline support* Alex Gosse -- TrafficScript lexer* Patrick Gotthardt -- PHP namespaces support* Hubert Gruniaux -- C and C++ lexer improvements* Olivier Guibe -- Asymptote lexer* Phil Hagelberg -- Fennel lexer* Florian Hahn -- Boogie lexer* Martin Harriman -- SNOBOL lexer* Matthew Harrison -- SVG formatter* Steven Hazel -- Tcl lexer* Dan Michael Heggø -- Turtle lexer* Aslak Hellesøy -- Gherkin lexer* Greg Hendershott -- Racket lexer* Justin Hendrick -- ParaSail lexer* Jordi Gutiérrez Hermoso -- Octave lexer* David Hess, Fish Software, Inc. -- Objective-J lexer* Ken Hilton -- Typographic Number Theory and Arrow lexers* Varun Hiremath -- Debian control lexer* Rob Hoelz -- Perl 6 lexer* Doug Hogan -- Mscgen lexer* Ben Hollis -- Mason lexer* Max Horn -- GAP lexer* Fred Hornsey -- OMG IDL Lexer* Alastair Houghton -- Lexer inheritance facility* Tim Howard -- BlitzMax lexer* Dustin Howett -- Logos lexer* Ivan Inozemtsev -- Fantom lexer* Hiroaki Itoh -- Shell console rewrite, Lexers for PowerShell session, MSDOS session, BC, WDiff* Brian R. Jackson -- Tea lexer* Alex Jeffery, ChromaWay AB -- Rell lexer* Christian Jann -- ShellSession lexer* Jonas Camillus Jeppesen -- Line numbers and line highlighting for RTF-formatter* Dennis Kaarsemaker -- sources.list lexer* Dmitri Kabak -- Inferno Limbo lexer* Igor Kalnitsky -- vhdl lexer* Colin Kennedy - USD lexer* Alexander Kit -- MaskJS lexer* Pekka Klärck -- Robot Framework lexer* Gerwin Klein -- Isabelle lexer* Eric Knibbe -- Lasso lexer* Stepan Koltsov -- Clay lexer* Oliver Kopp - Friendly grayscale style* Adam Koprowski -- Opa lexer* Benjamin Kowarsch -- Modula-2 lexer* Domen Kožar -- Nix lexer* Oleh Krekel -- Emacs Lisp lexer* Alexander Kriegisch -- Kconfig and AspectJ lexers* Marek Kubica -- Scheme lexer* Jochen Kupperschmidt -- Markdown processor* Gerd Kurzbach -- Modelica lexer* Jon Larimer, Google Inc. -- Smali lexer* Olov Lassus -- Dart lexer* Matt Layman -- TAP lexer* Dan Lazin, Google LLC -- GoogleSQL lexer* Kristian Lyngstøl -- Varnish lexers* Sylvestre Ledru -- Scilab lexer* Chee Sing Lee -- Flatline lexer* Mark Lee -- Vala lexer* Thomas Linder Puls -- Visual Prolog lexer* Pete Lomax -- Phix lexer* Valentin Lorentz -- C++ lexer improvements* Ben Mabey -- Gherkin lexer* Angus MacArthur -- QML lexer* Louis Mandel -- X10 lexer* Louis Marchand -- Eiffel lexer* Simone Margaritelli -- Hybris lexer* Tim Martin - World of Warcraft TOC lexer* Kirk McDonald -- D lexer* Gordon McGregor -- SystemVerilog lexer* Stephen McKamey -- Duel/JBST lexer* Brian McKenna -- F# lexer* Charles McLaughlin -- Puppet lexer* Kurt McKee -- Tera Term macro lexer, PostgreSQL updates, MySQL overhaul, JSON lexer* Joe Eli McIlvain -- Savi lexer* Lukas Meuser -- BBCode formatter, Lua lexer* Cat Miller -- Pig lexer* Paul Miller -- LiveScript lexer* Hong Minhee -- HTTP lexer* Michael Mior -- Awk lexer* Bruce Mitchener -- Dylan lexer rewrite* Reuben Morais -- SourcePawn lexer* Jon Morton -- Rust lexer* Paulo Moura -- Logtalk lexer* Mher Movsisyan -- DTD lexer* Dejan Muhamedagic -- Crmsh lexer* Adrien Nayrat -- PostgreSQL Explain lexer* Ana Nelson -- Ragel, ANTLR, R console lexers* David Neto, Google LLC -- WebGPU Shading Language lexer* Kurt Neufeld -- Markdown lexer* Nam T. Nguyen -- Monokai style* Jesper Noehr -- HTML formatter "anchorlinenos"* Mike Nolta -- Julia lexer* Avery Nortonsmith -- Pointless lexer* Jonas Obrist -- BBCode lexer* Edward O'Callaghan -- Cryptol lexer* David Oliva -- Rebol lexer* Pat Pannuto -- nesC lexer* Jon Parise -- Protocol buffers and Thrift lexers* Benjamin Peterson -- Test suite refactoring* Ronny Pfannschmidt -- BBCode lexer* Dominik Picheta -- Nimrod lexer* Andrew Pinkham -- RTF Formatter Refactoring* Clément Prévost -- UrbiScript lexer* Tanner Prynn -- cmdline -x option and loading lexers from files* Oleh Prypin -- Crystal lexer (based on Ruby lexer)* Nick Psaris -- K and Q lexers* Xidorn Quan -- Web IDL lexer* Elias Rabel -- Fortran fixed form lexer* raichoo -- Idris lexer* Daniel Ramirez -- GDScript lexer* Kashif Rasul -- CUDA lexer* Nathan Reed -- HLSL lexer* Justin Reidy -- MXML lexer* Jonathon Reinhart, Google LLC -- Soong lexer* Norman Richards -- JSON lexer* Corey Richardson -- Rust lexer updates* Fabrizio Riguzzi -- cplint leder* Lubomir Rintel -- GoodData MAQL and CL lexers* Andre Roberge -- Tango style* Georg Rollinger -- HSAIL lexer* Michiel Roos -- TypoScript lexer* Konrad Rudolph -- LaTeX formatter enhancements* Mario Ruggier -- Evoque lexers* Miikka Salminen -- Lovelace style, Hexdump lexer, lexer enhancements* Stou Sandalski -- NumPy, FORTRAN, tcsh and XSLT lexers* Matteo Sasso -- Common Lisp lexer* Joe Schafer -- Ada lexer* Max Schillinger -- TiddlyWiki5 lexer* Andrew Schmidt -- X++ lexer* Ken Schutte -- Matlab lexers* René Schwaiger -- Rainbow Dash style* Sebastian Schweizer -- Whiley lexer* Tassilo Schweyer -- Io, MOOCode lexers* Pablo Seminario -- PromQL lexer* Ted Shaw -- AutoIt lexer* Joerg Sieker -- ABAP lexer* Robert Simmons -- Standard ML lexer* Kirill Simonov -- YAML lexer* Corbin Simpson -- Monte lexer* Ville Skyttä -- ASCII armored lexer* Alexander Smishlajev -- Visual FoxPro lexer* Steve Spigarelli -- XQuery lexer* Jerome St-Louis -- eC lexer* Camil Staps -- Clean and NuSMV lexers; Solarized style* James Strachan -- Kotlin lexer* Tom Stuart -- Treetop lexer* Colin Sullivan -- SuperCollider lexer* Ben Swift -- Extempore lexer* tatt61880 -- Kuin lexer* Edoardo Tenani -- Arduino lexer* Tiberius Teng -- default style overhaul* Jeremy Thurgood -- Erlang, Squid config lexers* Brian Tiffin -- OpenCOBOL lexer* Bob Tolbert -- Hy lexer* Doug Torrance -- Macaulay2 lexer* Matthias Trute -- Forth lexer* Tuoa Spi T4 -- Bdd lexer* Erick Tryzelaar -- Felix lexer* Alexander Udalov -- Kotlin lexer improvements* Thomas Van Doren -- Chapel lexer* Dave Van Ee -- Uxntal lexer updates* Daniele Varrazzo -- PostgreSQL lexers* Abe Voelker -- OpenEdge ABL lexer* Pepijn de Vos -- HTML formatter CTags support* Matthias Vallentin -- Bro lexer* Benoît Vinot -- AMPL lexer* Linh Vu Hong -- RSL lexer* Taavi Väänänen -- Debian control, PHP lexers* Immanuel Washington -- Smithy lexer* Nathan Weizenbaum -- Haml and Sass lexers* Nathan Whetsell -- Csound lexers* Dietmar Winkler -- Modelica lexer* Nils Winter -- Smalltalk lexer* Davy Wybiral -- Clojure lexer* Whitney Young -- ObjectiveC lexer* Diego Zamboni -- CFengine3 lexer* Enrique Zamudio -- Ceylon lexer* Alex Zimin -- Nemerle lexer* Rob Zimmerman -- Kal lexer* Evgenii Zheltonozhskii -- Maple lexer* Vincent Zurczak -- Roboconf lexer* Hubert Gruniaux -- C and C++ lexer improvements* Thomas Symalla -- AMDGPU Lexer* 15b3 -- Image Formatter improvements* Fabian Neumann -- CDDL lexer* Thomas Duboucher -- CDDL lexer* Philipp Imhof -- Pango Markup formatter* Thomas Voss -- Sed lexer* Martin Fischer -- WCAG contrast testing* Marc Auberer -- Spice lexer* Amr Hesham -- Carbon lexer* diskdance -- Wikitext lexer* vanillajonathan -- PRQL lexer* Nikolay Antipov -- OpenSCAD lexer* Markus Meyer, Nextron Systems -- YARA lexer* Hannes Römer -- Mojo lexer* Jan Frederik Schaefer -- PDDL lexer
Many thanks for all contributions!12345678910111213141516171819202122232425Copyright (c) 2006-2022 by the respective authors (see AUTHORS file).All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOTLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182""" Pygments ~~~~~~~~
Pygments is a syntax highlighting package written in Python.
It is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code. Highlights are:
* a wide range of common languages and markup formats is supported * special attention is paid to details, increasing quality by a fair amount * support for new languages and formats are added easily * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image formats that PIL supports, and ANSI sequences * it is usable as a command-line tool and as a library * ... and it highlights even Brainfuck!
The `Pygments master branch`_ is installable with ``easy_install Pygments==dev``.
.. _Pygments master branch: https://github.com/pygments/pygments/archive/master.zip#egg=Pygments-dev
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""from io import StringIO, BytesIO
__version__ = '2.20.0'__docformat__ = 'restructuredtext'
__all__ = ['lex', 'format', 'highlight']
def lex(code, lexer): """ Lex `code` with the `lexer` (must be a `Lexer` instance) and return an iterable of tokens. Currently, this only calls `lexer.get_tokens()`. """ try: return lexer.get_tokens(code) except TypeError: # Heuristic to catch a common mistake. from pygments.lexer import RegexLexer if isinstance(lexer, type) and issubclass(lexer, RegexLexer): raise TypeError('lex() argument must be a lexer instance, ' 'not a class') raise
def format(tokens, formatter, outfile=None): # pylint: disable=redefined-builtin """ Format ``tokens`` (an iterable of tokens) with the formatter ``formatter`` (a `Formatter` instance).
If ``outfile`` is given and a valid file object (an object with a ``write`` method), the result will be written to it, otherwise it is returned as a string. """ try: if not outfile: realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO() formatter.format(tokens, realoutfile) return realoutfile.getvalue() else: formatter.format(tokens, outfile) except TypeError: # Heuristic to catch a common mistake. from pygments.formatter import Formatter if isinstance(formatter, type) and issubclass(formatter, Formatter): raise TypeError('format() argument must be a formatter instance, ' 'not a class') raise
def highlight(code, lexer, formatter, outfile=None): """ This is the most high-level highlighting function. It combines `lex` and `format` in one function. """ return format(lex(code, lexer), formatter, outfile)1234567891011121314151617""" pygments.__main__ ~~~~~~~~~~~~~~~~~
Main entry point for ``python -m pygments``.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import sysimport pygments.cmdline
try: sys.exit(pygments.cmdline.main(sys.argv))except KeyboardInterrupt: sys.exit(1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668""" pygments.cmdline ~~~~~~~~~~~~~~~~
Command line interface.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import osimport sysimport shutilimport argparsefrom textwrap import dedent
from pygments import __version__, highlightfrom pygments.util import ClassNotFound, OptionError, docstring_headline, \ guess_decode, guess_decode_from_terminal, terminal_encoding, \ UnclosingTextIOWrapperfrom pygments.lexers import get_all_lexers, get_lexer_by_name, guess_lexer, \ load_lexer_from_file, get_lexer_for_filename, find_lexer_class_for_filenamefrom pygments.lexers.special import TextLexerfrom pygments.formatters.latex import LatexEmbeddedLexer, LatexFormatterfrom pygments.formatters import get_all_formatters, get_formatter_by_name, \ load_formatter_from_file, get_formatter_for_filename, find_formatter_classfrom pygments.formatters.terminal import TerminalFormatterfrom pygments.formatters.terminal256 import Terminal256Formatter, TerminalTrueColorFormatterfrom pygments.filters import get_all_filters, find_filter_classfrom pygments.styles import get_all_styles, get_style_by_name
def _parse_options(o_strs): opts = {} if not o_strs: return opts for o_str in o_strs: if not o_str.strip(): continue o_args = o_str.split(',') for o_arg in o_args: o_arg = o_arg.strip() try: o_key, o_val = o_arg.split('=', 1) o_key = o_key.strip() o_val = o_val.strip() except ValueError: opts[o_arg] = True else: opts[o_key] = o_val return opts
def _parse_filters(f_strs): filters = [] if not f_strs: return filters for f_str in f_strs: if ':' in f_str: fname, fopts = f_str.split(':', 1) filters.append((fname, _parse_options([fopts]))) else: filters.append((f_str, {})) return filters
def _print_help(what, name): try: if what == 'lexer': cls = get_lexer_by_name(name) print(f"Help on the {cls.name} lexer:") print(dedent(cls.__doc__)) elif what == 'formatter': cls = find_formatter_class(name) print(f"Help on the {cls.name} formatter:") print(dedent(cls.__doc__)) elif what == 'filter': cls = find_filter_class(name) print(f"Help on the {name} filter:") print(dedent(cls.__doc__)) return 0 except (AttributeError, ValueError): print(f"{what} not found!", file=sys.stderr) return 1
def _print_list(what): if what == 'lexer': print() print("Lexers:") print("~~~~~~~")
info = [] for fullname, names, exts, _ in get_all_lexers(): tup = (', '.join(names)+':', fullname, exts and '(filenames ' + ', '.join(exts) + ')' or '') info.append(tup) info.sort() for i in info: print(('* {}\n {} {}').format(*i))
elif what == 'formatter': print() print("Formatters:") print("~~~~~~~~~~~")
info = [] for cls in get_all_formatters(): doc = docstring_headline(cls) tup = (', '.join(cls.aliases) + ':', doc, cls.filenames and '(filenames ' + ', '.join(cls.filenames) + ')' or '') info.append(tup) info.sort() for i in info: print(('* {}\n {} {}').format(*i))
elif what == 'filter': print() print("Filters:") print("~~~~~~~~")
for name in get_all_filters(): cls = find_filter_class(name) print("* " + name + ':') print(f" {docstring_headline(cls)}")
elif what == 'style': print() print("Styles:") print("~~~~~~~")
for name in get_all_styles(): cls = get_style_by_name(name) print("* " + name + ':') print(f" {docstring_headline(cls)}")
def _print_list_as_json(requested_items): import json result = {} if 'lexer' in requested_items: info = {} for fullname, names, filenames, mimetypes in get_all_lexers(): info[fullname] = { 'aliases': names, 'filenames': filenames, 'mimetypes': mimetypes } result['lexers'] = info
if 'formatter' in requested_items: info = {} for cls in get_all_formatters(): doc = docstring_headline(cls) info[cls.name] = { 'aliases': cls.aliases, 'filenames': cls.filenames, 'doc': doc } result['formatters'] = info
if 'filter' in requested_items: info = {} for name in get_all_filters(): cls = find_filter_class(name) info[name] = { 'doc': docstring_headline(cls) } result['filters'] = info
if 'style' in requested_items: info = {} for name in get_all_styles(): cls = get_style_by_name(name) info[name] = { 'doc': docstring_headline(cls) } result['styles'] = info
json.dump(result, sys.stdout)
def main_inner(parser, argns): if argns.help: parser.print_help() return 0
if argns.V: print(f'Pygments version {__version__}, (c) 2006-present by Georg Brandl, Matthäus ' 'Chajdas and contributors.') return 0
def is_only_option(opt): return not any(v for (k, v) in vars(argns).items() if k != opt)
# handle ``pygmentize -L`` if argns.L is not None: arg_set = set() for k, v in vars(argns).items(): if v: arg_set.add(k)
arg_set.discard('L') arg_set.discard('json')
if arg_set: parser.print_help(sys.stderr) return 2
# print version if not argns.json: main(['', '-V']) allowed_types = {'lexer', 'formatter', 'filter', 'style'} largs = [arg.rstrip('s') for arg in argns.L] if any(arg not in allowed_types for arg in largs): parser.print_help(sys.stderr) return 0 if not largs: largs = allowed_types if not argns.json: for arg in largs: _print_list(arg) else: _print_list_as_json(largs) return 0
# handle ``pygmentize -H`` if argns.H: if not is_only_option('H'): parser.print_help(sys.stderr) return 2 what, name = argns.H if what not in ('lexer', 'formatter', 'filter'): parser.print_help(sys.stderr) return 2 return _print_help(what, name)
# parse -O options parsed_opts = _parse_options(argns.O or [])
# parse -P options for p_opt in argns.P or []: try: name, value = p_opt.split('=', 1) except ValueError: parsed_opts[p_opt] = True else: parsed_opts[name] = value
# encodings inencoding = parsed_opts.get('inencoding', parsed_opts.get('encoding')) outencoding = parsed_opts.get('outencoding', parsed_opts.get('encoding'))
# handle ``pygmentize -N`` if argns.N: lexer = find_lexer_class_for_filename(argns.N) if lexer is None: lexer = TextLexer
print(lexer.aliases[0]) return 0
# handle ``pygmentize -C`` if argns.C: inp = sys.stdin.buffer.read() try: lexer = guess_lexer(inp, inencoding=inencoding) except ClassNotFound: lexer = TextLexer
print(lexer.aliases[0]) return 0
# handle ``pygmentize -S`` S_opt = argns.S a_opt = argns.a if S_opt is not None: f_opt = argns.f if not f_opt: parser.print_help(sys.stderr) return 2 if argns.l or argns.INPUTFILE: parser.print_help(sys.stderr) return 2
try: parsed_opts['style'] = S_opt fmter = get_formatter_by_name(f_opt, **parsed_opts) except ClassNotFound as err: print(err, file=sys.stderr) return 1
print(fmter.get_style_defs(a_opt or '')) return 0
# if no -S is given, -a is not allowed if argns.a is not None: parser.print_help(sys.stderr) return 2
# parse -F options F_opts = _parse_filters(argns.F or [])
# -x: allow custom (eXternal) lexers and formatters allow_custom_lexer_formatter = bool(argns.x)
# select lexer lexer = None
# given by name? lexername = argns.l if lexername: # custom lexer, located relative to user's cwd if allow_custom_lexer_formatter and '.py' in lexername: try: filename = None name = None if ':' in lexername: filename, name = lexername.rsplit(':', 1)
if '.py' in name: # This can happen on Windows: If the lexername is # C:\lexer.py -- return to normal load path in that case name = None
if filename and name: lexer = load_lexer_from_file(filename, name, **parsed_opts) else: lexer = load_lexer_from_file(lexername, **parsed_opts) except ClassNotFound as err: print('Error:', err, file=sys.stderr) return 1 else: try: lexer = get_lexer_by_name(lexername, **parsed_opts) except (OptionError, ClassNotFound) as err: print('Error:', err, file=sys.stderr) return 1
# read input code code = None
if argns.INPUTFILE: if argns.s: print('Error: -s option not usable when input file specified', file=sys.stderr) return 2
infn = argns.INPUTFILE try: with open(infn, 'rb') as infp: code = infp.read() except Exception as err: print('Error: cannot read infile:', err, file=sys.stderr) return 1 if not inencoding: code, inencoding = guess_decode(code)
# do we have to guess the lexer? if not lexer: try: lexer = get_lexer_for_filename(infn, code, **parsed_opts) except ClassNotFound as err: if argns.g: try: lexer = guess_lexer(code, **parsed_opts) except ClassNotFound: lexer = TextLexer(**parsed_opts) else: print('Error:', err, file=sys.stderr) return 1 except OptionError as err: print('Error:', err, file=sys.stderr) return 1
elif not argns.s: # treat stdin as full file (-s support is later) # read code from terminal, always in binary mode since we want to # decode ourselves and be tolerant with it code = sys.stdin.buffer.read() # use .buffer to get a binary stream if not inencoding: code, inencoding = guess_decode_from_terminal(code, sys.stdin) # else the lexer will do the decoding if not lexer: try: lexer = guess_lexer(code, **parsed_opts) except ClassNotFound: lexer = TextLexer(**parsed_opts)
else: # -s option needs a lexer with -l if not lexer: print('Error: when using -s a lexer has to be selected with -l', file=sys.stderr) return 2
# process filters for fname, fopts in F_opts: try: lexer.add_filter(fname, **fopts) except ClassNotFound as err: print('Error:', err, file=sys.stderr) return 1
# select formatter outfn = argns.o fmter = argns.f if fmter: # custom formatter, located relative to user's cwd if allow_custom_lexer_formatter and '.py' in fmter: try: filename = None name = None if ':' in fmter: # Same logic as above for custom lexer filename, name = fmter.rsplit(':', 1)
if '.py' in name: name = None
if filename and name: fmter = load_formatter_from_file(filename, name, **parsed_opts) else: fmter = load_formatter_from_file(fmter, **parsed_opts) except ClassNotFound as err: print('Error:', err, file=sys.stderr) return 1 else: try: fmter = get_formatter_by_name(fmter, **parsed_opts) except (OptionError, ClassNotFound) as err: print('Error:', err, file=sys.stderr) return 1
if outfn: if not fmter: try: fmter = get_formatter_for_filename(outfn, **parsed_opts) except (OptionError, ClassNotFound) as err: print('Error:', err, file=sys.stderr) return 1 try: outfile = open(outfn, 'wb') except Exception as err: print('Error: cannot open outfile:', err, file=sys.stderr) return 1 else: if not fmter: if os.environ.get('COLORTERM','') in ('truecolor', '24bit'): fmter = TerminalTrueColorFormatter(**parsed_opts) elif '256' in os.environ.get('TERM', ''): fmter = Terminal256Formatter(**parsed_opts) else: fmter = TerminalFormatter(**parsed_opts) outfile = sys.stdout.buffer
# determine output encoding if not explicitly selected if not outencoding: if outfn: # output file? use lexer encoding for now (can still be None) fmter.encoding = inencoding else: # else use terminal encoding fmter.encoding = terminal_encoding(sys.stdout)
# provide coloring under Windows, if possible if not outfn and sys.platform in ('win32', 'cygwin') and \ fmter.name in ('Terminal', 'Terminal256'): # pragma: no cover # unfortunately colorama doesn't support binary streams on Py3 outfile = UnclosingTextIOWrapper(outfile, encoding=fmter.encoding) fmter.encoding = None try: import colorama.initialise except ImportError: pass else: outfile = colorama.initialise.wrap_stream( outfile, convert=None, strip=None, autoreset=False, wrap=True)
# When using the LaTeX formatter and the option `escapeinside` is # specified, we need a special lexer which collects escaped text # before running the chosen language lexer. escapeinside = parsed_opts.get('escapeinside', '') if len(escapeinside) == 2 and isinstance(fmter, LatexFormatter): left = escapeinside[0] right = escapeinside[1] lexer = LatexEmbeddedLexer(left, right, lexer)
# ... and do it! if not argns.s: # process whole input as per normal... try: highlight(code, lexer, fmter, outfile) finally: if outfn: outfile.close() return 0 else: # line by line processing of stdin (eg: for 'tail -f')... try: while 1: line = sys.stdin.buffer.readline() if not line: break if not inencoding: line = guess_decode_from_terminal(line, sys.stdin)[0] highlight(line, lexer, fmter, outfile) if hasattr(outfile, 'flush'): outfile.flush() return 0 except KeyboardInterrupt: # pragma: no cover return 0 finally: if outfn: outfile.close()
class HelpFormatter(argparse.HelpFormatter): def __init__(self, prog, indent_increment=2, max_help_position=16, width=None): if width is None: try: width = shutil.get_terminal_size().columns - 2 except Exception: pass argparse.HelpFormatter.__init__(self, prog, indent_increment, max_help_position, width)
def main(args=sys.argv): """ Main command line entry point. """ desc = "Highlight an input file and write the result to an output file." parser = argparse.ArgumentParser(description=desc, add_help=False, formatter_class=HelpFormatter)
operation = parser.add_argument_group('Main operation') lexersel = operation.add_mutually_exclusive_group() lexersel.add_argument( '-l', metavar='LEXER', help='Specify the lexer to use. (Query names with -L.) If not ' 'given and -g is not present, the lexer is guessed from the filename.') lexersel.add_argument( '-g', action='store_true', help='Guess the lexer from the file contents, or pass through ' 'as plain text if nothing can be guessed.') operation.add_argument( '-F', metavar='FILTER[:options]', action='append', help='Add a filter to the token stream. (Query names with -L.) ' 'Filter options are given after a colon if necessary.') operation.add_argument( '-f', metavar='FORMATTER', help='Specify the formatter to use. (Query names with -L.) ' 'If not given, the formatter is guessed from the output filename, ' 'and defaults to the terminal formatter if the output is to the ' 'terminal or an unknown file extension.') operation.add_argument( '-O', metavar='OPTION=value[,OPTION=value,...]', action='append', help='Give options to the lexer and formatter as a comma-separated ' 'list of key-value pairs. ' 'Example: `-O bg=light,python=cool`.') operation.add_argument( '-P', metavar='OPTION=value', action='append', help='Give a single option to the lexer and formatter - with this ' 'you can pass options whose value contains commas and equal signs. ' 'Example: `-P "heading=Pygments, the Python highlighter"`.') operation.add_argument( '-o', metavar='OUTPUTFILE', help='Where to write the output. Defaults to standard output.')
operation.add_argument( 'INPUTFILE', nargs='?', help='Where to read the input. Defaults to standard input.')
flags = parser.add_argument_group('Operation flags') flags.add_argument( '-v', action='store_true', help='Print a detailed traceback on unhandled exceptions, which ' 'is useful for debugging and bug reports.') flags.add_argument( '-s', action='store_true', help='Process lines one at a time until EOF, rather than waiting to ' 'process the entire file. This only works for stdin, only for lexers ' 'with no line-spanning constructs, and is intended for streaming ' 'input such as you get from `tail -f`. ' 'Example usage: `tail -f sql.log | pygmentize -s -l sql`.') flags.add_argument( '-x', action='store_true', help='Allow custom lexers and formatters to be loaded from a .py file ' 'relative to the current working directory. For example, ' '`-l ./customlexer.py -x`. By default, this option expects a file ' 'with a class named CustomLexer or CustomFormatter; you can also ' 'specify your own class name with a colon (`-l ./lexer.py:MyLexer`). ' 'Users should be very careful not to use this option with untrusted ' 'files, because it will import and run them.') flags.add_argument('--json', help='Output as JSON. This can ' 'be only used in conjunction with -L.', default=False, action='store_true')
special_modes_group = parser.add_argument_group( 'Special modes - do not do any highlighting') special_modes = special_modes_group.add_mutually_exclusive_group() special_modes.add_argument( '-S', metavar='STYLE -f formatter', help='Print style definitions for STYLE for a formatter ' 'given with -f. The argument given by -a is formatter ' 'dependent.') special_modes.add_argument( '-L', nargs='*', metavar='WHAT', help='List lexers, formatters, styles or filters -- ' 'give additional arguments for the thing(s) you want to list ' '(e.g. "styles"), or omit them to list everything.') special_modes.add_argument( '-N', metavar='FILENAME', help='Guess and print out a lexer name based solely on the given ' 'filename. Does not take input or highlight anything. If no specific ' 'lexer can be determined, "text" is printed.') special_modes.add_argument( '-C', action='store_true', help='Like -N, but print out a lexer name based solely on ' 'a given content from standard input.') special_modes.add_argument( '-H', action='store', nargs=2, metavar=('NAME', 'TYPE'), help='Print detailed help for the object <name> of type <type>, ' 'where <type> is one of "lexer", "formatter" or "filter".') special_modes.add_argument( '-V', action='store_true', help='Print the package version.') special_modes.add_argument( '-h', '--help', action='store_true', help='Print this help.') special_modes_group.add_argument( '-a', metavar='ARG', help='Formatter-specific additional argument for the -S (print ' 'style sheet) mode.')
argns = parser.parse_args(args[1:])
try: return main_inner(parser, argns) except BrokenPipeError: # someone closed our stdout, e.g. by quitting a pager. return 0 except Exception: if argns.v: print(file=sys.stderr) print('*' * 65, file=sys.stderr) print('An unhandled exception occurred while highlighting.', file=sys.stderr) print('Please report the whole traceback to the issue tracker at', file=sys.stderr) print('<https://github.com/pygments/pygments/issues>.', file=sys.stderr) print('*' * 65, file=sys.stderr) print(file=sys.stderr) raise import traceback info = traceback.format_exception(*sys.exc_info()) msg = info[-1].strip() if len(info) >= 3: # extract relevant file and position info msg += '\n (f{})'.format(info[-2].split('\n')[0].strip()[1:]) print(file=sys.stderr) print('*** Error while highlighting:', file=sys.stderr) print(msg, file=sys.stderr) print('*** If this is a bug you want to report, please rerun with -v.', file=sys.stderr) return 112345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970""" pygments.filter ~~~~~~~~~~~~~~~
Module that implements the default filter.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
def apply_filters(stream, filters, lexer=None): """ Use this method to apply an iterable of filters to a stream. If lexer is given it's forwarded to the filter, otherwise the filter receives `None`. """ def _apply(filter_, stream): yield from filter_.filter(lexer, stream) for filter_ in filters: stream = _apply(filter_, stream) return stream
def simplefilter(f): """ Decorator that converts a function into a filter::
@simplefilter def lowercase(self, lexer, stream, options): for ttype, value in stream: yield ttype, value.lower() """ return type(f.__name__, (FunctionFilter,), { '__module__': getattr(f, '__module__'), '__doc__': f.__doc__, 'function': f, })
class Filter: """ Default filter. Subclass this class or use the `simplefilter` decorator to create own filters. """
def __init__(self, **options): self.options = options
def filter(self, lexer, stream): raise NotImplementedError()
class FunctionFilter(Filter): """ Abstract class used by `simplefilter` to create simple function filters on the fly. The `simplefilter` decorator automatically creates subclasses of this class for functions passed to it. """ function = None
def __init__(self, **options): if not hasattr(self, 'function'): raise TypeError(f'{self.__class__.__name__!r} used without bound function') Filter.__init__(self, **options)
def filter(self, lexer, stream): # pylint: disable=not-callable yield from self.function(lexer, stream, self.options)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129""" pygments.formatter ~~~~~~~~~~~~~~~~~~
Base formatter class.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import codecs
from pygments.util import get_bool_optfrom pygments.styles import get_style_by_name
__all__ = ['Formatter']
def _lookup_style(style): if isinstance(style, str): return get_style_by_name(style) return style
class Formatter: """ Converts a token stream to text.
Formatters should have attributes to help selecting them. These are similar to the corresponding :class:`~pygments.lexer.Lexer` attributes.
.. autoattribute:: name :no-value:
.. autoattribute:: aliases :no-value:
.. autoattribute:: filenames :no-value:
You can pass options as keyword arguments to the constructor. All formatters accept these basic options:
``style`` The style to use, can be a string or a Style subclass (default: "default"). Not used by e.g. the TerminalFormatter. ``full`` Tells the formatter to output a "full" document, i.e. a complete self-contained document. This doesn't have any effect for some formatters (default: false). ``title`` If ``full`` is true, the title that should be used to caption the document (default: ''). ``encoding`` If given, must be an encoding name. This will be used to convert the Unicode token strings to byte strings in the output. If it is "" or None, Unicode strings will be written to the output file, which most file-like objects do not support (default: None). ``outencoding`` Overrides ``encoding`` if given.
"""
#: Full name for the formatter, in human-readable form. name = None
#: A list of short, unique identifiers that can be used to lookup #: the formatter from a list, e.g. using :func:`.get_formatter_by_name()`. aliases = []
#: A list of fnmatch patterns that match filenames for which this #: formatter can produce output. The patterns in this list should be unique #: among all formatters. filenames = []
#: If True, this formatter outputs Unicode strings when no encoding #: option is given. unicodeoutput = True
def __init__(self, **options): """ As with lexers, this constructor takes arbitrary optional arguments, and if you override it, you should first process your own options, then call the base class implementation. """ self.style = _lookup_style(options.get('style', 'default')) self.full = get_bool_opt(options, 'full', False) self.title = options.get('title', '') self.encoding = options.get('encoding', None) or None if self.encoding in ('guess', 'chardet'): # can happen for e.g. pygmentize -O encoding=guess self.encoding = 'utf-8' self.encoding = options.get('outencoding') or self.encoding self.options = options
def get_style_defs(self, arg=''): """ This method must return statements or declarations suitable to define the current style for subsequent highlighted text (e.g. CSS classes in the `HTMLFormatter`).
The optional argument `arg` can be used to modify the generation and is formatter dependent (it is standardized because it can be given on the command line).
This method is called by the ``-S`` :doc:`command-line option <cmdline>`, the `arg` is then given by the ``-a`` option. """ return ''
def format(self, tokensource, outfile): """ This method must format the tokens from the `tokensource` iterable and write the formatted version to the file object `outfile`.
Formatter options can control how exactly the tokens are converted. """ if self.encoding: # wrap the outfile in a StreamWriter outfile = codecs.lookup(self.encoding)[3](outfile) return self.format_unencoded(tokensource, outfile)
# Allow writing Formatter[str] or Formatter[bytes]. That's equivalent to # Formatter. This helps when using third-party type stubs from typeshed. def __class_getitem__(cls, name): return cls123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963""" pygments.lexer ~~~~~~~~~~~~~~
Base lexer classes.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import reimport sysimport time
from pygments.filter import apply_filters, Filterfrom pygments.filters import get_filter_by_namefrom pygments.token import Error, Text, Other, Whitespace, _TokenTypefrom pygments.util import get_bool_opt, get_int_opt, get_list_opt, \ make_analysator, Future, guess_decodefrom pygments.regexopt import regex_opt
__all__ = ['Lexer', 'RegexLexer', 'ExtendedRegexLexer', 'DelegatingLexer', 'LexerContext', 'include', 'inherit', 'bygroups', 'using', 'this', 'default', 'words', 'line_re']
line_re = re.compile('.*?\n')
_encoding_map = [(b'\xef\xbb\xbf', 'utf-8'), (b'\xff\xfe\0\0', 'utf-32'), (b'\0\0\xfe\xff', 'utf-32be'), (b'\xff\xfe', 'utf-16'), (b'\xfe\xff', 'utf-16be')]
_default_analyse = staticmethod(lambda x: 0.0)
class LexerMeta(type): """ This metaclass automagically converts ``analyse_text`` methods into static methods which always return float values. """
def __new__(mcs, name, bases, d): if 'analyse_text' in d: d['analyse_text'] = make_analysator(d['analyse_text']) return type.__new__(mcs, name, bases, d)
class Lexer(metaclass=LexerMeta): """ Lexer for a specific language.
See also :doc:`lexerdevelopment`, a high-level guide to writing lexers.
Lexer classes have attributes used for choosing the most appropriate lexer based on various criteria.
.. autoattribute:: name :no-value: .. autoattribute:: aliases :no-value: .. autoattribute:: filenames :no-value: .. autoattribute:: alias_filenames .. autoattribute:: mimetypes :no-value: .. autoattribute:: priority
Lexers included in Pygments should have two additional attributes:
.. autoattribute:: url :no-value: .. autoattribute:: version_added :no-value:
Lexers included in Pygments may have additional attributes:
.. autoattribute:: _example :no-value:
You can pass options to the constructor. The basic options recognized by all lexers and processed by the base `Lexer` class are:
``stripnl`` Strip leading and trailing newlines from the input (default: True). ``stripall`` Strip all leading and trailing whitespace from the input (default: False). ``ensurenl`` Make sure that the input ends with a newline (default: True). This is required for some lexers that consume input linewise.
.. versionadded:: 1.3
``tabsize`` If given and greater than 0, expand tabs in the input (default: 0). ``encoding`` If given, must be an encoding name. This encoding will be used to convert the input string to Unicode, if it is not already a Unicode string (default: ``'guess'``, which uses a simple UTF-8 / Locale / Latin1 detection. Can also be ``'chardet'`` to use the chardet library, if it is installed. ``inencoding`` Overrides the ``encoding`` if given. """
#: Full name of the lexer, in human-readable form name = None
#: A list of short, unique identifiers that can be used to look #: up the lexer from a list, e.g., using `get_lexer_by_name()`. aliases = []
#: A list of `fnmatch` patterns that match filenames which contain #: content for this lexer. The patterns in this list should be unique among #: all lexers. filenames = []
#: A list of `fnmatch` patterns that match filenames which may or may not #: contain content for this lexer. This list is used by the #: :func:`.guess_lexer_for_filename()` function, to determine which lexers #: are then included in guessing the correct one. That means that #: e.g. every lexer for HTML and a template language should include #: ``\*.html`` in this list. alias_filenames = []
#: A list of MIME types for content that can be lexed with this lexer. mimetypes = []
#: Priority, should multiple lexers match and no content is provided priority = 0
#: URL of the language specification/definition. Used in the Pygments #: documentation. Set to an empty string to disable. url = None
#: Version of Pygments in which the lexer was added. version_added = None
#: Example file name. Relative to the ``tests/examplefiles`` directory. #: This is used by the documentation generator to show an example. _example = None
def __init__(self, **options): """ This constructor takes arbitrary options as keyword arguments. Every subclass must first process its own options and then call the `Lexer` constructor, since it processes the basic options like `stripnl`.
An example looks like this:
.. sourcecode:: python
def __init__(self, **options): self.compress = options.get('compress', '') Lexer.__init__(self, **options)
As these options must all be specifiable as strings (due to the command line usage), there are various utility functions available to help with that, see `Utilities`_. """ self.options = options self.stripnl = get_bool_opt(options, 'stripnl', True) self.stripall = get_bool_opt(options, 'stripall', False) self.ensurenl = get_bool_opt(options, 'ensurenl', True) self.tabsize = get_int_opt(options, 'tabsize', 0) self.encoding = options.get('encoding', 'guess') self.encoding = options.get('inencoding') or self.encoding self.filters = [] for filter_ in get_list_opt(options, 'filters', ()): self.add_filter(filter_)
def __repr__(self): if self.options: return f'<pygments.lexers.{self.__class__.__name__} with {self.options!r}>' else: return f'<pygments.lexers.{self.__class__.__name__}>'
def add_filter(self, filter_, **options): """ Add a new stream filter to this lexer. """ if not isinstance(filter_, Filter): filter_ = get_filter_by_name(filter_, **options) self.filters.append(filter_)
def analyse_text(text): """ A static method which is called for lexer guessing.
It should analyse the text and return a float in the range from ``0.0`` to ``1.0``. If it returns ``0.0``, the lexer will not be selected as the most probable one, if it returns ``1.0``, it will be selected immediately. This is used by `guess_lexer`.
The `LexerMeta` metaclass automatically wraps this function so that it works like a static method (no ``self`` or ``cls`` parameter) and the return value is automatically converted to `float`. If the return value is an object that is boolean `False` it's the same as if the return values was ``0.0``. """
def _preprocess_lexer_input(self, text): """Apply preprocessing such as decoding the input, removing BOM and normalizing newlines."""
if not isinstance(text, str): if self.encoding == 'guess': text, _ = guess_decode(text) elif self.encoding == 'chardet': try: import chardet except ImportError as e: raise ImportError('To enable chardet encoding guessing, ' 'please install the chardet library ' 'from http://chardet.feedparser.org/') from e # check for BOM first decoded = None for bom, encoding in _encoding_map: if text.startswith(bom): decoded = text[len(bom):].decode(encoding, 'replace') break # no BOM found, so use chardet if decoded is None: enc = chardet.detect(text[:1024]) # Guess using first 1KB decoded = text.decode(enc.get('encoding') or 'utf-8', 'replace') text = decoded else: text = text.decode(self.encoding) if text.startswith('\ufeff'): text = text[len('\ufeff'):] else: if text.startswith('\ufeff'): text = text[len('\ufeff'):]
# text now *is* a unicode string text = text.replace('\r\n', '\n') text = text.replace('\r', '\n') if self.stripall: text = text.strip() elif self.stripnl: text = text.strip('\n') if self.tabsize > 0: text = text.expandtabs(self.tabsize) if self.ensurenl and not text.endswith('\n'): text += '\n'
return text
def get_tokens(self, text, unfiltered=False): """ This method is the basic interface of a lexer. It is called by the `highlight()` function. It must process the text and return an iterable of ``(tokentype, value)`` pairs from `text`.
Normally, you don't need to override this method. The default implementation processes the options recognized by all lexers (`stripnl`, `stripall` and so on), and then yields all tokens from `get_tokens_unprocessed()`, with the ``index`` dropped.
If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined. """ text = self._preprocess_lexer_input(text)
def streamer(): for _, t, v in self.get_tokens_unprocessed(text): yield t, v stream = streamer() if not unfiltered: stream = apply_filters(stream, self.filters, self) return stream
def get_tokens_unprocessed(self, text): """ This method should process the text and return an iterable of ``(index, tokentype, value)`` tuples where ``index`` is the starting position of the token within the input text.
It must be overridden by subclasses. It is recommended to implement it as a generator to maximize effectiveness. """ raise NotImplementedError
class DelegatingLexer(Lexer): """ This lexer takes two lexer as arguments. A root lexer and a language lexer. First everything is scanned using the language lexer, afterwards all ``Other`` tokens are lexed using the root lexer.
The lexers from the ``template`` lexer package use this base lexer. """
def __init__(self, _root_lexer, _language_lexer, _needle=Other, **options): self.root_lexer = _root_lexer(**options) self.language_lexer = _language_lexer(**options) self.needle = _needle Lexer.__init__(self, **options)
def get_tokens_unprocessed(self, text): buffered = '' insertions = [] lng_buffer = [] for i, t, v in self.language_lexer.get_tokens_unprocessed(text): if t is self.needle: if lng_buffer: insertions.append((len(buffered), lng_buffer)) lng_buffer = [] buffered += v else: lng_buffer.append((i, t, v)) if lng_buffer: insertions.append((len(buffered), lng_buffer)) return do_insertions(insertions, self.root_lexer.get_tokens_unprocessed(buffered))
# ------------------------------------------------------------------------------# RegexLexer and ExtendedRegexLexer#
class include(str): # pylint: disable=invalid-name """ Indicates that a state should include rules from another state. """ pass
class _inherit: """ Indicates the a state should inherit from its superclass. """ def __repr__(self): return 'inherit'
inherit = _inherit() # pylint: disable=invalid-name
class combined(tuple): # pylint: disable=invalid-name """ Indicates a state combined from multiple states. """
def __new__(cls, *args): return tuple.__new__(cls, args)
def __init__(self, *args): # tuple.__init__ doesn't do anything pass
class _PseudoMatch: """ A pseudo match object constructed from a string. """
def __init__(self, start, text): self._text = text self._start = start
def start(self, arg=None): return self._start
def end(self, arg=None): return self._start + len(self._text)
def group(self, arg=None): if arg: raise IndexError('No such group') return self._text
def groups(self): return (self._text,)
def groupdict(self): return {}
def bygroups(*args): """ Callback that yields multiple actions for each group in the match. """ def callback(lexer, match, ctx=None): for i, action in enumerate(args): if action is None: continue elif type(action) is _TokenType: data = match.group(i + 1) if data: yield match.start(i + 1), action, data else: data = match.group(i + 1) if data is not None: if ctx: ctx.pos = match.start(i + 1) for item in action(lexer, _PseudoMatch(match.start(i + 1), data), ctx): if item: yield item if ctx: ctx.pos = match.end() return callback
class _This: """ Special singleton used for indicating the caller class. Used by ``using``. """
this = _This()
def using(_other, **kwargs): """ Callback that processes the match with a different lexer.
The keyword arguments are forwarded to the lexer, except `state` which is handled separately.
`state` specifies the state that the new lexer will start in, and can be an enumerable such as ('root', 'inline', 'string') or a simple string which is assumed to be on top of the root state.
Note: For that to work, `_other` must not be an `ExtendedRegexLexer`. """ gt_kwargs = {} if 'state' in kwargs: s = kwargs.pop('state') if isinstance(s, (list, tuple)): gt_kwargs['stack'] = s else: gt_kwargs['stack'] = ('root', s)
if _other is this: def callback(lexer, match, ctx=None): # if keyword arguments are given the callback # function has to create a new lexer instance if kwargs: # XXX: cache that somehow d = dict(lexer.options) d.update(kwargs) lx = lexer.__class__(**d) else: lx = lexer s = match.start() for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs): yield i + s, t, v if ctx: ctx.pos = match.end() else: def callback(lexer, match, ctx=None): # XXX: cache that somehow d = dict(lexer.options) d.update(kwargs) lx = _other(**d)
s = match.start() for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs): yield i + s, t, v if ctx: ctx.pos = match.end() return callback
class default: """ Indicates a state or state action (e.g. #pop) to apply. For example default('#pop') is equivalent to ('', Token, '#pop') Note that state tuples may be used as well.
.. versionadded:: 2.0 """ def __init__(self, state): self.state = state
class words(Future): """ Indicates a list of literal words that is transformed into an optimized regex that matches any of the words.
.. versionadded:: 2.0 """ def __init__(self, words, prefix='', suffix=''): self.words = words self.prefix = prefix self.suffix = suffix
def get(self): return regex_opt(self.words, prefix=self.prefix, suffix=self.suffix)
class RegexLexerMeta(LexerMeta): """ Metaclass for RegexLexer, creates the self._tokens attribute from self.tokens on the first instantiation. """
def _process_regex(cls, regex, rflags, state): """Preprocess the regular expression component of a token definition.""" if isinstance(regex, Future): regex = regex.get() return re.compile(regex, rflags).match
def _process_token(cls, token): """Preprocess the token component of a token definition.""" assert type(token) is _TokenType or callable(token), \ f'token type must be simple type or callable, not {token!r}' return token
def _process_new_state(cls, new_state, unprocessed, processed): """Preprocess the state transition action of a token definition.""" if isinstance(new_state, str): # an existing state if new_state == '#pop': return -1 elif new_state in unprocessed: return (new_state,) elif new_state == '#push': return new_state elif new_state[:5] == '#pop:': return -int(new_state[5:]) else: assert False, f'unknown new state {new_state!r}' elif isinstance(new_state, combined): # combine a new state from existing ones tmp_state = '_tmp_%d' % cls._tmpname cls._tmpname += 1 itokens = [] for istate in new_state: assert istate != new_state, f'circular state ref {istate!r}' itokens.extend(cls._process_state(unprocessed, processed, istate)) processed[tmp_state] = itokens return (tmp_state,) elif isinstance(new_state, tuple): # push more than one state for istate in new_state: assert (istate in unprocessed or istate in ('#pop', '#push')), \ 'unknown new state ' + istate return new_state else: assert False, f'unknown new state def {new_state!r}'
def _process_state(cls, unprocessed, processed, state): """Preprocess a single state definition.""" assert isinstance(state, str), f"wrong state name {state!r}" assert state[0] != '#', f"invalid state name {state!r}" if state in processed: return processed[state] tokens = processed[state] = [] rflags = cls.flags for tdef in unprocessed[state]: if isinstance(tdef, include): # it's a state reference assert tdef != state, f"circular state reference {state!r}" tokens.extend(cls._process_state(unprocessed, processed, str(tdef))) continue if isinstance(tdef, _inherit): # should be processed already, but may not in the case of: # 1. the state has no counterpart in any parent # 2. the state includes more than one 'inherit' continue if isinstance(tdef, default): new_state = cls._process_new_state(tdef.state, unprocessed, processed) tokens.append((re.compile('').match, None, new_state)) continue
assert type(tdef) is tuple, f"wrong rule def {tdef!r}"
try: rex = cls._process_regex(tdef[0], rflags, state) except Exception as err: raise ValueError(f"uncompilable regex {tdef[0]!r} in state {state!r} of {cls!r}: {err}") from err
token = cls._process_token(tdef[1])
if len(tdef) == 2: new_state = None else: new_state = cls._process_new_state(tdef[2], unprocessed, processed)
tokens.append((rex, token, new_state)) return tokens
def process_tokendef(cls, name, tokendefs=None): """Preprocess a dictionary of token definitions.""" processed = cls._all_tokens[name] = {} tokendefs = tokendefs or cls.tokens[name] for state in list(tokendefs): cls._process_state(tokendefs, processed, state) return processed
def get_tokendefs(cls): """ Merge tokens from superclasses in MRO order, returning a single tokendef dictionary.
Any state that is not defined by a subclass will be inherited automatically. States that *are* defined by subclasses will, by default, override that state in the superclass. If a subclass wishes to inherit definitions from a superclass, it can use the special value "inherit", which will cause the superclass' state definition to be included at that point in the state. """ tokens = {} inheritable = {} for c in cls.__mro__: toks = c.__dict__.get('tokens', {})
for state, items in toks.items(): curitems = tokens.get(state) if curitems is None: # N.b. because this is assigned by reference, sufficiently # deep hierarchies are processed incrementally (e.g. for # A(B), B(C), C(RegexLexer), B will be premodified so X(B) # will not see any inherits in B). tokens[state] = items try: inherit_ndx = items.index(inherit) except ValueError: continue inheritable[state] = inherit_ndx continue
inherit_ndx = inheritable.pop(state, None) if inherit_ndx is None: continue
# Replace the "inherit" value with the items curitems[inherit_ndx:inherit_ndx+1] = items try: # N.b. this is the index in items (that is, the superclass # copy), so offset required when storing below. new_inh_ndx = items.index(inherit) except ValueError: pass else: inheritable[state] = inherit_ndx + new_inh_ndx
return tokens
def __call__(cls, *args, **kwds): """Instantiate cls after preprocessing its token definitions.""" if '_tokens' not in cls.__dict__: cls._all_tokens = {} cls._tmpname = 0 if hasattr(cls, 'token_variants') and cls.token_variants: # don't process yet pass else: cls._tokens = cls.process_tokendef('', cls.get_tokendefs())
return type.__call__(cls, *args, **kwds)
class RegexLexer(Lexer, metaclass=RegexLexerMeta): """ Base for simple stateful regular expression-based lexers. Simplifies the lexing process so that you need only provide a list of states and regular expressions. """
#: Flags for compiling the regular expressions. #: Defaults to MULTILINE. flags = re.MULTILINE
#: At all time there is a stack of states. Initially, the stack contains #: a single state 'root'. The top of the stack is called "the current state". #: #: Dict of ``{'state': [(regex, tokentype, new_state), ...], ...}`` #: #: ``new_state`` can be omitted to signify no state transition. #: If ``new_state`` is a string, it is pushed on the stack. This ensure #: the new current state is ``new_state``. #: If ``new_state`` is a tuple of strings, all of those strings are pushed #: on the stack and the current state will be the last element of the list. #: ``new_state`` can also be ``combined('state1', 'state2', ...)`` #: to signify a new, anonymous state combined from the rules of two #: or more existing ones. #: Furthermore, it can be '#pop' to signify going back one step in #: the state stack, or '#push' to push the current state on the stack #: again. Note that if you push while in a combined state, the combined #: state itself is pushed, and not only the state in which the rule is #: defined. #: #: The tuple can also be replaced with ``include('state')``, in which #: case the rules from the state named by the string are included in the #: current one. tokens = {}
def get_tokens_unprocessed(self, text, stack=('root',)): """ Split ``text`` into (tokentype, text) pairs.
``stack`` is the initial stack (default: ``['root']``) """ pos = 0 tokendefs = self._tokens statestack = list(stack) statetokens = tokendefs[statestack[-1]] while 1: for rexmatch, action, new_state in statetokens: m = rexmatch(text, pos) if m: if action is not None: if type(action) is _TokenType: yield pos, action, m.group() else: yield from action(self, m) pos = m.end() if new_state is not None: # state transition if isinstance(new_state, tuple): for state in new_state: if state == '#pop': if len(statestack) > 1: statestack.pop() elif state == '#push': statestack.append(statestack[-1]) else: statestack.append(state) elif isinstance(new_state, int): # pop, but keep at least one state on the stack # (random code leading to unexpected pops should # not allow exceptions) if abs(new_state) >= len(statestack): del statestack[1:] else: del statestack[new_state:] elif new_state == '#push': statestack.append(statestack[-1]) else: assert False, f"wrong state def: {new_state!r}" statetokens = tokendefs[statestack[-1]] break else: # We are here only if all state tokens have been considered # and there was not a match on any of them. try: if text[pos] == '\n': # at EOL, reset state to "root" statestack = ['root'] statetokens = tokendefs['root'] yield pos, Whitespace, '\n' pos += 1 continue yield pos, Error, text[pos] pos += 1 except IndexError: break
class LexerContext: """ A helper object that holds lexer position data. """
def __init__(self, text, pos, stack=None, end=None): self.text = text self.pos = pos self.end = end or len(text) # end=0 not supported ;-) self.stack = stack or ['root']
def __repr__(self): return f'LexerContext({self.text!r}, {self.pos!r}, {self.stack!r})'
class ExtendedRegexLexer(RegexLexer): """ A RegexLexer that uses a context object to store its state. """
def get_tokens_unprocessed(self, text=None, context=None): """ Split ``text`` into (tokentype, text) pairs. If ``context`` is given, use this lexer context instead. """ tokendefs = self._tokens if not context: ctx = LexerContext(text, 0) statetokens = tokendefs['root'] else: ctx = context statetokens = tokendefs[ctx.stack[-1]] text = ctx.text while 1: for rexmatch, action, new_state in statetokens: m = rexmatch(text, ctx.pos, ctx.end) if m: if action is not None: if type(action) is _TokenType: yield ctx.pos, action, m.group() ctx.pos = m.end() else: yield from action(self, m, ctx) if not new_state: # altered the state stack? statetokens = tokendefs[ctx.stack[-1]] # CAUTION: callback must set ctx.pos! if new_state is not None: # state transition if isinstance(new_state, tuple): for state in new_state: if state == '#pop': if len(ctx.stack) > 1: ctx.stack.pop() elif state == '#push': ctx.stack.append(ctx.stack[-1]) else: ctx.stack.append(state) elif isinstance(new_state, int): # see RegexLexer for why this check is made if abs(new_state) >= len(ctx.stack): del ctx.stack[1:] else: del ctx.stack[new_state:] elif new_state == '#push': ctx.stack.append(ctx.stack[-1]) else: assert False, f"wrong state def: {new_state!r}" statetokens = tokendefs[ctx.stack[-1]] break else: try: if ctx.pos >= ctx.end: break if text[ctx.pos] == '\n': # at EOL, reset state to "root" ctx.stack = ['root'] statetokens = tokendefs['root'] yield ctx.pos, Text, '\n' ctx.pos += 1 continue yield ctx.pos, Error, text[ctx.pos] ctx.pos += 1 except IndexError: break
def do_insertions(insertions, tokens): """ Helper for lexers which must combine the results of several sublexers.
``insertions`` is a list of ``(index, itokens)`` pairs. Each ``itokens`` iterable should be inserted at position ``index`` into the token stream given by the ``tokens`` argument.
The result is a combined token stream.
TODO: clean up the code here. """ insertions = iter(insertions) try: index, itokens = next(insertions) except StopIteration: # no insertions yield from tokens return
realpos = None insleft = True
# iterate over the token stream where we want to insert # the tokens from the insertion list. for i, t, v in tokens: # first iteration. store the position of first item if realpos is None: realpos = i oldi = 0 while insleft and i + len(v) >= index: tmpval = v[oldi:index - i] if tmpval: yield realpos, t, tmpval realpos += len(tmpval) for it_index, it_token, it_value in itokens: yield realpos, it_token, it_value realpos += len(it_value) oldi = index - i try: index, itokens = next(insertions) except StopIteration: insleft = False break # not strictly necessary if oldi < len(v): yield realpos, t, v[oldi:] realpos += len(v) - oldi
# leftover tokens while insleft: # no normal tokens, set realpos to zero realpos = realpos or 0 for p, t, v in itokens: yield realpos, t, v realpos += len(v) try: index, itokens = next(insertions) except StopIteration: insleft = False break # not strictly necessary
class ProfilingRegexLexerMeta(RegexLexerMeta): """Metaclass for ProfilingRegexLexer, collects regex timing info."""
def _process_regex(cls, regex, rflags, state): if isinstance(regex, words): rex = regex_opt(regex.words, prefix=regex.prefix, suffix=regex.suffix) else: rex = regex compiled = re.compile(rex, rflags)
def match_func(text, pos, endpos=sys.maxsize): info = cls._prof_data[-1].setdefault((state, rex), [0, 0.0]) t0 = time.time() res = compiled.match(text, pos, endpos) t1 = time.time() info[0] += 1 info[1] += t1 - t0 return res return match_func
class ProfilingRegexLexer(RegexLexer, metaclass=ProfilingRegexLexerMeta): """Drop-in replacement for RegexLexer that does profiling of its regexes."""
_prof_data = [] _prof_sort_index = 4 # defaults to time per call
def get_tokens_unprocessed(self, text, stack=('root',)): # this needs to be a stack, since using(this) will produce nested calls self.__class__._prof_data.append({}) yield from RegexLexer.get_tokens_unprocessed(self, text, stack) rawdata = self.__class__._prof_data.pop() data = sorted(((s, repr(r).strip('u\'').replace('\\\\', '\\')[:65], n, 1000 * t, 1000 * t / n) for ((s, r), (n, t)) in rawdata.items()), key=lambda x: x[self._prof_sort_index], reverse=True) sum_total = sum(x[3] for x in data)
print() print('Profiling result for %s lexing %d chars in %.3f ms' % (self.__class__.__name__, len(text), sum_total)) print('=' * 110) print('%-20s %-64s ncalls tottime percall' % ('state', 'regex')) print('-' * 110) for d in data: print('%-20s %-65s %5d %8.4f %8.4f' % d) print('=' * 110)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798""" pygments.lexers.wren ~~~~~~~~~~~~~~~~~~~~
Lexer for Wren.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import include, RegexLexer, wordsfrom pygments.token import Whitespace, Punctuation, Keyword, Name, Comment, \ Operator, Number, String
__all__ = ['WrenLexer']
class WrenLexer(RegexLexer): """ For Wren source code, version 0.4.0. """ name = 'Wren' url = 'https://wren.io' aliases = ['wren'] filenames = ['*.wren'] version_added = '2.14'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ # Whitespace. (r'\s+', Whitespace), (r'[,\\\[\]{}]', Punctuation),
# Really 'root', not '#push': in 'interpolation', # parentheses inside the interpolation expression are # Punctuation, not String.Interpol. (r'\(', Punctuation, 'root'), (r'\)', Punctuation, '#pop'),
# Keywords. (words(( 'as', 'break', 'class', 'construct', 'continue', 'else', 'for', 'foreign', 'if', 'import', 'return', 'static', 'super', 'this', 'var', 'while'), prefix = r'(?<!\.)', suffix = r'\b'), Keyword),
(words(( 'true', 'false', 'null'), prefix = r'(?<!\.)', suffix = r'\b'), Keyword.Constant),
(words(( 'in', 'is'), prefix = r'(?<!\.)', suffix = r'\b'), Operator.Word),
# Comments. (r'/\*', Comment.Multiline, 'comment'), # Multiline, can nest. (r'//.*?$', Comment.Single), # Single line. (r'#.*?(\(.*?\))?$', Comment.Special), # Attribute or shebang.
# Names and operators. (r'[!%&*+\-./:<=>?\\^|~]+', Operator), (r'[a-z][a-zA-Z_0-9]*', Name), (r'[A-Z][a-zA-Z_0-9]*', Name.Class), (r'__[a-zA-Z_0-9]*', Name.Variable.Class), (r'_[a-zA-Z_0-9]*', Name.Variable.Instance),
# Numbers. (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+(\.\d+)?([eE][-+]?\d+)?', Number.Float),
# Strings. (r'""".*?"""', String), # Raw string (r'"', String, 'string'), # Other string ], 'comment': [ (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'([^*/]|\*(?!/)|/(?!\*))+', Comment.Multiline), ], 'string': [ (r'"', String, '#pop'), (r'\\[\\%"0abefnrtv]', String.Escape), # Escape. (r'\\x[a-fA-F0-9]{2}', String.Escape), # Byte escape. (r'\\u[a-fA-F0-9]{4}', String.Escape), # Unicode escape. (r'\\U[a-fA-F0-9]{8}', String.Escape), # Long Unicode escape.
(r'%\(', String.Interpol, 'interpolation'), (r'[^\\"%]+', String), # All remaining characters. ], 'interpolation': [ # redefine closing paren to be String.Interpol (r'\)', String.Interpol, '#pop'), include('root'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566""" pygments.lexers.x10 ~~~~~~~~~~~~~~~~~~~
Lexers for the X10 programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexerfrom pygments.token import Text, Comment, Keyword, String
__all__ = ['X10Lexer']
class X10Lexer(RegexLexer): """ For the X10 language. """
name = 'X10' url = 'http://x10-lang.org/' aliases = ['x10', 'xten'] filenames = ['*.x10'] mimetypes = ['text/x-x10'] version_added = '2.2'
keywords = ( 'as', 'assert', 'async', 'at', 'athome', 'ateach', 'atomic', 'break', 'case', 'catch', 'class', 'clocked', 'continue', 'def', 'default', 'do', 'else', 'final', 'finally', 'finish', 'for', 'goto', 'haszero', 'here', 'if', 'import', 'in', 'instanceof', 'interface', 'isref', 'new', 'offer', 'operator', 'package', 'return', 'struct', 'switch', 'throw', 'try', 'type', 'val', 'var', 'when', 'while' )
types = ( 'void' )
values = ( 'false', 'null', 'self', 'super', 'this', 'true' )
modifiers = ( 'abstract', 'extends', 'implements', 'native', 'offers', 'private', 'property', 'protected', 'public', 'static', 'throws', 'transient' )
tokens = { 'root': [ (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'/\*(.|\n)*?\*/', Comment.Multiline), (r'\b({})\b'.format('|'.join(keywords)), Keyword), (r'\b({})\b'.format('|'.join(types)), Keyword.Type), (r'\b({})\b'.format('|'.join(values)), Keyword.Constant), (r'\b({})\b'.format('|'.join(modifiers)), Keyword.Declaration), (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r"'\\.'|'[^\\]'|'\\u[0-9a-fA-F]{4}'", String.Char), (r'.', Text) ], }1234567891011121314151617181920212223242526272829303132333435363738""" pygments.lexers.xorg ~~~~~~~~~~~~~~~~~~~~
Lexers for Xorg configs.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroupsfrom pygments.token import Comment, String, Name, Text
__all__ = ['XorgLexer']
class XorgLexer(RegexLexer): """Lexer for xorg.conf files.""" name = 'Xorg' url = 'https://www.x.org/wiki/' aliases = ['xorg.conf'] filenames = ['xorg.conf'] mimetypes = [] version_added = ''
tokens = { 'root': [ (r'\s+', Text), (r'#.*$', Comment),
(r'((?:Sub)?Section)(\s+)("\w+")', bygroups(String.Escape, Text, String.Escape)), (r'(End(?:Sub)?Section)', String.Escape),
(r'(\w+)(\s+)([^\n#]+)', bygroups(Name.Builtin, Text, Name.Constant)), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103""" pygments.lexers.yang ~~~~~~~~~~~~~~~~~~~~
Lexer for the YANG 1.1 modeling language. See :rfc:`7950`.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, wordsfrom pygments.token import Text, Token, Name, String, Comment, Number
__all__ = ['YangLexer']
class YangLexer(RegexLexer): """ Lexer for YANG, based on RFC7950. """ name = 'YANG' url = 'https://tools.ietf.org/html/rfc7950/' aliases = ['yang'] filenames = ['*.yang'] mimetypes = ['application/yang'] version_added = '2.7'
#Keywords from RFC7950 ; oriented at BNF style TOP_STMTS_KEYWORDS = ("module", "submodule") MODULE_HEADER_STMT_KEYWORDS = ("belongs-to", "namespace", "prefix", "yang-version") META_STMT_KEYWORDS = ("contact", "description", "organization", "reference", "revision") LINKAGE_STMTS_KEYWORDS = ("import", "include", "revision-date") BODY_STMT_KEYWORDS = ("action", "argument", "augment", "deviation", "extension", "feature", "grouping", "identity", "if-feature", "input", "notification", "output", "rpc", "typedef") DATA_DEF_STMT_KEYWORDS = ("anydata", "anyxml", "case", "choice", "config", "container", "deviate", "leaf", "leaf-list", "list", "must", "presence", "refine", "uses", "when") TYPE_STMT_KEYWORDS = ("base", "bit", "default", "enum", "error-app-tag", "error-message", "fraction-digits", "length", "max-elements", "min-elements", "modifier", "ordered-by", "path", "pattern", "position", "range", "require-instance", "status", "type", "units", "value", "yin-element") LIST_STMT_KEYWORDS = ("key", "mandatory", "unique")
#RFC7950 other keywords CONSTANTS_KEYWORDS = ("add", "current", "delete", "deprecated", "false", "invert-match", "max", "min", "not-supported", "obsolete", "replace", "true", "unbounded", "user")
#RFC7950 Built-In Types TYPES = ("binary", "bits", "boolean", "decimal64", "empty", "enumeration", "identityref", "instance-identifier", "int16", "int32", "int64", "int8", "leafref", "string", "uint16", "uint32", "uint64", "uint8", "union")
suffix_re_pattern = r'(?=[^\w\-:])'
tokens = { 'comments': [ (r'[^*/]', Comment), (r'/\*', Comment, '#push'), (r'\*/', Comment, '#pop'), (r'[*/]', Comment), ], "root": [ (r'\s+', Text.Whitespace), (r'[{};]+', Token.Punctuation), (r'(?<![\-\w])(and|or|not|\+|\.)(?![\-\w])', Token.Operator),
(r'"(?:\\"|[^"])*?"', String.Double), (r"'(?:\\'|[^'])*?'", String.Single),
(r'/\*', Comment, 'comments'), (r'//.*?$', Comment),
#match BNF stmt for `node-identifier` with [ prefix ":"] (r'(?:^|(?<=[\s{};]))([\w.-]+)(:)([\w.-]+)(?=[\s{};])', bygroups(Name.Namespace, Token.Punctuation, Name.Variable)),
#match BNF stmt `date-arg-str` (r'([0-9]{4}\-[0-9]{2}\-[0-9]{2})(?=[\s{};])', Name.Label), (r'([0-9]+\.[0-9]+)(?=[\s{};])', Number.Float), (r'([0-9]+)(?=[\s{};])', Number.Integer),
(words(TOP_STMTS_KEYWORDS, suffix=suffix_re_pattern), Token.Keyword), (words(MODULE_HEADER_STMT_KEYWORDS, suffix=suffix_re_pattern), Token.Keyword), (words(META_STMT_KEYWORDS, suffix=suffix_re_pattern), Token.Keyword), (words(LINKAGE_STMTS_KEYWORDS, suffix=suffix_re_pattern), Token.Keyword), (words(BODY_STMT_KEYWORDS, suffix=suffix_re_pattern), Token.Keyword), (words(DATA_DEF_STMT_KEYWORDS, suffix=suffix_re_pattern), Token.Keyword), (words(TYPE_STMT_KEYWORDS, suffix=suffix_re_pattern), Token.Keyword), (words(LIST_STMT_KEYWORDS, suffix=suffix_re_pattern), Token.Keyword), (words(TYPES, suffix=suffix_re_pattern), Name.Class), (words(CONSTANTS_KEYWORDS, suffix=suffix_re_pattern), Name.Class),
(r'[^;{}\s\'"]+', Name.Variable), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869""" pygments.lexers.yara ~~~~~~~~~~~~~~~~~~~~
Lexers for YARA.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, String, Name, Text, Punctuation, \ Operator, Keyword, Whitespace, Number
__all__ = ['YaraLexer']
class YaraLexer(RegexLexer): """ For YARA rules """
name = 'YARA' url = 'https://virustotal.github.io/yara/' aliases = ['yara', 'yar'] filenames = ['*.yar'] mimetypes = ['text/x-yara'] version_added = '2.16'
tokens = { 'root': [ (r'\s+', Whitespace), (r'//.*?$', Comment.Single), (r'\#.*?$', Comment.Single), (r'/\*', Comment.Multiline, 'comment'), (words(('rule', 'private', 'global', 'import', 'include'), prefix=r'\b', suffix=r'\b'), Keyword.Declaration), (words(('strings', 'condition', 'meta'), prefix=r'\b', suffix=r'\b'), Keyword), (words(('ascii', 'at', 'base64', 'base64wide', 'condition', 'contains', 'endswith', 'entrypoint', 'filesize', 'for', 'fullword', 'icontains', 'iendswith', 'iequals', 'in', 'include', 'int16', 'int16be', 'int32', 'int32be', 'int8', 'int8be', 'istartswith', 'matches', 'meta', 'nocase', 'none', 'of', 'startswith', 'strings', 'them', 'uint16', 'uint16be', 'uint32', 'uint32be', 'uint8', 'uint8be', 'wide', 'xor', 'defined'), prefix=r'\b', suffix=r'\b'), Name.Builtin), (r'(true|false)\b', Keyword.Constant), (r'(and|or|not|any|all)\b', Operator.Word), (r'(\$\w+)', Name.Variable), (r'"[^"]*"', String.Double), (r'\'[^\']*\'', String.Single), (r'\{.*?\}$', Number.Hex), (r'(/.*?/)', String.Regex), (r'[a-z_]\w*', Name), (r'[$(){}[\].?+*|]', Punctuation), (r'[:=,;]', Punctuation), (r'.', Text) ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125""" pygments.lexers.zig ~~~~~~~~~~~~~~~~~~~
Lexers for Zig.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['ZigLexer']
class ZigLexer(RegexLexer): """ Lexer for the Zig language.
grammar: https://ziglang.org/documentation/master/#Grammar """ name = 'Zig' url = 'http://ziglang.org' aliases = ['zig'] filenames = ['*.zig'] mimetypes = ['text/zig'] version_added = ''
type_keywords = ( words(('bool', 'f16', 'f32', 'f64', 'f128', 'void', 'noreturn', 'type', 'anyerror', 'promise', 'i0', 'u0', 'isize', 'usize', 'comptime_int', 'comptime_float', 'c_short', 'c_ushort', 'c_int', 'c_uint', 'c_long', 'c_ulong', 'c_longlong', 'c_ulonglong', 'c_longdouble', 'c_void' 'i8', 'u8', 'i16', 'u16', 'i32', 'u32', 'i64', 'u64', 'i128', 'u128'), suffix=r'\b'), Keyword.Type)
storage_keywords = ( words(('const', 'var', 'extern', 'packed', 'export', 'pub', 'noalias', 'inline', 'comptime', 'nakedcc', 'stdcallcc', 'volatile', 'allowzero', 'align', 'linksection', 'threadlocal'), suffix=r'\b'), Keyword.Reserved)
structure_keywords = ( words(('struct', 'enum', 'union', 'error'), suffix=r'\b'), Keyword)
statement_keywords = ( words(('break', 'return', 'continue', 'asm', 'defer', 'errdefer', 'unreachable', 'try', 'catch', 'async', 'await', 'suspend', 'resume', 'cancel'), suffix=r'\b'), Keyword)
conditional_keywords = ( words(('if', 'else', 'switch', 'and', 'or', 'orelse'), suffix=r'\b'), Keyword)
repeat_keywords = ( words(('while', 'for'), suffix=r'\b'), Keyword)
other_keywords = ( words(('fn', 'usingnamespace', 'test'), suffix=r'\b'), Keyword)
constant_keywords = ( words(('true', 'false', 'null', 'undefined'), suffix=r'\b'), Keyword.Constant)
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'//.*?\n', Comment.Single),
# Keywords statement_keywords, storage_keywords, structure_keywords, repeat_keywords, type_keywords, constant_keywords, conditional_keywords, other_keywords,
# Floats (r'0x[0-9a-fA-F]+\.[0-9a-fA-F]+([pP][\-+]?[0-9a-fA-F]+)?', Number.Float), (r'0x[0-9a-fA-F]+\.?[pP][\-+]?[0-9a-fA-F]+', Number.Float), (r'[0-9]+\.[0-9]+([eE][-+]?[0-9]+)?', Number.Float), (r'[0-9]+\.?[eE][-+]?[0-9]+', Number.Float),
# Integers (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+', Number.Integer),
# Identifier (r'@[a-zA-Z_]\w*', Name.Builtin), (r'[a-zA-Z_]\w*', Name),
# Characters (r'\'\\\'\'', String.Escape), (r'\'\\(x[a-fA-F0-9]{2}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{6}|[nr\\t\'"])\'', String.Escape), (r'\'[^\\\']\'', String),
# Strings (r'\\\\[^\n]*', String.Heredoc), (r'c\\\\[^\n]*', String.Heredoc), (r'c?"', String, 'string'),
# Operators, Punctuation (r'[+%=><|^!?/\-*&~:]', Operator), (r'[{}()\[\],.;]', Punctuation) ], 'string': [ (r'\\(x[a-fA-F0-9]{2}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{6}|[nr\\t\'"])', String.Escape), (r'[^\\"\n]+', String), (r'"', String, '#pop') ] }12345678910111213141516171819202122232425262728293031323334353637383940414243""" pygments.modeline ~~~~~~~~~~~~~~~~~
A simple modeline parser (based on pymodeline).
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
__all__ = ['get_filetype_from_buffer']
modeline_re = re.compile(r''' (?: vi | vim | ex ) (?: [<=>]? \d* )? : .* (?: ft | filetype | syn | syntax ) = ( [^:\s]+ )''', re.VERBOSE)
def get_filetype_from_line(l): # noqa: E741 m = modeline_re.search(l) if m: return m.group(1)
def get_filetype_from_buffer(buf, max_lines=5): """ Scan the buffer for modelines and return filetype if one is found. """ lines = buf.splitlines() for line in lines[-1:-max_lines-1:-1]: ret = get_filetype_from_line(line) if ret: return ret for i in range(max_lines, -1, -1): if i < len(lines): ret = get_filetype_from_line(lines[i]) if ret: return ret
return None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374""" pygments.plugin ~~~~~~~~~~~~~~~
Pygments plugin interface.
lexer plugins::
[pygments.lexers] yourlexer = yourmodule:YourLexer
formatter plugins::
[pygments.formatters] yourformatter = yourformatter:YourFormatter /.ext = yourformatter:YourFormatter
As you can see, you can define extensions for the formatter with a leading slash.
syntax plugins::
[pygments.styles] yourstyle = yourstyle:YourStyle
filter plugin::
[pygments.filter] yourfilter = yourfilter:YourFilter
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""import functoolsfrom importlib.metadata import entry_points
LEXER_ENTRY_POINT = 'pygments.lexers'FORMATTER_ENTRY_POINT = 'pygments.formatters'STYLE_ENTRY_POINT = 'pygments.styles'FILTER_ENTRY_POINT = 'pygments.filters'
@functools.cachedef iter_entry_points(group_name): groups = entry_points() if hasattr(groups, 'select'): # New interface in Python 3.10 and newer versions of the # importlib_metadata backport. return groups.select(group=group_name) else: # Older interface, deprecated in Python 3.10 and recent # importlib_metadata, but we need it in Python 3.8 and 3.9. return groups.get(group_name, [])
def find_plugin_lexers(): for entrypoint in iter_entry_points(LEXER_ENTRY_POINT): yield entrypoint.load()
def find_plugin_formatters(): for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT): yield entrypoint.name, entrypoint.load()
def find_plugin_styles(): for entrypoint in iter_entry_points(STYLE_ENTRY_POINT): yield entrypoint.name, entrypoint.load()
def find_plugin_filters(): for entrypoint in iter_entry_points(FILTER_ENTRY_POINT): yield entrypoint.name, entrypoint.load()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102""" pygments.regexopt ~~~~~~~~~~~~~~~~~
An algorithm that generates optimized regexes for matching long lists of literal strings.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import refrom re import escapefrom itertools import groupbyfrom operator import itemgetter
CS_ESCAPE = re.compile(r'[\[\^\\\-\]]')FIRST_ELEMENT = itemgetter(0)
def commonprefix(m): """Given an iterable of strings, returns the longest common leading substring""" if not m: return "" s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
def make_charset(letters): return '[' + CS_ESCAPE.sub(lambda m: '\\' + m.group(), ''.join(letters)) + ']'
def regex_opt_inner(strings, open_paren): """Return a regex that matches any string in the sorted list of strings.""" close_paren = open_paren and ')' or '' # print strings, repr(open_paren) if not strings: # print '-> nothing left' return '' first = strings[0] if len(strings) == 1: # print '-> only 1 string' return open_paren + escape(first) + close_paren if not first: # print '-> first string empty' return open_paren + regex_opt_inner(strings[1:], '(?:') \ + '?' + close_paren if len(first) == 1: # multiple one-char strings? make a charset oneletter = [] rest = [] for s in strings: if len(s) == 1: oneletter.append(s) else: rest.append(s) if len(oneletter) > 1: # do we have more than one oneletter string? if rest: # print '-> 1-character + rest' return open_paren + regex_opt_inner(rest, '') + '|' \ + make_charset(oneletter) + close_paren # print '-> only 1-character' return open_paren + make_charset(oneletter) + close_paren prefix = commonprefix(strings) if prefix: plen = len(prefix) # we have a prefix for all strings # print '-> prefix:', prefix return open_paren + escape(prefix) \ + regex_opt_inner([s[plen:] for s in strings], '(?:') \ + close_paren # is there a suffix? strings_rev = [s[::-1] for s in strings] suffix = commonprefix(strings_rev) if suffix: slen = len(suffix) # print '-> suffix:', suffix[::-1] return open_paren \ + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \ + escape(suffix[::-1]) + close_paren # recurse on common 1-string prefixes # print '-> last resort' return open_paren + \ '|'.join(regex_opt_inner(list(group[1]), '') for group in groupby(strings, lambda s: s[0] == first[0])) \ + close_paren
def regex_opt(strings, prefix='', suffix=''): """Return a compiled regex that matches any string in the given list.
The strings to match must be literal strings, not regexes. They will be regex-escaped.
*prefix* and *suffix* are pre- and appended to the final regex. """ strings = sorted(strings) return prefix + regex_opt_inner(strings, '(') + suffix123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104""" pygments.scanner ~~~~~~~~~~~~~~~~
This library implements a regex based scanner. Some languages like Pascal are easy to parse but have some keywords that depend on the context. Because of this it's impossible to lex that just by using a regular expression lexer like the `RegexLexer`.
Have a look at the `DelphiLexer` to get an idea of how to use this scanner.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""import re
class EndOfText(RuntimeError): """ Raise if end of text is reached and the user tried to call a match function. """
class Scanner: """ Simple scanner
All method patterns are regular expression strings (not compiled expressions!) """
def __init__(self, text, flags=0): """ :param text: The text which should be scanned :param flags: default regular expression flags """ self.data = text self.data_length = len(text) self.start_pos = 0 self.pos = 0 self.flags = flags self.last = None self.match = None self._re_cache = {}
def eos(self): """`True` if the scanner reached the end of text.""" return self.pos >= self.data_length eos = property(eos, eos.__doc__)
def check(self, pattern): """ Apply `pattern` on the current position and return the match object. (Doesn't touch pos). Use this for lookahead. """ if self.eos: raise EndOfText() if pattern not in self._re_cache: self._re_cache[pattern] = re.compile(pattern, self.flags) return self._re_cache[pattern].match(self.data, self.pos)
def test(self, pattern): """Apply a pattern on the current position and check if it patches. Doesn't touch pos. """ return self.check(pattern) is not None
def scan(self, pattern): """ Scan the text for the given pattern and update pos/match and related fields. The return value is a boolean that indicates if the pattern matched. The matched value is stored on the instance as ``match``, the last value is stored as ``last``. ``start_pos`` is the position of the pointer before the pattern was matched, ``pos`` is the end position. """ if self.eos: raise EndOfText() if pattern not in self._re_cache: self._re_cache[pattern] = re.compile(pattern, self.flags) self.last = self.match m = self._re_cache[pattern].match(self.data, self.pos) if m is None: return False self.start_pos = m.start() self.pos = m.end() self.match = m.group() return True
def get_char(self): """Scan exactly one char.""" self.scan('.')
def __repr__(self): return '<%s %d/%d>' % ( self.__class__.__name__, self.pos, self.data_length )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247""" pygments.sphinxext ~~~~~~~~~~~~~~~~~~
Sphinx extension to generate automatic documentation of lexers, formatters and filters.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import sys
from docutils import nodesfrom docutils.statemachine import ViewListfrom docutils.parsers.rst import Directivefrom sphinx.util.nodes import nested_parse_with_titles
MODULEDOC = '''.. module:: %s
%s%s'''
LEXERDOC = '''.. class:: %s
:Short names: %s :Filenames: %s :MIME types: %s
%s
%s
'''
FMTERDOC = '''.. class:: %s
:Short names: %s :Filenames: %s
%s
'''
FILTERDOC = '''.. class:: %s
:Name: %s
%s
'''
class PygmentsDoc(Directive): """ A directive to collect all lexers/formatters/filters and generate autoclass directives for them. """ has_content = False required_arguments = 1 optional_arguments = 0 final_argument_whitespace = False option_spec = {}
def run(self): self.filenames = set() if self.arguments[0] == 'lexers': out = self.document_lexers() elif self.arguments[0] == 'formatters': out = self.document_formatters() elif self.arguments[0] == 'filters': out = self.document_filters() elif self.arguments[0] == 'lexers_overview': out = self.document_lexers_overview() else: raise Exception('invalid argument for "pygmentsdoc" directive') node = nodes.compound() vl = ViewList(out.split('\n'), source='') nested_parse_with_titles(self.state, vl, node) for fn in self.filenames: self.state.document.settings.record_dependencies.add(fn) return node.children
def document_lexers_overview(self): """Generate a tabular overview of all lexers.
The columns are the lexer name, the extensions handled by this lexer (or "None"), the aliases and a link to the lexer class.""" from pygments.lexers._mapping import LEXERS import pygments.lexers out = []
table = []
def format_link(name, url): if url: return f'`{name} <{url}>`_' return name
for classname, data in sorted(LEXERS.items(), key=lambda x: x[1][1].lower()): lexer_cls = pygments.lexers.find_lexer_class(data[1]) extensions = lexer_cls.filenames + lexer_cls.alias_filenames
table.append({ 'name': format_link(data[1], lexer_cls.url), 'extensions': ', '.join(extensions).replace('*', '\\*').replace('_', '\\') or 'None', 'aliases': ', '.join(data[2]), 'class': f'{data[0]}.{classname}' })
column_names = ['name', 'extensions', 'aliases', 'class'] column_lengths = [max([len(row[column]) for row in table if row[column]]) for column in column_names]
def write_row(*columns): """Format a table row""" out = [] for length, col in zip(column_lengths, columns): if col: out.append(col.ljust(length)) else: out.append(' '*length)
return ' '.join(out)
def write_seperator(): """Write a table separator row""" sep = ['='*c for c in column_lengths] return write_row(*sep)
out.append(write_seperator()) out.append(write_row('Name', 'Extension(s)', 'Short name(s)', 'Lexer class')) out.append(write_seperator()) for row in table: out.append(write_row( row['name'], row['extensions'], row['aliases'], f':class:`~{row["class"]}`')) out.append(write_seperator())
return '\n'.join(out)
def document_lexers(self): from pygments.lexers._mapping import LEXERS import pygments import inspect import pathlib
out = [] modules = {} moduledocstrings = {} for classname, data in sorted(LEXERS.items(), key=lambda x: x[0]): module = data[0] mod = __import__(module, None, None, [classname]) self.filenames.add(mod.__file__) cls = getattr(mod, classname) if not cls.__doc__: print(f"Warning: {classname} does not have a docstring.") docstring = cls.__doc__ if isinstance(docstring, bytes): docstring = docstring.decode('utf8')
example_file = getattr(cls, '_example', None) if example_file: p = pathlib.Path(inspect.getabsfile(pygments)).parent.parent /\ 'tests' / 'examplefiles' / example_file content = p.read_text(encoding='utf-8') if not content: raise Exception( f"Empty example file '{example_file}' for lexer " f"{classname}")
if data[2]: lexer_name = data[2][0] docstring += '\n\n .. admonition:: Example\n' docstring += f'\n .. code-block:: {lexer_name}\n\n' for line in content.splitlines(): docstring += f' {line}\n'
if cls.version_added: version_line = f'.. versionadded:: {cls.version_added}' else: version_line = ''
modules.setdefault(module, []).append(( classname, ', '.join(data[2]) or 'None', ', '.join(data[3]).replace('*', '\\*').replace('_', '\\') or 'None', ', '.join(data[4]) or 'None', docstring, version_line)) if module not in moduledocstrings: moddoc = mod.__doc__ if isinstance(moddoc, bytes): moddoc = moddoc.decode('utf8') moduledocstrings[module] = moddoc
for module, lexers in sorted(modules.items(), key=lambda x: x[0]): if moduledocstrings[module] is None: raise Exception(f"Missing docstring for {module}") heading = moduledocstrings[module].splitlines()[4].strip().rstrip('.') out.append(MODULEDOC % (module, heading, '-'*len(heading))) for data in lexers: out.append(LEXERDOC % data)
return ''.join(out)
def document_formatters(self): from pygments.formatters import FORMATTERS
out = [] for classname, data in sorted(FORMATTERS.items(), key=lambda x: x[0]): module = data[0] mod = __import__(module, None, None, [classname]) self.filenames.add(mod.__file__) cls = getattr(mod, classname) docstring = cls.__doc__ if isinstance(docstring, bytes): docstring = docstring.decode('utf8') heading = cls.__name__ out.append(FMTERDOC % (heading, ', '.join(data[2]) or 'None', ', '.join(data[3]).replace('*', '\\*') or 'None', docstring)) return ''.join(out)
def document_filters(self): from pygments.filters import FILTERS
out = [] for name, cls in FILTERS.items(): self.filenames.add(sys.modules[cls.__module__].__file__) docstring = cls.__doc__ if isinstance(docstring, bytes): docstring = docstring.decode('utf8') out.append(FILTERDOC % (cls.__name__, name, docstring)) return ''.join(out)
def setup(app): app.add_directive('pygmentsdoc', PygmentsDoc)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203""" pygments.style ~~~~~~~~~~~~~~
Basic style object.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.token import Token, STANDARD_TYPES
# Default mapping of ansixxx to RGB colors._ansimap = { # dark 'ansiblack': '000000', 'ansired': '7f0000', 'ansigreen': '007f00', 'ansiyellow': '7f7fe0', 'ansiblue': '00007f', 'ansimagenta': '7f007f', 'ansicyan': '007f7f', 'ansigray': 'e5e5e5', # normal 'ansibrightblack': '555555', 'ansibrightred': 'ff0000', 'ansibrightgreen': '00ff00', 'ansibrightyellow': 'ffff00', 'ansibrightblue': '0000ff', 'ansibrightmagenta': 'ff00ff', 'ansibrightcyan': '00ffff', 'ansiwhite': 'ffffff',}# mapping of deprecated #ansixxx colors to new color names_deprecated_ansicolors = { # dark '#ansiblack': 'ansiblack', '#ansidarkred': 'ansired', '#ansidarkgreen': 'ansigreen', '#ansibrown': 'ansiyellow', '#ansidarkblue': 'ansiblue', '#ansipurple': 'ansimagenta', '#ansiteal': 'ansicyan', '#ansilightgray': 'ansigray', # normal '#ansidarkgray': 'ansibrightblack', '#ansired': 'ansibrightred', '#ansigreen': 'ansibrightgreen', '#ansiyellow': 'ansibrightyellow', '#ansiblue': 'ansibrightblue', '#ansifuchsia': 'ansibrightmagenta', '#ansiturquoise': 'ansibrightcyan', '#ansiwhite': 'ansiwhite',}ansicolors = set(_ansimap)
class StyleMeta(type):
def __new__(mcs, name, bases, dct): obj = type.__new__(mcs, name, bases, dct) for token in STANDARD_TYPES: if token not in obj.styles: obj.styles[token] = ''
def colorformat(text): if text in ansicolors: return text if text[0:1] == '#': col = text[1:] if len(col) == 6: return col elif len(col) == 3: return col[0] * 2 + col[1] * 2 + col[2] * 2 elif text == '': return '' elif text.startswith('var') or text.startswith('calc'): return text assert False, f"wrong color format {text!r}"
_styles = obj._styles = {}
for ttype in obj.styles: for token in ttype.split(): if token in _styles: continue ndef = _styles.get(token.parent, None) styledefs = obj.styles.get(token, '').split() if not ndef or token is None: ndef = ['', 0, 0, 0, '', '', 0, 0, 0] elif 'noinherit' in styledefs and token is not Token: ndef = _styles[Token][:] else: ndef = ndef[:] _styles[token] = ndef for styledef in obj.styles.get(token, '').split(): if styledef == 'noinherit': pass elif styledef == 'bold': ndef[1] = 1 elif styledef == 'nobold': ndef[1] = 0 elif styledef == 'italic': ndef[2] = 1 elif styledef == 'noitalic': ndef[2] = 0 elif styledef == 'underline': ndef[3] = 1 elif styledef == 'nounderline': ndef[3] = 0 elif styledef[:3] == 'bg:': ndef[4] = colorformat(styledef[3:]) elif styledef[:7] == 'border:': ndef[5] = colorformat(styledef[7:]) elif styledef == 'roman': ndef[6] = 1 elif styledef == 'sans': ndef[7] = 1 elif styledef == 'mono': ndef[8] = 1 else: ndef[0] = colorformat(styledef)
return obj
def style_for_token(cls, token): t = cls._styles[token] ansicolor = bgansicolor = None color = t[0] if color in _deprecated_ansicolors: color = _deprecated_ansicolors[color] if color in ansicolors: ansicolor = color color = _ansimap[color] bgcolor = t[4] if bgcolor in _deprecated_ansicolors: bgcolor = _deprecated_ansicolors[bgcolor] if bgcolor in ansicolors: bgansicolor = bgcolor bgcolor = _ansimap[bgcolor]
return { 'color': color or None, 'bold': bool(t[1]), 'italic': bool(t[2]), 'underline': bool(t[3]), 'bgcolor': bgcolor or None, 'border': t[5] or None, 'roman': bool(t[6]) or None, 'sans': bool(t[7]) or None, 'mono': bool(t[8]) or None, 'ansicolor': ansicolor, 'bgansicolor': bgansicolor, }
def list_styles(cls): return list(cls)
def styles_token(cls, ttype): return ttype in cls._styles
def __iter__(cls): for token in cls._styles: yield token, cls.style_for_token(token)
def __len__(cls): return len(cls._styles)
class Style(metaclass=StyleMeta):
#: overall background color (``None`` means transparent) background_color = '#ffffff'
#: highlight background color highlight_color = '#ffffcc'
#: line number font color line_number_color = 'inherit'
#: line number background color line_number_background_color = 'transparent'
#: special line number font color line_number_special_color = '#000000'
#: special line number background color line_number_special_background_color = '#ffffc0'
#: Style definitions for individual token types. styles = {}
#: user-friendly style name (used when selecting the style, so this # should be all-lowercase, no spaces, hyphens) name = 'unnamed'
aliases = []
# Attribute for lexers defined within Pygments. If set # to True, the style is not shown in the style gallery # on the website. This is intended for language-specific # styles. web_style_gallery_exclude = False12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061""" pygments.styles ~~~~~~~~~~~~~~~
Contains built-in styles.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.plugin import find_plugin_stylesfrom pygments.util import ClassNotFoundfrom pygments.styles._mapping import STYLES
#: A dictionary of built-in styles, mapping style names to#: ``'submodule::classname'`` strings.#: This list is deprecated. Use `pygments.styles.STYLES` insteadSTYLE_MAP = {v[1]: v[0].split('.')[-1] + '::' + k for k, v in STYLES.items()}
#: Internal reverse mapping to make `get_style_by_name` more efficient_STYLE_NAME_TO_MODULE_MAP = {v[1]: (v[0], k) for k, v in STYLES.items()}
def get_style_by_name(name): """ Return a style class by its short name. The names of the builtin styles are listed in :data:`pygments.styles.STYLE_MAP`.
Will raise :exc:`pygments.util.ClassNotFound` if no style of that name is found. """ if name in _STYLE_NAME_TO_MODULE_MAP: mod, cls = _STYLE_NAME_TO_MODULE_MAP[name] builtin = "yes" else: for found_name, style in find_plugin_styles(): if name == found_name: return style # perhaps it got dropped into our styles package builtin = "" mod = 'pygments.styles.' + name cls = name.title() + "Style"
try: mod = __import__(mod, None, None, [cls]) except ImportError: raise ClassNotFound(f"Could not find style module {mod!r}" + (builtin and ", though it should be builtin") + ".") try: return getattr(mod, cls) except AttributeError: raise ClassNotFound(f"Could not find style class {cls!r} in style module.")
def get_all_styles(): """Return a generator for all styles by name, both builtin and plugin.""" for v in STYLES.values(): yield v[1] for name, _ in find_plugin_styles(): yield name123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# Automatically generated by scripts/gen_mapfiles.py.# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead.
STYLES = { 'AbapStyle': ('pygments.styles.abap', 'abap', ()), 'AlgolStyle': ('pygments.styles.algol', 'algol', ()), 'Algol_NuStyle': ('pygments.styles.algol_nu', 'algol_nu', ()), 'ArduinoStyle': ('pygments.styles.arduino', 'arduino', ()), 'AutumnStyle': ('pygments.styles.autumn', 'autumn', ()), 'BlackWhiteStyle': ('pygments.styles.bw', 'bw', ()), 'BorlandStyle': ('pygments.styles.borland', 'borland', ()), 'CoffeeStyle': ('pygments.styles.coffee', 'coffee', ()), 'ColorfulStyle': ('pygments.styles.colorful', 'colorful', ()), 'DefaultStyle': ('pygments.styles.default', 'default', ()), 'DraculaStyle': ('pygments.styles.dracula', 'dracula', ()), 'EmacsStyle': ('pygments.styles.emacs', 'emacs', ()), 'FriendlyGrayscaleStyle': ('pygments.styles.friendly_grayscale', 'friendly_grayscale', ()), 'FriendlyStyle': ('pygments.styles.friendly', 'friendly', ()), 'FruityStyle': ('pygments.styles.fruity', 'fruity', ()), 'GhDarkStyle': ('pygments.styles.gh_dark', 'github-dark', ()), 'GruvboxDarkStyle': ('pygments.styles.gruvbox', 'gruvbox-dark', ()), 'GruvboxLightStyle': ('pygments.styles.gruvbox', 'gruvbox-light', ()), 'IgorStyle': ('pygments.styles.igor', 'igor', ()), 'InkPotStyle': ('pygments.styles.inkpot', 'inkpot', ()), 'LightbulbStyle': ('pygments.styles.lightbulb', 'lightbulb', ()), 'LilyPondStyle': ('pygments.styles.lilypond', 'lilypond', ()), 'LovelaceStyle': ('pygments.styles.lovelace', 'lovelace', ()), 'ManniStyle': ('pygments.styles.manni', 'manni', ()), 'MaterialStyle': ('pygments.styles.material', 'material', ()), 'MonokaiStyle': ('pygments.styles.monokai', 'monokai', ()), 'MurphyStyle': ('pygments.styles.murphy', 'murphy', ()), 'NativeStyle': ('pygments.styles.native', 'native', ()), 'NordDarkerStyle': ('pygments.styles.nord', 'nord-darker', ()), 'NordStyle': ('pygments.styles.nord', 'nord', ()), 'OneDarkStyle': ('pygments.styles.onedark', 'one-dark', ()), 'ParaisoDarkStyle': ('pygments.styles.paraiso_dark', 'paraiso-dark', ()), 'ParaisoLightStyle': ('pygments.styles.paraiso_light', 'paraiso-light', ()), 'PastieStyle': ('pygments.styles.pastie', 'pastie', ()), 'PerldocStyle': ('pygments.styles.perldoc', 'perldoc', ()), 'RainbowDashStyle': ('pygments.styles.rainbow_dash', 'rainbow_dash', ()), 'RrtStyle': ('pygments.styles.rrt', 'rrt', ()), 'SasStyle': ('pygments.styles.sas', 'sas', ()), 'SolarizedDarkStyle': ('pygments.styles.solarized', 'solarized-dark', ()), 'SolarizedLightStyle': ('pygments.styles.solarized', 'solarized-light', ()), 'StarofficeStyle': ('pygments.styles.staroffice', 'staroffice', ()), 'StataDarkStyle': ('pygments.styles.stata_dark', 'stata-dark', ()), 'StataLightStyle': ('pygments.styles.stata_light', 'stata-light', ()), 'TangoStyle': ('pygments.styles.tango', 'tango', ()), 'TracStyle': ('pygments.styles.trac', 'trac', ()), 'VimStyle': ('pygments.styles.vim', 'vim', ()), 'VisualStudioStyle': ('pygments.styles.vs', 'vs', ()), 'XcodeStyle': ('pygments.styles.xcode', 'xcode', ()), 'ZenburnStyle': ('pygments.styles.zenburn', 'zenburn', ()),}1234567891011121314151617181920212223242526272829303132""" pygments.styles.abap ~~~~~~~~~~~~~~~~~~~~
ABAP workbench like style.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator
__all__ = ['AbapStyle']
class AbapStyle(Style): name = 'abap'
styles = { Comment: 'italic #888', Comment.Special: '#888', Keyword: '#00f', Operator.Word: '#00f', Name: '#000', Number: '#3af', String: '#5a2',
Error: '#F00', }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465""" pygments.styles.algol ~~~~~~~~~~~~~~~~~~~~~
Algol publication style.
This style renders source code for publication of algorithms in scientific papers and academic texts, where its format is frequently used.
It is based on the style of the revised Algol-60 language report[1].
o No colours, only black, white and shades of grey are used. o Keywords are rendered in lowercase underline boldface. o Builtins are rendered in lowercase boldface italic. o Docstrings and pragmas are rendered in dark grey boldface. o Library identifiers are rendered in dark grey boldface italic. o Comments are rendered in grey italic.
To render keywords without underlining, refer to the `Algol_Nu` style.
For lowercase conversion of keywords and builtins in languages where these are not or might not be lowercase, a supporting lexer is required. The Algol and Modula-2 lexers automatically convert to lowercase whenever this style is selected.
[1] `Revised Report on the Algorithmic Language Algol-60 <http://www.masswerk.at/algol60/report.htm>`
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, Operator
__all__ = ['AlgolStyle']
class AlgolStyle(Style): name = 'algol'
background_color = "#ffffff"
styles = { Comment: "italic #888", Comment.Preproc: "bold noitalic #888", Comment.Special: "bold noitalic #888",
Keyword: "underline bold", Keyword.Declaration: "italic",
Name.Builtin: "bold italic", Name.Builtin.Pseudo: "bold italic", Name.Namespace: "bold italic #666", Name.Class: "bold italic #666", Name.Function: "bold italic #666", Name.Variable: "bold italic #666", Name.Constant: "bold italic #666",
Operator.Word: "bold",
String: "italic #666",
Error: "border:#FF0000" }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465""" pygments.styles.algol_nu ~~~~~~~~~~~~~~~~~~~~~~~~
Algol publication style without underlining of keywords.
This style renders source code for publication of algorithms in scientific papers and academic texts, where its format is frequently used.
It is based on the style of the revised Algol-60 language report[1].
o No colours, only black, white and shades of grey are used. o Keywords are rendered in lowercase boldface. o Builtins are rendered in lowercase boldface italic. o Docstrings and pragmas are rendered in dark grey boldface. o Library identifiers are rendered in dark grey boldface italic. o Comments are rendered in grey italic.
To render keywords with underlining, refer to the `Algol` style.
For lowercase conversion of keywords and builtins in languages where these are not or might not be lowercase, a supporting lexer is required. The Algol and Modula-2 lexers automatically convert to lowercase whenever this style is selected.
[1] `Revised Report on the Algorithmic Language Algol-60 <http://www.masswerk.at/algol60/report.htm>`
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, Operator
__all__ = ['Algol_NuStyle']
class Algol_NuStyle(Style): name = 'algol_nu'
background_color = "#ffffff"
styles = { Comment: "italic #888", Comment.Preproc: "bold noitalic #888", Comment.Special: "bold noitalic #888",
Keyword: "bold", Keyword.Declaration: "italic",
Name.Builtin: "bold italic", Name.Builtin.Pseudo: "bold italic", Name.Namespace: "bold italic #666", Name.Class: "bold italic #666", Name.Function: "bold italic #666", Name.Variable: "bold italic #666", Name.Constant: "bold italic #666",
Operator.Word: "bold",
String: "italic #666",
Error: "border:#FF0000" }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100""" pygments.styles.arduino ~~~~~~~~~~~~~~~~~~~~~~~
Arduino® Syntax highlighting style.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace
__all__ = ['ArduinoStyle']
class ArduinoStyle(Style): """ The Arduino® language style. This style is designed to highlight the Arduino source code, so expect the best results with it. """ name = 'arduino'
background_color = "#ffffff"
styles = { Whitespace: "", # class: 'w' Error: "#a61717", # class: 'err'
Comment: "#95a5a6", # class: 'c' Comment.Multiline: "", # class: 'cm' Comment.Preproc: "#728E00", # class: 'cp' Comment.Single: "", # class: 'c1' Comment.Special: "", # class: 'cs'
Keyword: "#728E00", # class: 'k' Keyword.Constant: "#00979D", # class: 'kc' Keyword.Declaration: "", # class: 'kd' Keyword.Namespace: "", # class: 'kn' Keyword.Pseudo: "#00979D", # class: 'kp' Keyword.Reserved: "#00979D", # class: 'kr' Keyword.Type: "#00979D", # class: 'kt'
Operator: "#728E00", # class: 'o' Operator.Word: "", # class: 'ow'
Name: "#434f54", # class: 'n' Name.Attribute: "", # class: 'na' Name.Builtin: "#728E00", # class: 'nb' Name.Builtin.Pseudo: "", # class: 'bp' Name.Class: "", # class: 'nc' Name.Constant: "", # class: 'no' Name.Decorator: "", # class: 'nd' Name.Entity: "", # class: 'ni' Name.Exception: "", # class: 'ne' Name.Function: "#D35400", # class: 'nf' Name.Property: "", # class: 'py' Name.Label: "", # class: 'nl' Name.Namespace: "", # class: 'nn' Name.Other: "#728E00", # class: 'nx' Name.Tag: "", # class: 'nt' Name.Variable: "", # class: 'nv' Name.Variable.Class: "", # class: 'vc' Name.Variable.Global: "", # class: 'vg' Name.Variable.Instance: "", # class: 'vi'
Number: "#8A7B52", # class: 'm' Number.Float: "", # class: 'mf' Number.Hex: "", # class: 'mh' Number.Integer: "", # class: 'mi' Number.Integer.Long: "", # class: 'il' Number.Oct: "", # class: 'mo'
String: "#7F8C8D", # class: 's' String.Backtick: "", # class: 'sb' String.Char: "", # class: 'sc' String.Doc: "", # class: 'sd' String.Double: "", # class: 's2' String.Escape: "", # class: 'se' String.Heredoc: "", # class: 'sh' String.Interpol: "", # class: 'si' String.Other: "", # class: 'sx' String.Regex: "", # class: 'sr' String.Single: "", # class: 's1' String.Symbol: "", # class: 'ss'
Generic: "", # class: 'g' Generic.Deleted: "", # class: 'gd', Generic.Emph: "", # class: 'ge' Generic.Error: "", # class: 'gr' Generic.Heading: "", # class: 'gh' Generic.Inserted: "", # class: 'gi' Generic.Output: "", # class: 'go' Generic.Prompt: "", # class: 'gp' Generic.Strong: "", # class: 'gs' Generic.Subheading: "", # class: 'gu' Generic.Traceback: "", # class: 'gt' }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667""" pygments.styles.autumn ~~~~~~~~~~~~~~~~~~~~~~
A colorful style, inspired by the terminal highlighting style.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace
__all__ = ['AutumnStyle']
class AutumnStyle(Style): """ A colorful style, inspired by the terminal highlighting style. """ name = 'autumn'
styles = { Whitespace: '#bbbbbb',
Comment: 'italic #aaaaaa', Comment.Preproc: 'noitalic #4c8317', Comment.Special: 'italic #0000aa',
Keyword: '#0000aa', Keyword.Type: '#00aaaa',
Operator.Word: '#0000aa',
Name.Builtin: '#00aaaa', Name.Function: '#00aa00', Name.Class: 'underline #00aa00', Name.Namespace: 'underline #00aaaa', Name.Variable: '#aa0000', Name.Constant: '#aa0000', Name.Entity: 'bold #800', Name.Attribute: '#1e90ff', Name.Tag: 'bold #1e90ff', Name.Decorator: '#888888',
String: '#aa5500', String.Symbol: '#0000aa', String.Regex: '#009999',
Number: '#009999',
Generic.Heading: 'bold #000080', Generic.Subheading: 'bold #800080', Generic.Deleted: '#aa0000', Generic.Inserted: '#00aa00', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.EmphStrong: 'bold italic', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000',
Error: '#F00 bg:#FAA' }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253""" pygments.styles.borland ~~~~~~~~~~~~~~~~~~~~~~~
Style similar to the style used in the Borland IDEs.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace
__all__ = ['BorlandStyle']
class BorlandStyle(Style): """ Style similar to the style used in the borland IDEs. """ name = 'borland'
styles = { Whitespace: '#bbbbbb',
Comment: 'italic #008800', Comment.Preproc: 'noitalic #008080', Comment.Special: 'noitalic bold',
String: '#0000FF', String.Char: '#800080', Number: '#0000FF', Keyword: 'bold #000080', Operator.Word: 'bold', Name.Tag: 'bold #000080', Name.Attribute: '#FF0000',
Generic.Heading: '#999999', Generic.Subheading: '#aaaaaa', Generic.Deleted: 'bg:#ffdddd #000000', Generic.Inserted: 'bg:#ddffdd #000000', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.EmphStrong: 'bold italic', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000',
Error: 'bg:#e3d2d2 #a61717' }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152""" pygments.styles.bw ~~~~~~~~~~~~~~~~~~
Simple black/white only style.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Operator, Generic
__all__ = ['BlackWhiteStyle']
class BlackWhiteStyle(Style): name = 'bw'
background_color = "#ffffff"
styles = { Comment: "italic", Comment.Preproc: "noitalic",
Keyword: "bold", Keyword.Pseudo: "nobold", Keyword.Type: "nobold",
Operator.Word: "bold",
Name.Class: "bold", Name.Namespace: "bold", Name.Exception: "bold", Name.Entity: "bold", Name.Tag: "bold",
String: "italic", String.Interpol: "bold", String.Escape: "bold",
Generic.Heading: "bold", Generic.Subheading: "bold", Generic.Emph: "italic", Generic.Strong: "bold", Generic.EmphStrong: "bold italic", Generic.Prompt: "bold",
Error: "border:#FF0000" }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980""" pygments.styles.coffee ~~~~~~~~~~~~~~~~~~~~~~
A warm and cozy theme based off gruvbox
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import (Comment, Error, Generic, Keyword, Literal, Name, Number, Operator, Punctuation, String, Token)
__all__ = ["CoffeeStyle"]
class CoffeeStyle(Style): """ A warm and cozy theme based off gruvbox """
name = "coffee"
background_color = "#262220" highlight_color = "#ddd0c0"
line_number_color = "#4e4e4e" line_number_special_color = "#8f9494"
styles = { Comment: "#70757A", Comment.Hashbang: "#8f9f9f", Comment.Preproc: "#fdd0c0", Comment.PreprocFile: "#c9b98f", Comment.Special: "#af5f5f", Error: "#af5f5f", Generic.Deleted: "#bb6868", Generic.Emph: "italic", Generic.Error: "#af5f5f", Generic.Inserted: "#849155", Generic.Output: "#ddd0c0", Generic.Strong: "bold", Generic.Traceback: "#af5f5f", Keyword: "#919191", Keyword.Constant: "#875f5f", Keyword.Declaration: "#875f5f", Keyword.Namespace: "#875f5f", Keyword.Reserved: "#b46276", Keyword.Type: "#af875f", Literal: "#af875f", Name: "#ddd0c0", Name.Attribute: "#ddd0c0", Name.Builtin: "#ddd0c0", Name.Builtin.Pseudo: "#87afaf", Name.Class: "#875f5f", Name.Constant: "#af8787", Name.Decorator: "#fdd0c0", Name.Entity: "#ddd0c0", Name.Exception: "#877575", Name.Function: "#fdd0c0", Name.Function.Magic: "#fdd0c0", Name.Other: "#ddd0c0", Name.Property: "#dfaf87", Name.Tag: "#87afaf", Name.Variable: "#ddd0c0", Number: "#87afaf", Operator: "#878787", Operator.Word: "#878787", Punctuation: "#ddd0c0", String: "#c9b98f", String.Affix: "#dfaf87", String.Doc: "#878787", String.Escape: "#af5f5f", String.Interpol: "#af5f5f", String.Other: "#fdd0c0", String.Regex: "#af5f5f", String.Symbol: "#af5f5f", Token: "#ddd0c0", }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283""" pygments.styles.colorful ~~~~~~~~~~~~~~~~~~~~~~~~
A colorful style, inspired by CodeRay.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace
__all__ = ['ColorfulStyle']
class ColorfulStyle(Style): """ A colorful style, inspired by CodeRay. """ name = 'colorful'
styles = { Whitespace: "#bbbbbb",
Comment: "#888", Comment.Preproc: "#579", Comment.Special: "bold #cc0000",
Keyword: "bold #080", Keyword.Pseudo: "#038", Keyword.Type: "#339",
Operator: "#333", Operator.Word: "bold #000",
Name.Builtin: "#007020", Name.Function: "bold #06B", Name.Class: "bold #B06", Name.Namespace: "bold #0e84b5", Name.Exception: "bold #F00", Name.Variable: "#963", Name.Variable.Instance: "#33B", Name.Variable.Class: "#369", Name.Variable.Global: "bold #d70", Name.Constant: "bold #036", Name.Label: "bold #970", Name.Entity: "bold #800", Name.Attribute: "#00C", Name.Tag: "#070", Name.Decorator: "bold #555",
String: "bg:#fff0f0", String.Char: "#04D bg:", String.Doc: "#D42 bg:", String.Interpol: "bg:#eee", String.Escape: "bold #666", String.Regex: "bg:#fff0ff #000", String.Symbol: "#A60 bg:", String.Other: "#D20",
Number: "bold #60E", Number.Integer: "bold #00D", Number.Float: "bold #60E", Number.Hex: "bold #058", Number.Oct: "bold #40E",
Generic.Heading: "bold #000080", Generic.Subheading: "bold #800080", Generic.Deleted: "#A00000", Generic.Inserted: "#00A000", Generic.Error: "#FF0000", Generic.Emph: "italic", Generic.Strong: "bold", Generic.EmphStrong: "bold italic", Generic.Prompt: "bold #c65d09", Generic.Output: "#888", Generic.Traceback: "#04D",
Error: "#F00 bg:#FAA" }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576""" pygments.styles.default ~~~~~~~~~~~~~~~~~~~~~~~
The default highlighting style.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace
__all__ = ['DefaultStyle']
class DefaultStyle(Style): """ The default style (inspired by Emacs 22). """ name = 'default'
background_color = "#f8f8f8"
styles = { Whitespace: "#bbbbbb", Comment: "italic #3D7B7B", Comment.Preproc: "noitalic #9C6500",
#Keyword: "bold #AA22FF", Keyword: "bold #008000", Keyword.Pseudo: "nobold", Keyword.Type: "nobold #B00040",
Operator: "#666666", Operator.Word: "bold #AA22FF",
Name.Builtin: "#008000", Name.Function: "#0000FF", Name.Class: "bold #0000FF", Name.Namespace: "bold #0000FF", Name.Exception: "bold #CB3F38", Name.Variable: "#19177C", Name.Constant: "#880000", Name.Label: "#767600", Name.Entity: "bold #717171", Name.Attribute: "#687822", Name.Tag: "bold #008000", Name.Decorator: "#AA22FF",
String: "#BA2121", String.Doc: "italic", String.Interpol: "bold #A45A77", String.Escape: "bold #AA5D1F", String.Regex: "#A45A77", #String.Symbol: "#B8860B", String.Symbol: "#19177C", String.Other: "#008000", Number: "#666666",
Generic.Heading: "bold #000080", Generic.Subheading: "bold #800080", Generic.Deleted: "#A00000", Generic.Inserted: "#008400", Generic.Error: "#E40000", Generic.Emph: "italic", Generic.Strong: "bold", Generic.EmphStrong: "bold italic", Generic.Prompt: "bold #000080", Generic.Output: "#717171", Generic.Traceback: "#04D",
Error: "border:#FF0000" }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990""" pygments.styles.dracula ~~~~~~~~~~~~~~~~~~~~~~~
Pygments version of `Dracula` from https://github.com/dracula/dracula-theme.
Based on the Dracula Theme for pygments by Chris Bracco. See https://github.com/dracula/pygments/tree/fee9ed5613d1086bc01b9d0a5a0e9867a009f571
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, Literal, \ Number, Operator, Other, Punctuation, Text, Generic, Whitespace
__all__ = ['DraculaStyle']
background = "#282a36"foreground = "#f8f8f2"selection = "#44475a"comment = "#6272a4"cyan = "#8be9fd"green = "#50fa7b"orange = "#ffb86c"pink = "#ff79c6"purple = "#bd93f9"red = "#ff5555"yellow = "#f1fa8c"
deletion = "#8b080b"
class DraculaStyle(Style): name = 'dracula'
background_color = background highlight_color = selection line_number_color = yellow line_number_background_color = selection line_number_special_color = green line_number_special_background_color = comment
styles = { Whitespace: foreground,
Comment: comment, Comment.Preproc: pink,
Generic: foreground, Generic.Deleted: deletion, Generic.Emph: "underline", Generic.Heading: "bold", Generic.Inserted: "bold", Generic.Output: selection, Generic.EmphStrong: "underline", Generic.Subheading: "bold",
Error: foreground,
Keyword: pink, Keyword.Constant: pink, Keyword.Declaration: cyan + " italic", Keyword.Type: cyan,
Literal: foreground,
Name: foreground, Name.Attribute: green, Name.Builtin: cyan + " italic", Name.Builtin.Pseudo: foreground, Name.Class: green, Name.Function: green, Name.Label: cyan + " italic", Name.Tag: pink, Name.Variable: cyan + " italic",
Number: orange,
Operator: pink,
Other: foreground,
Punctuation: foreground,
String: purple,
Text: foreground, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475""" pygments.styles.emacs ~~~~~~~~~~~~~~~~~~~~~
A highlighting style for Pygments, inspired by Emacs.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace
__all__ = ['EmacsStyle']
class EmacsStyle(Style): """ The default style (inspired by Emacs 22). """ name = 'emacs'
background_color = "#f8f8f8"
styles = { Whitespace: "#bbbbbb", Comment: "italic #008800", Comment.Preproc: "noitalic", Comment.Special: "noitalic bold",
Keyword: "bold #AA22FF", Keyword.Pseudo: "nobold", Keyword.Type: "bold #00BB00",
Operator: "#666666", Operator.Word: "bold #AA22FF",
Name.Builtin: "#AA22FF", Name.Function: "#00A000", Name.Class: "#0000FF", Name.Namespace: "bold #0000FF", Name.Exception: "bold #D2413A", Name.Variable: "#B8860B", Name.Constant: "#880000", Name.Label: "#A0A000", Name.Entity: "bold #999999", Name.Attribute: "#BB4444", Name.Tag: "bold #008000", Name.Decorator: "#AA22FF",
String: "#BB4444", String.Doc: "italic", String.Interpol: "bold #BB6688", String.Escape: "bold #BB6622", String.Regex: "#BB6688", String.Symbol: "#B8860B", String.Other: "#008000", Number: "#666666",
Generic.Heading: "bold #000080", Generic.Subheading: "bold #800080", Generic.Deleted: "#A00000", Generic.Inserted: "#00A000", Generic.Error: "#FF0000", Generic.Emph: "italic", Generic.Strong: "bold", Generic.EmphStrong: "bold italic", Generic.Prompt: "bold #000080", Generic.Output: "#888", Generic.Traceback: "#04D",
Error: "border:#FF0000" }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576""" pygments.styles.friendly ~~~~~~~~~~~~~~~~~~~~~~~~
A modern style based on the VIM pyte theme.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace
__all__ = ['FriendlyStyle']
class FriendlyStyle(Style): """ A modern style based on the VIM pyte theme. """ name = 'friendly'
background_color = "#f0f0f0" line_number_color = "#666666"
styles = { Whitespace: "#bbbbbb", Comment: "italic #60a0b0", Comment.Preproc: "noitalic #007020", Comment.Special: "noitalic bg:#fff0f0",
Keyword: "bold #007020", Keyword.Pseudo: "nobold", Keyword.Type: "nobold #902000",
Operator: "#666666", Operator.Word: "bold #007020",
Name.Builtin: "#007020", Name.Function: "#06287e", Name.Class: "bold #0e84b5", Name.Namespace: "bold #0e84b5", Name.Exception: "#007020", Name.Variable: "#bb60d5", Name.Constant: "#60add5", Name.Label: "bold #002070", Name.Entity: "bold #d55537", Name.Attribute: "#4070a0", Name.Tag: "bold #062873", Name.Decorator: "bold #555555",
String: "#4070a0", String.Doc: "italic", String.Interpol: "italic #70a0d0", String.Escape: "bold #4070a0", String.Regex: "#235388", String.Symbol: "#517918", String.Other: "#c65d09", Number: "#40a070",
Generic.Heading: "bold #000080", Generic.Subheading: "bold #800080", Generic.Deleted: "#A00000", Generic.Inserted: "#00A000", Generic.Error: "#FF0000", Generic.Emph: "italic", Generic.Strong: "bold", Generic.EmphStrong: "bold italic", Generic.Prompt: "bold #c65d09", Generic.Output: "#888", Generic.Traceback: "#04D",
Error: "border:#FF0000" }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980""" pygments.styles.friendly_grayscale ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A style based on friendly style. The color values of the friendly style have been converted to grayscale using the luminosity value calculated by http://www.workwithcolor.com/color-converter-01.htm
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace
__all__ = ['FriendlyGrayscaleStyle']
class FriendlyGrayscaleStyle(Style): """ A modern grayscale style based on the friendly style.
.. versionadded:: 2.11 """ name = 'friendly_grayscale'
background_color = "#f0f0f0"
styles = { Whitespace: "#bbbbbb", Comment: "italic #959595", Comment.Preproc: "noitalic #575757", Comment.Special: "noitalic bg:#F4F4F4",
Keyword: "bold #575757", Keyword.Pseudo: "nobold", Keyword.Type: "nobold #4F4F4F",
Operator: "#666666", Operator.Word: "bold #575757",
Name.Builtin: "#575757", Name.Function: "#3F3F3F", Name.Class: "bold #7E7E7E", Name.Namespace: "bold #7E7E7E", Name.Exception: "#575757", Name.Variable: "#9A9A9A", Name.Constant: "#A5A5A5", Name.Label: "bold #363636", Name.Entity: "bold #848484", Name.Attribute: "#707070", Name.Tag: "bold #3B3B3B", Name.Decorator: "bold #555555",
String: "#717171", String.Doc: "italic", String.Interpol: "italic #9F9F9F", String.Escape: "bold #717171", String.Regex: "#575757", String.Symbol: "#676767", String.Other: "#7E7E7E", Number: "#888888",
Generic.Heading: "bold #373737", Generic.Subheading: "bold #5A5A5A", Generic.Deleted: "#545454", Generic.Inserted: "#7D7D7D", Generic.Error: "#898989", Generic.Emph: "italic", Generic.Strong: "bold", Generic.EmphStrong: "bold italic", Generic.Prompt: "bold #7E7E7E", Generic.Output: "#888888", Generic.Traceback: "#6D6D6D",
Error: "border:#898989" }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647""" pygments.styles.fruity ~~~~~~~~~~~~~~~~~~~~~~
pygments version of my "fruity" vim theme.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Token, Comment, Name, Keyword, \ Generic, Number, String, Whitespace
__all__ = ['FruityStyle']
class FruityStyle(Style): """ Pygments version of the "native" vim theme. """
name = 'fruity'
background_color = '#111111' highlight_color = '#333333'
styles = { Whitespace: '#888888', Token: '#ffffff', Generic.Output: '#444444 bg:#222222', Keyword: '#fb660a bold', Keyword.Pseudo: 'nobold', Number: '#0086f7 bold', Name.Tag: '#fb660a bold', Name.Variable: '#fb660a', Comment: '#008800 bg:#0f140f italic', Name.Attribute: '#ff0086 bold', String: '#0086d2', Name.Function: '#ff0086 bold', Generic.Heading: '#ffffff bold', Keyword.Type: '#cdcaa9 bold', Generic.Subheading: '#ffffff bold', Name.Constant: '#0086d2', Comment.Preproc: '#ff0007 bold' }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113""" pygments.styles.gh_dark ~~~~~~~~~~~~~~~~~~~~~~~
Github's Dark-Colorscheme based theme for Pygments Colors extracted from https://github.com/primer/primitives
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, Error, Number, Operator, \ Generic, Text, Literal, String, Token
__all__ = ['GhDarkStyle']
# vars are defined to match the defs in# - [GitHub's VS Code theme](https://github.com/primer/github-vscode-theme) and# - [Primer styles](https://github.com/primer/primitives)RED_2 = "#ffa198"RED_3 = "#ff7b72"RED_9 = "#490202"ORANGE_2 = "#ffa657"ORANGE_3 = "#f0883e"GREEN_1 = "#7ee787"GREEN_2 = "#56d364"GREEN_7 = "#0f5323"BLUE_1 = "#a5d6ff"BLUE_2 = "#79c0ff"PURPLE_2 = "#d2a8ff"GRAY_3 = "#8b949e"GRAY_4 = "#6e7681"FG_SUBTLE = "#6e7681"FG_DEFAULT = "#e6edf3"BG_DEFAULT = "#0d1117"DANGER_FG = "#f85149"
class GhDarkStyle(Style): """ Github's Dark-Colorscheme based theme for Pygments """ name = 'github-dark'
background_color = BG_DEFAULT
# has transparency in VS Code theme as `colors.codemirror.activelineBg` highlight_color = GRAY_4
line_number_special_color = FG_DEFAULT line_number_special_background_color = FG_SUBTLE
line_number_color = GRAY_4 line_number_background_color = BG_DEFAULT
styles = { Token: FG_DEFAULT,
Error: DANGER_FG,
Keyword: RED_3, Keyword.Constant: BLUE_2, Keyword.Pseudo: BLUE_2,
Name: FG_DEFAULT, Name.Class: "bold "+ORANGE_3, Name.Constant: "bold "+BLUE_2, Name.Decorator: 'bold '+PURPLE_2, Name.Entity: ORANGE_2, Name.Exception: "bold "+ORANGE_3, Name.Function: 'bold '+PURPLE_2, Name.Label: "bold "+BLUE_2, Name.Namespace: RED_3, Name.Property: BLUE_2, Name.Tag: GREEN_1, Name.Variable: BLUE_2,
Literal: BLUE_1, Literal.Date: BLUE_2, String: BLUE_1, String.Affix: BLUE_2, String.Delimiter: BLUE_2, String.Escape: BLUE_2, String.Heredoc: BLUE_2, String.Regex: BLUE_2, Number: BLUE_1,
Comment: 'italic '+GRAY_3, Comment.Preproc: "bold " + GRAY_3, Comment.Special: "bold italic " + GRAY_3,
Operator: 'bold ' + RED_3,
Generic: FG_DEFAULT, Generic.Deleted: f"bg:{RED_9} {RED_2}", Generic.Emph: "italic", Generic.Error: RED_2, Generic.Heading: "bold "+BLUE_2, Generic.Inserted: f'bg:{GREEN_7} {GREEN_2}', Generic.Output: GRAY_3, Generic.Prompt: GRAY_3, Generic.Strong: "bold", Generic.EmphStrong: "bold italic", Generic.Subheading: BLUE_2, Generic.Traceback: RED_3, Generic.Underline: "underline",
Text.Whitespace: FG_SUBTLE, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118""" pygments.styles.gruvbox ~~~~~~~~~~~~~~~~~~~~~~~
pygments version of the "gruvbox" vim theme. https://github.com/morhetz/gruvbox
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Token, Keyword, Name, Comment, String, Error, \ Number, Operator, Generic
__all__ = ['GruvboxDarkStyle', 'GruvboxLightStyle']
class GruvboxDarkStyle(Style): """ Pygments version of the "gruvbox" dark vim theme. """ name = 'gruvbox-dark'
background_color = '#282828' highlight_color = '#ebdbb2'
styles = { Token: '#dddddd',
Comment: 'italic #928374', Comment.PreProc: '#8ec07c', Comment.Special: 'bold italic #ebdbb2',
Keyword: '#fb4934', Operator.Word: '#fb4934',
String: '#b8bb26', String.Escape: '#fe8019',
Number: '#d3869b',
Name.Builtin: '#fe8019', Name.Variable: '#83a598', Name.Constant: '#d3869b', Name.Class: '#8ec07c', Name.Function: '#8ec07c', Name.Namespace: '#8ec07c', Name.Exception: '#fb4934', Name.Tag: '#8ec07c', Name.Attribute: '#fabd2f', Name.Decorator: '#fb4934',
Generic.Heading: 'bold #ebdbb2', Generic.Subheading: 'underline #ebdbb2', Generic.Deleted: 'bg:#fb4934 #282828', Generic.Inserted: 'bg:#b8bb26 #282828', Generic.Error: '#fb4934', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.EmphStrong: 'bold italic', Generic.Prompt: '#a89984', Generic.Output: '#f2e5bc', Generic.Traceback: '#fb4934',
Error: 'bg:#fb4934 #282828' }
class GruvboxLightStyle(Style): """ Pygments version of the "gruvbox" Light vim theme. """
name = 'gruvbox-light'
background_color = '#fbf1c7' highlight_color = '#3c3836'
styles = { Comment: 'italic #928374', Comment.PreProc: '#427b58', Comment.Special: 'bold italic #3c3836',
Keyword: '#9d0006', Operator.Word: '#9d0006',
String: '#79740e', String.Escape: '#af3a03',
Number: '#8f3f71',
Name.Builtin: '#af3a03', Name.Variable: '#076678', Name.Constant: '#8f3f71', Name.Class: '#427b58', Name.Function: '#427b58', Name.Namespace: '#427b58', Name.Exception: '#9d0006', Name.Tag: '#427b58', Name.Attribute: '#b57614', Name.Decorator: '#9d0006',
Generic.Heading: 'bold #3c3836', Generic.Subheading: 'underline #3c3836', Generic.Deleted: 'bg:#9d0006 #fbf1c7', Generic.Inserted: 'bg:#79740e #fbf1c7', Generic.Error: '#9d0006', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#7c6f64', Generic.Output: '#32302f', Generic.Traceback: '#9d0006',
Error: 'bg:#9d0006 #fbf1c7' }1234567891011121314151617181920212223242526272829303132""" pygments.styles.igor ~~~~~~~~~~~~~~~~~~~~
Igor Pro default style.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String
__all__ = ['IgorStyle']
class IgorStyle(Style): """ Pygments version of the official colors for Igor Pro procedures. """
name = 'igor'
styles = { Comment: 'italic #FF0000', Keyword: '#0000FF', Name.Function: '#C34E00', Name.Decorator: '#CC00A3', Name.Class: '#007575', String: '#009C00' }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172""" pygments.styles.inkpot ~~~~~~~~~~~~~~~~~~~~~~
A highlighting style for Pygments, inspired by the Inkpot theme for VIM.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Text, Other, Keyword, Name, Comment, String, \ Error, Number, Operator, Generic, Whitespace, Punctuation
__all__ = ['InkPotStyle']
class InkPotStyle(Style): name = 'inkpot' background_color = "#1e1e27"
styles = { Text: "#cfbfad", Other: "#cfbfad", Whitespace: "#434357", Comment: "#cd8b00", Comment.Preproc: "#409090", Comment.PreprocFile: "bg:#404040 #ffcd8b", Comment.Special: "#808bed",
Keyword: "#808bed", Keyword.Pseudo: "nobold", Keyword.Type: "#ff8bff",
Operator: "#666666",
Punctuation: "#cfbfad",
Name: "#cfbfad", Name.Attribute: "#cfbfad", Name.Builtin.Pseudo: '#ffff00', Name.Builtin: "#808bed", Name.Class: "#ff8bff", Name.Constant: "#409090", Name.Decorator: "#409090", Name.Exception: "#ff0000", Name.Function: "#c080d0", Name.Label: "#808bed", Name.Namespace: "#ff0000", Name.Variable: "#cfbfad",
String: "bg:#404040 #ffcd8b", String.Doc: "#808bed",
Number: "#f0ad6d",
Generic.Heading: "bold #000080", Generic.Subheading: "bold #800080", Generic.Deleted: "#A00000", Generic.Inserted: "#00A000", Generic.Error: "#FF0000", Generic.Emph: "italic", Generic.Strong: "bold", Generic.EmphStrong: "bold italic", Generic.Prompt: "bold #000080", Generic.Output: "#888", Generic.Traceback: "#04D",
Error: "bg:#6e2e2e #ffffff" }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110""" pygments.styles.lightbulb ~~~~~~~~~~~~~~~~~~~~~~~~~
A minimal dark theme based on the Lightbulb theme for VSCode.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import ( Comment, Error, Generic, Keyword, Literal, Name, Number, Operator, Punctuation, String, Token,)
__all__ = ['LightbulbStyle']
COLORS = { "bg": "#1d2331", "blue_1": "#73D0FF", "gray_1": "#7e8aa1", "gray_2": "#3c4354", "gray_3": "#6e7681", "red_1": "#f88f7f", "red_2": "#3d1e20", "orange_1": "#FFAD66", "orange_2": "#F29E74", "yellow_1": "#FFD173", "white": "#d4d2c8", "magenta_1": "#DFBFFF", "green_1": "#D5FF80", "green_2": "#19362c", "cyan_1": "#95E6CB",}
class LightbulbStyle(Style): """ A minimal dark theme based on the Lightbulb theme for VSCode. """
name = 'lightbulb'
background_color = COLORS['bg'] highlight_color = COLORS['gray_3']
line_number_color = COLORS['gray_2'] line_number_special_color = COLORS['gray_2']
styles = { Comment: COLORS["gray_1"], Comment.Hashbang: "italic " + COLORS['red_1'], Comment.Preproc: "bold " + COLORS['orange_1'], Comment.Special: "italic " + COLORS['gray_1'], Error: COLORS['red_1'], Generic.Deleted: f"bg:{COLORS['red_2']} #f88f7f", Generic.Emph: "italic", Generic.Error: "#f88f7f", Generic.Inserted: f"bg:{COLORS['green_2']} #6ad4af", Generic.Output: COLORS['gray_1'], Generic.Strong: "bold", Generic.Traceback: COLORS['red_1'], Keyword: COLORS['orange_1'], Keyword.Constant: COLORS['orange_1'], Keyword.Declaration: COLORS['orange_1'], Keyword.Namespace: COLORS['orange_1'], Keyword.Reserved: COLORS['orange_1'], Keyword.Type: COLORS['blue_1'], Literal: COLORS['green_1'], Name: COLORS['white'], Name.Attribute: COLORS['yellow_1'], Name.Builtin: COLORS['yellow_1'], Name.Builtin.Pseudo: "#5CCFE6", Name.Class: COLORS['blue_1'], Name.Constant: COLORS['yellow_1'], Name.Decorator: "bold italic " + COLORS['gray_1'], Name.Entity: COLORS['cyan_1'], Name.Exception: COLORS['blue_1'], Name.Function: COLORS['yellow_1'], Name.Function.Magic: COLORS['yellow_1'], Name.Other: COLORS['white'], Name.Property: COLORS['yellow_1'], Name.Tag: "#5CCFE6", Name.Variable: COLORS['white'], Number: COLORS['magenta_1'], Operator: COLORS['orange_1'], Operator.Word: COLORS['orange_1'], Punctuation: COLORS['white'], String: COLORS['green_1'], String.Affix: COLORS['orange_2'], String.Doc: COLORS['gray_1'], String.Escape: COLORS['cyan_1'], String.Interpol: COLORS['cyan_1'], String.Other: COLORS['cyan_1'], String.Regex: COLORS['cyan_1'], String.Symbol: COLORS['magenta_1'], Token: COLORS['white'], }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162""" pygments.styles.lilypond ~~~~~~~~~~~~~~~~~~~~~~~~
LilyPond-specific style.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Token
__all__ = ['LilyPondStyle']
class LilyPondStyle(Style): """ Style for the LilyPond language.
.. versionadded:: 2.11 """
name = 'lilypond' # Don't show it in the gallery, it's intended for LilyPond # input only and doesn't show good output on Python code. web_style_gallery_exclude = True
styles = { Token.Text: "", Token.Keyword: "bold", Token.Comment: "italic #A3AAB2", Token.String: "#AB0909", Token.String.Escape: "#C46C6C", Token.String.Symbol: "noinherit", Token.Pitch: "", #"#911520", Token.Number: "#976806", # includes durations # A bare 11 is not distinguishable from a number, so we highlight # the same. Token.ChordModifier: "#976806", Token.Name.Lvalue: "#08547A", Token.Name.BackslashReference: "#08547A", Token.Name.Builtin.MusicCommand: "bold #08547A", Token.Name.Builtin.PaperVariable: "bold #6C5A05", Token.Name.Builtin.HeaderVariable: "bold #6C5A05", Token.Name.Builtin.MusicFunction: "bold #08547A", Token.Name.Builtin.Clef: "bold #08547A", Token.Name.Builtin.Scale: "bold #08547A", Token.Name.Builtin.RepeatType: "#08547A", Token.Name.Builtin.Dynamic: "#68175A", Token.Name.Builtin.Articulation: "#68175A", Token.Name.Builtin.SchemeFunction: "bold #A83401", Token.Name.Builtin.SchemeBuiltin: "bold", Token.Name.Builtin.MarkupCommand: "bold #831E71", Token.Name.Builtin.Context: "bold #038B8B", Token.Name.Builtin.ContextProperty: "#038B8B", Token.Name.Builtin.Grob: "bold #0C7441", Token.Name.Builtin.GrobProperty: "#0C7441", Token.Name.Builtin.Translator: "bold #6200A4", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100""" pygments.styles.lovelace ~~~~~~~~~~~~~~~~~~~~~~~~
Lovelace by Miikka Salminen
Pygments style by Miikka Salminen (https://github.com/miikkas) A desaturated, somewhat subdued style created for the Lovelace interactive learning environment.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Punctuation, Generic, Whitespace
__all__ = ['LovelaceStyle']
class LovelaceStyle(Style): """ The style used in Lovelace interactive learning environment. Tries to avoid the "angry fruit salad" effect with desaturated and dim colours. """ name = 'lovelace'
_KW_BLUE = '#2838b0' _NAME_GREEN = '#388038' _DOC_ORANGE = '#b85820' _OW_PURPLE = '#a848a8' _FUN_BROWN = '#785840' _STR_RED = '#b83838' _CLS_CYAN = '#287088' _ESCAPE_LIME = '#709030' _LABEL_CYAN = '#289870' _EXCEPT_YELLOW = '#908828'
styles = { Whitespace: '#a89028', Comment: 'italic #888888', Comment.Hashbang: _CLS_CYAN, Comment.Multiline: '#888888', Comment.Preproc: 'noitalic '+_LABEL_CYAN,
Keyword: _KW_BLUE, Keyword.Constant: 'italic #444444', Keyword.Declaration: 'italic', Keyword.Type: 'italic',
Operator: '#666666', Operator.Word: _OW_PURPLE,
Punctuation: '#888888',
Name.Attribute: _NAME_GREEN, Name.Builtin: _NAME_GREEN, Name.Builtin.Pseudo: 'italic', Name.Class: _CLS_CYAN, Name.Constant: _DOC_ORANGE, Name.Decorator: _CLS_CYAN, Name.Entity: _ESCAPE_LIME, Name.Exception: _EXCEPT_YELLOW, Name.Function: _FUN_BROWN, Name.Function.Magic: _DOC_ORANGE, Name.Label: _LABEL_CYAN, Name.Namespace: _LABEL_CYAN, Name.Tag: _KW_BLUE, Name.Variable: '#b04040', Name.Variable.Global:_EXCEPT_YELLOW, Name.Variable.Magic: _DOC_ORANGE,
String: _STR_RED, String.Affix: '#444444', String.Char: _OW_PURPLE, String.Delimiter: _DOC_ORANGE, String.Doc: 'italic '+_DOC_ORANGE, String.Escape: _ESCAPE_LIME, String.Interpol: 'underline', String.Other: _OW_PURPLE, String.Regex: _OW_PURPLE,
Number: '#444444',
Generic.Deleted: '#c02828', Generic.Emph: 'italic', Generic.Error: '#c02828', Generic.Heading: '#666666', Generic.Subheading: '#444444', Generic.Inserted: _NAME_GREEN, Generic.Output: '#666666', Generic.Prompt: '#444444', Generic.Strong: 'bold', Generic.EmphStrong: 'bold italic', Generic.Traceback: _KW_BLUE,
Error: 'bg:'+_OW_PURPLE, }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879""" pygments.styles.manni ~~~~~~~~~~~~~~~~~~~~~
A colorful style, inspired by the terminal highlighting style.
This is a port of the style used in the `php port`_ of pygments by Manni. The style is called 'default' there.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace
__all__ = ['ManniStyle']
class ManniStyle(Style): """ A colorful style, inspired by the terminal highlighting style. """ name = 'manni' background_color = '#f0f3f3'
styles = { Whitespace: '#bbbbbb', Comment: 'italic #0099FF', Comment.Preproc: 'noitalic #009999', Comment.Special: 'bold',
Keyword: 'bold #006699', Keyword.Pseudo: 'nobold', Keyword.Type: '#007788',
Operator: '#555555', Operator.Word: 'bold #000000',
Name.Builtin: '#336666', Name.Function: '#CC00FF', Name.Class: 'bold #00AA88', Name.Namespace: 'bold #00CCFF', Name.Exception: 'bold #CC0000', Name.Variable: '#003333', Name.Constant: '#336600', Name.Label: '#9999FF', Name.Entity: 'bold #999999', Name.Attribute: '#330099', Name.Tag: 'bold #330099', Name.Decorator: '#9999FF',
String: '#CC3300', String.Doc: 'italic', String.Interpol: '#AA0000', String.Escape: 'bold #CC3300', String.Regex: '#33AAAA', String.Symbol: '#FFCC33', String.Other: '#CC3300',
Number: '#FF6600',
Generic.Heading: 'bold #003300', Generic.Subheading: 'bold #003300', Generic.Deleted: 'border:#CC0000 bg:#FFCCCC', Generic.Inserted: 'border:#00CC00 bg:#CCFFCC', Generic.Error: '#FF0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.EmphStrong: 'bold italic', Generic.Prompt: 'bold #000099', Generic.Output: '#AAAAAA', Generic.Traceback: '#99CC66',
Error: 'bg:#FFAAAA #AA0000' }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124""" pygments.styles.material ~~~~~~~~~~~~~~~~~~~~~~~~
Mimic the Material theme color scheme.
https://github.com/material-theme/vsc-material-theme
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Escape, \ Error, Text, Number, Operator, Generic, Punctuation, Literal
__all__ = ['MaterialStyle']
class MaterialStyle(Style): """ This style mimics the Material Theme color scheme. """ name = 'material' dark_teal = '#263238' white = '#FFFFFF' black = '#000000' red = '#FF5370' orange = '#F78C6C' yellow = '#FFCB6B' green = '#C3E88D' cyan = '#89DDFF' blue = '#82AAFF' paleblue = '#B2CCD6' purple = '#C792EA' brown = '#C17E70' pink = '#F07178' violet = '#BB80B3' foreground = '#EEFFFF' faded = '#546E7A'
background_color = dark_teal highlight_color = '#2C3B41' line_number_color = '#37474F' line_number_background_color = dark_teal line_number_special_color = '#607A86' line_number_special_background_color = dark_teal
styles = { Text: foreground, Escape: cyan, Error: red,
Keyword: violet, Keyword.Constant: cyan, Keyword.Declaration: violet, Keyword.Namespace: 'italic ' + cyan, Keyword.Pseudo: cyan, Keyword.Type: violet,
Name: foreground, Name.Attribute: violet, Name.Builtin: blue, Name.Builtin.Pseudo: cyan, Name.Class: yellow, Name.Constant: foreground, Name.Decorator: blue, Name.Entity: cyan, Name.Exception: yellow, Name.Function: blue, Name.Function.Magic: blue, Name.Label: blue, Name.Property: yellow, Name.Namespace: yellow, Name.Other: foreground, Name.Tag: red, Name.Variable: cyan, Name.Variable.Class: cyan, Name.Variable.Global: cyan, Name.Variable.Instance: cyan, Name.Variable.Magic: blue,
Literal: green, Literal.Date: green,
String: green, String.Affix: violet, String.Backtick: green, String.Char: green, String.Delimiter: foreground, String.Doc: 'italic ' + faded, String.Double: green, String.Escape: foreground, String.Heredoc: green, String.Interpol: cyan, String.Other: green, String.Regex: cyan, String.Single: green, String.Symbol: cyan,
Number: orange,
Operator: cyan, Operator.Word: 'italic ' + cyan,
Punctuation: cyan,
Comment: 'italic ' + faded,
Generic: foreground, Generic.Deleted: red, Generic.Emph: cyan, Generic.Error: red, Generic.Heading: green, Generic.Inserted: green, Generic.Output: faded, Generic.Prompt: yellow, Generic.Strong: red, Generic.EmphStrong: yellow, Generic.Subheading: cyan, Generic.Traceback: red, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112""" pygments.styles.monokai ~~~~~~~~~~~~~~~~~~~~~~~
Mimic the Monokai color scheme. Based on tango.py.
http://www.monokai.nl/blog/2006/07/15/textmate-color-theme/
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, Token, \ Number, Operator, Generic, Whitespace, Punctuation, Other, Literal
__all__ = ['MonokaiStyle']
class MonokaiStyle(Style): """ This style mimics the Monokai color scheme. """ name = 'monokai' background_color = "#272822" highlight_color = "#49483e"
styles = { # No corresponding class for the following: Token: "#f8f8f2", # class: '' Whitespace: "", # class: 'w' Error: "#ed007e bg:#1e0010", # class: 'err' Other: "", # class 'x'
Comment: "#959077", # class: 'c' Comment.Multiline: "", # class: 'cm' Comment.Preproc: "", # class: 'cp' Comment.Single: "", # class: 'c1' Comment.Special: "", # class: 'cs'
Keyword: "#66d9ef", # class: 'k' Keyword.Constant: "", # class: 'kc' Keyword.Declaration: "", # class: 'kd' Keyword.Namespace: "#ff4689", # class: 'kn' Keyword.Pseudo: "", # class: 'kp' Keyword.Reserved: "", # class: 'kr' Keyword.Type: "", # class: 'kt'
Operator: "#ff4689", # class: 'o' Operator.Word: "", # class: 'ow' - like keywords
Punctuation: "#f8f8f2", # class: 'p'
Name: "#f8f8f2", # class: 'n' Name.Attribute: "#a6e22e", # class: 'na' - to be revised Name.Builtin: "", # class: 'nb' Name.Builtin.Pseudo: "", # class: 'bp' Name.Class: "#a6e22e", # class: 'nc' - to be revised Name.Constant: "#66d9ef", # class: 'no' - to be revised Name.Decorator: "#a6e22e", # class: 'nd' - to be revised Name.Entity: "", # class: 'ni' Name.Exception: "#a6e22e", # class: 'ne' Name.Function: "#a6e22e", # class: 'nf' Name.Property: "", # class: 'py' Name.Label: "", # class: 'nl' Name.Namespace: "", # class: 'nn' - to be revised Name.Other: "#a6e22e", # class: 'nx' Name.Tag: "#ff4689", # class: 'nt' - like a keyword Name.Variable: "", # class: 'nv' - to be revised Name.Variable.Class: "", # class: 'vc' - to be revised Name.Variable.Global: "", # class: 'vg' - to be revised Name.Variable.Instance: "", # class: 'vi' - to be revised
Number: "#ae81ff", # class: 'm' Number.Float: "", # class: 'mf' Number.Hex: "", # class: 'mh' Number.Integer: "", # class: 'mi' Number.Integer.Long: "", # class: 'il' Number.Oct: "", # class: 'mo'
Literal: "#ae81ff", # class: 'l' Literal.Date: "#e6db74", # class: 'ld'
String: "#e6db74", # class: 's' String.Backtick: "", # class: 'sb' String.Char: "", # class: 'sc' String.Doc: "", # class: 'sd' - like a comment String.Double: "", # class: 's2' String.Escape: "#ae81ff", # class: 'se' String.Heredoc: "", # class: 'sh' String.Interpol: "", # class: 'si' String.Other: "", # class: 'sx' String.Regex: "", # class: 'sr' String.Single: "", # class: 's1' String.Symbol: "", # class: 'ss'
Generic: "", # class: 'g' Generic.Deleted: "#ff4689", # class: 'gd', Generic.Emph: "italic", # class: 'ge' Generic.Error: "", # class: 'gr' Generic.Heading: "", # class: 'gh' Generic.Inserted: "#a6e22e", # class: 'gi' Generic.Output: "#66d9ef", # class: 'go' Generic.Prompt: "bold #ff4689", # class: 'gp' Generic.Strong: "bold", # class: 'gs' Generic.EmphStrong: "bold italic", # class: 'ges' Generic.Subheading: "#959077", # class: 'gu' Generic.Traceback: "", # class: 'gt' }.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/METADATAAdded+57
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/WHEELAdded+4
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/entry_points.txtAdded+2
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/licenses/AUTHORSAdded+292
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments-2.20.0.dist-info/licenses/LICENSEAdded+25
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/__init__.pyAdded+82
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/__main__.pyAdded+17
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/cmdline.pyAdded+668
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/filter.pyAdded+70
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/formatter.pyAdded+129
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexer.pyAdded+963
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/wren.pyAdded+98
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/x10.pyAdded+66
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/xorg.pyAdded+38
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/yang.pyAdded+103
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/yara.pyAdded+69
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/lexers/zig.pyAdded+125
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/modeline.pyAdded+43
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/plugin.pyAdded+74
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/regexopt.pyAdded+102
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/scanner.pyAdded+104
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/sphinxext.pyAdded+247
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/style.pyAdded+203
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/__init__.pyAdded+61
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/_mapping.pyAdded+54
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/abap.pyAdded+32
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/algol.pyAdded+65
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/algol_nu.pyAdded+65
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/arduino.pyAdded+100
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/autumn.pyAdded+67
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/borland.pyAdded+53
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/bw.pyAdded+52
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/coffee.pyAdded+80
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/colorful.pyAdded+83
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/default.pyAdded+76
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/dracula.pyAdded+90
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/emacs.pyAdded+75
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/friendly.pyAdded+76
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/friendly_grayscale.pyAdded+80
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/fruity.pyAdded+47
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/gh_dark.pyAdded+113
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/gruvbox.pyAdded+118
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/igor.pyAdded+32
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/inkpot.pyAdded+72
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/lightbulb.pyAdded+110
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/lilypond.pyAdded+62
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/lovelace.pyAdded+100
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/manni.pyAdded+79
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/material.pyAdded+124
.cache/uv/archive-v0/8HXDPXsFSToj27nOg3aiO/pygments/styles/monokai.pyAdded+112